OSDN Git Service

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