OSDN Git Service

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