OSDN Git Service

2008-04-08 Hristian Kirtchev <kirtchev@adacore.com>
[pf3gnuchains/gcc-fork.git] / gcc / ada / bindgen.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT COMPILER COMPONENTS                         --
4 --                                                                          --
5 --                              B I N D G E N                               --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2007, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17 -- for  more details.  You should have  received  a copy of the GNU General --
18 -- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19 -- http://www.gnu.org/licenses for a complete copy of the license.          --
20 --                                                                          --
21 -- GNAT was originally developed  by the GNAT team at  New York University. --
22 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
23 --                                                                          --
24 ------------------------------------------------------------------------------
25
26 with ALI;      use ALI;
27 with Binde;    use Binde;
28 with Casing;   use Casing;
29 with Fname;    use Fname;
30 with Gnatvsn;  use Gnatvsn;
31 with Hostparm;
32 with Namet;    use Namet;
33 with Opt;      use Opt;
34 with Osint;    use Osint;
35 with Osint.B;  use Osint.B;
36 with Output;   use Output;
37 with Rident;   use Rident;
38 with Table;    use Table;
39 with Targparm; use Targparm;
40 with Types;    use Types;
41
42 with System.OS_Lib;  use System.OS_Lib;
43 with System.WCh_Con; use System.WCh_Con;
44
45 with GNAT.Heap_Sort_A; use GNAT.Heap_Sort_A;
46
47 package body Bindgen is
48
49    Statement_Buffer : String (1 .. 1000);
50    --  Buffer used for constructing output statements
51
52    Last : Natural := 0;
53    --  Last location in Statement_Buffer currently set
54
55    With_DECGNAT : Boolean := False;
56    --  Flag which indicates whether the program uses the DECGNAT library
57    --  (presence of the unit DEC).
58
59    With_GNARL : Boolean := False;
60    --  Flag which indicates whether the program uses the GNARL library
61    --  (presence of the unit System.OS_Interface)
62
63    Num_Elab_Calls : Nat := 0;
64    --  Number of generated calls to elaboration routines
65
66    System_Restrictions_Used : Boolean;
67    --  Flag indicating whether the unit System.Restrictions is in the closure
68    --  of the partition. This is set by Check_System_Restrictions_Used, and
69    --  is used to determine whether or not to initialize the restrictions
70    --  information in the body of the binder generated file (we do not want
71    --  to do this unconditionally, since it drags in the System.Restrictions
72    --  unit unconditionally, which is unpleasand, especially for ZFP etc.)
73
74    ----------------------------------
75    -- Interface_State Pragma Table --
76    ----------------------------------
77
78    --  This table assembles the interface state pragma information from
79    --  all the units in the partition. Note that Bcheck has already checked
80    --  that the information is consistent across units. The entries
81    --  in this table are n/u/r/s for not set/user/runtime/system.
82
83    package IS_Pragma_Settings is new Table.Table (
84      Table_Component_Type => Character,
85      Table_Index_Type     => Int,
86      Table_Low_Bound      => 0,
87      Table_Initial        => 100,
88      Table_Increment      => 200,
89      Table_Name           => "IS_Pragma_Settings");
90
91    --  This table assembles the Priority_Specific_Dispatching pragma
92    --  information from all the units in the partition. Note that Bcheck has
93    --  already checked that the information is consistent across units.
94    --  The entries in this table are the upper case first character of the
95    --  policy name, e.g. 'F' for FIFO_Within_Priorities.
96
97    package PSD_Pragma_Settings is new Table.Table (
98      Table_Component_Type => Character,
99      Table_Index_Type     => Int,
100      Table_Low_Bound      => 0,
101      Table_Initial        => 100,
102      Table_Increment      => 200,
103      Table_Name           => "PSD_Pragma_Settings");
104
105    ----------------------
106    -- Run-Time Globals --
107    ----------------------
108
109    --  This section documents the global variables that set from the
110    --  generated binder file.
111
112    --     Main_Priority                 : Integer;
113    --     Time_Slice_Value              : Integer;
114    --     WC_Encoding                   : Character;
115    --     Locking_Policy                : Character;
116    --     Queuing_Policy                : Character;
117    --     Task_Dispatching_Policy       : Character;
118    --     Priority_Specific_Dispatching : System.Address;
119    --     Num_Specific_Dispatching      : Integer;
120    --     Restrictions                  : System.Address;
121    --     Interrupt_States              : System.Address;
122    --     Num_Interrupt_States          : Integer;
123    --     Unreserve_All_Interrupts      : Integer;
124    --     Exception_Tracebacks          : Integer;
125    --     Zero_Cost_Exceptions          : Integer;
126    --     Detect_Blocking               : Integer;
127    --     Default_Stack_Size            : Integer;
128    --     Leap_Seconds_Support          : Integer;
129
130    --  Main_Priority is the priority value set by pragma Priority in the
131    --  main program. If no such pragma is present, the value is -1.
132
133    --  Time_Slice_Value is the time slice value set by pragma Time_Slice
134    --  in the main program, or by the use of a -Tnnn parameter for the
135    --  binder (if both are present, the binder value overrides). The
136    --  value is in milliseconds. A value of zero indicates that time
137    --  slicing should be suppressed. If no pragma is present, and no
138    --  -T switch was used, the value is -1.
139
140    --  WC_Encoding shows the wide character encoding method used for
141    --  the main program. This is one of the encoding letters defined
142    --  in System.WCh_Con.WC_Encoding_Letters.
143
144    --  Locking_Policy is a space if no locking policy was specified
145    --  for the partition. If a locking policy was specified, the value
146    --  is the upper case first character of the locking policy name,
147    --  for example, 'C' for Ceiling_Locking.
148
149    --  Queuing_Policy is a space if no queuing policy was specified
150    --  for the partition. If a queuing policy was specified, the value
151    --  is the upper case first character of the queuing policy name
152    --  for example, 'F' for FIFO_Queuing.
153
154    --  Task_Dispatching_Policy is a space if no task dispatching policy
155    --  was specified for the partition. If a task dispatching policy
156    --  was specified, the value is the upper case first character of
157    --  the policy name, e.g. 'F' for FIFO_Within_Priorities.
158
159    --  Priority_Specific_Dispatching is the address of a string used to
160    --  store the task dispatching policy specified for the different priorities
161    --  in the partition. The length of this string is determined by the last
162    --  priority for which such a pragma applies (the string will be a null
163    --  string if no specific dispatching policies were used). If pragma were
164    --  present, the entries apply to the priorities in sequence from the first
165    --  priority. The value stored is the upper case first character of the
166    --  policy name, or 'F' (for FIFO_Within_Priorities) as the default value
167    --  for those priority ranges not specified.
168
169    --  Num_Specific_Dispatching is the length of the
170    --  Priority_Specific_Dispatching string. It will be set to zero if no
171    --  Priority_Specific_Dispatching pragmas are present.
172
173    --  Restrictions is the address of a null-terminated string specifying the
174    --  restrictions information for the partition. The format is identical to
175    --  that of the parameter string found on R lines in ali files (see Lib.Writ
176    --  spec in lib-writ.ads for full details). The difference is that in this
177    --  context the values are the cumulative ones for the entire partition.
178
179    --  Interrupt_States is the address of a string used to specify the
180    --  cumulative results of Interrupt_State pragmas used in the partition.
181    --  The length of this string is determined by the last interrupt for which
182    --  such a pragma is given (the string will be a null string if no pragmas
183    --  were used). If pragma were present the entries apply to the interrupts
184    --  in sequence from the first interrupt, and are set to one of four
185    --  possible settings: 'n' for not specified, 'u' for user, 'r' for
186    --  run time, 's' for system, see description of Interrupt_State pragma
187    --  for further details.
188
189    --  Num_Interrupt_States is the length of the Interrupt_States string.
190    --  It will be set to zero if no Interrupt_State pragmas are present.
191
192    --  Unreserve_All_Interrupts is set to one if at least one unit in the
193    --  partition had a pragma Unreserve_All_Interrupts, and zero otherwise.
194
195    --  Exception_Tracebacks is set to one if the -E parameter was present
196    --  in the bind and to zero otherwise. Note that on some targets exception
197    --  tracebacks are provided by default, so a value of zero for this
198    --  parameter does not necessarily mean no trace backs are available.
199
200    --  Zero_Cost_Exceptions is set to one if zero cost exceptions are used for
201    --  this partition, and to zero if longjmp/setjmp exceptions are used.
202    --  the use of zero
203
204    --  Detect_Blocking indicates whether pragma Detect_Blocking is
205    --  active or not. A value of zero indicates that the pragma is not
206    --  present, while a value of 1 signals its presence in the
207    --  partition.
208
209    --  Default_Stack_Size is the default stack size used when creating an
210    --  Ada task with no explicit Storize_Size clause.
211
212    --  Leap_Seconds_Support denotes whether leap seconds have been enabled or
213    --  disabled. A value of zero indicates that leap seconds are turned "off",
214    --  while a value of one signifies "on" status.
215
216    -----------------------
217    -- Local Subprograms --
218    -----------------------
219
220    procedure WBI (Info : String) renames Osint.B.Write_Binder_Info;
221    --  Convenient shorthand used throughout
222
223    procedure Check_System_Restrictions_Used;
224    --  Sets flag System_Restrictions_Used (Set to True if and only if the unit
225    --  System.Restrictions is present in the partition, otherwise False).
226
227    procedure Gen_Adainit_Ada;
228    --  Generates the Adainit procedure (Ada code case)
229
230    procedure Gen_Adainit_C;
231    --  Generates the Adainit procedure (C code case)
232
233    procedure Gen_Adafinal_Ada;
234    --  Generate the Adafinal procedure (Ada code case)
235
236    procedure Gen_Adafinal_C;
237    --  Generate the Adafinal procedure (C code case)
238
239    procedure Gen_Elab_Calls_Ada;
240    --  Generate sequence of elaboration calls (Ada code case)
241
242    procedure Gen_Elab_Calls_C;
243    --  Generate sequence of elaboration calls (C code case)
244
245    procedure Gen_Elab_Order_Ada;
246    --  Generate comments showing elaboration order chosen (Ada case)
247
248    procedure Gen_Elab_Order_C;
249    --  Generate comments showing elaboration order chosen (C case)
250
251    procedure Gen_Elab_Defs_C;
252    --  Generate sequence of definitions for elaboration routines (C code case)
253
254    procedure Gen_Main_Ada;
255    --  Generate procedure main (Ada code case)
256
257    procedure Gen_Main_C;
258    --  Generate main() procedure (C code case)
259
260    procedure Gen_Object_Files_Options;
261    --  Output comments containing a list of the full names of the object
262    --  files to be linked and the list of linker options supplied by
263    --  Linker_Options pragmas in the source. (C and Ada code case)
264
265    procedure Gen_Output_File_Ada (Filename : String);
266    --  Generate output file (Ada code case)
267
268    procedure Gen_Output_File_C (Filename : String);
269    --  Generate output file (C code case)
270
271    procedure Gen_Restrictions_Ada;
272    --  Generate initialization of restrictions variable (Ada code case)
273
274    procedure Gen_Restrictions_C;
275    --  Generate initialization of restrictions variable (C code case)
276
277    procedure Gen_Versions_Ada;
278    --  Output series of definitions for unit versions (Ada code case)
279
280    procedure Gen_Versions_C;
281    --  Output series of definitions for unit versions (C code case)
282
283    function Get_Ada_Main_Name return String;
284    --  This function is used in the Ada main output case to compute a usable
285    --  name for the generated main program. The normal main program name is
286    --  Ada_Main, but this won't work if the user has a unit with this name.
287    --  This function tries Ada_Main first, and if there is such a clash, then
288    --  it tries Ada_Name_01, Ada_Name_02 ... Ada_Name_99 in sequence.
289
290    function Get_Main_Unit_Name (S : String) return String;
291    --  Return the main unit name corresponding to S by replacing '.' with '_'
292
293    function Get_Main_Name return String;
294    --  This function is used in the Ada main output case to compute the
295    --  correct external main program. It is "main" by default, unless the
296    --  flag Use_Ada_Main_Program_Name_On_Target is set, in which case it
297    --  is the name of the Ada main name without the "_ada". This default
298    --  can be overridden explicitly using the -Mname binder switch.
299
300    function Get_WC_Encoding return Character;
301    --  Return wide character encoding method to set as WC_Encoding in output.
302    --  If -W has been used, returns the specified encoding, otherwise returns
303    --  the encoding method used for the main program source. If there is no
304    --  main program source (-z switch used), returns brackets ('b').
305
306    function Lt_Linker_Option (Op1, Op2 : Natural) return Boolean;
307    --  Compare linker options, when sorting, first according to
308    --  Is_Internal_File (internal files come later) and then by
309    --  elaboration order position (latest to earliest).
310
311    procedure Move_Linker_Option (From : Natural; To : Natural);
312    --  Move routine for sorting linker options
313
314    procedure Resolve_Binder_Options;
315    --  Set the value of With_GNARL and With_DECGNAT. The latter only on VMS
316    --  since it tests for a package named "dec" which might cause a conflict
317    --  on non-VMS systems.
318
319    procedure Set_Char (C : Character);
320    --  Set given character in Statement_Buffer at the Last + 1 position
321    --  and increment Last by one to reflect the stored character.
322
323    procedure Set_Int (N : Int);
324    --  Set given value in decimal in Statement_Buffer with no spaces
325    --  starting at the Last + 1 position, and updating Last past the value.
326    --  A minus sign is output for a negative value.
327
328    procedure Set_Boolean (B : Boolean);
329    --  Set given boolean value in Statement_Buffer at the Last + 1 position
330    --  and update Last past the value.
331
332    procedure Set_IS_Pragma_Table;
333    --  Initializes contents of IS_Pragma_Settings table from ALI table
334
335    procedure Set_Main_Program_Name;
336    --  Given the main program name in Name_Buffer (length in Name_Len)
337    --  generate the name of the routine to be used in the call. The name
338    --  is generated starting at Last + 1, and Last is updated past it.
339
340    procedure Set_Name_Buffer;
341    --  Set the value stored in positions 1 .. Name_Len of the Name_Buffer
342
343    procedure Set_PSD_Pragma_Table;
344    --  Initializes contents of PSD_Pragma_Settings table from ALI table
345
346    procedure Set_String (S : String);
347    --  Sets characters of given string in Statement_Buffer, starting at the
348    --  Last + 1 position, and updating last past the string value.
349
350    procedure Set_Unit_Name;
351    --  Given a unit name in the Name_Buffer, copies it to Statement_Buffer,
352    --  starting at the Last + 1 position, and updating last past the value.
353    --  changing periods to double underscores, and updating Last appropriately.
354
355    procedure Set_Unit_Number (U : Unit_Id);
356    --  Sets unit number (first unit is 1, leading zeroes output to line
357    --  up all output unit numbers nicely as required by the value, and
358    --  by the total number of units.
359
360    procedure Write_Info_Ada_C (Ada : String; C : String; Common : String);
361    --  For C code case, write C & Common, for Ada case write Ada & Common
362    --  to current binder output file using Write_Binder_Info.
363
364    procedure Write_Statement_Buffer;
365    --  Write out contents of statement buffer up to Last, and reset Last to 0
366
367    procedure Write_Statement_Buffer (S : String);
368    --  First writes its argument (using Set_String (S)), then writes out the
369    --  contents of statement buffer up to Last, and reset Last to 0
370
371    ------------------------------------
372    -- Check_System_Restrictions_Used --
373    ------------------------------------
374
375    procedure Check_System_Restrictions_Used is
376    begin
377       for J in Units.First .. Units.Last loop
378          if Get_Name_String (Units.Table (J).Sfile) = "s-restri.ads" then
379             System_Restrictions_Used := True;
380             return;
381          end if;
382       end loop;
383
384       System_Restrictions_Used := False;
385    end Check_System_Restrictions_Used;
386
387    ----------------------
388    -- Gen_Adafinal_Ada --
389    ----------------------
390
391    procedure Gen_Adafinal_Ada is
392    begin
393       WBI ("");
394       WBI ("   procedure " & Ada_Final_Name.all & " is");
395       WBI ("   begin");
396
397       --  If compiling for the JVM, we directly call Adafinal because
398       --  we don't import it via Do_Finalize (see Gen_Output_File_Ada).
399
400       if VM_Target /= No_VM then
401          WBI ("      System.Standard_Library.Adafinal;");
402
403       --  If there is no finalization, there is nothing to do
404
405       elsif Cumulative_Restrictions.Set (No_Finalization) then
406          WBI ("      null;");
407       else
408          WBI ("      Do_Finalize;");
409       end if;
410
411       WBI ("   end " & Ada_Final_Name.all & ";");
412    end Gen_Adafinal_Ada;
413
414    --------------------
415    -- Gen_Adafinal_C --
416    --------------------
417
418    procedure Gen_Adafinal_C is
419    begin
420       WBI ("void " & Ada_Final_Name.all & " (void) {");
421       WBI ("   system__standard_library__adafinal ();");
422       WBI ("}");
423       WBI ("");
424    end Gen_Adafinal_C;
425
426    ---------------------
427    -- Gen_Adainit_Ada --
428    ---------------------
429
430    procedure Gen_Adainit_Ada is
431       Main_Priority : Int renames ALIs.Table (ALIs.First).Main_Priority;
432
433    begin
434       WBI ("   procedure " & Ada_Init_Name.all & " is");
435
436       --  Generate externals for elaboration entities
437
438       for E in Elab_Order.First .. Elab_Order.Last loop
439          declare
440             Unum : constant Unit_Id := Elab_Order.Table (E);
441             U    : Unit_Record renames Units.Table (Unum);
442
443          begin
444             --  Check for Elab_Entity to be set for this unit
445
446             if U.Set_Elab_Entity
447
448             --  Don't generate reference for stand alone library
449
450               and then not U.SAL_Interface
451
452             --  Don't generate reference for predefined file in No_Run_Time
453             --  mode, since we don't include the object files in this case
454
455               and then not
456                 (No_Run_Time_Mode
457                    and then Is_Predefined_File_Name (U.Sfile))
458             then
459                Set_String ("      ");
460                Set_String ("E");
461                Set_Unit_Number (Unum);
462
463                case VM_Target is
464                   when No_VM | JVM_Target =>
465                      Set_String (" : Boolean; pragma Import (Ada, ");
466                   when CLI_Target =>
467                      Set_String (" : Boolean; pragma Import (CIL, ");
468                end case;
469
470                Set_String ("E");
471                Set_Unit_Number (Unum);
472                Set_String (", """);
473                Get_Name_String (U.Uname);
474
475                --  In the case of JGNAT we need to emit an Import name
476                --  that includes the class name (using '$' separators
477                --  in the case of a child unit name).
478
479                if VM_Target /= No_VM then
480                   for J in 1 .. Name_Len - 2 loop
481                      if VM_Target = CLI_Target
482                        or else Name_Buffer (J) /= '.'
483                      then
484                         Set_Char (Name_Buffer (J));
485                      else
486                         Set_String ("$");
487                      end if;
488                   end loop;
489
490                   if VM_Target /= CLI_Target or else U.Unit_Kind = 's' then
491                      Set_String (".");
492                   else
493                      Set_String ("_pkg.");
494                   end if;
495
496                   --  If the unit name is very long, then split the
497                   --  Import link name across lines using "&" (occurs
498                   --  in some C2 tests).
499
500                   if 2 * Name_Len + 60 > Hostparm.Max_Line_Length then
501                      Set_String (""" &");
502                      Write_Statement_Buffer;
503                      Set_String ("         """);
504                   end if;
505                end if;
506
507                Set_Unit_Name;
508                Set_String ("_E"");");
509                Write_Statement_Buffer;
510             end if;
511          end;
512       end loop;
513
514       Write_Statement_Buffer;
515
516       --  If the standard library is suppressed, then the only global variable
517       --  that might be needed (by the Ravenscar profile) is the priority of
518       --  the environment.
519
520       if Suppress_Standard_Library_On_Target then
521          if Main_Priority /= No_Main_Priority then
522             WBI ("      Main_Priority : Integer;");
523             WBI ("      pragma Import (C, Main_Priority," &
524                  " ""__gl_main_priority"");");
525             WBI ("");
526          end if;
527
528          WBI ("   begin");
529
530          if Main_Priority /= No_Main_Priority then
531             Set_String ("      Main_Priority := ");
532             Set_Int    (Main_Priority);
533             Set_Char   (';');
534             Write_Statement_Buffer;
535
536          else
537             WBI ("      null;");
538          end if;
539
540       --  Normal case (standard library not suppressed). Set all global values
541       --  used by the run time.
542
543       else
544          WBI ("      Main_Priority : Integer;");
545          WBI ("      pragma Import (C, Main_Priority, " &
546               """__gl_main_priority"");");
547          WBI ("      Time_Slice_Value : Integer;");
548          WBI ("      pragma Import (C, Time_Slice_Value, " &
549               """__gl_time_slice_val"");");
550          WBI ("      WC_Encoding : Character;");
551          WBI ("      pragma Import (C, WC_Encoding, ""__gl_wc_encoding"");");
552          WBI ("      Locking_Policy : Character;");
553          WBI ("      pragma Import (C, Locking_Policy, " &
554               """__gl_locking_policy"");");
555          WBI ("      Queuing_Policy : Character;");
556          WBI ("      pragma Import (C, Queuing_Policy, " &
557               """__gl_queuing_policy"");");
558          WBI ("      Task_Dispatching_Policy : Character;");
559          WBI ("      pragma Import (C, Task_Dispatching_Policy, " &
560               """__gl_task_dispatching_policy"");");
561          WBI ("      Priority_Specific_Dispatching : System.Address;");
562          WBI ("      pragma Import (C, Priority_Specific_Dispatching, " &
563               """__gl_priority_specific_dispatching"");");
564          WBI ("      Num_Specific_Dispatching : Integer;");
565          WBI ("      pragma Import (C, Num_Specific_Dispatching, " &
566               """__gl_num_specific_dispatching"");");
567
568          WBI ("      Interrupt_States : System.Address;");
569          WBI ("      pragma Import (C, Interrupt_States, " &
570               """__gl_interrupt_states"");");
571          WBI ("      Num_Interrupt_States : Integer;");
572          WBI ("      pragma Import (C, Num_Interrupt_States, " &
573               """__gl_num_interrupt_states"");");
574          WBI ("      Unreserve_All_Interrupts : Integer;");
575          WBI ("      pragma Import (C, Unreserve_All_Interrupts, " &
576               """__gl_unreserve_all_interrupts"");");
577
578          if Exception_Tracebacks then
579             WBI ("      Exception_Tracebacks : Integer;");
580             WBI ("      pragma Import (C, Exception_Tracebacks, " &
581                  """__gl_exception_tracebacks"");");
582          end if;
583
584          WBI ("      Zero_Cost_Exceptions : Integer;");
585          WBI ("      pragma Import (C, Zero_Cost_Exceptions, " &
586               """__gl_zero_cost_exceptions"");");
587          WBI ("      Detect_Blocking : Integer;");
588          WBI ("      pragma Import (C, Detect_Blocking, " &
589               """__gl_detect_blocking"");");
590          WBI ("      Default_Stack_Size : Integer;");
591          WBI ("      pragma Import (C, Default_Stack_Size, " &
592               """__gl_default_stack_size"");");
593          WBI ("      Leap_Seconds_Support : Integer;");
594          WBI ("      pragma Import (C, Leap_Seconds_Support, " &
595               """__gl_leap_seconds_support"");");
596
597          --  Import entry point for elaboration time signal handler
598          --  installation, and indication of if it's been called previously.
599
600          WBI ("");
601          WBI ("      procedure Install_Handler;");
602          WBI ("      pragma Import (C, Install_Handler, " &
603               """__gnat_install_handler"");");
604          WBI ("");
605          WBI ("      Handler_Installed : Integer;");
606          WBI ("      pragma Import (C, Handler_Installed, " &
607               """__gnat_handler_installed"");");
608
609          --  Initialize stack limit variable of the environment task if the
610          --  stack check method is stack limit and stack check is enabled.
611
612          if Stack_Check_Limits_On_Target
613            and then (Stack_Check_Default_On_Target or Stack_Check_Switch_Set)
614          then
615             WBI ("");
616             WBI ("      procedure Initialize_Stack_Limit;");
617             WBI ("      pragma Import (C, Initialize_Stack_Limit, " &
618                  """__gnat_initialize_stack_limit"");");
619          end if;
620
621          if VM_Target = CLI_Target
622            and then Bind_Main_Program
623            and then not No_Main_Subprogram
624          then
625             WBI ("");
626
627             if ALIs.Table (ALIs.First).Main_Program = Func then
628                WBI ("      Result : Integer;");
629                WBI ("");
630                WBI ("      function Ada_Main_Program return Integer;");
631
632             else
633                WBI ("      procedure Ada_Main_Program;");
634             end if;
635
636             Get_Name_String (Units.Table (First_Unit_Entry).Uname);
637             Name_Len := Name_Len - 2;
638             WBI ("      pragma Import (CIL, Ada_Main_Program, """
639                  & Name_Buffer (1 .. Name_Len) & "."
640                  & Get_Main_Unit_Name (Name_Buffer (1 .. Name_Len)) & """);");
641          end if;
642
643          WBI ("   begin");
644
645          Set_String ("      Main_Priority := ");
646          Set_Int    (Main_Priority);
647          Set_Char   (';');
648          Write_Statement_Buffer;
649
650          Set_String ("      Time_Slice_Value := ");
651
652          if Task_Dispatching_Policy_Specified = 'F'
653            and then ALIs.Table (ALIs.First).Time_Slice_Value = -1
654          then
655             Set_Int (0);
656          else
657             Set_Int (ALIs.Table (ALIs.First).Time_Slice_Value);
658          end if;
659
660          Set_Char   (';');
661          Write_Statement_Buffer;
662
663          Set_String ("      WC_Encoding := '");
664          Set_Char   (Get_WC_Encoding);
665
666          Set_String ("';");
667          Write_Statement_Buffer;
668
669          Set_String ("      Locking_Policy := '");
670          Set_Char   (Locking_Policy_Specified);
671          Set_String ("';");
672          Write_Statement_Buffer;
673
674          Set_String ("      Queuing_Policy := '");
675          Set_Char   (Queuing_Policy_Specified);
676          Set_String ("';");
677          Write_Statement_Buffer;
678
679          Set_String ("      Task_Dispatching_Policy := '");
680          Set_Char   (Task_Dispatching_Policy_Specified);
681          Set_String ("';");
682          Write_Statement_Buffer;
683
684          Gen_Restrictions_Ada;
685
686          WBI ("      Priority_Specific_Dispatching :=");
687          WBI ("        Local_Priority_Specific_Dispatching'Address;");
688
689          Set_String ("      Num_Specific_Dispatching := ");
690          Set_Int (PSD_Pragma_Settings.Last + 1);
691          Set_Char (';');
692          Write_Statement_Buffer;
693
694          WBI ("      Interrupt_States := Local_Interrupt_States'Address;");
695
696          Set_String ("      Num_Interrupt_States := ");
697          Set_Int (IS_Pragma_Settings.Last + 1);
698          Set_Char (';');
699          Write_Statement_Buffer;
700
701          Set_String ("      Unreserve_All_Interrupts := ");
702
703          if Unreserve_All_Interrupts_Specified then
704             Set_String ("1");
705          else
706             Set_String ("0");
707          end if;
708
709          Set_Char (';');
710          Write_Statement_Buffer;
711
712          if Exception_Tracebacks then
713             WBI ("      Exception_Tracebacks := 1;");
714          end if;
715
716          Set_String ("      Zero_Cost_Exceptions := ");
717
718          if Zero_Cost_Exceptions_Specified then
719             Set_String ("1");
720          else
721             Set_String ("0");
722          end if;
723
724          Set_String (";");
725          Write_Statement_Buffer;
726
727          Set_String ("      Detect_Blocking := ");
728
729          if Detect_Blocking then
730             Set_Int (1);
731          else
732             Set_Int (0);
733          end if;
734
735          Set_String (";");
736          Write_Statement_Buffer;
737
738          Set_String ("      Default_Stack_Size := ");
739          Set_Int (Default_Stack_Size);
740          Set_String (";");
741          Write_Statement_Buffer;
742
743          Set_String ("      Leap_Seconds_Support := ");
744
745          if Leap_Seconds_Support then
746             Set_Int (1);
747          else
748             Set_Int (0);
749          end if;
750
751          Set_String (";");
752          Write_Statement_Buffer;
753
754          --  Generate call to Install_Handler
755
756          WBI ("");
757          WBI ("      if Handler_Installed = 0 then");
758          WBI ("         Install_Handler;");
759          WBI ("      end if;");
760       end if;
761
762       --  Generate call to set Initialize_Scalar values if active
763
764       if Initialize_Scalars_Used then
765          WBI ("");
766          Set_String ("      System.Scalar_Values.Initialize ('");
767          Set_Char (Initialize_Scalars_Mode1);
768          Set_String ("', '");
769          Set_Char (Initialize_Scalars_Mode2);
770          Set_String ("');");
771          Write_Statement_Buffer;
772       end if;
773
774       --  Generate assignment of default secondary stack size if set
775
776       if Sec_Stack_Used and then Default_Sec_Stack_Size /= -1 then
777          WBI ("");
778          Set_String ("      System.Secondary_Stack.");
779          Set_String ("Default_Secondary_Stack_Size := ");
780          Set_Int (Opt.Default_Sec_Stack_Size);
781          Set_Char (';');
782          Write_Statement_Buffer;
783       end if;
784
785       --  Initialize stack limit variable of the environment task if the
786       --  stack check method is stack limit and stack check is enabled.
787
788       if Stack_Check_Limits_On_Target
789         and then (Stack_Check_Default_On_Target or Stack_Check_Switch_Set)
790       then
791          WBI ("");
792          WBI ("      Initialize_Stack_Limit;");
793       end if;
794
795       --  Generate elaboration calls
796
797       WBI ("");
798       Gen_Elab_Calls_Ada;
799
800       if VM_Target = CLI_Target
801         and then Bind_Main_Program
802         and then not No_Main_Subprogram
803       then
804          if ALIs.Table (ALIs.First).Main_Program = Func then
805             WBI ("      Result := Ada_Main_Program;");
806          else
807             WBI ("      Ada_Main_Program;");
808          end if;
809       end if;
810
811       WBI ("   end " & Ada_Init_Name.all & ";");
812    end Gen_Adainit_Ada;
813
814    -------------------
815    -- Gen_Adainit_C --
816    --------------------
817
818    procedure Gen_Adainit_C is
819       Main_Priority : Int renames ALIs.Table (ALIs.First).Main_Priority;
820
821    begin
822       WBI ("void " & Ada_Init_Name.all & " (void)");
823       WBI ("{");
824
825       --  Generate externals for elaboration entities
826
827       for E in Elab_Order.First .. Elab_Order.Last loop
828          declare
829             Unum : constant Unit_Id := Elab_Order.Table (E);
830             U    : Unit_Record renames Units.Table (Unum);
831
832          begin
833             --  Check for Elab entity to be set for this unit
834
835             if U.Set_Elab_Entity
836
837             --  Don't generate reference for stand alone library
838
839               and then not U.SAL_Interface
840
841             --  Don't generate reference for predefined file in No_Run_Time
842             --  mode, since we don't include the object files in this case
843
844               and then not
845                 (No_Run_Time_Mode
846                    and then Is_Predefined_File_Name (U.Sfile))
847             then
848                Set_String ("   extern char ");
849                Get_Name_String (U.Uname);
850                Set_Unit_Name;
851                Set_String ("_E;");
852                Write_Statement_Buffer;
853             end if;
854          end;
855       end loop;
856
857       Write_Statement_Buffer;
858
859       --  Standard library suppressed
860
861       if Suppress_Standard_Library_On_Target then
862
863          --  Case of High_Integrity_Mode mode. Set __gl_main_priority if needed
864          --  for the Ravenscar profile.
865
866          if Main_Priority /= No_Main_Priority then
867             WBI ("   extern int __gl_main_priority;");
868             Set_String ("   __gl_main_priority = ");
869             Set_Int    (Main_Priority);
870             Set_Char   (';');
871             Write_Statement_Buffer;
872          end if;
873
874       --  Normal case (standard library not suppressed)
875
876       else
877          --  Generate definition for interrupt states string
878
879          Set_String ("   static const char *local_interrupt_states = """);
880
881          for J in 0 .. IS_Pragma_Settings.Last loop
882             Set_Char (IS_Pragma_Settings.Table (J));
883          end loop;
884
885          Set_String (""";");
886          Write_Statement_Buffer;
887
888          --  Generate definition for priority specific dispatching string
889
890          Set_String
891            ("   static const char *local_priority_specific_dispatching = """);
892
893          for J in 0 .. PSD_Pragma_Settings.Last loop
894             Set_Char (PSD_Pragma_Settings.Table (J));
895          end loop;
896
897          Set_String (""";");
898          Write_Statement_Buffer;
899
900          --  Generate declaration for secondary stack default if needed
901
902          if Sec_Stack_Used and then Default_Sec_Stack_Size /= -1 then
903             WBI ("   extern int system__secondary_stack__" &
904                  "default_secondary_stack_size;");
905          end if;
906
907          WBI ("");
908
909          --  Code for normal case (standard library not suppressed)
910
911          --  We call the routine from inside adainit() because this works for
912          --  both programs with and without binder generated "main" functions.
913
914          WBI ("   extern int __gl_main_priority;");
915          Set_String ("   __gl_main_priority = ");
916          Set_Int (Main_Priority);
917          Set_Char (';');
918          Write_Statement_Buffer;
919
920          WBI ("   extern int __gl_time_slice_val;");
921          Set_String ("   __gl_time_slice_val = ");
922
923          if Task_Dispatching_Policy = 'F'
924            and then ALIs.Table (ALIs.First).Time_Slice_Value = -1
925          then
926             Set_Int (0);
927          else
928             Set_Int (ALIs.Table (ALIs.First).Time_Slice_Value);
929          end if;
930
931          Set_Char   (';');
932          Write_Statement_Buffer;
933
934          WBI ("   extern char __gl_wc_encoding;");
935          Set_String ("   __gl_wc_encoding = '");
936          Set_Char (Get_WC_Encoding);
937
938          Set_String ("';");
939          Write_Statement_Buffer;
940
941          WBI ("   extern char __gl_locking_policy;");
942          Set_String ("   __gl_locking_policy = '");
943          Set_Char (Locking_Policy_Specified);
944          Set_String ("';");
945          Write_Statement_Buffer;
946
947          WBI ("   extern char __gl_queuing_policy;");
948          Set_String ("   __gl_queuing_policy = '");
949          Set_Char (Queuing_Policy_Specified);
950          Set_String ("';");
951          Write_Statement_Buffer;
952
953          WBI ("   extern char __gl_task_dispatching_policy;");
954          Set_String ("   __gl_task_dispatching_policy = '");
955          Set_Char (Task_Dispatching_Policy_Specified);
956          Set_String ("';");
957          Write_Statement_Buffer;
958
959          Gen_Restrictions_C;
960
961          WBI ("   extern const void *__gl_interrupt_states;");
962          WBI ("   __gl_interrupt_states = local_interrupt_states;");
963
964          WBI ("   extern int __gl_num_interrupt_states;");
965          Set_String ("   __gl_num_interrupt_states = ");
966          Set_Int (IS_Pragma_Settings.Last + 1);
967          Set_String (";");
968          Write_Statement_Buffer;
969
970          WBI ("   extern const void *__gl_priority_specific_dispatching;");
971          WBI ("   __gl_priority_specific_dispatching =" &
972               " local_priority_specific_dispatching;");
973
974          WBI ("   extern int __gl_num_specific_dispatching;");
975          Set_String ("   __gl_num_specific_dispatching = ");
976          Set_Int (PSD_Pragma_Settings.Last + 1);
977          Set_String (";");
978          Write_Statement_Buffer;
979
980          WBI ("   extern int __gl_unreserve_all_interrupts;");
981          Set_String ("   __gl_unreserve_all_interrupts = ");
982          Set_Int    (Boolean'Pos (Unreserve_All_Interrupts_Specified));
983          Set_String (";");
984          Write_Statement_Buffer;
985
986          if Exception_Tracebacks then
987             WBI ("   extern int __gl_exception_tracebacks;");
988             WBI ("   __gl_exception_tracebacks = 1;");
989          end if;
990
991          WBI ("   extern int __gl_zero_cost_exceptions;");
992          Set_String ("   __gl_zero_cost_exceptions = ");
993          Set_Int    (Boolean'Pos (Zero_Cost_Exceptions_Specified));
994          Set_String (";");
995          Write_Statement_Buffer;
996
997          WBI ("   extern int __gl_detect_blocking;");
998          Set_String ("   __gl_detect_blocking = ");
999
1000          if Detect_Blocking then
1001             Set_Int (1);
1002          else
1003             Set_Int (0);
1004          end if;
1005
1006          Set_String (";");
1007          Write_Statement_Buffer;
1008
1009          WBI ("   extern int __gl_default_stack_size;");
1010          Set_String ("   __gl_default_stack_size = ");
1011          Set_Int    (Default_Stack_Size);
1012          Set_String (";");
1013          Write_Statement_Buffer;
1014
1015          WBI ("   extern int __gl_leap_seconds_support;");
1016          Set_String ("   __gl_leap_seconds_support = ");
1017
1018          if Leap_Seconds_Support then
1019             Set_Int (1);
1020          else
1021             Set_Int (0);
1022          end if;
1023
1024          Set_String (";");
1025          Write_Statement_Buffer;
1026
1027          WBI ("");
1028
1029          --  Install elaboration time signal handler
1030
1031          WBI ("   if (__gnat_handler_installed == 0)");
1032          WBI ("     {");
1033          WBI ("        __gnat_install_handler ();");
1034          WBI ("     }");
1035       end if;
1036
1037       --  Initialize stack limit for the environment task if the stack
1038       --  check method is stack limit and stack check is enabled.
1039
1040       if Stack_Check_Limits_On_Target
1041         and then (Stack_Check_Default_On_Target or Stack_Check_Switch_Set)
1042       then
1043          WBI ("");
1044          WBI ("   __gnat_initialize_stack_limit ();");
1045       end if;
1046
1047       --  Generate call to set Initialize_Scalar values if needed
1048
1049       if Initialize_Scalars_Used then
1050          WBI ("");
1051          Set_String ("      system__scalar_values__initialize('");
1052          Set_Char (Initialize_Scalars_Mode1);
1053          Set_String ("', '");
1054          Set_Char (Initialize_Scalars_Mode2);
1055          Set_String ("');");
1056          Write_Statement_Buffer;
1057       end if;
1058
1059       --  Generate assignment of default secondary stack size if set
1060
1061       if Sec_Stack_Used and then Default_Sec_Stack_Size /= -1 then
1062          WBI ("");
1063          Set_String ("   system__secondary_stack__");
1064          Set_String ("default_secondary_stack_size = ");
1065          Set_Int (Opt.Default_Sec_Stack_Size);
1066          Set_Char (';');
1067          Write_Statement_Buffer;
1068       end if;
1069
1070       --  Generate elaboration calls
1071
1072       WBI ("");
1073       Gen_Elab_Calls_C;
1074       WBI ("}");
1075    end Gen_Adainit_C;
1076
1077    ------------------------
1078    -- Gen_Elab_Calls_Ada --
1079    ------------------------
1080
1081    procedure Gen_Elab_Calls_Ada is
1082    begin
1083       for E in Elab_Order.First .. Elab_Order.Last loop
1084          declare
1085             Unum : constant Unit_Id := Elab_Order.Table (E);
1086             U    : Unit_Record renames Units.Table (Unum);
1087
1088             Unum_Spec : Unit_Id;
1089             --  This is the unit number of the spec that corresponds to
1090             --  this entry. It is the same as Unum except when the body
1091             --  and spec are different and we are currently processing
1092             --  the body, in which case it is the spec (Unum + 1).
1093
1094          begin
1095             if U.Utype = Is_Body then
1096                Unum_Spec := Unum + 1;
1097             else
1098                Unum_Spec := Unum;
1099             end if;
1100
1101             --  Nothing to do if predefined unit in no run time mode
1102
1103             if No_Run_Time_Mode and then Is_Predefined_File_Name (U.Sfile) then
1104                null;
1105
1106             --  Case of no elaboration code
1107
1108             elsif U.No_Elab then
1109
1110                --  The only case in which we have to do something is if
1111                --  this is a body, with a separate spec, where the separate
1112                --  spec has an elaboration entity defined.
1113
1114                --  In that case, this is where we set the elaboration entity
1115                --  to True, we do not need to test if this has already been
1116                --  done, since it is quicker to set the flag than to test it.
1117
1118                if not U.SAL_Interface and then U.Utype = Is_Body
1119                  and then Units.Table (Unum_Spec).Set_Elab_Entity
1120                then
1121                   Set_String ("      E");
1122                   Set_Unit_Number (Unum_Spec);
1123                   Set_String (" := True;");
1124                   Write_Statement_Buffer;
1125                end if;
1126
1127             --  Here if elaboration code is present. If binding a library
1128             --  or if there is a non-Ada main subprogram then we generate:
1129
1130             --    if not uname_E then
1131             --       uname'elab_[spec|body];
1132             --       uname_E := True;
1133             --    end if;
1134
1135             --  Otherwise, elaboration routines are called unconditionally:
1136
1137             --    uname'elab_[spec|body];
1138             --    uname_E := True;
1139
1140             --  The uname_E assignment is skipped if this is a separate spec,
1141             --  since the assignment will be done when we process the body.
1142
1143             elsif not U.SAL_Interface then
1144                if Force_Checking_Of_Elaboration_Flags or
1145                   Interface_Library_Unit or
1146                   (not Bind_Main_Program)
1147                then
1148                   Set_String ("      if not E");
1149                   Set_Unit_Number (Unum_Spec);
1150                   Set_String (" then");
1151                   Write_Statement_Buffer;
1152                   Set_String ("   ");
1153                end if;
1154
1155                Set_String ("      ");
1156                Get_Decoded_Name_String_With_Brackets (U.Uname);
1157
1158                if VM_Target = CLI_Target and then U.Unit_Kind /= 's' then
1159                   if Name_Buffer (Name_Len) = 's' then
1160                      Name_Buffer (Name_Len - 1 .. Name_Len + 12) :=
1161                        "_pkg'elab_spec";
1162                   else
1163                      Name_Buffer (Name_Len - 1 .. Name_Len + 12) :=
1164                        "_pkg'elab_body";
1165                   end if;
1166
1167                   Name_Len := Name_Len + 12;
1168
1169                else
1170                   if Name_Buffer (Name_Len) = 's' then
1171                      Name_Buffer (Name_Len - 1 .. Name_Len + 8) :=
1172                        "'elab_spec";
1173                   else
1174                      Name_Buffer (Name_Len - 1 .. Name_Len + 8) :=
1175                        "'elab_body";
1176                   end if;
1177
1178                   Name_Len := Name_Len + 8;
1179                end if;
1180
1181                Set_Casing (U.Icasing);
1182                Set_Name_Buffer;
1183                Set_Char (';');
1184                Write_Statement_Buffer;
1185
1186                if U.Utype /= Is_Spec then
1187                   if Force_Checking_Of_Elaboration_Flags or
1188                      Interface_Library_Unit or
1189                      (not Bind_Main_Program)
1190                   then
1191                      Set_String ("   ");
1192                   end if;
1193
1194                   Set_String ("      E");
1195                   Set_Unit_Number (Unum_Spec);
1196                   Set_String (" := True;");
1197                   Write_Statement_Buffer;
1198                end if;
1199
1200                if Force_Checking_Of_Elaboration_Flags or
1201                   Interface_Library_Unit or
1202                   (not Bind_Main_Program)
1203                then
1204                   WBI ("      end if;");
1205                end if;
1206             end if;
1207          end;
1208       end loop;
1209    end Gen_Elab_Calls_Ada;
1210
1211    ----------------------
1212    -- Gen_Elab_Calls_C --
1213    ----------------------
1214
1215    procedure Gen_Elab_Calls_C is
1216    begin
1217       for E in Elab_Order.First .. Elab_Order.Last loop
1218          declare
1219             Unum : constant Unit_Id := Elab_Order.Table (E);
1220             U    : Unit_Record renames Units.Table (Unum);
1221
1222             Unum_Spec : Unit_Id;
1223             --  This is the unit number of the spec that corresponds to
1224             --  this entry. It is the same as Unum except when the body
1225             --  and spec are different and we are currently processing
1226             --  the body, in which case it is the spec (Unum + 1).
1227
1228          begin
1229             if U.Utype = Is_Body then
1230                Unum_Spec := Unum + 1;
1231             else
1232                Unum_Spec := Unum;
1233             end if;
1234
1235             --  Nothing to do if predefined unit in no run time mode
1236
1237             if No_Run_Time_Mode and then Is_Predefined_File_Name (U.Sfile) then
1238                null;
1239
1240             --  Case of no elaboration code
1241
1242             elsif U.No_Elab then
1243
1244                --  The only case in which we have to do something is if
1245                --  this is a body, with a separate spec, where the separate
1246                --  spec has an elaboration entity defined.
1247
1248                --  In that case, this is where we set the elaboration entity
1249                --  to True, we do not need to test if this has already been
1250                --  done, since it is quicker to set the flag than to test it.
1251
1252                if not U.SAL_Interface and then U.Utype = Is_Body
1253                  and then Units.Table (Unum_Spec).Set_Elab_Entity
1254                then
1255                   Set_String ("   ");
1256                   Get_Name_String (U.Uname);
1257                   Set_Unit_Name;
1258                   Set_String ("_E = 1;");
1259                   Write_Statement_Buffer;
1260                end if;
1261
1262             --  Here if elaboration code is present. If binding a library
1263             --  or if there is a non-Ada main subprogram then we generate:
1264
1265             --    if (uname_E == 0) {
1266             --       uname__elab[s|b] ();
1267             --       uname_E++;
1268             --    }
1269
1270             --  The uname_E assignment is skipped if this is a separate spec,
1271             --  since the assignment will be done when we process the body.
1272
1273             elsif not U.SAL_Interface then
1274                Get_Name_String (U.Uname);
1275
1276                if Force_Checking_Of_Elaboration_Flags or
1277                   Interface_Library_Unit or
1278                   (not Bind_Main_Program)
1279                then
1280                   Set_String ("   if (");
1281                   Set_Unit_Name;
1282                   Set_String ("_E == 0) {");
1283                   Write_Statement_Buffer;
1284                   Set_String ("   ");
1285                end if;
1286
1287                Set_String ("   ");
1288                Set_Unit_Name;
1289                Set_String ("___elab");
1290                Set_Char (Name_Buffer (Name_Len)); -- 's' or 'b' for spec/body
1291                Set_String (" ();");
1292                Write_Statement_Buffer;
1293
1294                if U.Utype /= Is_Spec then
1295                   if Force_Checking_Of_Elaboration_Flags or
1296                      Interface_Library_Unit or
1297                      (not Bind_Main_Program)
1298                   then
1299                      Set_String ("   ");
1300                   end if;
1301
1302                   Set_String ("   ");
1303                   Set_Unit_Name;
1304                   Set_String ("_E++;");
1305                   Write_Statement_Buffer;
1306                end if;
1307
1308                if Force_Checking_Of_Elaboration_Flags or
1309                   Interface_Library_Unit or
1310                   (not Bind_Main_Program)
1311                then
1312                   WBI ("   }");
1313                end if;
1314             end if;
1315          end;
1316       end loop;
1317
1318    end Gen_Elab_Calls_C;
1319
1320    ----------------------
1321    -- Gen_Elab_Defs_C --
1322    ----------------------
1323
1324    procedure Gen_Elab_Defs_C is
1325    begin
1326       for E in Elab_Order.First .. Elab_Order.Last loop
1327
1328          --  Generate declaration of elaboration procedure if elaboration
1329          --  needed. Note that passive units are always excluded.
1330
1331          if not Units.Table (Elab_Order.Table (E)).No_Elab then
1332             Get_Name_String (Units.Table (Elab_Order.Table (E)).Uname);
1333             Set_String ("extern void ");
1334             Set_Unit_Name;
1335             Set_String ("___elab");
1336             Set_Char (Name_Buffer (Name_Len)); -- 's' or 'b' for spec/body
1337             Set_String (" (void);");
1338             Write_Statement_Buffer;
1339          end if;
1340
1341       end loop;
1342
1343       WBI ("");
1344    end Gen_Elab_Defs_C;
1345
1346    ------------------------
1347    -- Gen_Elab_Order_Ada --
1348    ------------------------
1349
1350    procedure Gen_Elab_Order_Ada is
1351    begin
1352       WBI ("");
1353       WBI ("   --  BEGIN ELABORATION ORDER");
1354
1355       for J in Elab_Order.First .. Elab_Order.Last loop
1356          Set_String ("   --  ");
1357          Get_Name_String (Units.Table (Elab_Order.Table (J)).Uname);
1358          Set_Name_Buffer;
1359          Write_Statement_Buffer;
1360       end loop;
1361
1362       WBI ("   --  END ELABORATION ORDER");
1363    end Gen_Elab_Order_Ada;
1364
1365    ----------------------
1366    -- Gen_Elab_Order_C --
1367    ----------------------
1368
1369    procedure Gen_Elab_Order_C is
1370    begin
1371       WBI ("");
1372       WBI ("/* BEGIN ELABORATION ORDER");
1373
1374       for J in Elab_Order.First .. Elab_Order.Last loop
1375          Get_Name_String (Units.Table (Elab_Order.Table (J)).Uname);
1376          Set_Name_Buffer;
1377          Write_Statement_Buffer;
1378       end loop;
1379
1380       WBI ("   END ELABORATION ORDER */");
1381    end Gen_Elab_Order_C;
1382
1383    ------------------
1384    -- Gen_Main_Ada --
1385    ------------------
1386
1387    procedure Gen_Main_Ada is
1388    begin
1389       WBI ("");
1390
1391       if Exit_Status_Supported_On_Target then
1392          Set_String ("   function ");
1393       else
1394          Set_String ("   procedure ");
1395       end if;
1396
1397       Set_String (Get_Main_Name);
1398
1399       if Command_Line_Args_On_Target then
1400          Write_Statement_Buffer;
1401          WBI ("     (argc : Integer;");
1402          WBI ("      argv : System.Address;");
1403          WBI ("      envp : System.Address)");
1404
1405          if Exit_Status_Supported_On_Target then
1406             WBI ("      return Integer");
1407          end if;
1408
1409          WBI ("   is");
1410
1411       else
1412          if Exit_Status_Supported_On_Target then
1413             Set_String (" return Integer is");
1414          else
1415             Set_String (" is");
1416          end if;
1417
1418          Write_Statement_Buffer;
1419       end if;
1420
1421       if Opt.Default_Exit_Status /= 0
1422         and then Bind_Main_Program
1423         and then not Configurable_Run_Time_Mode
1424       then
1425          WBI ("      procedure Set_Exit_Status (Status : Integer);");
1426          WBI ("      pragma Import (C, Set_Exit_Status, " &
1427                      """__gnat_set_exit_status"");");
1428          WBI ("");
1429       end if;
1430
1431       --  Initialize and Finalize
1432
1433       if not Cumulative_Restrictions.Set (No_Finalization) then
1434          WBI ("      procedure initialize (Addr : System.Address);");
1435          WBI ("      pragma Import (C, initialize, ""__gnat_initialize"");");
1436          WBI ("");
1437          WBI ("      procedure finalize;");
1438          WBI ("      pragma Import (C, finalize, ""__gnat_finalize"");");
1439       end if;
1440
1441       --  If we want to analyze the stack, we have to import corresponding
1442       --  symbols
1443
1444       if Dynamic_Stack_Measurement then
1445          WBI ("");
1446          WBI ("      procedure Output_Results;");
1447          WBI ("      pragma Import (C, Output_Results, " &
1448               """__gnat_stack_usage_output_results"");");
1449
1450          WBI ("");
1451          WBI ("      " &
1452               "procedure Initialize_Stack_Analysis (Buffer_Size : Natural);");
1453          WBI ("      pragma Import (C, Initialize_Stack_Analysis, " &
1454               """__gnat_stack_usage_initialize"");");
1455       end if;
1456
1457       --  Deal with declarations for main program case
1458
1459       if not No_Main_Subprogram then
1460
1461          --  To call the main program, we declare it using a pragma Import
1462          --  Ada with the right link name.
1463
1464          --  It might seem more obvious to "with" the main program, and call
1465          --  it in the normal Ada manner. We do not do this for three reasons:
1466
1467          --    1. It is more efficient not to recompile the main program
1468          --    2. We are not entitled to assume the source is accessible
1469          --    3. We don't know what options to use to compile it
1470
1471          --  It is really reason 3 that is most critical (indeed we used
1472          --  to generate the "with", but several regression tests failed).
1473
1474          WBI ("");
1475
1476          if ALIs.Table (ALIs.First).Main_Program = Func then
1477             WBI ("      Result : Integer;");
1478             WBI ("");
1479             WBI ("      function Ada_Main_Program return Integer;");
1480
1481          else
1482             WBI ("      procedure Ada_Main_Program;");
1483          end if;
1484
1485          Set_String ("      pragma Import (Ada, Ada_Main_Program, """);
1486          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
1487          Set_Main_Program_Name;
1488          Set_String (""");");
1489
1490          Write_Statement_Buffer;
1491          WBI ("");
1492
1493          if Bind_Main_Program
1494            and then not Suppress_Standard_Library_On_Target
1495          then
1496             WBI ("      SEH : aliased array (1 .. 2) of Integer;");
1497             WBI ("");
1498          end if;
1499       end if;
1500
1501       --  Generate a reference to Ada_Main_Program_Name. This symbol is
1502       --  not referenced elsewhere in the generated program, but is needed
1503       --  by the debugger (that's why it is generated in the first place).
1504       --  The reference stops Ada_Main_Program_Name from being optimized
1505       --  away by smart linkers, such as the AiX linker.
1506
1507       --  Because this variable is unused, we make this variable "aliased"
1508       --  with a pragma Volatile in order to tell the compiler to preserve
1509       --  this variable at any level of optimization.
1510
1511       if Bind_Main_Program then
1512          WBI
1513            ("      Ensure_Reference : aliased System.Address := " &
1514             "Ada_Main_Program_Name'Address;");
1515          WBI ("      pragma Volatile (Ensure_Reference);");
1516          WBI ("");
1517       end if;
1518
1519       WBI ("   begin");
1520
1521       --  Acquire command line arguments if present on target
1522
1523       if Command_Line_Args_On_Target then
1524          WBI ("      gnat_argc := argc;");
1525          WBI ("      gnat_argv := argv;");
1526          WBI ("      gnat_envp := envp;");
1527          WBI ("");
1528
1529       --  If configurable run time and no command line args, then nothing
1530       --  needs to be done since the gnat_argc/argv/envp variables are
1531       --  suppressed in this case.
1532
1533       elsif Configurable_Run_Time_On_Target then
1534          null;
1535
1536       --  Otherwise set dummy values (to be filled in by some other unit?)
1537
1538       else
1539          WBI ("      gnat_argc := 0;");
1540          WBI ("      gnat_argv := System.Null_Address;");
1541          WBI ("      gnat_envp := System.Null_Address;");
1542       end if;
1543
1544       if Opt.Default_Exit_Status /= 0
1545         and then Bind_Main_Program
1546         and then not Configurable_Run_Time_Mode
1547       then
1548          Set_String ("      Set_Exit_Status (");
1549          Set_Int (Opt.Default_Exit_Status);
1550          Set_String (");");
1551          Write_Statement_Buffer;
1552       end if;
1553
1554       if Dynamic_Stack_Measurement then
1555          Set_String ("      Initialize_Stack_Analysis (");
1556          Set_Int (Dynamic_Stack_Measurement_Array_Size);
1557          Set_String (");");
1558          Write_Statement_Buffer;
1559       end if;
1560
1561       if not Cumulative_Restrictions.Set (No_Finalization) then
1562          if not No_Main_Subprogram
1563            and then Bind_Main_Program
1564            and then not Suppress_Standard_Library_On_Target
1565          then
1566             WBI ("      Initialize (SEH'Address);");
1567          else
1568             WBI ("      Initialize (System.Null_Address);");
1569          end if;
1570       end if;
1571
1572       WBI ("      " & Ada_Init_Name.all & ";");
1573
1574       if not No_Main_Subprogram then
1575          WBI ("      Break_Start;");
1576
1577          if ALIs.Table (ALIs.First).Main_Program = Proc then
1578             WBI ("      Ada_Main_Program;");
1579          else
1580             WBI ("      Result := Ada_Main_Program;");
1581          end if;
1582       end if;
1583
1584       --  Adafinal call is skipped if no finalization
1585
1586       if not Cumulative_Restrictions.Set (No_Finalization) then
1587
1588          --  If compiling for the JVM, we directly call Adafinal because
1589          --  we don't import it via Do_Finalize (see Gen_Output_File_Ada).
1590
1591          if VM_Target = No_VM then
1592             WBI ("      Do_Finalize;");
1593          else
1594             WBI ("      System.Standard_Library.Adafinal;");
1595          end if;
1596       end if;
1597
1598       --  Prints the result of static stack analysis
1599
1600       if Dynamic_Stack_Measurement then
1601          WBI ("      Output_Results;");
1602       end if;
1603
1604       --  Finalize is only called if we have a run time
1605
1606       if not Cumulative_Restrictions.Set (No_Finalization) then
1607          WBI ("      Finalize;");
1608       end if;
1609
1610       --  Return result
1611
1612       if Exit_Status_Supported_On_Target then
1613          if No_Main_Subprogram
1614            or else ALIs.Table (ALIs.First).Main_Program = Proc
1615          then
1616             WBI ("      return (gnat_exit_status);");
1617          else
1618             WBI ("      return (Result);");
1619          end if;
1620       end if;
1621
1622       WBI ("   end;");
1623    end Gen_Main_Ada;
1624
1625    ----------------
1626    -- Gen_Main_C --
1627    ----------------
1628
1629    procedure Gen_Main_C is
1630    begin
1631       if Exit_Status_Supported_On_Target then
1632          WBI ("#include <stdlib.h>");
1633          Set_String ("int ");
1634       else
1635          Set_String ("void ");
1636       end if;
1637
1638       Set_String (Get_Main_Name);
1639
1640       --  Generate command line args in prototype if present on target
1641
1642       if Command_Line_Args_On_Target then
1643          Write_Statement_Buffer (" (int argc, char **argv, char **envp)");
1644
1645       --  Case of no command line arguments on target
1646
1647       else
1648          Write_Statement_Buffer (" (void)");
1649       end if;
1650
1651       WBI ("{");
1652
1653       --  Generate a reference to __gnat_ada_main_program_name. This symbol
1654       --  is  not referenced elsewhere in the generated program, but is
1655       --  needed by the debugger (that's why it is generated in the first
1656       --  place). The reference stops Ada_Main_Program_Name from being
1657       --  optimized away by smart linkers, such as the AiX linker.
1658
1659       --  Because this variable is unused, we declare this variable as
1660       --  volatile in order to tell the compiler to preserve it at any
1661       --  level of optimization.
1662
1663       if Bind_Main_Program then
1664          WBI ("   char * volatile ensure_reference " &
1665               "__attribute__ ((__unused__)) = " &
1666               "__gnat_ada_main_program_name;");
1667          WBI ("");
1668
1669          if not Suppress_Standard_Library_On_Target
1670            and then not No_Main_Subprogram
1671          then
1672             WBI ("   int SEH [2];");
1673             WBI ("");
1674          end if;
1675       end if;
1676
1677       --  If main program is a function, generate result variable
1678
1679       if ALIs.Table (ALIs.First).Main_Program = Func then
1680          WBI ("   int result;");
1681       end if;
1682
1683       --  Set command line argument values from parameters if command line
1684       --  arguments are present on target
1685
1686       if Command_Line_Args_On_Target then
1687          WBI ("   gnat_argc = argc;");
1688          WBI ("   gnat_argv = argv;");
1689          WBI ("   gnat_envp = envp;");
1690          WBI (" ");
1691
1692       --  If configurable run-time, then nothing to do, since in this case
1693       --  the gnat_argc/argv/envp variables are entirely suppressed.
1694
1695       elsif Configurable_Run_Time_On_Target then
1696          null;
1697
1698       --  if no command line arguments on target, set dummy values
1699
1700       else
1701          WBI ("   gnat_argc = 0;");
1702          WBI ("   gnat_argv = 0;");
1703          WBI ("   gnat_envp = 0;");
1704       end if;
1705
1706       if Opt.Default_Exit_Status /= 0
1707         and then Bind_Main_Program
1708         and then not Configurable_Run_Time_Mode
1709       then
1710          Set_String ("   __gnat_set_exit_status (");
1711          Set_Int (Opt.Default_Exit_Status);
1712          Set_String (");");
1713          Write_Statement_Buffer;
1714       end if;
1715
1716       --  Initializes dynamic stack measurement if needed
1717
1718       if Dynamic_Stack_Measurement then
1719          Set_String ("   __gnat_stack_usage_initialize (");
1720          Set_Int (Dynamic_Stack_Measurement_Array_Size);
1721          Set_String (");");
1722          Write_Statement_Buffer;
1723       end if;
1724
1725       --  The __gnat_initialize routine is used only if we have a run-time
1726
1727       if not Suppress_Standard_Library_On_Target then
1728          if not No_Main_Subprogram and then Bind_Main_Program then
1729             WBI ("   __gnat_initialize ((void *)SEH);");
1730          else
1731             WBI ("   __gnat_initialize ((void *)0);");
1732          end if;
1733       end if;
1734
1735       WBI ("   " & Ada_Init_Name.all & " ();");
1736
1737       if not No_Main_Subprogram then
1738          WBI ("   __gnat_break_start ();");
1739          WBI (" ");
1740
1741          --  Output main program name
1742
1743          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
1744
1745          --  Main program is procedure case
1746
1747          if ALIs.Table (ALIs.First).Main_Program = Proc then
1748             Set_String ("   ");
1749             Set_Main_Program_Name;
1750             Set_String (" ();");
1751             Write_Statement_Buffer;
1752
1753          --  Main program is function case
1754
1755          else -- ALIs.Table (ALIs_First).Main_Program = Func
1756             Set_String ("   result = ");
1757             Set_Main_Program_Name;
1758             Set_String (" ();");
1759             Write_Statement_Buffer;
1760          end if;
1761
1762       end if;
1763
1764       --  Call adafinal if finalization active
1765
1766       if not Cumulative_Restrictions.Set (No_Finalization) then
1767          WBI (" ");
1768          WBI ("   system__standard_library__adafinal ();");
1769       end if;
1770
1771       --  Outputs the dynamic stack measurement if needed
1772
1773       if Dynamic_Stack_Measurement then
1774          WBI ("   __gnat_stack_usage_output_results ();");
1775       end if;
1776
1777       --  The finalize routine is used only if we have a run-time
1778
1779       if not Suppress_Standard_Library_On_Target then
1780          WBI ("   __gnat_finalize ();");
1781       end if;
1782
1783       --  Case of main program is a function, so the value it returns
1784       --  is the exit status in this case.
1785
1786       if ALIs.Table (ALIs.First).Main_Program = Func then
1787          if Exit_Status_Supported_On_Target then
1788
1789             --  VMS must use Posix exit routine in order to get the effect
1790             --  of a Unix compatible setting of the program exit status.
1791             --  For all other systems, we use the standard exit routine.
1792
1793             if OpenVMS_On_Target then
1794                WBI ("   decc$__posix_exit (result);");
1795             else
1796                WBI ("   exit (result);");
1797             end if;
1798          end if;
1799
1800       --  Case of main program is a procedure, in which case the exit
1801       --  status is whatever was set by a Set_Exit call most recently
1802
1803       else
1804          if Exit_Status_Supported_On_Target then
1805
1806             --  VMS must use Posix exit routine in order to get the effect
1807             --  of a Unix compatible setting of the program exit status.
1808             --  For all other systems, we use the standard exit routine.
1809
1810             if OpenVMS_On_Target then
1811                WBI ("   decc$__posix_exit (gnat_exit_status);");
1812             else
1813                WBI ("   exit (gnat_exit_status);");
1814             end if;
1815          end if;
1816       end if;
1817
1818       WBI ("}");
1819    end Gen_Main_C;
1820
1821    ------------------------------
1822    -- Gen_Object_Files_Options --
1823    ------------------------------
1824
1825    procedure Gen_Object_Files_Options is
1826       Lgnat : Natural;
1827       --  This keeps track of the position in the sorted set of entries
1828       --  in the Linker_Options table of where the first entry from an
1829       --  internal file appears.
1830
1831       Linker_Option_List_Started : Boolean := False;
1832       --  Set to True when "LINKER OPTION LIST" is displayed
1833
1834       procedure Write_Linker_Option;
1835       --  Write binder info linker option
1836
1837       -------------------------
1838       -- Write_Linker_Option --
1839       -------------------------
1840
1841       procedure Write_Linker_Option is
1842          Start : Natural;
1843          Stop  : Natural;
1844
1845       begin
1846          --  Loop through string, breaking at null's
1847
1848          Start := 1;
1849          while Start < Name_Len loop
1850
1851             --  Find null ending this section
1852
1853             Stop := Start + 1;
1854             while Name_Buffer (Stop) /= ASCII.NUL
1855               and then Stop <= Name_Len loop
1856                Stop := Stop + 1;
1857             end loop;
1858
1859             --  Process section if non-null
1860
1861             if Stop > Start then
1862                if Output_Linker_Option_List then
1863                   if not Zero_Formatting then
1864                      if not Linker_Option_List_Started then
1865                         Linker_Option_List_Started := True;
1866                         Write_Eol;
1867                         Write_Str ("     LINKER OPTION LIST");
1868                         Write_Eol;
1869                         Write_Eol;
1870                      end if;
1871
1872                      Write_Str ("   ");
1873                   end if;
1874
1875                   Write_Str (Name_Buffer (Start .. Stop - 1));
1876                   Write_Eol;
1877                end if;
1878                Write_Info_Ada_C
1879                  ("   --   ", "", Name_Buffer (Start .. Stop - 1));
1880             end if;
1881
1882             Start := Stop + 1;
1883          end loop;
1884       end Write_Linker_Option;
1885
1886    --  Start of processing for Gen_Object_Files_Options
1887
1888    begin
1889       WBI ("");
1890       Write_Info_Ada_C ("-- ", "/* ", " BEGIN Object file/option list");
1891
1892       for E in Elab_Order.First .. Elab_Order.Last loop
1893
1894          --  If not spec that has an associated body, then generate a
1895          --  comment giving the name of the corresponding object file.
1896
1897          if (not Units.Table (Elab_Order.Table (E)).SAL_Interface)
1898            and then Units.Table (Elab_Order.Table (E)).Utype /= Is_Spec
1899          then
1900             Get_Name_String
1901               (ALIs.Table
1902                 (Units.Table (Elab_Order.Table (E)).My_ALI).Ofile_Full_Name);
1903
1904             --  If the presence of an object file is necessary or if it
1905             --  exists, then use it.
1906
1907             if not Hostparm.Exclude_Missing_Objects
1908               or else
1909                 System.OS_Lib.Is_Regular_File (Name_Buffer (1 .. Name_Len))
1910             then
1911                Write_Info_Ada_C ("   --   ", "", Name_Buffer (1 .. Name_Len));
1912
1913                if Output_Object_List then
1914                   Write_Str (Name_Buffer (1 .. Name_Len));
1915                   Write_Eol;
1916                end if;
1917
1918                --  Don't link with the shared library on VMS if an internal
1919                --  filename object is seen. Multiply defined symbols will
1920                --  result.
1921
1922                if OpenVMS_On_Target
1923                  and then Is_Internal_File_Name
1924                   (ALIs.Table
1925                    (Units.Table (Elab_Order.Table (E)).My_ALI).Sfile)
1926                then
1927                   --  Special case for g-trasym.obj, which is not included
1928                   --  in libgnat.
1929
1930                   Get_Name_String (ALIs.Table
1931                             (Units.Table (Elab_Order.Table (E)).My_ALI).Sfile);
1932
1933                   if Name_Buffer (1 .. 8) /= "g-trasym" then
1934                      Opt.Shared_Libgnat := False;
1935                   end if;
1936                end if;
1937             end if;
1938          end if;
1939       end loop;
1940
1941       --  Add a "-Ldir" for each directory in the object path
1942
1943       for J in 1 .. Nb_Dir_In_Obj_Search_Path loop
1944          declare
1945             Dir : constant String_Ptr := Dir_In_Obj_Search_Path (J);
1946          begin
1947             Name_Len := 0;
1948             Add_Str_To_Name_Buffer ("-L");
1949             Add_Str_To_Name_Buffer (Dir.all);
1950             Write_Linker_Option;
1951          end;
1952       end loop;
1953
1954       --  Sort linker options
1955
1956       --  This sort accomplishes two important purposes:
1957
1958       --    a) All application files are sorted to the front, and all
1959       --       GNAT internal files are sorted to the end. This results
1960       --       in a well defined dividing line between the two sets of
1961       --       files, for the purpose of inserting certain standard
1962       --       library references into the linker arguments list.
1963
1964       --    b) Given two different units, we sort the linker options so
1965       --       that those from a unit earlier in the elaboration order
1966       --       comes later in the list. This is a heuristic designed
1967       --       to create a more friendly order of linker options when
1968       --       the operations appear in separate units. The idea is that
1969       --       if unit A must be elaborated before unit B, then it is
1970       --       more likely that B references libraries included by A,
1971       --       than vice versa, so we want the libraries included by
1972       --       A to come after the libraries included by B.
1973
1974       --  These two criteria are implemented by function Lt_Linker_Option.
1975       --  Note that a special case of b) is that specs are elaborated before
1976       --  bodies, so linker options from specs come after linker options
1977       --  for bodies, and again, the assumption is that libraries used by
1978       --  the body are more likely to reference libraries used by the spec,
1979       --  than vice versa.
1980
1981       Sort
1982         (Linker_Options.Last,
1983          Move_Linker_Option'Access,
1984          Lt_Linker_Option'Access);
1985
1986       --  Write user linker options, i.e. the set of linker options that
1987       --  come from all files other than GNAT internal files, Lgnat is
1988       --  left set to point to the first entry from a GNAT internal file,
1989       --  or past the end of the entriers if there are no internal files.
1990
1991       Lgnat := Linker_Options.Last + 1;
1992
1993       for J in 1 .. Linker_Options.Last loop
1994          if not Linker_Options.Table (J).Internal_File then
1995             Get_Name_String (Linker_Options.Table (J).Name);
1996             Write_Linker_Option;
1997          else
1998             Lgnat := J;
1999             exit;
2000          end if;
2001       end loop;
2002
2003       --  Now we insert standard linker options that must appear after the
2004       --  entries from user files, and before the entries from GNAT run-time
2005       --  files. The reason for this decision is that libraries referenced
2006       --  by internal routines may reference these standard library entries.
2007
2008       --  Note that we do not insert anything when pragma No_Run_Time has been
2009       --  specified or when the standard libraries are not to be used,
2010       --  otherwise on some platforms, such as VMS, we may get duplicate
2011       --  symbols when linking.
2012
2013       if not (Opt.No_Run_Time_Mode or else Opt.No_Stdlib) then
2014          Name_Len := 0;
2015
2016          if Opt.Shared_Libgnat then
2017             Add_Str_To_Name_Buffer ("-shared");
2018          else
2019             Add_Str_To_Name_Buffer ("-static");
2020          end if;
2021
2022          --  Write directly to avoid -K output (why???)
2023
2024          Write_Info_Ada_C ("   --   ", "", Name_Buffer (1 .. Name_Len));
2025
2026          if With_DECGNAT then
2027             Name_Len := 0;
2028
2029             if Opt.Shared_Libgnat then
2030                Add_Str_To_Name_Buffer (Shared_Lib ("decgnat"));
2031             else
2032                Add_Str_To_Name_Buffer ("-ldecgnat");
2033             end if;
2034
2035             Write_Linker_Option;
2036          end if;
2037
2038          if With_GNARL then
2039             Name_Len := 0;
2040
2041             if Opt.Shared_Libgnat then
2042                Add_Str_To_Name_Buffer (Shared_Lib ("gnarl"));
2043             else
2044                Add_Str_To_Name_Buffer ("-lgnarl");
2045             end if;
2046
2047             Write_Linker_Option;
2048          end if;
2049
2050          Name_Len := 0;
2051
2052          if Opt.Shared_Libgnat then
2053             Add_Str_To_Name_Buffer (Shared_Lib ("gnat"));
2054          else
2055             Add_Str_To_Name_Buffer ("-lgnat");
2056          end if;
2057
2058          Write_Linker_Option;
2059       end if;
2060
2061       --  Write linker options from all internal files
2062
2063       for J in Lgnat .. Linker_Options.Last loop
2064          Get_Name_String (Linker_Options.Table (J).Name);
2065          Write_Linker_Option;
2066       end loop;
2067
2068       if Output_Linker_Option_List and then not Zero_Formatting then
2069          Write_Eol;
2070       end if;
2071
2072       if Ada_Bind_File then
2073          WBI ("--  END Object file/option list   ");
2074       else
2075          WBI ("    END Object file/option list */");
2076       end if;
2077    end Gen_Object_Files_Options;
2078
2079    ---------------------
2080    -- Gen_Output_File --
2081    ---------------------
2082
2083    procedure Gen_Output_File (Filename : String) is
2084    begin
2085       --  Acquire settings for Interrupt_State pragmas
2086
2087       Set_IS_Pragma_Table;
2088
2089       --  Acquire settings for Priority_Specific_Dispatching pragma
2090
2091       Set_PSD_Pragma_Table;
2092
2093       --  Override Ada_Bind_File and Bind_Main_Program for VMs since
2094       --  JGNAT only supports Ada code, and the main program is already
2095       --  generated by the compiler.
2096
2097       if VM_Target /= No_VM then
2098          Ada_Bind_File := True;
2099
2100          if VM_Target = JVM_Target then
2101             Bind_Main_Program := False;
2102          end if;
2103       end if;
2104
2105       --  Override time slice value if -T switch is set
2106
2107       if Time_Slice_Set then
2108          ALIs.Table (ALIs.First).Time_Slice_Value := Opt.Time_Slice_Value;
2109       end if;
2110
2111       --  Count number of elaboration calls
2112
2113       for E in Elab_Order.First .. Elab_Order.Last loop
2114          if Units.Table (Elab_Order.Table (E)).No_Elab then
2115             null;
2116          else
2117             Num_Elab_Calls := Num_Elab_Calls + 1;
2118          end if;
2119       end loop;
2120
2121       --  Generate output file in appropriate language
2122
2123       Check_System_Restrictions_Used;
2124
2125       if Ada_Bind_File then
2126          Gen_Output_File_Ada (Filename);
2127       else
2128          Gen_Output_File_C (Filename);
2129       end if;
2130    end Gen_Output_File;
2131
2132    -------------------------
2133    -- Gen_Output_File_Ada --
2134    -------------------------
2135
2136    procedure Gen_Output_File_Ada (Filename : String) is
2137
2138       Bfiles : Name_Id;
2139       --  Name of generated bind file (spec)
2140
2141       Bfileb : Name_Id;
2142       --  Name of generated bind file (body)
2143
2144       Ada_Main : constant String := Get_Ada_Main_Name;
2145       --  Name to be used for generated Ada main program. See the body of
2146       --  function Get_Ada_Main_Name for details on the form of the name.
2147
2148    begin
2149       --  Create spec first
2150
2151       Create_Binder_Output (Filename, 's', Bfiles);
2152
2153       --  We always compile the binder file in Ada 95 mode so that we properly
2154       --  handle use of Ada 2005 keywords as identifiers in Ada 95 mode. None
2155       --  of the Ada 2005 constructs are needed by the binder file.
2156
2157       WBI ("pragma Ada_95;");
2158
2159       --  If we are operating in Restrictions (No_Exception_Handlers) mode,
2160       --  then we need to make sure that the binder program is compiled with
2161       --  the same restriction, so that no exception tables are generated.
2162
2163       if Cumulative_Restrictions.Set (No_Exception_Handlers) then
2164          WBI ("pragma Restrictions (No_Exception_Handlers);");
2165       end if;
2166
2167       --  Same processing for Restrictions (No_Exception_Propagation)
2168
2169       if Cumulative_Restrictions.Set (No_Exception_Propagation) then
2170          WBI ("pragma Restrictions (No_Exception_Propagation);");
2171       end if;
2172
2173       --  Same processing for pragma No_Run_Time
2174
2175       if No_Run_Time_Mode then
2176          WBI ("pragma No_Run_Time;");
2177       end if;
2178
2179       --  Generate with of System so we can reference System.Address
2180
2181       WBI ("with System;");
2182
2183       --  Generate with of System.Initialize_Scalars if active
2184
2185       if Initialize_Scalars_Used then
2186          WBI ("with System.Scalar_Values;");
2187       end if;
2188
2189       --  Generate with of System.Secondary_Stack if active
2190
2191       if Sec_Stack_Used and then Default_Sec_Stack_Size /= -1 then
2192          WBI ("with System.Secondary_Stack;");
2193       end if;
2194
2195       Resolve_Binder_Options;
2196
2197       if VM_Target /= No_VM then
2198          if not Suppress_Standard_Library_On_Target then
2199
2200             --  Usually, adafinal is called using a pragma Import C. Since
2201             --  Import C doesn't have the same semantics for JGNAT, we use
2202             --  standard Ada.
2203
2204             WBI ("with System.Standard_Library;");
2205          end if;
2206       end if;
2207
2208       WBI ("package " & Ada_Main & " is");
2209       WBI ("   pragma Warnings (Off);");
2210
2211       --  Main program case
2212
2213       if Bind_Main_Program then
2214          if VM_Target = No_VM then
2215
2216             --  Generate argc/argv stuff unless suppressed
2217
2218             if Command_Line_Args_On_Target
2219               or not Configurable_Run_Time_On_Target
2220             then
2221                WBI ("");
2222                WBI ("   gnat_argc : Integer;");
2223                WBI ("   gnat_argv : System.Address;");
2224                WBI ("   gnat_envp : System.Address;");
2225
2226                --  If the standard library is not suppressed, these variables
2227                --  are in the runtime data area for easy access from the
2228                --  runtime
2229
2230                if not Suppress_Standard_Library_On_Target then
2231                   WBI ("");
2232                   WBI ("   pragma Import (C, gnat_argc);");
2233                   WBI ("   pragma Import (C, gnat_argv);");
2234                   WBI ("   pragma Import (C, gnat_envp);");
2235                end if;
2236             end if;
2237
2238             --  Define exit status. Again in normal mode, this is in the
2239             --  run-time library, and is initialized there, but in the
2240             --  configurable runtime case, the variable is declared and
2241             --  initialized in this file.
2242
2243             WBI ("");
2244
2245             if Configurable_Run_Time_Mode then
2246                if Exit_Status_Supported_On_Target then
2247                   WBI ("   gnat_exit_status : Integer := 0;");
2248                end if;
2249
2250             else
2251                WBI ("   gnat_exit_status : Integer;");
2252                WBI ("   pragma Import (C, gnat_exit_status);");
2253             end if;
2254
2255             --  Generate the GNAT_Version and Ada_Main_Program_Name info only
2256             --  for the main program. Otherwise, it can lead under some
2257             --  circumstances to a symbol duplication during the link (for
2258             --  instance when a C program uses 2 Ada libraries)
2259          end if;
2260
2261          WBI ("");
2262          WBI ("   GNAT_Version : constant String :=");
2263          WBI ("                    ""GNAT Version: " &
2264                                 Gnat_Version_String & """;");
2265          WBI ("   pragma Export (C, GNAT_Version, ""__gnat_version"");");
2266
2267          WBI ("");
2268          Set_String ("   Ada_Main_Program_Name : constant String := """);
2269          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
2270
2271          if VM_Target = No_VM then
2272             Set_Main_Program_Name;
2273             Set_String (""" & Ascii.NUL;");
2274          else
2275             Set_String (Name_Buffer (1 .. Name_Len - 2) & """;");
2276          end if;
2277
2278          Write_Statement_Buffer;
2279
2280          WBI
2281            ("   pragma Export (C, Ada_Main_Program_Name, " &
2282             """__gnat_ada_main_program_name"");");
2283       end if;
2284
2285       WBI ("");
2286       WBI ("   procedure " & Ada_Final_Name.all & ";");
2287       WBI ("   pragma Export (C, " & Ada_Final_Name.all & ", """ &
2288            Ada_Final_Name.all & """);");
2289       WBI ("");
2290       WBI ("   procedure " & Ada_Init_Name.all & ";");
2291       WBI ("   pragma Export (C, " & Ada_Init_Name.all & ", """ &
2292            Ada_Init_Name.all & """);");
2293
2294       --  If -a has been specified use pragma Linker_Constructor for the init
2295       --  procedure. No need to use a similar pragma for the final procedure as
2296       --  global finalization will occur when the executable finishes execution
2297       --  and for plugins (shared stand-alone libraries that can be
2298       --  "unloaded"), finalization should not occur automatically, otherwise
2299       --  the main executable may not continue to work properly.
2300
2301       if Use_Pragma_Linker_Constructor then
2302          WBI ("   pragma Linker_Constructor (" & Ada_Init_Name.all & ");");
2303       end if;
2304
2305       if Bind_Main_Program and then VM_Target = No_VM then
2306
2307          --  If we have the standard library, then Break_Start is defined
2308          --  there, but when the standard library is suppressed, Break_Start
2309          --  is defined here.
2310
2311          WBI ("");
2312          WBI ("   procedure Break_Start;");
2313
2314          if Suppress_Standard_Library_On_Target then
2315             WBI ("   pragma Export (C, Break_Start, ""__gnat_break_start"");");
2316          else
2317             WBI ("   pragma Import (C, Break_Start, ""__gnat_break_start"");");
2318          end if;
2319
2320          WBI ("");
2321
2322          if Exit_Status_Supported_On_Target then
2323             Set_String ("   function ");
2324          else
2325             Set_String ("   procedure ");
2326          end if;
2327
2328          Set_String (Get_Main_Name);
2329
2330          --  Generate argument list if present
2331
2332          if Command_Line_Args_On_Target then
2333             Write_Statement_Buffer;
2334             WBI ("     (argc : Integer;");
2335             WBI ("      argv : System.Address;");
2336             Set_String
2337                 ("      envp : System.Address)");
2338
2339             if Exit_Status_Supported_On_Target then
2340                Write_Statement_Buffer;
2341                WBI ("      return Integer;");
2342             else
2343                Write_Statement_Buffer (";");
2344             end if;
2345
2346          else
2347             if Exit_Status_Supported_On_Target then
2348                Write_Statement_Buffer (" return Integer;");
2349             else
2350                Write_Statement_Buffer (";");
2351             end if;
2352          end if;
2353
2354          WBI ("   pragma Export (C, " & Get_Main_Name & ", """ &
2355            Get_Main_Name & """);");
2356       end if;
2357
2358       Gen_Versions_Ada;
2359       Gen_Elab_Order_Ada;
2360
2361       --  Spec is complete
2362
2363       WBI ("");
2364       WBI ("end " & Ada_Main & ";");
2365       Close_Binder_Output;
2366
2367       --  Prepare to write body
2368
2369       Create_Binder_Output (Filename, 'b', Bfileb);
2370
2371       --  We always compile the binder file in Ada 95 mode so that we properly
2372       --  handle use of Ada 2005 keywords as identifiers in Ada 95 mode. None
2373       --  of the Ada 2005 constructs are needed by the binder file.
2374
2375       WBI ("pragma Ada_95;");
2376
2377       --  Output Source_File_Name pragmas which look like
2378
2379       --    pragma Source_File_Name (Ada_Main, Spec_File_Name => "sss");
2380       --    pragma Source_File_Name (Ada_Main, Body_File_Name => "bbb");
2381
2382       --  where sss/bbb are the spec/body file names respectively
2383
2384       Get_Name_String (Bfiles);
2385       Name_Buffer (Name_Len + 1 .. Name_Len + 3) := """);";
2386
2387       WBI ("pragma Source_File_Name (" &
2388            Ada_Main &
2389            ", Spec_File_Name => """ &
2390            Name_Buffer (1 .. Name_Len + 3));
2391
2392       Get_Name_String (Bfileb);
2393       Name_Buffer (Name_Len + 1 .. Name_Len + 3) := """);";
2394
2395       WBI ("pragma Source_File_Name (" &
2396            Ada_Main &
2397            ", Body_File_Name => """ &
2398            Name_Buffer (1 .. Name_Len + 3));
2399
2400       --  Generate with of System.Restrictions to initialize
2401       --  Run_Time_Restrictions.
2402
2403       if System_Restrictions_Used
2404         and not Suppress_Standard_Library_On_Target
2405       then
2406          WBI ("");
2407          WBI ("with System.Restrictions;");
2408       end if;
2409
2410       WBI ("");
2411       WBI ("package body " & Ada_Main & " is");
2412       WBI ("   pragma Warnings (Off);");
2413
2414       --  Import the finalization procedure only if finalization active
2415
2416       if not Cumulative_Restrictions.Set (No_Finalization) then
2417
2418          --  In the Java case, pragma Import C cannot be used, so the
2419          --  standard Ada constructs will be used instead.
2420
2421          if VM_Target = No_VM then
2422             WBI ("");
2423             WBI ("   procedure Do_Finalize;");
2424             WBI
2425               ("   pragma Import (C, Do_Finalize, " &
2426                """system__standard_library__adafinal"");");
2427             WBI ("");
2428          end if;
2429       end if;
2430
2431       if not Suppress_Standard_Library_On_Target then
2432
2433          --  Generate Priority_Specific_Dispatching pragma string
2434
2435          Set_String
2436            ("   Local_Priority_Specific_Dispatching : constant String := """);
2437
2438          for J in 0 .. PSD_Pragma_Settings.Last loop
2439             Set_Char (PSD_Pragma_Settings.Table (J));
2440          end loop;
2441
2442          Set_String (""";");
2443          Write_Statement_Buffer;
2444
2445          --  Generate Interrupt_State pragma string
2446
2447          Set_String ("   Local_Interrupt_States : constant String := """);
2448
2449          for J in 0 .. IS_Pragma_Settings.Last loop
2450             Set_Char (IS_Pragma_Settings.Table (J));
2451          end loop;
2452
2453          Set_String (""";");
2454          Write_Statement_Buffer;
2455          WBI ("");
2456       end if;
2457
2458       Gen_Adainit_Ada;
2459
2460       Gen_Adafinal_Ada;
2461
2462       if Bind_Main_Program and then VM_Target = No_VM then
2463
2464          --  When suppressing the standard library then generate dummy body
2465          --  for Break_Start
2466
2467          if Suppress_Standard_Library_On_Target then
2468             WBI ("");
2469             WBI ("   procedure Break_Start is");
2470             WBI ("   begin");
2471             WBI ("      null;");
2472             WBI ("   end;");
2473          end if;
2474
2475          Gen_Main_Ada;
2476       end if;
2477
2478       --  Output object file list and the Ada body is complete
2479
2480       Gen_Object_Files_Options;
2481
2482       WBI ("");
2483       WBI ("end " & Ada_Main & ";");
2484
2485       Close_Binder_Output;
2486    end Gen_Output_File_Ada;
2487
2488    -----------------------
2489    -- Gen_Output_File_C --
2490    -----------------------
2491
2492    procedure Gen_Output_File_C (Filename : String) is
2493       Bfile : Name_Id;
2494       pragma Warnings (Off, Bfile);
2495       --  Name of generated bind file (not referenced)
2496
2497    begin
2498       Create_Binder_Output (Filename, 'c', Bfile);
2499
2500       Resolve_Binder_Options;
2501
2502       WBI ("extern void " & Ada_Final_Name.all & " (void);");
2503
2504       --  If -a has been specified use __attribute__((constructor)) for the
2505       --  init procedure. No need to use a similar featute for the final
2506       --  procedure as global finalization will occur when the executable
2507       --  finishes execution and for plugins (shared stand-alone libraries that
2508       --  can be "unloaded"), finalization should not occur automatically,
2509       --  otherwise the main executable may not continue to work properly.
2510
2511       if Use_Pragma_Linker_Constructor then
2512          WBI ("extern void " & Ada_Init_Name.all &
2513               " (void) __attribute__((constructor));");
2514       else
2515          WBI ("extern void " & Ada_Init_Name.all & " (void);");
2516       end if;
2517
2518       WBI ("extern void system__standard_library__adafinal (void);");
2519
2520       if not No_Main_Subprogram then
2521          Set_String ("extern ");
2522
2523          if Exit_Status_Supported_On_Target then
2524             Set_String ("int");
2525          else
2526             Set_String ("void");
2527          end if;
2528
2529          Set_String (" main ");
2530
2531          if Command_Line_Args_On_Target then
2532             Write_Statement_Buffer ("(int, char **, char **);");
2533          else
2534             Write_Statement_Buffer ("(void);");
2535          end if;
2536
2537          if OpenVMS_On_Target then
2538             WBI ("extern void decc$__posix_exit (int);");
2539          else
2540             WBI ("extern void exit (int);");
2541          end if;
2542
2543          WBI ("extern void __gnat_break_start (void);");
2544          Set_String ("extern ");
2545
2546          if ALIs.Table (ALIs.First).Main_Program = Proc then
2547             Set_String ("void ");
2548          else
2549             Set_String ("int ");
2550          end if;
2551
2552          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
2553          Set_Main_Program_Name;
2554          Set_String (" (void);");
2555          Write_Statement_Buffer;
2556       end if;
2557
2558       if not Suppress_Standard_Library_On_Target then
2559          WBI ("extern void __gnat_initialize (void *);");
2560          WBI ("extern void __gnat_finalize (void);");
2561          WBI ("extern void __gnat_install_handler (void);");
2562       end if;
2563
2564       if Dynamic_Stack_Measurement then
2565          WBI ("");
2566          WBI ("extern void __gnat_stack_usage_output_results (void);");
2567          WBI ("extern void __gnat_stack_usage_initialize (int size);");
2568       end if;
2569
2570       --  Initialize stack limit for the environment task if the stack
2571       --  check method is stack limit and stack check is enabled.
2572
2573       if Stack_Check_Limits_On_Target
2574         and then (Stack_Check_Default_On_Target or Stack_Check_Switch_Set)
2575       then
2576          WBI ("");
2577          WBI ("extern void __gnat_initialize_stack_limit (void);");
2578       end if;
2579
2580       WBI ("");
2581
2582       Gen_Elab_Defs_C;
2583
2584       --  Imported variable used to track elaboration/finalization phase.
2585       --  Used only when we have a runtime.
2586
2587       if not Suppress_Standard_Library_On_Target then
2588          WBI ("extern int  __gnat_handler_installed;");
2589          WBI ("");
2590       end if;
2591
2592       --  Write argv/argc exit status stuff if main program case
2593
2594       if Bind_Main_Program then
2595
2596          --  First deal with argc/argv/envp. In the normal case they
2597          --  are in the run-time library.
2598
2599          if not Configurable_Run_Time_On_Target then
2600             WBI ("extern int gnat_argc;");
2601             WBI ("extern char **gnat_argv;");
2602             WBI ("extern char **gnat_envp;");
2603
2604          --  If configurable run time and no command line args, then the
2605          --  generation of these variables is entirely suppressed.
2606
2607          elsif not Command_Line_Args_On_Target then
2608             null;
2609
2610          --  Otherwise, in the configurable run-time case they are right in
2611          --  the binder file.
2612
2613          else
2614             WBI ("int gnat_argc;");
2615             WBI ("char **gnat_argv;");
2616             WBI ("char **gnat_envp;");
2617          end if;
2618
2619          --  Similarly deal with exit status
2620          --  are in the run-time library.
2621
2622          if not Configurable_Run_Time_On_Target then
2623             WBI ("extern int gnat_exit_status;");
2624
2625          --  If configurable run time and no exit status on target, then
2626          --  the generation of this variables is entirely suppressed.
2627
2628          elsif not Exit_Status_Supported_On_Target then
2629             null;
2630
2631          --  Otherwise, in the configurable run-time case this variable is
2632          --  right in the binder file, and initialized to zero there.
2633
2634          else
2635             WBI ("int gnat_exit_status = 0;");
2636          end if;
2637
2638          WBI ("");
2639       end if;
2640
2641       --  When suppressing the standard library, the __gnat_break_start
2642       --  routine (for the debugger to get initial control) is defined in
2643       --  this file.
2644
2645       if Suppress_Standard_Library_On_Target then
2646          WBI ("");
2647          WBI ("void __gnat_break_start (void) {}");
2648       end if;
2649
2650       --  Generate the __gnat_version and __gnat_ada_main_program_name info
2651       --  only for the main program. Otherwise, it can lead under some
2652       --  circumstances to a symbol duplication during the link (for instance
2653       --  when a C program uses 2 Ada libraries)
2654
2655       if Bind_Main_Program then
2656          WBI ("");
2657          WBI ("char __gnat_version[] = ""GNAT Version: " &
2658                                    Gnat_Version_String & """;");
2659
2660          Set_String ("char __gnat_ada_main_program_name[] = """);
2661          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
2662          Set_Main_Program_Name;
2663          Set_String (""";");
2664          Write_Statement_Buffer;
2665       end if;
2666
2667       --  Generate the adafinal routine. In no runtime mode, this is
2668       --  not needed, since there is no finalization to do.
2669
2670       if not Cumulative_Restrictions.Set (No_Finalization) then
2671          Gen_Adafinal_C;
2672       end if;
2673
2674       Gen_Adainit_C;
2675
2676       --  Main is only present for Ada main case
2677
2678       if Bind_Main_Program then
2679          Gen_Main_C;
2680       end if;
2681
2682       --  Generate versions, elaboration order, list of object files
2683
2684       Gen_Versions_C;
2685       Gen_Elab_Order_C;
2686       Gen_Object_Files_Options;
2687
2688       --  C binder output is complete
2689
2690       Close_Binder_Output;
2691    end Gen_Output_File_C;
2692
2693    --------------------------
2694    -- Gen_Restrictions_Ada --
2695    --------------------------
2696
2697    procedure Gen_Restrictions_Ada is
2698       Count : Integer;
2699
2700    begin
2701       if Suppress_Standard_Library_On_Target
2702         or not System_Restrictions_Used
2703       then
2704          return;
2705       end if;
2706
2707       WBI ("      System.Restrictions.Run_Time_Restrictions :=");
2708       WBI ("        (Set =>");
2709       Set_String      ("          (");
2710
2711       Count := 0;
2712
2713       for J in Cumulative_Restrictions.Set'First ..
2714         Restriction_Id'Pred (Cumulative_Restrictions.Set'Last)
2715       loop
2716          Set_Boolean (Cumulative_Restrictions.Set (J));
2717          Set_String (", ");
2718          Count := Count + 1;
2719
2720          if Count = 8 then
2721             Write_Statement_Buffer;
2722             Set_String ("           ");
2723             Count := 0;
2724          end if;
2725       end loop;
2726
2727       Set_Boolean
2728         (Cumulative_Restrictions.Set (Cumulative_Restrictions.Set'Last));
2729       Set_String ("),");
2730       Write_Statement_Buffer;
2731       Set_String ("         Value => (");
2732
2733       for J in Cumulative_Restrictions.Value'First ..
2734         Restriction_Id'Pred (Cumulative_Restrictions.Value'Last)
2735       loop
2736          Set_Int (Int (Cumulative_Restrictions.Value (J)));
2737          Set_String (", ");
2738       end loop;
2739
2740       Set_Int (Int (Cumulative_Restrictions.Value
2741         (Cumulative_Restrictions.Value'Last)));
2742       Set_String ("),");
2743       Write_Statement_Buffer;
2744       WBI ("         Violated =>");
2745       Set_String ("          (");
2746       Count := 0;
2747
2748       for J in Cumulative_Restrictions.Violated'First ..
2749         Restriction_Id'Pred (Cumulative_Restrictions.Violated'Last)
2750       loop
2751          Set_Boolean (Cumulative_Restrictions.Violated (J));
2752          Set_String (", ");
2753          Count := Count + 1;
2754
2755          if Count = 8 then
2756             Write_Statement_Buffer;
2757             Set_String ("           ");
2758             Count := 0;
2759          end if;
2760       end loop;
2761
2762       Set_Boolean (Cumulative_Restrictions.Violated
2763         (Cumulative_Restrictions.Violated'Last));
2764       Set_String ("),");
2765       Write_Statement_Buffer;
2766       Set_String ("         Count => (");
2767
2768       for J in Cumulative_Restrictions.Count'First ..
2769         Restriction_Id'Pred (Cumulative_Restrictions.Count'Last)
2770       loop
2771          Set_Int (Int (Cumulative_Restrictions.Count (J)));
2772          Set_String (", ");
2773       end loop;
2774
2775       Set_Int (Int (Cumulative_Restrictions.Count
2776         (Cumulative_Restrictions.Count'Last)));
2777       Set_String ("),");
2778       Write_Statement_Buffer;
2779       Set_String ("         Unknown => (");
2780
2781       for J in Cumulative_Restrictions.Unknown'First ..
2782         Restriction_Id'Pred (Cumulative_Restrictions.Unknown'Last)
2783       loop
2784          Set_Boolean (Cumulative_Restrictions.Unknown (J));
2785          Set_String (", ");
2786       end loop;
2787
2788       Set_Boolean
2789         (Cumulative_Restrictions.Unknown
2790           (Cumulative_Restrictions.Unknown'Last));
2791       Set_String ("));");
2792       Write_Statement_Buffer;
2793    end Gen_Restrictions_Ada;
2794
2795    ------------------------
2796    -- Gen_Restrictions_C --
2797    ------------------------
2798
2799    procedure Gen_Restrictions_C is
2800    begin
2801       if Suppress_Standard_Library_On_Target
2802         or not System_Restrictions_Used
2803       then
2804          return;
2805       end if;
2806
2807       WBI ("   typedef struct {");
2808       Set_String ("     char set [");
2809       Set_Int (Cumulative_Restrictions.Set'Length);
2810       Set_String ("];");
2811       Write_Statement_Buffer;
2812
2813       Set_String ("     int value [");
2814       Set_Int (Cumulative_Restrictions.Value'Length);
2815       Set_String ("];");
2816       Write_Statement_Buffer;
2817
2818       Set_String ("     char violated [");
2819       Set_Int (Cumulative_Restrictions.Violated'Length);
2820       Set_String ("];");
2821       Write_Statement_Buffer;
2822
2823       Set_String ("     int count [");
2824       Set_Int (Cumulative_Restrictions.Count'Length);
2825       Set_String ("];");
2826       Write_Statement_Buffer;
2827
2828       Set_String ("     char unknown [");
2829       Set_Int (Cumulative_Restrictions.Unknown'Length);
2830       Set_String ("];");
2831       Write_Statement_Buffer;
2832       WBI ("   } restrictions;");
2833       WBI ("   extern restrictions " &
2834            "system__restrictions__run_time_restrictions;");
2835       WBI ("   restrictions r = {");
2836       Set_String ("     {");
2837
2838       for J in Cumulative_Restrictions.Set'First ..
2839         Restriction_Id'Pred (Cumulative_Restrictions.Set'Last)
2840       loop
2841          Set_Int (Boolean'Pos (Cumulative_Restrictions.Set (J)));
2842          Set_String (", ");
2843       end loop;
2844
2845       Set_Int (Boolean'Pos
2846         (Cumulative_Restrictions.Set (Cumulative_Restrictions.Set'Last)));
2847       Set_String ("},");
2848       Write_Statement_Buffer;
2849       Set_String ("     {");
2850
2851       for J in Cumulative_Restrictions.Value'First ..
2852         Restriction_Id'Pred (Cumulative_Restrictions.Value'Last)
2853       loop
2854          Set_Int (Int (Cumulative_Restrictions.Value (J)));
2855          Set_String (", ");
2856       end loop;
2857
2858       Set_Int (Int (Cumulative_Restrictions.Value
2859         (Cumulative_Restrictions.Value'Last)));
2860       Set_String ("},");
2861       Write_Statement_Buffer;
2862       Set_String ("     {");
2863
2864       for J in Cumulative_Restrictions.Violated'First ..
2865         Restriction_Id'Pred (Cumulative_Restrictions.Violated'Last)
2866       loop
2867          Set_Int (Boolean'Pos (Cumulative_Restrictions.Violated (J)));
2868          Set_String (", ");
2869       end loop;
2870
2871       Set_Int (Boolean'Pos (Cumulative_Restrictions.Violated
2872         (Cumulative_Restrictions.Violated'Last)));
2873       Set_String ("},");
2874       Write_Statement_Buffer;
2875       Set_String ("     {");
2876
2877       for J in Cumulative_Restrictions.Count'First ..
2878         Restriction_Id'Pred (Cumulative_Restrictions.Count'Last)
2879       loop
2880          Set_Int (Int (Cumulative_Restrictions.Count (J)));
2881          Set_String (", ");
2882       end loop;
2883
2884       Set_Int (Int (Cumulative_Restrictions.Count
2885         (Cumulative_Restrictions.Count'Last)));
2886       Set_String ("},");
2887       Write_Statement_Buffer;
2888       Set_String ("     {");
2889
2890       for J in Cumulative_Restrictions.Unknown'First ..
2891         Restriction_Id'Pred (Cumulative_Restrictions.Unknown'Last)
2892       loop
2893          Set_Int (Boolean'Pos (Cumulative_Restrictions.Unknown (J)));
2894          Set_String (", ");
2895       end loop;
2896
2897       Set_Int (Boolean'Pos (Cumulative_Restrictions.Unknown
2898           (Cumulative_Restrictions.Unknown'Last)));
2899       Set_String ("}};");
2900       Write_Statement_Buffer;
2901       WBI ("   system__restrictions__run_time_restrictions = r;");
2902    end Gen_Restrictions_C;
2903
2904    ----------------------
2905    -- Gen_Versions_Ada --
2906    ----------------------
2907
2908    --  This routine generates two sets of lines. The first set has the form:
2909
2910    --    unnnnn : constant Integer := 16#hhhhhhhh#;
2911
2912    --  The second set has the form
2913
2914    --    pragma Export (C, unnnnn, unam);
2915
2916    --  for each unit, where unam is the unit name suffixed by either B or
2917    --  S for body or spec, with dots replaced by double underscores, and
2918    --  hhhhhhhh is the version number, and nnnnn is a 5-digits serial number.
2919
2920    procedure Gen_Versions_Ada is
2921       Ubuf : String (1 .. 6) := "u00000";
2922
2923       procedure Increment_Ubuf;
2924       --  Little procedure to increment the serial number
2925
2926       procedure Increment_Ubuf is
2927       begin
2928          for J in reverse Ubuf'Range loop
2929             Ubuf (J) := Character'Succ (Ubuf (J));
2930             exit when Ubuf (J) <= '9';
2931             Ubuf (J) := '0';
2932          end loop;
2933       end Increment_Ubuf;
2934
2935    --  Start of processing for Gen_Versions_Ada
2936
2937    begin
2938       if Bind_For_Library then
2939
2940          --  When building libraries, the version number of each unit can
2941          --  not be computed, since the binder does not know the full list
2942          --  of units. Therefore, the 'Version and 'Body_Version
2943          --  attributes cannot supported in this case.
2944
2945          return;
2946       end if;
2947
2948       WBI ("");
2949
2950       WBI ("   type Version_32 is mod 2 ** 32;");
2951       for U in Units.First .. Units.Last loop
2952          Increment_Ubuf;
2953          WBI ("   " & Ubuf & " : constant Version_32 := 16#" &
2954               Units.Table (U).Version & "#;");
2955       end loop;
2956
2957       WBI ("");
2958       Ubuf := "u00000";
2959
2960       for U in Units.First .. Units.Last loop
2961          Increment_Ubuf;
2962          Set_String ("   pragma Export (C, ");
2963          Set_String (Ubuf);
2964          Set_String (", """);
2965
2966          Get_Name_String (Units.Table (U).Uname);
2967
2968          for K in 1 .. Name_Len loop
2969             if Name_Buffer (K) = '.' then
2970                Set_Char ('_');
2971                Set_Char ('_');
2972
2973             elsif Name_Buffer (K) = '%' then
2974                exit;
2975
2976             else
2977                Set_Char (Name_Buffer (K));
2978             end if;
2979          end loop;
2980
2981          if Name_Buffer (Name_Len) = 's' then
2982             Set_Char ('S');
2983          else
2984             Set_Char ('B');
2985          end if;
2986
2987          Set_String (""");");
2988          Write_Statement_Buffer;
2989       end loop;
2990
2991    end Gen_Versions_Ada;
2992
2993    --------------------
2994    -- Gen_Versions_C --
2995    --------------------
2996
2997    --  This routine generates a line of the form:
2998
2999    --    unsigned unam = 0xhhhhhhhh;
3000
3001    --  for each unit, where unam is the unit name suffixed by either B or
3002    --  S for body or spec, with dots replaced by double underscores.
3003
3004    procedure Gen_Versions_C is
3005    begin
3006       if Bind_For_Library then
3007
3008          --  When building libraries, the version number of each unit can
3009          --  not be computed, since the binder does not know the full list
3010          --  of units. Therefore, the 'Version and 'Body_Version
3011          --  attributes cannot supported.
3012
3013          return;
3014       end if;
3015
3016       for U in Units.First .. Units.Last loop
3017          Set_String ("unsigned ");
3018
3019          Get_Name_String (Units.Table (U).Uname);
3020
3021          for K in 1 .. Name_Len loop
3022             if Name_Buffer (K) = '.' then
3023                Set_String ("__");
3024
3025             elsif Name_Buffer (K) = '%' then
3026                exit;
3027
3028             else
3029                Set_Char (Name_Buffer (K));
3030             end if;
3031          end loop;
3032
3033          if Name_Buffer (Name_Len) = 's' then
3034             Set_Char ('S');
3035          else
3036             Set_Char ('B');
3037          end if;
3038
3039          Set_String (" = 0x");
3040          Set_String (Units.Table (U).Version);
3041          Set_Char   (';');
3042          Write_Statement_Buffer;
3043       end loop;
3044
3045    end Gen_Versions_C;
3046
3047    ------------------------
3048    -- Get_Main_Unit_Name --
3049    ------------------------
3050
3051    function Get_Main_Unit_Name (S : String) return String is
3052       Result : String := S;
3053
3054    begin
3055       for J in S'Range loop
3056          if Result (J) = '.' then
3057             Result (J) := '_';
3058          end if;
3059       end loop;
3060
3061       return Result;
3062    end Get_Main_Unit_Name;
3063
3064    -----------------------
3065    -- Get_Ada_Main_Name --
3066    -----------------------
3067
3068    function Get_Ada_Main_Name return String is
3069       Suffix : constant String := "_00";
3070       Name   : String (1 .. Opt.Ada_Main_Name.all'Length + Suffix'Length) :=
3071                  Opt.Ada_Main_Name.all & Suffix;
3072       Nlen   : Natural;
3073
3074    begin
3075       --  The main program generated by JGNAT expects a package called
3076       --  ada_<main procedure>.
3077
3078       if VM_Target /= No_VM then
3079          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
3080          return "ada_" & Get_Main_Unit_Name (Name_Buffer (1 .. Name_Len - 2));
3081       end if;
3082
3083       --  This loop tries the following possibilities in order
3084       --    <Ada_Main>
3085       --    <Ada_Main>_01
3086       --    <Ada_Main>_02
3087       --    ..
3088       --    <Ada_Main>_99
3089       --  where <Ada_Main> is equal to Opt.Ada_Main_Name. By default,
3090       --  it is set to 'ada_main'.
3091
3092       for J in 0 .. 99 loop
3093          if J = 0 then
3094             Nlen := Name'Length - Suffix'Length;
3095          else
3096             Nlen := Name'Length;
3097             Name (Name'Last) := Character'Val (J mod 10 + Character'Pos ('0'));
3098             Name (Name'Last - 1) :=
3099               Character'Val (J /   10 + Character'Pos ('0'));
3100          end if;
3101
3102          for K in ALIs.First .. ALIs.Last loop
3103             for L in ALIs.Table (K).First_Unit .. ALIs.Table (K).Last_Unit loop
3104
3105                --  Get unit name, removing %b or %e at end
3106
3107                Get_Name_String (Units.Table (L).Uname);
3108                Name_Len := Name_Len - 2;
3109
3110                if Name_Buffer (1 .. Name_Len) = Name (1 .. Nlen) then
3111                   goto Continue;
3112                end if;
3113             end loop;
3114          end loop;
3115
3116          return Name (1 .. Nlen);
3117
3118       <<Continue>>
3119          null;
3120       end loop;
3121
3122       --  If we fall through, just use a peculiar unlikely name
3123
3124       return ("Qwertyuiop");
3125    end Get_Ada_Main_Name;
3126
3127    -------------------
3128    -- Get_Main_Name --
3129    -------------------
3130
3131    function Get_Main_Name return String is
3132    begin
3133       --  Explicit name given with -M switch
3134
3135       if Bind_Alternate_Main_Name then
3136          return Alternate_Main_Name.all;
3137
3138       --  Case of main program name to be used directly
3139
3140       elsif Use_Ada_Main_Program_Name_On_Target then
3141
3142          --  Get main program name
3143
3144          Get_Name_String (Units.Table (First_Unit_Entry).Uname);
3145
3146          --  If this is a child name, return only the name of the child,
3147          --  since we can't have dots in a nested program name. Note that
3148          --  we do not include the %b at the end of the unit name.
3149
3150          for J in reverse 1 .. Name_Len - 2 loop
3151             if J = 1 or else Name_Buffer (J - 1) = '.' then
3152                return Name_Buffer (J .. Name_Len - 2);
3153             end if;
3154          end loop;
3155
3156          raise Program_Error; -- impossible exit
3157
3158       --  Case where "main" is to be used as default
3159
3160       else
3161          return "main";
3162       end if;
3163    end Get_Main_Name;
3164
3165    ---------------------
3166    -- Get_WC_Encoding --
3167    ---------------------
3168
3169    function Get_WC_Encoding return Character is
3170    begin
3171       --  If encoding method specified by -W switch, then return it
3172
3173       if Wide_Character_Encoding_Method_Specified then
3174          return WC_Encoding_Letters (Wide_Character_Encoding_Method);
3175
3176       --  If no main program, and not specified, set brackets, we really have
3177       --  no better choice. If some other encoding is required when there is
3178       --  no main, it must be set explicitly using -Wx.
3179
3180       --  Note: if the ALI file always passed the wide character encoding
3181       --  of every file, then we could use the encoding of the initial
3182       --  specified file, but this information is passed only for potential
3183       --  main programs. We could fix this sometime, but it is a very minor
3184       --  point (wide character default encoding for [Wide_[Wide_]Text_IO
3185       --  when there is no main program).
3186
3187       elsif No_Main_Subprogram then
3188          return 'b';
3189
3190       --  Otherwise if there is a main program, take encoding from it
3191
3192       else
3193          return ALIs.Table (ALIs.First).WC_Encoding;
3194       end if;
3195    end Get_WC_Encoding;
3196
3197    ----------------------
3198    -- Lt_Linker_Option --
3199    ----------------------
3200
3201    function Lt_Linker_Option (Op1, Op2 : Natural) return Boolean is
3202    begin
3203       --  Sort internal files last
3204
3205       if Linker_Options.Table (Op1).Internal_File
3206            /=
3207          Linker_Options.Table (Op2).Internal_File
3208       then
3209          --  Note: following test uses False < True
3210
3211          return Linker_Options.Table (Op1).Internal_File
3212                   <
3213                 Linker_Options.Table (Op2).Internal_File;
3214
3215       --  If both internal or both non-internal, sort according to the
3216       --  elaboration position. A unit that is elaborated later should
3217       --  come earlier in the linker options list.
3218
3219       else
3220          return Units.Table (Linker_Options.Table (Op1).Unit).Elab_Position
3221                   >
3222                 Units.Table (Linker_Options.Table (Op2).Unit).Elab_Position;
3223
3224       end if;
3225    end Lt_Linker_Option;
3226
3227    ------------------------
3228    -- Move_Linker_Option --
3229    ------------------------
3230
3231    procedure Move_Linker_Option (From : Natural; To : Natural) is
3232    begin
3233       Linker_Options.Table (To) := Linker_Options.Table (From);
3234    end Move_Linker_Option;
3235
3236    ----------------------------
3237    -- Resolve_Binder_Options --
3238    ----------------------------
3239
3240    procedure Resolve_Binder_Options is
3241    begin
3242       for E in Elab_Order.First .. Elab_Order.Last loop
3243          Get_Name_String (Units.Table (Elab_Order.Table (E)).Uname);
3244
3245          --  The procedure of looking for specific packages and setting
3246          --  flags is somewhat dubious, but there isn't a good alternative
3247          --  at the current time ???
3248
3249          if Name_Buffer (1 .. 19) = "system.os_interface" then
3250             With_GNARL := True;
3251          end if;
3252
3253          if OpenVMS_On_Target and then Name_Buffer (1 .. 5) = "dec%s" then
3254             With_DECGNAT := True;
3255          end if;
3256       end loop;
3257    end Resolve_Binder_Options;
3258
3259    -----------------
3260    -- Set_Boolean --
3261    -----------------
3262
3263    procedure Set_Boolean (B : Boolean) is
3264       True_Str  : constant String := "True";
3265       False_Str : constant String := "False";
3266    begin
3267       if B then
3268          Statement_Buffer (Last + 1 .. Last + True_Str'Length) := True_Str;
3269          Last := Last + True_Str'Length;
3270       else
3271          Statement_Buffer (Last + 1 .. Last + False_Str'Length) := False_Str;
3272          Last := Last + False_Str'Length;
3273       end if;
3274    end Set_Boolean;
3275
3276    --------------
3277    -- Set_Char --
3278    --------------
3279
3280    procedure Set_Char (C : Character) is
3281    begin
3282       Last := Last + 1;
3283       Statement_Buffer (Last) := C;
3284    end Set_Char;
3285
3286    -------------
3287    -- Set_Int --
3288    -------------
3289
3290    procedure Set_Int (N : Int) is
3291    begin
3292       if N < 0 then
3293          Set_String ("-");
3294          Set_Int (-N);
3295
3296       else
3297          if N > 9 then
3298             Set_Int (N / 10);
3299          end if;
3300
3301          Last := Last + 1;
3302          Statement_Buffer (Last) :=
3303            Character'Val (N mod 10 + Character'Pos ('0'));
3304       end if;
3305    end Set_Int;
3306
3307    -------------------------
3308    -- Set_IS_Pragma_Table --
3309    -------------------------
3310
3311    procedure Set_IS_Pragma_Table is
3312    begin
3313       for F in ALIs.First .. ALIs.Last loop
3314          for K in ALIs.Table (F).First_Interrupt_State ..
3315                   ALIs.Table (F).Last_Interrupt_State
3316          loop
3317             declare
3318                Inum : constant Int :=
3319                         Interrupt_States.Table (K).Interrupt_Id;
3320                Stat : constant Character :=
3321                         Interrupt_States.Table (K).Interrupt_State;
3322
3323             begin
3324                while IS_Pragma_Settings.Last < Inum loop
3325                   IS_Pragma_Settings.Append ('n');
3326                end loop;
3327
3328                IS_Pragma_Settings.Table (Inum) := Stat;
3329             end;
3330          end loop;
3331       end loop;
3332    end Set_IS_Pragma_Table;
3333
3334    ---------------------------
3335    -- Set_Main_Program_Name --
3336    ---------------------------
3337
3338    procedure Set_Main_Program_Name is
3339    begin
3340       --  Note that name has %b on the end which we ignore
3341
3342       --  First we output the initial _ada_ since we know that the main
3343       --  program is a library level subprogram.
3344
3345       Set_String ("_ada_");
3346
3347       --  Copy name, changing dots to double underscores
3348
3349       for J in 1 .. Name_Len - 2 loop
3350          if Name_Buffer (J) = '.' then
3351             Set_String ("__");
3352          else
3353             Set_Char (Name_Buffer (J));
3354          end if;
3355       end loop;
3356    end Set_Main_Program_Name;
3357
3358    ---------------------
3359    -- Set_Name_Buffer --
3360    ---------------------
3361
3362    procedure Set_Name_Buffer is
3363    begin
3364       for J in 1 .. Name_Len loop
3365          Set_Char (Name_Buffer (J));
3366       end loop;
3367    end Set_Name_Buffer;
3368
3369    -------------------------
3370    -- Set_PSD_Pragma_Table --
3371    -------------------------
3372
3373    procedure Set_PSD_Pragma_Table is
3374    begin
3375       for F in ALIs.First .. ALIs.Last loop
3376          for K in ALIs.Table (F).First_Specific_Dispatching ..
3377                   ALIs.Table (F).Last_Specific_Dispatching
3378          loop
3379             declare
3380                DTK : Specific_Dispatching_Record
3381                        renames Specific_Dispatching.Table (K);
3382
3383             begin
3384                while PSD_Pragma_Settings.Last < DTK.Last_Priority loop
3385                   PSD_Pragma_Settings.Append ('F');
3386                end loop;
3387
3388                for Prio in DTK.First_Priority .. DTK.Last_Priority loop
3389                   PSD_Pragma_Settings.Table (Prio) := DTK.Dispatching_Policy;
3390                end loop;
3391             end;
3392          end loop;
3393       end loop;
3394    end Set_PSD_Pragma_Table;
3395
3396    ----------------
3397    -- Set_String --
3398    ----------------
3399
3400    procedure Set_String (S : String) is
3401    begin
3402       Statement_Buffer (Last + 1 .. Last + S'Length) := S;
3403       Last := Last + S'Length;
3404    end Set_String;
3405
3406    -------------------
3407    -- Set_Unit_Name --
3408    -------------------
3409
3410    procedure Set_Unit_Name is
3411    begin
3412       for J in 1 .. Name_Len - 2 loop
3413          if Name_Buffer (J) /= '.' then
3414             Set_Char (Name_Buffer (J));
3415          else
3416             Set_String ("__");
3417          end if;
3418       end loop;
3419    end Set_Unit_Name;
3420
3421    ---------------------
3422    -- Set_Unit_Number --
3423    ---------------------
3424
3425    procedure Set_Unit_Number (U : Unit_Id) is
3426       Num_Units : constant Nat := Nat (Units.Last) - Nat (Unit_Id'First);
3427       Unum      : constant Nat := Nat (U) - Nat (Unit_Id'First);
3428
3429    begin
3430       if Num_Units >= 10 and then Unum < 10 then
3431          Set_Char ('0');
3432       end if;
3433
3434       if Num_Units >= 100 and then Unum < 100 then
3435          Set_Char ('0');
3436       end if;
3437
3438       Set_Int (Unum);
3439    end Set_Unit_Number;
3440
3441    ----------------------
3442    -- Write_Info_Ada_C --
3443    ----------------------
3444
3445    procedure Write_Info_Ada_C (Ada : String; C : String; Common : String) is
3446    begin
3447       if Ada_Bind_File then
3448          declare
3449             S : String (1 .. Ada'Length + Common'Length);
3450          begin
3451             S (1 .. Ada'Length) := Ada;
3452             S (Ada'Length + 1 .. S'Length) := Common;
3453             WBI (S);
3454          end;
3455
3456       else
3457          declare
3458             S : String (1 .. C'Length + Common'Length);
3459          begin
3460             S (1 .. C'Length) := C;
3461             S (C'Length + 1 .. S'Length) := Common;
3462             WBI (S);
3463          end;
3464       end if;
3465    end Write_Info_Ada_C;
3466
3467    ----------------------------
3468    -- Write_Statement_Buffer --
3469    ----------------------------
3470
3471    procedure Write_Statement_Buffer is
3472    begin
3473       WBI (Statement_Buffer (1 .. Last));
3474       Last := 0;
3475    end Write_Statement_Buffer;
3476
3477    procedure Write_Statement_Buffer (S : String) is
3478    begin
3479       Set_String (S);
3480       Write_Statement_Buffer;
3481    end Write_Statement_Buffer;
3482
3483 end Bindgen;