OSDN Git Service

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