OSDN Git Service

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