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