1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                                 M A K E                                  --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2014, 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
26with ALI;      use ALI;
27with ALI.Util; use ALI.Util;
28with Csets;
29with Debug;
30with Errutil;
31with Fmap;
32with Fname;    use Fname;
33with Fname.SF; use Fname.SF;
34with Fname.UF; use Fname.UF;
35with Gnatvsn;  use Gnatvsn;
36with Hostparm; use Hostparm;
37with Makeusg;
38with Makeutl;  use Makeutl;
39with MLib;
40with MLib.Prj;
41with MLib.Tgt; use MLib.Tgt;
42with MLib.Utl;
43with Namet;    use Namet;
44with Opt;      use Opt;
45with Osint.M;  use Osint.M;
46with Osint;    use Osint;
47with Output;   use Output;
48with Prj;      use Prj;
49with Prj.Com;
50with Prj.Env;
51with Prj.Pars;
52with Prj.Tree; use Prj.Tree;
53with Prj.Util;
54with Sdefault;
55with SFN_Scan;
56with Sinput.P;
57with Snames;   use Snames;
58with Stringt;
59
60pragma Warnings (Off);
61with System.HTable;
62pragma Warnings (On);
63
64with Switch;   use Switch;
65with Switch.M; use Switch.M;
66with Table;
67with Targparm; use Targparm;
68with Tempdir;
69with Types;    use Types;
70
71with Ada.Command_Line; use Ada.Command_Line;
72with Ada.Directories;
73with Ada.Exceptions;   use Ada.Exceptions;
74
75with GNAT.Case_Util;            use GNAT.Case_Util;
76with GNAT.Command_Line;         use GNAT.Command_Line;
77with GNAT.Directory_Operations; use GNAT.Directory_Operations;
78with GNAT.Dynamic_HTables;      use GNAT.Dynamic_HTables;
79with GNAT.OS_Lib;               use GNAT.OS_Lib;
80
81package body Make is
82
83   use ASCII;
84   --  Make control characters visible
85
86   Standard_Library_Package_Body_Name : constant String := "s-stalib.adb";
87   --  Every program depends on this package, that must then be checked,
88   --  especially when -f and -a are used.
89
90   procedure Kill (Pid : Process_Id; Sig_Num : Integer; Close : Integer);
91   pragma Import (C, Kill, "__gnat_kill");
92   --  Called by Sigint_Intercepted to kill all spawned compilation processes
93
94   type Sigint_Handler is access procedure;
95   pragma Convention (C, Sigint_Handler);
96
97   procedure Install_Int_Handler (Handler : Sigint_Handler);
98   pragma Import (C, Install_Int_Handler, "__gnat_install_int_handler");
99   --  Called by Gnatmake to install the SIGINT handler below
100
101   procedure Sigint_Intercepted;
102   pragma Convention (C, Sigint_Intercepted);
103   --  Called when the program is interrupted by Ctrl-C to delete the
104   --  temporary mapping files and configuration pragmas files.
105
106   No_Mapping_File : constant Natural := 0;
107
108   type Compilation_Data is record
109      Pid              : Process_Id;
110      Full_Source_File : File_Name_Type;
111      Lib_File         : File_Name_Type;
112      Source_Unit      : Unit_Name_Type;
113      Full_Lib_File    : File_Name_Type;
114      Lib_File_Attr    : aliased File_Attributes;
115      Mapping_File     : Natural := No_Mapping_File;
116      Project          : Project_Id := No_Project;
117   end record;
118   --  Data recorded for each compilation process spawned
119
120   No_Compilation_Data : constant Compilation_Data :=
121     (Invalid_Pid, No_File, No_File, No_Unit_Name, No_File, Unknown_Attributes,
122      No_Mapping_File, No_Project);
123
124   type Comp_Data_Arr is array (Positive range <>) of Compilation_Data;
125   type Comp_Data_Ptr is access Comp_Data_Arr;
126   Running_Compile : Comp_Data_Ptr;
127   --  Used to save information about outstanding compilations
128
129   Outstanding_Compiles : Natural := 0;
130   --  Current number of outstanding compiles
131
132   -------------------------
133   -- Note on terminology --
134   -------------------------
135
136   --  In this program, we use the phrase "termination" of a file name to refer
137   --  to the suffix that appears after the unit name portion. Very often this
138   --  is simply the extension, but in some cases, the sequence may be more
139   --  complex, for example in main.1.ada, the termination in this name is
140   --  ".1.ada" and in main_.ada the termination is "_.ada".
141
142   procedure Insert_Project_Sources
143     (The_Project  : Project_Id;
144      All_Projects : Boolean;
145      Into_Q       : Boolean);
146   --  If Into_Q is True, insert all sources of the project file(s) that are
147   --  not already marked into the Q. If Into_Q is False, call Osint.Add_File
148   --  for the first source, then insert all other sources that are not already
149   --  marked into the Q. If All_Projects is True, all sources of all projects
150   --  are concerned; otherwise, only sources of The_Project are concerned,
151   --  including, if The_Project is an extending project, sources inherited
152   --  from projects being extended.
153
154   Unique_Compile : Boolean := False;
155   --  Set to True if -u or -U or a project file with no main is used
156
157   Unique_Compile_All_Projects : Boolean := False;
158   --  Set to True if -U is used
159
160   Must_Compile : Boolean := False;
161   --  True if gnatmake is invoked with -f -u and one or several mains on the
162   --  command line.
163
164   Project_Tree : constant Project_Tree_Ref :=
165                    new Project_Tree_Data (Is_Root_Tree => True);
166   --  The project tree
167
168   Main_On_Command_Line : Boolean := False;
169   --  True if gnatmake is invoked with one or several mains on the command
170   --  line.
171
172   RTS_Specified : String_Access := null;
173   --  Used to detect multiple --RTS= switches
174
175   N_M_Switch : Natural := 0;
176   --  Used to count -mxxx switches that can affect multilib
177
178   --  The 3 following packages are used to store gcc, gnatbind and gnatlink
179   --  switches found in the project files.
180
181   package Gcc_Switches is new Table.Table (
182     Table_Component_Type => String_Access,
183     Table_Index_Type     => Integer,
184     Table_Low_Bound      => 1,
185     Table_Initial        => 20,
186     Table_Increment      => 100,
187     Table_Name           => "Make.Gcc_Switches");
188
189   package Binder_Switches is new Table.Table (
190     Table_Component_Type => String_Access,
191     Table_Index_Type     => Integer,
192     Table_Low_Bound      => 1,
193     Table_Initial        => 20,
194     Table_Increment      => 100,
195     Table_Name           => "Make.Binder_Switches");
196
197   package Linker_Switches is new Table.Table (
198     Table_Component_Type => String_Access,
199     Table_Index_Type     => Integer,
200     Table_Low_Bound      => 1,
201     Table_Initial        => 20,
202     Table_Increment      => 100,
203     Table_Name           => "Make.Linker_Switches");
204
205   --  The following instantiations and variables are necessary to save what
206   --  is found on the command line, in case there is a project file specified.
207
208   package Saved_Gcc_Switches is new Table.Table (
209     Table_Component_Type => String_Access,
210     Table_Index_Type     => Integer,
211     Table_Low_Bound      => 1,
212     Table_Initial        => 20,
213     Table_Increment      => 100,
214     Table_Name           => "Make.Saved_Gcc_Switches");
215
216   package Saved_Binder_Switches is new Table.Table (
217     Table_Component_Type => String_Access,
218     Table_Index_Type     => Integer,
219     Table_Low_Bound      => 1,
220     Table_Initial        => 20,
221     Table_Increment      => 100,
222     Table_Name           => "Make.Saved_Binder_Switches");
223
224   package Saved_Linker_Switches is new Table.Table
225     (Table_Component_Type => String_Access,
226      Table_Index_Type     => Integer,
227      Table_Low_Bound      => 1,
228      Table_Initial        => 20,
229      Table_Increment      => 100,
230      Table_Name           => "Make.Saved_Linker_Switches");
231
232   package Switches_To_Check is new Table.Table (
233     Table_Component_Type => String_Access,
234     Table_Index_Type     => Integer,
235     Table_Low_Bound      => 1,
236     Table_Initial        => 20,
237     Table_Increment      => 100,
238     Table_Name           => "Make.Switches_To_Check");
239
240   package Library_Paths is new Table.Table (
241     Table_Component_Type => String_Access,
242     Table_Index_Type     => Integer,
243     Table_Low_Bound      => 1,
244     Table_Initial        => 20,
245     Table_Increment      => 100,
246     Table_Name           => "Make.Library_Paths");
247
248   package Failed_Links is new Table.Table (
249     Table_Component_Type => File_Name_Type,
250     Table_Index_Type     => Integer,
251     Table_Low_Bound      => 1,
252     Table_Initial        => 10,
253     Table_Increment      => 100,
254     Table_Name           => "Make.Failed_Links");
255
256   package Successful_Links is new Table.Table (
257     Table_Component_Type => File_Name_Type,
258     Table_Index_Type     => Integer,
259     Table_Low_Bound      => 1,
260     Table_Initial        => 10,
261     Table_Increment      => 100,
262     Table_Name           => "Make.Successful_Links");
263
264   package Library_Projs is new Table.Table (
265     Table_Component_Type => Project_Id,
266     Table_Index_Type     => Integer,
267     Table_Low_Bound      => 1,
268     Table_Initial        => 10,
269     Table_Increment      => 100,
270     Table_Name           => "Make.Library_Projs");
271
272   --  Two variables to keep the last binder and linker switch index in tables
273   --  Binder_Switches and Linker_Switches, before adding switches from the
274   --  project file (if any) and switches from the command line (if any).
275
276   Last_Binder_Switch : Integer := 0;
277   Last_Linker_Switch : Integer := 0;
278
279   Normalized_Switches : Argument_List_Access := new Argument_List (1 .. 10);
280   Last_Norm_Switch    : Natural := 0;
281
282   Saved_Maximum_Processes : Natural := 0;
283
284   Gnatmake_Switch_Found : Boolean;
285   --  Set by Scan_Make_Arg. True when the switch is a gnatmake switch.
286   --  Tested by Add_Switches when switches in package Builder must all be
287   --  gnatmake switches.
288
289   Switch_May_Be_Passed_To_The_Compiler : Boolean;
290   --  Set by Add_Switches and Switches_Of. True when unrecognized switches
291   --  are passed to the Ada compiler.
292
293   type Arg_List_Ref is access Argument_List;
294   The_Saved_Gcc_Switches : Arg_List_Ref;
295
296   Project_File_Name : String_Access  := null;
297   --  The path name of the main project file, if any
298
299   Project_File_Name_Present : Boolean := False;
300   --  True when -P is used with a space between -P and the project file name
301
302   Current_Verbosity : Prj.Verbosity  := Prj.Default;
303   --  Verbosity to parse the project files
304
305   Main_Project : Prj.Project_Id := No_Project;
306   --  The project id of the main project file, if any
307
308   Project_Of_Current_Object_Directory : Project_Id := No_Project;
309   --  The object directory of the project for the last compilation. Avoid
310   --  calling Change_Dir if the current working directory is already this
311   --  directory.
312
313   Map_File : String_Access := null;
314   --  Value of switch --create-map-file
315
316   --  Packages of project files where unknown attributes are errors
317
318   Naming_String   : aliased String := "naming";
319   Builder_String  : aliased String := "builder";
320   Compiler_String : aliased String := "compiler";
321   Binder_String   : aliased String := "binder";
322   Linker_String   : aliased String := "linker";
323
324   Gnatmake_Packages : aliased String_List :=
325     (Naming_String   'Access,
326      Builder_String  'Access,
327      Compiler_String 'Access,
328      Binder_String   'Access,
329      Linker_String   'Access);
330
331   Packages_To_Check_By_Gnatmake : constant String_List_Access :=
332     Gnatmake_Packages'Access;
333
334   procedure Add_Library_Search_Dir
335     (Path            : String;
336      On_Command_Line : Boolean);
337   --  Call Add_Lib_Search_Dir with an absolute directory path. If Path is
338   --  relative path, when On_Command_Line is True, it is relative to the
339   --  current working directory. When On_Command_Line is False, it is relative
340   --  to the project directory of the main project.
341
342   procedure Add_Source_Search_Dir
343     (Path            : String;
344      On_Command_Line : Boolean);
345   --  Call Add_Src_Search_Dir with an absolute directory path. If Path is a
346   --  relative path, when On_Command_Line is True, it is relative to the
347   --  current working directory. When On_Command_Line is False, it is relative
348   --  to the project directory of the main project.
349
350   procedure Add_Source_Dir (N : String);
351   --  Call Add_Src_Search_Dir (output one line when in verbose mode)
352
353   procedure Add_Source_Directories is
354     new Prj.Env.For_All_Source_Dirs (Action => Add_Source_Dir);
355
356   procedure Add_Object_Dir (N : String);
357   --  Call Add_Lib_Search_Dir (output one line when in verbose mode)
358
359   procedure Add_Object_Directories is
360     new Prj.Env.For_All_Object_Dirs (Action => Add_Object_Dir);
361
362   procedure Change_To_Object_Directory (Project : Project_Id);
363   --  Change to the object directory of project Project, if this is not
364   --  already the current working directory.
365
366   type Bad_Compilation_Info is record
367      File  : File_Name_Type;
368      Unit  : Unit_Name_Type;
369      Found : Boolean;
370   end record;
371   --  File is the name of the file for which a compilation failed. Unit is for
372   --  gnatdist use in order to easily get the unit name of a file when its
373   --  name is krunched or declared in gnat.adc. Found is False if the
374   --  compilation failed because the file could not be found.
375
376   package Bad_Compilation is new Table.Table (
377     Table_Component_Type => Bad_Compilation_Info,
378     Table_Index_Type     => Natural,
379     Table_Low_Bound      => 1,
380     Table_Initial        => 20,
381     Table_Increment      => 100,
382     Table_Name           => "Make.Bad_Compilation");
383   --  Full name of all the source files for which compilation fails
384
385   Do_Compile_Step : Boolean := True;
386   Do_Bind_Step    : Boolean := True;
387   Do_Link_Step    : Boolean := True;
388   --  Flags to indicate what step should be executed. Can be set to False
389   --  with the switches -c, -b and -l. These flags are reset to True for
390   --  each invocation of procedure Gnatmake.
391
392   Shared_String           : aliased String := "-shared";
393   Force_Elab_Flags_String : aliased String := "-F";
394   CodePeer_Mode_String    : aliased String := "-P";
395
396   No_Shared_Switch : aliased Argument_List := (1 .. 0 => null);
397   Shared_Switch    : aliased Argument_List := (1 => Shared_String'Access);
398   Bind_Shared      : Argument_List_Access := No_Shared_Switch'Access;
399   --  Switch to added in front of gnatbind switches. By default no switch is
400   --  added. Switch "-shared" is added if there is a non-static Library
401   --  Project File.
402
403   Shared_Libgcc : aliased String := "-shared-libgcc";
404
405   No_Shared_Libgcc_Switch : aliased Argument_List := (1 .. 0 => null);
406   Shared_Libgcc_Switch    : aliased Argument_List :=
407                               (1 => Shared_Libgcc'Access);
408   Link_With_Shared_Libgcc : Argument_List_Access :=
409                               No_Shared_Libgcc_Switch'Access;
410
411   procedure Make_Failed (S : String);
412   --  Delete all temp files created by Gnatmake and call Osint.Fail, with the
413   --  parameter S (see osint.ads). This is called from the Prj hierarchy and
414   --  the MLib hierarchy. This subprogram also prints current error messages
415   --  (i.e. finalizes Errutil).
416
417   --------------------------
418   -- Obsolete Executables --
419   --------------------------
420
421   Executable_Obsolete : Boolean := False;
422   --  Executable_Obsolete is initially set to False for each executable,
423   --  and is set to True whenever one of the source of the executable is
424   --  compiled, or has already been compiled for another executable.
425
426   Max_Header : constant := 200;
427   --  This needs a proper comment, it used to say "arbitrary" that's not an
428   --  adequate comment ???
429
430   type Header_Num is range 1 .. Max_Header;
431   --  Header_Num for the hash table Obsoleted below
432
433   function Hash (F : File_Name_Type) return Header_Num;
434   --  Hash function for the hash table Obsoleted below
435
436   package Obsoleted is new System.HTable.Simple_HTable
437     (Header_Num => Header_Num,
438      Element    => Boolean,
439      No_Element => False,
440      Key        => File_Name_Type,
441      Hash       => Hash,
442      Equal      => "=");
443   --  A hash table to keep all files that have been compiled, to detect
444   --  if an executable is up to date or not.
445
446   procedure Enter_Into_Obsoleted (F : File_Name_Type);
447   --  Enter a file name, without directory information, into the hash table
448   --  Obsoleted.
449
450   function Is_In_Obsoleted (F : File_Name_Type) return Boolean;
451   --  Check if a file name, without directory information, has already been
452   --  entered into the hash table Obsoleted.
453
454   type Dependency is record
455      This       : File_Name_Type;
456      Depends_On : File_Name_Type;
457   end record;
458   --  Components of table Dependencies below
459
460   package Dependencies is new Table.Table (
461     Table_Component_Type => Dependency,
462     Table_Index_Type     => Integer,
463     Table_Low_Bound      => 1,
464     Table_Initial        => 20,
465     Table_Increment      => 100,
466     Table_Name           => "Make.Dependencies");
467   --  A table to keep dependencies, to be able to decide if an executable
468   --  is obsolete. More explanation needed ???
469
470   ----------------------------
471   -- Arguments and Switches --
472   ----------------------------
473
474   Arguments : Argument_List_Access;
475   --  Used to gather the arguments for invocation of the compiler
476
477   Last_Argument : Natural := 0;
478   --  Last index of arguments in Arguments above
479
480   Arguments_Project : Project_Id;
481   --  Project id, if any, of the source to be compiled
482
483   Arguments_Path_Name : Path_Name_Type;
484   --  Full path of the source to be compiled, when Arguments_Project is not
485   --  No_Project.
486
487   Dummy_Switch : constant String_Access := new String'("- ");
488   --  Used to initialized Prev_Switch in procedure Check
489
490   procedure Add_Arguments (Args : Argument_List);
491   --  Add arguments to global variable Arguments, increasing its size
492   --  if necessary and adjusting Last_Argument.
493
494   function Configuration_Pragmas_Switch
495     (For_Project : Project_Id) return Argument_List;
496   --  Return an argument list of one element, if there is a configuration
497   --  pragmas file to be specified for For_Project,
498   --  otherwise return an empty argument list.
499
500   -------------------
501   -- Misc Routines --
502   -------------------
503
504   procedure List_Depend;
505   --  Prints to standard output the list of object dependencies. This list
506   --  can be used directly in a Makefile. A call to Compile_Sources must
507   --  precede the call to List_Depend. Also because this routine uses the
508   --  ALI files that were originally loaded and scanned by Compile_Sources,
509   --  no additional ALI files should be scanned between the two calls (i.e.
510   --  between the call to Compile_Sources and List_Depend.)
511
512   procedure List_Bad_Compilations;
513   --  Prints out the list of all files for which the compilation failed
514
515   Usage_Needed : Boolean := True;
516   --  Flag used to make sure Makeusg is call at most once
517
518   procedure Usage;
519   --  Call Makeusg, if Usage_Needed is True.
520   --  Set Usage_Needed to False.
521
522   procedure Debug_Msg (S : String; N : Name_Id);
523   procedure Debug_Msg (S : String; N : File_Name_Type);
524   procedure Debug_Msg (S : String; N : Unit_Name_Type);
525   --  If Debug.Debug_Flag_W is set outputs string S followed by name N
526
527   procedure Recursive_Compute_Depth (Project : Project_Id);
528   --  Compute depth of Project and of the projects it depends on
529
530   -----------------------
531   -- Gnatmake Routines --
532   -----------------------
533
534   subtype Lib_Mark_Type is Byte;
535   --  Used in Mark_Directory
536
537   Ada_Lib_Dir : constant Lib_Mark_Type := 1;
538   --  Used to mark a directory as a GNAT lib dir
539
540   --  Note that the notion of GNAT lib dir is no longer used. The code related
541   --  to it has not been removed to give an idea on how to use the directory
542   --  prefix marking mechanism.
543
544   --  An Ada library directory is a directory containing ali and object files
545   --  but no source files for the bodies (the specs can be in the same or some
546   --  other directory). These directories are specified in the Gnatmake
547   --  command line with the switch "-Adir" (to specify the spec location -Idir
548   --  cab be used). Gnatmake skips the missing sources whose ali are in Ada
549   --  library directories. For an explanation of why Gnatmake behaves that
550   --  way, see the spec of Make.Compile_Sources. The directory lookup penalty
551   --  is incurred every single time this routine is called.
552
553   procedure Check_Steps;
554   --  Check what steps (Compile, Bind, Link) must be executed.
555   --  Set the step flags accordingly.
556
557   function In_Ada_Lib_Dir (File : File_Name_Type) return Boolean;
558   --  Get directory prefix of this file and get lib mark stored in name
559   --  table for this directory. Then check if an Ada lib mark has been set.
560
561   procedure Mark_Directory
562     (Dir             : String;
563      Mark            : Lib_Mark_Type;
564      On_Command_Line : Boolean);
565   --  Store the absolute path from Dir in name table and set lib mark as name
566   --  info to identify Ada libraries.
567   --
568   --  If Dir is a relative path, when On_Command_Line is True, it is relative
569   --  to the current working directory; when On_Command_Line is False, it is
570   --  relative to the project directory of the main project.
571
572   Output_Is_Object : Boolean := True;
573   --  Set to False when using a switch -S for the compiler
574
575   procedure Check_For_S_Switch;
576   --  Set Output_Is_Object to False when the -S switch is used for the
577   --  compiler.
578
579   function Switches_Of
580     (Source_File      : File_Name_Type;
581      Project          : Project_Id;
582      In_Package       : Package_Id;
583      Allow_ALI        : Boolean) return Variable_Value;
584   --  Return the switches for the source file in the specified package of a
585   --  project file. If the Source_File ends with a standard GNAT extension
586   --  (".ads" or ".adb"), try first the full name, then the name without the
587   --  extension, then, if Allow_ALI is True, the name with the extension
588   --  ".ali". If there is no switches for either names, try first Switches
589   --  (others) then the default switches for Ada. If all failed, return
590   --  No_Variable_Value.
591
592   function Is_In_Object_Directory
593     (Source_File   : File_Name_Type;
594      Full_Lib_File : File_Name_Type) return Boolean;
595   --  Check if, when using a project file, the ALI file is in the project
596   --  directory of the ultimate extending project. If it is not, we ignore
597   --  the fact that this ALI file is read-only.
598
599   procedure Process_Multilib (Env : in out Prj.Tree.Environment);
600   --  Add appropriate --RTS argument to handle multilib
601
602   procedure Resolve_Relative_Names_In_Switches (Current_Work_Dir : String);
603   --  Resolve all relative paths found in the linker and binder switches,
604   --  when using project files.
605
606   procedure Queue_Library_Project_Sources;
607   --  For all library project, if the library file does not exist, put all the
608   --  project sources in the queue, and flag the project so that the library
609   --  is generated.
610
611   procedure Compute_Switches_For_Main
612     (Main_Source_File  : in out File_Name_Type;
613      Root_Environment  : in out Prj.Tree.Environment;
614      Compute_Builder   : Boolean;
615      Current_Work_Dir  : String);
616   --  Find compiler, binder and linker switches to use for the given main
617
618   procedure Compute_Executable
619     (Main_Source_File   : File_Name_Type;
620      Executable         : out File_Name_Type;
621      Non_Std_Executable : out Boolean);
622   --  Parse the linker switches and project file to compute the name of the
623   --  executable to generate.
624   --  ??? What is the meaning of Non_Std_Executable
625
626   procedure Compilation_Phase
627     (Main_Source_File           : File_Name_Type;
628      Current_Main_Index         : Int := 0;
629      Total_Compilation_Failures : in out Natural;
630      Stand_Alone_Libraries      : in out Boolean;
631      Executable                 : File_Name_Type := No_File;
632      Is_Last_Main               : Boolean;
633      Stop_Compile               : out Boolean);
634   --  Build all source files for a given main file
635   --
636   --  Current_Main_Index, if not zero, is the index of the current main unit
637   --  in its source file.
638   --
639   --  Stand_Alone_Libraries is set to True when there are Stand-Alone
640   --  Libraries, so that gnatbind is invoked with the -F switch to force
641   --  checking of elaboration flags.
642   --
643   --  Stop_Compile is set to true if we should not try to compile any more
644   --  of the main units
645
646   procedure Binding_Phase
647     (Stand_Alone_Libraries : Boolean := False;
648      Main_ALI_File : File_Name_Type);
649   --  Stand_Alone_Libraries should be set to True when there are Stand-Alone
650   --  Libraries, so that gnatbind is invoked with the -F switch to force
651   --  checking of elaboration flags.
652
653   procedure Library_Phase
654      (Stand_Alone_Libraries : in out Boolean;
655       Library_Rebuilt : in out Boolean);
656   --  Build libraries.
657   --  Stand_Alone_Libraries is set to True when there are Stand-Alone
658   --  Libraries, so that gnatbind is invoked with the -F switch to force
659   --  checking of elaboration flags.
660
661   procedure Linking_Phase
662     (Non_Std_Executable : Boolean := False;
663      Executable         : File_Name_Type := No_File;
664      Main_ALI_File      : File_Name_Type);
665   --  Perform the link of a single executable. The ali file corresponds
666   --  to Main_ALI_File. Executable is the file name of an executable.
667   --  Non_Std_Executable is set to True when there is a possibility that
668   --  the linker will not choose the correct executable file name.
669
670   ----------------------------------------------------
671   -- Compiler, Binder & Linker Data and Subprograms --
672   ----------------------------------------------------
673
674   Gcc          : String_Access := Program_Name ("gcc", "gnatmake");
675   Original_Gcc : constant String_Access := Gcc;
676   --  Original_Gcc is used to check if Gcc has been modified by a switch
677   --  --GCC=, so that for VM platforms, it is not modified again, as it can
678   --  result in incorrect error messages if the compiler cannot be found.
679
680   Gnatbind : String_Access := Program_Name ("gnatbind", "gnatmake");
681   Gnatlink : String_Access := Program_Name ("gnatlink", "gnatmake");
682   --  Default compiler, binder, linker programs
683
684   Globalizer : constant String := "codepeer_globalizer";
685   --  CodePeer globalizer executable name
686
687   Saved_Gcc      : String_Access := null;
688   Saved_Gnatbind : String_Access := null;
689   Saved_Gnatlink : String_Access := null;
690   --  Given by the command line. Will be used, if non null
691
692   Gcc_Path      : String_Access :=
693                     GNAT.OS_Lib.Locate_Exec_On_Path (Gcc.all);
694   Gnatbind_Path : String_Access :=
695                     GNAT.OS_Lib.Locate_Exec_On_Path (Gnatbind.all);
696   Gnatlink_Path : String_Access :=
697                     GNAT.OS_Lib.Locate_Exec_On_Path (Gnatlink.all);
698   --  Path for compiler, binder, linker programs, defaulted now for gnatdist.
699   --  Changed later if overridden on command line.
700
701   Globalizer_Path : constant String_Access :=
702                       GNAT.OS_Lib.Locate_Exec_On_Path (Globalizer);
703   --  Path for CodePeer globalizer
704
705   Comp_Flag         : constant String_Access := new String'("-c");
706   Output_Flag       : constant String_Access := new String'("-o");
707   Ada_Flag_1        : constant String_Access := new String'("-x");
708   Ada_Flag_2        : constant String_Access := new String'("ada");
709   AdaSCIL_Flag      : constant String_Access := new String'("adascil");
710   No_gnat_adc       : constant String_Access := new String'("-gnatA");
711   GNAT_Flag         : constant String_Access := new String'("-gnatpg");
712   Do_Not_Check_Flag : constant String_Access := new String'("-x");
713
714   Object_Suffix : constant String := Get_Target_Object_Suffix.all;
715
716   Syntax_Only : Boolean := False;
717   --  Set to True when compiling with -gnats
718
719   Display_Executed_Programs : Boolean := True;
720   --  Set to True if name of commands should be output on stderr (or on stdout
721   --  if the Commands_To_Stdout flag was set by use of the -eS switch).
722
723   Output_File_Name_Seen : Boolean := False;
724   --  Set to True after having scanned the file_name for
725   --  switch "-o file_name"
726
727   Object_Directory_Seen : Boolean := False;
728   --  Set to True after having scanned the object directory for
729   --  switch "-D obj_dir".
730
731   Object_Directory_Path : String_Access := null;
732   --  The path name of the object directory, set with switch -D
733
734   type Make_Program_Type is (None, Compiler, Binder, Linker);
735
736   Program_Args : Make_Program_Type := None;
737   --  Used to indicate if we are scanning gnatmake, gcc, gnatbind, or gnatbind
738   --  options within the gnatmake command line. Used in Scan_Make_Arg only,
739   --  but must be global since value preserved from one call to another.
740
741   Temporary_Config_File : Boolean := False;
742   --  Set to True when there is a temporary config file used for a project
743   --  file, to avoid displaying the -gnatec switch for a temporary file.
744
745   procedure Add_Switches
746     (The_Package                      : Package_Id;
747      File_Name                        : String;
748      Program                          : Make_Program_Type;
749      Unknown_Switches_To_The_Compiler : Boolean := True;
750      Env                              : in out Prj.Tree.Environment);
751   procedure Add_Switch
752     (S             : String_Access;
753      Program       : Make_Program_Type;
754      Append_Switch : Boolean := True;
755      And_Save      : Boolean := True);
756   procedure Add_Switch
757     (S             : String;
758      Program       : Make_Program_Type;
759      Append_Switch : Boolean := True;
760      And_Save      : Boolean := True);
761   --  Make invokes one of three programs (the compiler, the binder or the
762   --  linker). For the sake of convenience, some program specific switches
763   --  can be passed directly on the gnatmake command line. This procedure
764   --  records these switches so that gnatmake can pass them to the right
765   --  program.  S is the switch to be added at the end of the command line
766   --  for Program if Append_Switch is True. If Append_Switch is False S is
767   --  added at the beginning of the command line.
768
769   procedure Check
770     (Source_File    : File_Name_Type;
771      Is_Main_Source : Boolean;
772      The_Args       : Argument_List;
773      Lib_File       : File_Name_Type;
774      Full_Lib_File  : File_Name_Type;
775      Lib_File_Attr  : access File_Attributes;
776      Read_Only      : Boolean;
777      ALI            : out ALI_Id;
778      O_File         : out File_Name_Type;
779      O_Stamp        : out Time_Stamp_Type);
780   --  Determines whether the library file Lib_File is up-to-date or not. The
781   --  full name (with path information) of the object file corresponding to
782   --  Lib_File is returned in O_File. Its time stamp is saved in O_Stamp.
783   --  ALI is the ALI_Id corresponding to Lib_File. If Lib_File in not
784   --  up-to-date, then the corresponding source file needs to be recompiled.
785   --  In this case ALI = No_ALI_Id.
786   --  Full_Lib_File must be the result of calling Osint.Full_Lib_File_Name on
787   --  Lib_File. Precomputing it saves system calls. Lib_File_Attr is the
788   --  initialized attributes of that file, which is also used to save on
789   --  system calls (it can safely be initialized to Unknown_Attributes).
790
791   procedure Check_Linker_Options
792     (E_Stamp : Time_Stamp_Type;
793      O_File  : out File_Name_Type;
794      O_Stamp : out Time_Stamp_Type);
795   --  Checks all linker options for linker files that are newer
796   --  than E_Stamp. If such objects are found, the youngest object
797   --  is returned in O_File and its stamp in O_Stamp.
798   --
799   --  If no obsolete linker files were found, the first missing
800   --  linker file is returned in O_File and O_Stamp is empty.
801   --  Otherwise O_File is No_File.
802
803   procedure Collect_Arguments
804     (Source_File    : File_Name_Type;
805      Is_Main_Source : Boolean;
806      Args           : Argument_List);
807   --  Collect all arguments for a source to be compiled, including those
808   --  that come from a project file.
809
810   procedure Display (Program : String; Args : Argument_List);
811   --  Displays Program followed by the arguments in Args if variable
812   --  Display_Executed_Programs is set. The lower bound of Args must be 1.
813
814   procedure Report_Compilation_Failed;
815   --  Delete all temporary files and fail graciously
816
817   -----------------
818   --  Mapping files
819   -----------------
820
821   type Temp_Path_Names is array (Positive range <>) of Path_Name_Type;
822   type Temp_Path_Ptr is access Temp_Path_Names;
823
824   type Free_File_Indexes is array (Positive range <>) of Positive;
825   type Free_Indexes_Ptr is access Free_File_Indexes;
826
827   type Project_Compilation_Data is record
828      Mapping_File_Names : Temp_Path_Ptr;
829      --  The name ids of the temporary mapping files used. This is indexed
830      --  on the maximum number of compilation processes we will be spawning
831      --  (-j parameter)
832
833      Last_Mapping_File_Names : Natural;
834      --  Index of the last mapping file created for this project
835
836      Free_Mapping_File_Indexes : Free_Indexes_Ptr;
837      --  Indexes in Mapping_File_Names of the mapping file names that can be
838      --  reused for subsequent compilations.
839
840      Last_Free_Indexes : Natural;
841      --  Number of mapping files that can be reused
842   end record;
843   --  Information necessary when compiling a project
844
845   type Project_Compilation_Access is access Project_Compilation_Data;
846
847   package Project_Compilation_Htable is new Simple_HTable
848     (Header_Num => Prj.Header_Num,
849      Element    => Project_Compilation_Access,
850      No_Element => null,
851      Key        => Project_Id,
852      Hash       => Prj.Hash,
853      Equal      => "=");
854
855   Project_Compilation : Project_Compilation_Htable.Instance;
856
857   Gnatmake_Mapping_File : String_Access := null;
858   --  The path name of a mapping file specified by switch -C=
859
860   procedure Init_Mapping_File
861     (Project    : Project_Id;
862      Data       : in out Project_Compilation_Data;
863      File_Index : in out Natural);
864   --  Create a new temporary mapping file, and fill it with the project file
865   --  mappings, when using project file(s). The out parameter File_Index is
866   --  the index to the name of the file in the array The_Mapping_File_Names.
867
868   -------------------------------------------------
869   -- Subprogram declarations moved from the spec --
870   -------------------------------------------------
871
872   procedure Bind (ALI_File : File_Name_Type; Args : Argument_List);
873   --  Binds ALI_File. Args are the arguments to pass to the binder.
874   --  Args must have a lower bound of 1.
875
876   procedure Display_Commands (Display : Boolean := True);
877   --  The default behavior of Make commands (Compile_Sources, Bind, Link)
878   --  is to display them on stderr. This behavior can be changed repeatedly
879   --  by invoking this procedure.
880
881   --  If a compilation, bind or link failed one of the following 3 exceptions
882   --  is raised. These need to be handled by the calling routines.
883
884   procedure Compile_Sources
885     (Main_Source           : File_Name_Type;
886      Args                  : Argument_List;
887      First_Compiled_File   : out File_Name_Type;
888      Most_Recent_Obj_File  : out File_Name_Type;
889      Most_Recent_Obj_Stamp : out Time_Stamp_Type;
890      Main_Unit             : out Boolean;
891      Compilation_Failures  : out Natural;
892      Main_Index            : Int      := 0;
893      Check_Readonly_Files  : Boolean  := False;
894      Do_Not_Execute        : Boolean  := False;
895      Force_Compilations    : Boolean  := False;
896      Keep_Going            : Boolean  := False;
897      In_Place_Mode         : Boolean  := False;
898      Initialize_ALI_Data   : Boolean  := True;
899      Max_Process           : Positive := 1);
900   --  Compile_Sources will recursively compile all the sources needed by
901   --  Main_Source. Before calling this routine make sure Namet has been
902   --  initialized. This routine can be called repeatedly with different
903   --  Main_Source file as long as all the source (-I flags), library
904   --  (-B flags) and ada library (-A flags) search paths between calls are
905   --  *exactly* the same. The default directory must also be the same.
906   --
907   --    Args contains the arguments to use during the compilations.
908   --    The lower bound of Args must be 1.
909   --
910   --    First_Compiled_File is set to the name of the first file that is
911   --    compiled or that needs to be compiled. This is set to No_Name if no
912   --    compilations were needed.
913   --
914   --    Most_Recent_Obj_File is set to the full name of the most recent
915   --    object file found when no compilations are needed, that is when
916   --    First_Compiled_File is set to No_Name. When First_Compiled_File
917   --    is set then Most_Recent_Obj_File is set to No_Name.
918   --
919   --    Most_Recent_Obj_Stamp is the time stamp of Most_Recent_Obj_File.
920   --
921   --    Main_Unit is set to True if Main_Source can be a main unit.
922   --    If Do_Not_Execute is False and First_Compiled_File /= No_Name
923   --    the value of Main_Unit is always False.
924   --    Is this used any more??? It is certainly not used by gnatmake???
925   --
926   --    Compilation_Failures is a count of compilation failures. This count
927   --    is used to extract compilation failure reports with Extract_Failure.
928   --
929   --    Main_Index, when not zero, is the index of the main unit in source
930   --    file Main_Source which is a multi-unit source.
931   --    Zero indicates that Main_Source is a single unit source file.
932   --
933   --    Check_Readonly_Files set it to True to compile source files
934   --    which library files are read-only. When compiling GNAT predefined
935   --    files the "-gnatg" flag is used.
936   --
937   --    Do_Not_Execute set it to True to find out the first source that
938   --    needs to be recompiled, but without recompiling it. This file is
939   --    saved in First_Compiled_File.
940   --
941   --    Force_Compilations forces all compilations no matter what but
942   --    recompiles read-only files only if Check_Readonly_Files
943   --    is set.
944   --
945   --    Keep_Going when True keep compiling even in the presence of
946   --    compilation errors.
947   --
948   --    In_Place_Mode when True save library/object files in their object
949   --    directory if they already exist; otherwise, in the source directory.
950   --
951   --    Initialize_ALI_Data set it to True when you want to initialize ALI
952   --    data-structures. This is what you should do most of the time.
953   --    (especially the first time around when you call this routine).
954   --    This parameter is set to False to preserve previously recorded
955   --    ALI file data.
956   --
957   --    Max_Process is the maximum number of processes that should be spawned
958   --    to carry out compilations.
959   --
960   --  Flags in Package Opt Affecting Compile_Sources
961   --  -----------------------------------------------
962   --
963   --    Check_Object_Consistency set it to False to omit all consistency
964   --      checks between an .ali file and its corresponding object file.
965   --      When this flag is set to true, every time an .ali is read,
966   --      package Osint checks that the corresponding object file
967   --      exists and is more recent than the .ali.
968   --
969   --  Use of Name Table Info
970   --  ----------------------
971   --
972   --  All file names manipulated by Compile_Sources are entered into the
973   --  Names table. The Byte field of a source file is used to mark it.
974   --
975   --  Calling Compile_Sources Several Times
976   --  -------------------------------------
977   --
978   --  Upon return from Compile_Sources all the ALI data structures are left
979   --  intact for further browsing. HOWEVER upon entry to this routine ALI
980   --  data structures are re-initialized if parameter Initialize_ALI_Data
981   --  above is set to true. Typically this is what you want the first time
982   --  you call Compile_Sources. You should not load an ali file, call this
983   --  routine with flag Initialize_ALI_Data set to True and then expect
984   --  that ALI information to be around after the call. Note that the first
985   --  time you call Compile_Sources you better set Initialize_ALI_Data to
986   --  True unless you have called Initialize_ALI yourself.
987   --
988   --  Compile_Sources ALGORITHM : Compile_Sources (Main_Source)
989   --  -------------------------
990   --
991   --  1. Insert Main_Source in a Queue (Q) and mark it.
992   --
993   --  2. Let unit.adb be the file at the head of the Q. If unit.adb is
994   --     missing but its corresponding ali file is in an Ada library directory
995   --     (see below) then, remove unit.adb from the Q and goto step 4.
996   --     Otherwise, look at the files under the D (dependency) section of
997   --     unit.ali. If unit.ali does not exist or some of the time stamps do
998   --     not match, (re)compile unit.adb.
999   --
1000   --     An Ada library directory is a directory containing Ada specs, ali
1001   --     and object files but no source files for the bodies. An Ada library
1002   --     directory is communicated to gnatmake by means of some switch so that
1003   --     gnatmake can skip the sources whole ali are in that directory.
1004   --     There are two reasons for skipping the sources in this case. Firstly,
1005   --     Ada libraries typically come without full sources but binding and
1006   --     linking against those libraries is still possible. Secondly, it would
1007   --     be very wasteful for gnatmake to systematically check the consistency
1008   --     of every external Ada library used in a program. The binder is
1009   --     already in charge of catching any potential inconsistencies.
1010   --
1011   --  3. Look into the W section of unit.ali and insert into the Q all
1012   --     unmarked source files. Mark all files newly inserted in the Q.
1013   --     Specifically, assuming that the W section looks like
1014   --
1015   --     W types%s               types.adb               types.ali
1016   --     W unchecked_deallocation%s
1017   --     W xref_tab%s            xref_tab.adb            xref_tab.ali
1018   --
1019   --     Then xref_tab.adb and types.adb are inserted in the Q if they are not
1020   --     already marked.
1021   --     Note that there is no file listed under W unchecked_deallocation%s
1022   --     so no generic body should ever be explicitly compiled (unless the
1023   --     Main_Source at the start was a generic body).
1024   --
1025   --  4. Repeat steps 2 and 3 above until the Q is empty
1026   --
1027   --  Note that the above algorithm works because the units withed in
1028   --  subunits are transitively included in the W section (with section) of
1029   --  the main unit. Likewise the withed units in a generic body needed
1030   --  during a compilation are also transitively included in the W section
1031   --  of the originally compiled file.
1032
1033   procedure Globalize (Success : out Boolean);
1034   --  Call the CodePeer globalizer on all the project's object directories,
1035   --  or on the current directory if no projects.
1036
1037   procedure Initialize
1038      (Project_Node_Tree : out Project_Node_Tree_Ref;
1039       Env               : out Prj.Tree.Environment);
1040   --  Performs default and package initialization. Therefore,
1041   --  Compile_Sources can be called by an external unit.
1042
1043   procedure Link
1044     (ALI_File : File_Name_Type;
1045      Args     : Argument_List;
1046      Success  : out Boolean);
1047   --  Links ALI_File. Args are the arguments to pass to the linker.
1048   --  Args must have a lower bound of 1. Success indicates if the link
1049   --  succeeded or not.
1050
1051   procedure Scan_Make_Arg
1052     (Env               : in out Prj.Tree.Environment;
1053      Argv              : String;
1054      And_Save          : Boolean);
1055   --  Scan make arguments. Argv is a single argument to be processed.
1056   --  Project_Node_Tree will be used to initialize external references. It
1057   --  must have been initialized.
1058
1059   -------------------
1060   -- Add_Arguments --
1061   -------------------
1062
1063   procedure Add_Arguments (Args : Argument_List) is
1064   begin
1065      if Arguments = null then
1066         Arguments := new Argument_List (1 .. Args'Length + 10);
1067
1068      else
1069         while Last_Argument + Args'Length > Arguments'Last loop
1070            declare
1071               New_Arguments : constant Argument_List_Access :=
1072                                 new Argument_List (1 .. Arguments'Last * 2);
1073            begin
1074               New_Arguments (1 .. Last_Argument) :=
1075                 Arguments (1 .. Last_Argument);
1076               Arguments := New_Arguments;
1077            end;
1078         end loop;
1079      end if;
1080
1081      Arguments (Last_Argument + 1 .. Last_Argument + Args'Length) := Args;
1082      Last_Argument := Last_Argument + Args'Length;
1083   end Add_Arguments;
1084
1085--     --------------------
1086--     -- Add_Dependency --
1087--     --------------------
1088--
1089--     procedure Add_Dependency (S : File_Name_Type; On : File_Name_Type) is
1090--     begin
1091--        Dependencies.Increment_Last;
1092--        Dependencies.Table (Dependencies.Last) := (S, On);
1093--     end Add_Dependency;
1094
1095   ----------------------------
1096   -- Add_Library_Search_Dir --
1097   ----------------------------
1098
1099   procedure Add_Library_Search_Dir
1100     (Path            : String;
1101      On_Command_Line : Boolean)
1102   is
1103   begin
1104      if On_Command_Line then
1105         Add_Lib_Search_Dir (Normalize_Pathname (Path));
1106
1107      else
1108         Get_Name_String (Main_Project.Directory.Display_Name);
1109         Add_Lib_Search_Dir
1110           (Normalize_Pathname (Path, Name_Buffer (1 .. Name_Len)));
1111      end if;
1112   end Add_Library_Search_Dir;
1113
1114   --------------------
1115   -- Add_Object_Dir --
1116   --------------------
1117
1118   procedure Add_Object_Dir (N : String) is
1119   begin
1120      Add_Lib_Search_Dir (N);
1121
1122      if Verbose_Mode then
1123         Write_Str ("Adding object directory """);
1124         Write_Str (N);
1125         Write_Str (""".");
1126         Write_Eol;
1127      end if;
1128   end Add_Object_Dir;
1129
1130   --------------------
1131   -- Add_Source_Dir --
1132   --------------------
1133
1134   procedure Add_Source_Dir (N : String) is
1135   begin
1136      Add_Src_Search_Dir (N);
1137
1138      if Verbose_Mode then
1139         Write_Str ("Adding source directory """);
1140         Write_Str (N);
1141         Write_Str (""".");
1142         Write_Eol;
1143      end if;
1144   end Add_Source_Dir;
1145
1146   ---------------------------
1147   -- Add_Source_Search_Dir --
1148   ---------------------------
1149
1150   procedure Add_Source_Search_Dir
1151     (Path            : String;
1152      On_Command_Line : Boolean)
1153   is
1154   begin
1155      if On_Command_Line then
1156         Add_Src_Search_Dir (Normalize_Pathname (Path));
1157
1158      else
1159         Get_Name_String (Main_Project.Directory.Display_Name);
1160         Add_Src_Search_Dir
1161           (Normalize_Pathname (Path, Name_Buffer (1 .. Name_Len)));
1162      end if;
1163   end Add_Source_Search_Dir;
1164
1165   ----------------
1166   -- Add_Switch --
1167   ----------------
1168
1169   procedure Add_Switch
1170     (S             : String_Access;
1171      Program       : Make_Program_Type;
1172      Append_Switch : Boolean := True;
1173      And_Save      : Boolean := True)
1174   is
1175      generic
1176         with package T is new Table.Table (<>);
1177      procedure Generic_Position (New_Position : out Integer);
1178      --  Generic procedure that chooses a position for S in T at the
1179      --  beginning or the end, depending on the boolean Append_Switch.
1180      --  Calling this procedure may expand the table.
1181
1182      ----------------------
1183      -- Generic_Position --
1184      ----------------------
1185
1186      procedure Generic_Position (New_Position : out Integer) is
1187      begin
1188         T.Increment_Last;
1189
1190         if Append_Switch then
1191            New_Position := Integer (T.Last);
1192         else
1193            for J in reverse T.Table_Index_Type'Succ (T.First) .. T.Last loop
1194               T.Table (J) := T.Table (T.Table_Index_Type'Pred (J));
1195            end loop;
1196
1197            New_Position := Integer (T.First);
1198         end if;
1199      end Generic_Position;
1200
1201      procedure Gcc_Switches_Pos    is new Generic_Position (Gcc_Switches);
1202      procedure Binder_Switches_Pos is new Generic_Position (Binder_Switches);
1203      procedure Linker_Switches_Pos is new Generic_Position (Linker_Switches);
1204
1205      procedure Saved_Gcc_Switches_Pos is new
1206        Generic_Position (Saved_Gcc_Switches);
1207
1208      procedure Saved_Binder_Switches_Pos is new
1209        Generic_Position (Saved_Binder_Switches);
1210
1211      procedure Saved_Linker_Switches_Pos is new
1212        Generic_Position (Saved_Linker_Switches);
1213
1214      New_Position : Integer;
1215
1216   --  Start of processing for Add_Switch
1217
1218   begin
1219      if And_Save then
1220         case Program is
1221            when Compiler =>
1222               Saved_Gcc_Switches_Pos (New_Position);
1223               Saved_Gcc_Switches.Table (New_Position) := S;
1224
1225            when Binder   =>
1226               Saved_Binder_Switches_Pos (New_Position);
1227               Saved_Binder_Switches.Table (New_Position) := S;
1228
1229            when Linker   =>
1230               Saved_Linker_Switches_Pos (New_Position);
1231               Saved_Linker_Switches.Table (New_Position) := S;
1232
1233            when None =>
1234               raise Program_Error;
1235         end case;
1236
1237      else
1238         case Program is
1239            when Compiler =>
1240               Gcc_Switches_Pos (New_Position);
1241               Gcc_Switches.Table (New_Position) := S;
1242
1243            when Binder   =>
1244               Binder_Switches_Pos (New_Position);
1245               Binder_Switches.Table (New_Position) := S;
1246
1247            when Linker   =>
1248               Linker_Switches_Pos (New_Position);
1249               Linker_Switches.Table (New_Position) := S;
1250
1251            when None =>
1252               raise Program_Error;
1253         end case;
1254      end if;
1255   end Add_Switch;
1256
1257   procedure Add_Switch
1258     (S             : String;
1259      Program       : Make_Program_Type;
1260      Append_Switch : Boolean := True;
1261      And_Save      : Boolean := True)
1262   is
1263   begin
1264      Add_Switch (S             => new String'(S),
1265                  Program       => Program,
1266                  Append_Switch => Append_Switch,
1267                  And_Save      => And_Save);
1268   end Add_Switch;
1269
1270   ------------------
1271   -- Add_Switches --
1272   ------------------
1273
1274   procedure Add_Switches
1275     (The_Package                      : Package_Id;
1276      File_Name                        : String;
1277      Program                          : Make_Program_Type;
1278      Unknown_Switches_To_The_Compiler : Boolean := True;
1279      Env                              : in out Prj.Tree.Environment)
1280   is
1281      Switches    : Variable_Value;
1282      Switch_List : String_List_Id;
1283      Element     : String_Element;
1284
1285   begin
1286      Switch_May_Be_Passed_To_The_Compiler :=
1287        Unknown_Switches_To_The_Compiler;
1288
1289      if File_Name'Length > 0 then
1290         Name_Len := 0;
1291         Add_Str_To_Name_Buffer (File_Name);
1292         Switches :=
1293           Switches_Of
1294             (Source_File => Name_Find,
1295              Project     => Main_Project,
1296              In_Package  => The_Package,
1297              Allow_ALI   => Program = Binder or else Program = Linker);
1298
1299         if Switches.Kind = List then
1300            Program_Args := Program;
1301
1302            Switch_List := Switches.Values;
1303            while Switch_List /= Nil_String loop
1304               Element :=
1305                 Project_Tree.Shared.String_Elements.Table (Switch_List);
1306               Get_Name_String (Element.Value);
1307
1308               if Name_Len > 0 then
1309                  declare
1310                     Argv : constant String := Name_Buffer (1 .. Name_Len);
1311                     --  We need a copy, because Name_Buffer may be modified
1312
1313                  begin
1314                     if Verbose_Mode then
1315                        Write_Str ("   Adding ");
1316                        Write_Line (Argv);
1317                     end if;
1318
1319                     Scan_Make_Arg (Env, Argv, And_Save => False);
1320
1321                     if not Gnatmake_Switch_Found
1322                       and then not Switch_May_Be_Passed_To_The_Compiler
1323                     then
1324                        Errutil.Error_Msg
1325                          ('"' & Argv &
1326                           """ is not a gnatmake switch. Consider moving "
1327                           & "it to Global_Compilation_Switches.",
1328                           Element.Location);
1329                        Make_Failed ("*** illegal switch """ & Argv & """");
1330                     end if;
1331                  end;
1332               end if;
1333
1334               Switch_List := Element.Next;
1335            end loop;
1336         end if;
1337      end if;
1338   end Add_Switches;
1339
1340   ----------
1341   -- Bind --
1342   ----------
1343
1344   procedure Bind (ALI_File : File_Name_Type; Args : Argument_List) is
1345      Bind_Args : Argument_List (1 .. Args'Last + 2);
1346      Bind_Last : Integer;
1347      Success   : Boolean;
1348
1349   begin
1350      pragma Assert (Args'First = 1);
1351
1352      --  Optimize the simple case where the gnatbind command line looks like
1353      --     gnatbind -aO. -I- file.ali
1354      --  into
1355      --     gnatbind file.adb
1356
1357      if Args'Length = 2
1358        and then Args (Args'First).all = "-aO" & Normalized_CWD
1359        and then Args (Args'Last).all = "-I-"
1360        and then ALI_File = Strip_Directory (ALI_File)
1361      then
1362         Bind_Last := Args'First - 1;
1363
1364      else
1365         Bind_Last := Args'Last;
1366         Bind_Args (Args'Range) := Args;
1367      end if;
1368
1369      --  It is completely pointless to re-check source file time stamps. This
1370      --  has been done already by gnatmake
1371
1372      Bind_Last := Bind_Last + 1;
1373      Bind_Args (Bind_Last) := Do_Not_Check_Flag;
1374
1375      Get_Name_String (ALI_File);
1376
1377      Bind_Last := Bind_Last + 1;
1378      Bind_Args (Bind_Last) := new String'(Name_Buffer (1 .. Name_Len));
1379
1380      GNAT.OS_Lib.Normalize_Arguments (Bind_Args (Args'First .. Bind_Last));
1381
1382      Display (Gnatbind.all, Bind_Args (Args'First .. Bind_Last));
1383
1384      if Gnatbind_Path = null then
1385         Make_Failed ("error, unable to locate " & Gnatbind.all);
1386      end if;
1387
1388      GNAT.OS_Lib.Spawn
1389        (Gnatbind_Path.all, Bind_Args (Args'First .. Bind_Last), Success);
1390
1391      if not Success then
1392         Make_Failed ("*** bind failed.");
1393      end if;
1394   end Bind;
1395
1396   --------------------------------
1397   -- Change_To_Object_Directory --
1398   --------------------------------
1399
1400   procedure Change_To_Object_Directory (Project : Project_Id) is
1401      Object_Directory : Path_Name_Type;
1402
1403   begin
1404      pragma Assert (Project /= No_Project);
1405
1406      --  Nothing to do if the current working directory is already the correct
1407      --  object directory.
1408
1409      if Project_Of_Current_Object_Directory /= Project then
1410         Project_Of_Current_Object_Directory := Project;
1411         Object_Directory := Project.Object_Directory.Display_Name;
1412
1413         --  Set the working directory to the object directory of the actual
1414         --  project.
1415
1416         if Verbose_Mode then
1417            Write_Str  ("Changing to object directory of """);
1418            Write_Name (Project.Display_Name);
1419            Write_Str  (""": """);
1420            Write_Name (Object_Directory);
1421            Write_Line ("""");
1422         end if;
1423
1424         Change_Dir (Get_Name_String (Object_Directory));
1425      end if;
1426
1427   exception
1428      --  Fail if unable to change to the object directory
1429
1430      when Directory_Error =>
1431         Make_Failed ("unable to change to object directory """ &
1432                      Path_Or_File_Name
1433                        (Project.Object_Directory.Display_Name) &
1434                      """ of project " &
1435                      Get_Name_String (Project.Display_Name));
1436   end Change_To_Object_Directory;
1437
1438   -----------
1439   -- Check --
1440   -----------
1441
1442   procedure Check
1443     (Source_File    : File_Name_Type;
1444      Is_Main_Source : Boolean;
1445      The_Args       : Argument_List;
1446      Lib_File       : File_Name_Type;
1447      Full_Lib_File  : File_Name_Type;
1448      Lib_File_Attr  : access File_Attributes;
1449      Read_Only      : Boolean;
1450      ALI            : out ALI_Id;
1451      O_File         : out File_Name_Type;
1452      O_Stamp        : out Time_Stamp_Type)
1453   is
1454      function First_New_Spec (A : ALI_Id) return File_Name_Type;
1455      --  Looks in the with table entries of A and returns the spec file name
1456      --  of the first withed unit (subprogram) for which no spec existed when
1457      --  A was generated but for which there exists one now, implying that A
1458      --  is now obsolete. If no such unit is found No_File is returned.
1459      --  Otherwise the spec file name of the unit is returned.
1460      --
1461      --  **WARNING** in the event of Uname format modifications, one *MUST*
1462      --  make sure this function is also updated.
1463      --
1464      --  Note: This function should really be in ali.adb and use Uname
1465      --  services, but this causes the whole compiler to be dragged along
1466      --  for gnatbind and gnatmake.
1467
1468      --------------------
1469      -- First_New_Spec --
1470      --------------------
1471
1472      function First_New_Spec (A : ALI_Id) return File_Name_Type is
1473         Spec_File_Name : File_Name_Type := No_File;
1474
1475         function New_Spec (Uname : Unit_Name_Type) return Boolean;
1476         --  Uname is the name of the spec or body of some ada unit. This
1477         --  function returns True if the Uname is the name of a body which has
1478         --  a spec not mentioned in ALI file A. If True is returned
1479         --  Spec_File_Name above is set to the name of this spec file.
1480
1481         --------------
1482         -- New_Spec --
1483         --------------
1484
1485         function New_Spec (Uname : Unit_Name_Type) return Boolean is
1486            Spec_Name : Unit_Name_Type;
1487            File_Name : File_Name_Type;
1488
1489         begin
1490            --  Test whether Uname is the name of a body unit (i.e. ends
1491            --  with %b).
1492
1493            Get_Name_String (Uname);
1494            pragma
1495              Assert (Name_Len > 2 and then Name_Buffer (Name_Len - 1) = '%');
1496
1497            if Name_Buffer (Name_Len) /= 'b' then
1498               return False;
1499            end if;
1500
1501            --  Convert unit name into spec name
1502
1503            --  ??? this code seems dubious in presence of pragma
1504            --  Source_File_Name since there is no more direct relationship
1505            --  between unit name and file name.
1506
1507            --  ??? Further, what about alternative subunit naming
1508
1509            Name_Buffer (Name_Len) := 's';
1510            Spec_Name := Name_Find;
1511            File_Name := Get_File_Name (Spec_Name, Subunit => False);
1512
1513            --  Look if File_Name is mentioned in A's sdep list.
1514            --  If not look if the file exists. If it does return True.
1515
1516            for D in
1517              ALIs.Table (A).First_Sdep .. ALIs.Table (A).Last_Sdep
1518            loop
1519               if Sdep.Table (D).Sfile = File_Name then
1520                  return False;
1521               end if;
1522            end loop;
1523
1524            if Full_Source_Name (File_Name) /= No_File then
1525               Spec_File_Name := File_Name;
1526               return True;
1527            end if;
1528
1529            return False;
1530         end New_Spec;
1531
1532      --  Start of processing for First_New_Spec
1533
1534      begin
1535         U_Chk : for U in
1536           ALIs.Table (A).First_Unit .. ALIs.Table (A).Last_Unit
1537         loop
1538            exit U_Chk when Units.Table (U).Utype = Is_Body_Only
1539               and then New_Spec (Units.Table (U).Uname);
1540
1541            for W in Units.Table (U).First_With
1542                       ..
1543                     Units.Table (U).Last_With
1544            loop
1545               exit U_Chk when
1546                 Withs.Table (W).Afile /= No_File
1547                 and then New_Spec (Withs.Table (W).Uname);
1548            end loop;
1549         end loop U_Chk;
1550
1551         return Spec_File_Name;
1552      end First_New_Spec;
1553
1554      ---------------------------------
1555      -- Data declarations for Check --
1556      ---------------------------------
1557
1558      Full_Obj_File : File_Name_Type;
1559      --  Full name of the object file corresponding to Lib_File
1560
1561      Lib_Stamp : Time_Stamp_Type;
1562      --  Time stamp of the current ada library file
1563
1564      Obj_Stamp : Time_Stamp_Type;
1565      --  Time stamp of the current object file
1566
1567      Modified_Source : File_Name_Type;
1568      --  The first source in Lib_File whose current time stamp differs from
1569      --  that stored in Lib_File.
1570
1571      New_Spec : File_Name_Type;
1572      --  If Lib_File contains in its W (with) section a body (for a
1573      --  subprogram) for which there exists a spec, and the spec did not
1574      --  appear in the Sdep section of Lib_File, New_Spec contains the file
1575      --  name of this new spec.
1576
1577      Source_Name : File_Name_Type;
1578      Text        : Text_Buffer_Ptr;
1579
1580      Prev_Switch : String_Access;
1581      --  Previous switch processed
1582
1583      Arg : Arg_Id := Arg_Id'First;
1584      --  Current index in Args.Table for a given unit (init to stop warning)
1585
1586      Switch_Found : Boolean;
1587      --  True if a given switch has been found
1588
1589      ALI_Project : Project_Id;
1590      --  If the ALI file is in the object directory of a project, this is
1591      --  the project id.
1592
1593   --  Start of processing for Check
1594
1595   begin
1596      pragma Assert (Lib_File /= No_File);
1597
1598      --  If ALI file is read-only, temporarily set Check_Object_Consistency to
1599      --  False. We don't care if the object file is not there (presumably a
1600      --  library will be used for linking.)
1601
1602      if Read_Only then
1603         declare
1604            Saved_Check_Object_Consistency : constant Boolean :=
1605                                               Check_Object_Consistency;
1606         begin
1607            Check_Object_Consistency := False;
1608            Text := Read_Library_Info_From_Full (Full_Lib_File, Lib_File_Attr);
1609            Check_Object_Consistency := Saved_Check_Object_Consistency;
1610         end;
1611
1612      else
1613         Text := Read_Library_Info_From_Full (Full_Lib_File, Lib_File_Attr);
1614      end if;
1615
1616      Full_Obj_File := Full_Object_File_Name;
1617      Lib_Stamp     := Current_Library_File_Stamp;
1618      Obj_Stamp     := Current_Object_File_Stamp;
1619
1620      if Full_Lib_File = No_File then
1621         Verbose_Msg
1622           (Lib_File,
1623            "being checked ...",
1624            Prefix => "  ",
1625            Minimum_Verbosity => Opt.Medium);
1626      else
1627         Verbose_Msg
1628           (Full_Lib_File,
1629            "being checked ...",
1630            Prefix => "  ",
1631            Minimum_Verbosity => Opt.Medium);
1632      end if;
1633
1634      ALI     := No_ALI_Id;
1635      O_File  := Full_Obj_File;
1636      O_Stamp := Obj_Stamp;
1637
1638      if Text = null then
1639         if Full_Lib_File = No_File then
1640            Verbose_Msg (Lib_File, "missing.");
1641
1642         elsif Obj_Stamp (Obj_Stamp'First) = ' ' then
1643            Verbose_Msg (Full_Obj_File, "missing.");
1644
1645         else
1646            Verbose_Msg
1647              (Full_Lib_File, "(" & String (Lib_Stamp) & ") newer than",
1648               Full_Obj_File, "(" & String (Obj_Stamp) & ")");
1649         end if;
1650
1651      else
1652         ALI := Scan_ALI (Lib_File, Text, Ignore_ED => False, Err => True);
1653         Free (Text);
1654
1655         if ALI = No_ALI_Id then
1656            Verbose_Msg (Full_Lib_File, "incorrectly formatted ALI file");
1657            return;
1658
1659         elsif ALIs.Table (ALI).Ver (1 .. ALIs.Table (ALI).Ver_Len) /=
1660                 Verbose_Library_Version
1661         then
1662            Verbose_Msg (Full_Lib_File, "compiled with old GNAT version");
1663            ALI := No_ALI_Id;
1664            return;
1665         end if;
1666
1667         --  Don't take ALI file into account if it was generated with errors
1668
1669         if ALIs.Table (ALI).Compile_Errors then
1670            Verbose_Msg (Full_Lib_File, "had errors, must be recompiled");
1671            ALI := No_ALI_Id;
1672            return;
1673         end if;
1674
1675         --  Don't take ALI file into account if no object was generated
1676
1677         if Operating_Mode /= Check_Semantics
1678           and then ALIs.Table (ALI).No_Object
1679         then
1680            Verbose_Msg (Full_Lib_File, "has no corresponding object");
1681            ALI := No_ALI_Id;
1682            return;
1683         end if;
1684
1685         --  When compiling with -gnatc, don't take ALI file into account if
1686         --  it has not been generated for the current source, for example if
1687         --  it has been generated for the spec, but we are compiling the body.
1688
1689         if Operating_Mode = Check_Semantics then
1690            declare
1691               File_Name : String  := Get_Name_String (Source_File);
1692               OK        : Boolean := False;
1693
1694            begin
1695               --  In the ALI file, the source file names are in canonical case
1696
1697               Canonical_Case_File_Name (File_Name);
1698
1699               for U in ALIs.Table (ALI).First_Unit ..
1700                 ALIs.Table (ALI).Last_Unit
1701               loop
1702                  OK := Get_Name_String (Units.Table (U).Sfile) = File_Name;
1703                  exit when OK;
1704               end loop;
1705
1706               if not OK then
1707                  Verbose_Msg
1708                    (Full_Lib_File, "not generated for the same source");
1709                  ALI := No_ALI_Id;
1710                  return;
1711               end if;
1712            end;
1713         end if;
1714
1715         --  Check for matching compiler switches if needed
1716
1717         if Check_Switches then
1718
1719            --  First, collect all the switches
1720
1721            Collect_Arguments (Source_File, Is_Main_Source, The_Args);
1722            Prev_Switch := Dummy_Switch;
1723            Get_Name_String (ALIs.Table (ALI).Sfile);
1724            Switches_To_Check.Set_Last (0);
1725
1726            for J in 1 .. Last_Argument loop
1727
1728               --  Skip non switches -c, -I and -o switches
1729
1730               if Arguments (J) (1) = '-'
1731                 and then Arguments (J) (2) /= 'c'
1732                 and then Arguments (J) (2) /= 'o'
1733                 and then Arguments (J) (2) /= 'I'
1734               then
1735                  Normalize_Compiler_Switches
1736                    (Arguments (J).all,
1737                     Normalized_Switches,
1738                     Last_Norm_Switch);
1739
1740                  for K in 1 .. Last_Norm_Switch loop
1741                     Switches_To_Check.Increment_Last;
1742                     Switches_To_Check.Table (Switches_To_Check.Last) :=
1743                       Normalized_Switches (K);
1744                  end loop;
1745               end if;
1746            end loop;
1747
1748            for J in 1 .. Switches_To_Check.Last loop
1749
1750               --  Comparing switches is delicate because gcc reorders a number
1751               --  of switches, according to lang-specs.h, but gnatmake doesn't
1752               --  have sufficient knowledge to perform the same reordering.
1753               --  Instead, we ignore orders between different "first letter"
1754               --  switches, but keep orders between same switches, e.g -O -O2
1755               --  is different than -O2 -O, but -g -O is equivalent to -O -g.
1756
1757               if Switches_To_Check.Table (J) (2) /= Prev_Switch (2) or else
1758                   (Prev_Switch'Length >= 6 and then
1759                    Prev_Switch (2 .. 5) = "gnat" and then
1760                    Switches_To_Check.Table (J)'Length >= 6 and then
1761                    Switches_To_Check.Table (J) (2 .. 5) = "gnat" and then
1762                    Prev_Switch (6) /= Switches_To_Check.Table (J) (6))
1763               then
1764                  Prev_Switch := Switches_To_Check.Table (J);
1765                  Arg :=
1766                    Units.Table (ALIs.Table (ALI).First_Unit).First_Arg;
1767               end if;
1768
1769               Switch_Found := False;
1770
1771               for K in Arg ..
1772                 Units.Table (ALIs.Table (ALI).First_Unit).Last_Arg
1773               loop
1774                  if
1775                    Switches_To_Check.Table (J).all = Args.Table (K).all
1776                  then
1777                     Arg := K + 1;
1778                     Switch_Found := True;
1779                     exit;
1780                  end if;
1781               end loop;
1782
1783               if not Switch_Found then
1784                  if Verbose_Mode then
1785                     Verbose_Msg (ALIs.Table (ALI).Sfile,
1786                                  "switch mismatch """ &
1787                                  Switches_To_Check.Table (J).all & '"');
1788                  end if;
1789
1790                  ALI := No_ALI_Id;
1791                  return;
1792               end if;
1793            end loop;
1794
1795            if Switches_To_Check.Last /=
1796              Integer (Units.Table (ALIs.Table (ALI).First_Unit).Last_Arg -
1797                       Units.Table (ALIs.Table (ALI).First_Unit).First_Arg + 1)
1798            then
1799               if Verbose_Mode then
1800                  Verbose_Msg (ALIs.Table (ALI).Sfile,
1801                               "different number of switches");
1802
1803                  for K in Units.Table (ALIs.Table (ALI).First_Unit).First_Arg
1804                    .. Units.Table (ALIs.Table (ALI).First_Unit).Last_Arg
1805                  loop
1806                     Write_Str (Args.Table (K).all);
1807                     Write_Char (' ');
1808                  end loop;
1809
1810                  Write_Eol;
1811
1812                  for J in 1 .. Switches_To_Check.Last loop
1813                     Write_Str (Switches_To_Check.Table (J).all);
1814                     Write_Char (' ');
1815                  end loop;
1816
1817                  Write_Eol;
1818               end if;
1819
1820               ALI := No_ALI_Id;
1821               return;
1822            end if;
1823         end if;
1824
1825         --  Get the source files and their message digests. Note that some
1826         --  sources may be missing if ALI is out-of-date.
1827
1828         Set_Source_Table (ALI);
1829
1830         Modified_Source := Time_Stamp_Mismatch (ALI, Read_Only);
1831
1832         --  To avoid using too much memory when switch -m is used, free the
1833         --  memory allocated for the source file when computing the checksum.
1834
1835         if Minimal_Recompilation then
1836            Sinput.P.Clear_Source_File_Table;
1837         end if;
1838
1839         if Modified_Source /= No_File then
1840            ALI := No_ALI_Id;
1841
1842            if Verbose_Mode then
1843               Source_Name := Full_Source_Name (Modified_Source);
1844
1845               if Source_Name /= No_File then
1846                  Verbose_Msg (Source_Name, "time stamp mismatch");
1847               else
1848                  Verbose_Msg (Modified_Source, "missing");
1849               end if;
1850            end if;
1851
1852         else
1853            New_Spec := First_New_Spec (ALI);
1854
1855            if New_Spec /= No_File then
1856               ALI := No_ALI_Id;
1857
1858               if Verbose_Mode then
1859                  Source_Name := Full_Source_Name (New_Spec);
1860
1861                  if Source_Name /= No_File then
1862                     Verbose_Msg (Source_Name, "new spec");
1863                  else
1864                     Verbose_Msg (New_Spec, "old spec missing");
1865                  end if;
1866               end if;
1867
1868            elsif not Read_Only and then Main_Project /= No_Project then
1869               declare
1870                  Uname : constant Name_Id :=
1871                            Check_Source_Info_In_ALI (ALI, Project_Tree);
1872
1873                  Udata : Prj.Unit_Index;
1874
1875               begin
1876                  if Uname = No_Name then
1877                     ALI := No_ALI_Id;
1878                     return;
1879                  end if;
1880
1881                  --  Check that ALI file is in the correct object directory.
1882                  --  If it is in the object directory of a project that is
1883                  --  extended and it depends on a source that is in one of
1884                  --  its extending projects, then the ALI file is not in the
1885                  --  correct object directory.
1886
1887                  --  First, find the project of this ALI file. As there may be
1888                  --  several projects with the same object directory, we first
1889                  --  need to find the project of the source.
1890
1891                  ALI_Project := No_Project;
1892
1893                  Udata := Units_Htable.Get (Project_Tree.Units_HT, Uname);
1894
1895                  if Udata /= No_Unit_Index then
1896                     if Udata.File_Names (Impl) /= null
1897                       and then Udata.File_Names (Impl).File = Source_File
1898                     then
1899                        ALI_Project := Udata.File_Names (Impl).Project;
1900
1901                     elsif Udata.File_Names (Spec) /= null
1902                       and then Udata.File_Names (Spec).File = Source_File
1903                     then
1904                        ALI_Project := Udata.File_Names (Spec).Project;
1905                     end if;
1906                  end if;
1907               end;
1908
1909               if ALI_Project = No_Project then
1910                  return;
1911               end if;
1912
1913               declare
1914                  Obj_Dir : Path_Name_Type;
1915                  Res_Obj_Dir : constant String :=
1916                                  Normalize_Pathname
1917                                    (Dir_Name
1918                                      (Get_Name_String (Full_Lib_File)),
1919                                     Resolve_Links  =>
1920                                       Opt.Follow_Links_For_Dirs,
1921                                     Case_Sensitive => False);
1922
1923               begin
1924                  Name_Len := 0;
1925                  Add_Str_To_Name_Buffer (Res_Obj_Dir);
1926
1927                  if not Is_Directory_Separator (Name_Buffer (Name_Len)) then
1928                     Add_Char_To_Name_Buffer (Directory_Separator);
1929                  end if;
1930
1931                  Obj_Dir := Name_Find;
1932
1933                  while ALI_Project /= No_Project
1934                    and then Obj_Dir /= ALI_Project.Object_Directory.Name
1935                  loop
1936                     ALI_Project := ALI_Project.Extended_By;
1937                  end loop;
1938               end;
1939
1940               if ALI_Project = No_Project then
1941                  ALI := No_ALI_Id;
1942
1943                  Verbose_Msg (Lib_File, " wrong object directory");
1944                  return;
1945               end if;
1946
1947               --  If the ALI project is not extended, then it must be in
1948               --  the correct object directory.
1949
1950               if ALI_Project.Extended_By = No_Project then
1951                  return;
1952               end if;
1953
1954               --  Count the extending projects
1955
1956               declare
1957                  Num_Ext : Natural;
1958                  Proj    : Project_Id;
1959
1960               begin
1961                  Num_Ext := 0;
1962                  Proj := ALI_Project;
1963                  loop
1964                     Proj := Proj.Extended_By;
1965                     exit when Proj = No_Project;
1966                     Num_Ext := Num_Ext + 1;
1967                  end loop;
1968
1969                  --  Make a list of the extending projects
1970
1971                  declare
1972                     Projects : array (1 .. Num_Ext) of Project_Id;
1973                     Dep      : Sdep_Record;
1974                     OK       : Boolean := True;
1975                     UID      : Unit_Index;
1976
1977                  begin
1978                     Proj := ALI_Project;
1979                     for J in Projects'Range loop
1980                        Proj := Proj.Extended_By;
1981                        Projects (J) := Proj;
1982                     end loop;
1983
1984                     --  Now check if any of the dependant sources are in any
1985                     --  of these extending projects.
1986
1987                     D_Chk :
1988                     for D in ALIs.Table (ALI).First_Sdep ..
1989                              ALIs.Table (ALI).Last_Sdep
1990                     loop
1991                        Dep := Sdep.Table (D);
1992                        UID  := Units_Htable.Get_First (Project_Tree.Units_HT);
1993                        Proj := No_Project;
1994
1995                        Unit_Loop :
1996                        while UID /= null loop
1997                           if UID.File_Names (Impl) /= null
1998                             and then UID.File_Names (Impl).File = Dep.Sfile
1999                           then
2000                              Proj := UID.File_Names (Impl).Project;
2001
2002                           elsif UID.File_Names (Spec) /= null
2003                             and then UID.File_Names (Spec).File = Dep.Sfile
2004                           then
2005                              Proj := UID.File_Names (Spec).Project;
2006                           end if;
2007
2008                           --  If a source is in a project, check if it is one
2009                           --  in the list.
2010
2011                           if Proj /= No_Project then
2012                              for J in Projects'Range loop
2013                                 if Proj = Projects (J) then
2014                                    OK := False;
2015                                    exit D_Chk;
2016                                 end if;
2017                              end loop;
2018
2019                              exit Unit_Loop;
2020                           end if;
2021
2022                           UID :=
2023                             Units_Htable.Get_Next (Project_Tree.Units_HT);
2024                        end loop Unit_Loop;
2025                     end loop D_Chk;
2026
2027                     --  If one of the dependent sources is in one project of
2028                     --  the list, then we must recompile.
2029
2030                     if not OK then
2031                        ALI := No_ALI_Id;
2032                        Verbose_Msg (Lib_File, " wrong object directory");
2033                     end if;
2034                  end;
2035               end;
2036            end if;
2037         end if;
2038      end if;
2039   end Check;
2040
2041   ------------------------
2042   -- Check_For_S_Switch --
2043   ------------------------
2044
2045   procedure Check_For_S_Switch is
2046   begin
2047      --  By default, we generate an object file
2048
2049      Output_Is_Object := True;
2050
2051      for Arg in 1 .. Last_Argument loop
2052         if Arguments (Arg).all = "-S" then
2053            Output_Is_Object := False;
2054
2055         elsif Arguments (Arg).all = "-c" then
2056            Output_Is_Object := True;
2057         end if;
2058      end loop;
2059   end Check_For_S_Switch;
2060
2061   --------------------------
2062   -- Check_Linker_Options --
2063   --------------------------
2064
2065   procedure Check_Linker_Options
2066     (E_Stamp   : Time_Stamp_Type;
2067      O_File    : out File_Name_Type;
2068      O_Stamp   : out Time_Stamp_Type)
2069   is
2070      procedure Check_File (File : File_Name_Type);
2071      --  Update O_File and O_Stamp if the given file is younger than E_Stamp
2072      --  and O_Stamp, or if O_File is No_File and File does not exist.
2073
2074      function Get_Library_File (Name : String) return File_Name_Type;
2075      --  Return the full file name including path of a library based
2076      --  on the name specified with the -l linker option, using the
2077      --  Ada object path. Return No_File if no such file can be found.
2078
2079      type Char_Array is array (Natural) of Character;
2080      type Char_Array_Access is access constant Char_Array;
2081
2082      Template : Char_Array_Access;
2083      pragma Import (C, Template, "__gnat_library_template");
2084
2085      ----------------
2086      -- Check_File --
2087      ----------------
2088
2089      procedure Check_File (File : File_Name_Type) is
2090         Stamp : Time_Stamp_Type;
2091         Name  : File_Name_Type := File;
2092
2093      begin
2094         Get_Name_String (Name);
2095
2096         --  Remove any trailing NUL characters
2097
2098         while Name_Len >= Name_Buffer'First
2099           and then Name_Buffer (Name_Len) = NUL
2100         loop
2101            Name_Len := Name_Len - 1;
2102         end loop;
2103
2104         if Name_Len = 0 then
2105            return;
2106
2107         elsif Name_Buffer (1) = '-' then
2108
2109            --  Do not check if File is a switch other than "-l"
2110
2111            if Name_Buffer (2) /= 'l' then
2112               return;
2113            end if;
2114
2115            --  The argument is a library switch, get actual name. It
2116            --  is necessary to make a copy of the relevant part of
2117            --  Name_Buffer as Get_Library_Name uses Name_Buffer as well.
2118
2119            declare
2120               Base_Name : constant String := Name_Buffer (3 .. Name_Len);
2121
2122            begin
2123               Name := Get_Library_File (Base_Name);
2124            end;
2125
2126            if Name = No_File then
2127               return;
2128            end if;
2129         end if;
2130
2131         Stamp := File_Stamp (Name);
2132
2133         --  Find the youngest object file that is younger than the
2134         --  executable. If no such file exist, record the first object
2135         --  file that is not found.
2136
2137         if (O_Stamp < Stamp and then E_Stamp < Stamp)
2138           or else (O_File = No_File and then Stamp (Stamp'First) = ' ')
2139         then
2140            O_Stamp := Stamp;
2141            O_File := Name;
2142
2143            --  Strip the trailing NUL if present
2144
2145            Get_Name_String (O_File);
2146
2147            if Name_Buffer (Name_Len) = NUL then
2148               Name_Len := Name_Len - 1;
2149               O_File := Name_Find;
2150            end if;
2151         end if;
2152      end Check_File;
2153
2154      ----------------------
2155      -- Get_Library_Name --
2156      ----------------------
2157
2158      --  See comments in a-adaint.c about template syntax
2159
2160      function Get_Library_File (Name : String) return File_Name_Type is
2161         File : File_Name_Type := No_File;
2162
2163      begin
2164         Name_Len := 0;
2165
2166         for Ptr in Template'Range loop
2167            case Template (Ptr) is
2168               when '*'    =>
2169                  Add_Str_To_Name_Buffer (Name);
2170
2171               when ';'    =>
2172                  File := Full_Lib_File_Name (Name_Find);
2173                  exit when File /= No_File;
2174                  Name_Len := 0;
2175
2176               when NUL    =>
2177                  exit;
2178
2179               when others =>
2180                  Add_Char_To_Name_Buffer (Template (Ptr));
2181            end case;
2182         end loop;
2183
2184         --  The for loop exited because the end of the template
2185         --  was reached. File contains the last possible file name
2186         --  for the library.
2187
2188         if File = No_File and then Name_Len > 0 then
2189            File := Full_Lib_File_Name (Name_Find);
2190         end if;
2191
2192         return File;
2193      end Get_Library_File;
2194
2195   --  Start of processing for Check_Linker_Options
2196
2197   begin
2198      O_File  := No_File;
2199      O_Stamp := (others => ' ');
2200
2201      --  Process linker options from the ALI files
2202
2203      for Opt in 1 .. Linker_Options.Last loop
2204         Check_File (File_Name_Type (Linker_Options.Table (Opt).Name));
2205      end loop;
2206
2207      --  Process options given on the command line
2208
2209      for Opt in Linker_Switches.First .. Linker_Switches.Last loop
2210
2211         --  Check if the previous Opt has one of the two switches
2212         --  that take an extra parameter. (See GCC manual.)
2213
2214         if Opt = Linker_Switches.First
2215           or else (Linker_Switches.Table (Opt - 1).all /= "-u"
2216                      and then
2217                    Linker_Switches.Table (Opt - 1).all /= "-Xlinker"
2218                      and then
2219                    Linker_Switches.Table (Opt - 1).all /= "-L")
2220         then
2221            Name_Len := 0;
2222            Add_Str_To_Name_Buffer (Linker_Switches.Table (Opt).all);
2223            Check_File (Name_Find);
2224         end if;
2225      end loop;
2226   end Check_Linker_Options;
2227
2228   -----------------
2229   -- Check_Steps --
2230   -----------------
2231
2232   procedure Check_Steps is
2233   begin
2234      --  If either -c, -b or -l has been specified, we will not necessarily
2235      --  execute all steps.
2236
2237      if Make_Steps then
2238         Do_Compile_Step := Do_Compile_Step and Compile_Only;
2239         Do_Bind_Step    := Do_Bind_Step    and Bind_Only;
2240         Do_Link_Step    := Do_Link_Step    and Link_Only;
2241
2242         --  If -c has been specified, but not -b, ignore any potential -l
2243
2244         if Do_Compile_Step and then not Do_Bind_Step then
2245            Do_Link_Step := False;
2246         end if;
2247      end if;
2248   end Check_Steps;
2249
2250   -----------------------
2251   -- Collect_Arguments --
2252   -----------------------
2253
2254   procedure Collect_Arguments
2255     (Source_File    : File_Name_Type;
2256      Is_Main_Source : Boolean;
2257      Args           : Argument_List)
2258   is
2259      pragma Unreferenced (Is_Main_Source);
2260
2261   begin
2262      Arguments_Project := No_Project;
2263      Last_Argument := 0;
2264      Add_Arguments (Args);
2265
2266      if Main_Project /= No_Project then
2267         declare
2268            Source_File_Name : constant String :=
2269                                 Get_Name_String (Source_File);
2270            Compiler_Package : Prj.Package_Id;
2271            Switches         : Prj.Variable_Value;
2272
2273         begin
2274            Prj.Env.
2275              Get_Reference
2276              (Source_File_Name => Source_File_Name,
2277               Project          => Arguments_Project,
2278               Path             => Arguments_Path_Name,
2279               In_Tree          => Project_Tree);
2280
2281            --  If the source is not a source of a project file, add the
2282            --  recorded arguments. Check will be done later if the source
2283            --  need to be compiled that the switch -x has been used.
2284
2285            if Arguments_Project = No_Project then
2286               Add_Arguments (The_Saved_Gcc_Switches.all);
2287
2288            elsif not Arguments_Project.Externally_Built or else Must_Compile
2289            then
2290               --  We get the project directory for the relative path
2291               --  switches and arguments.
2292
2293               Arguments_Project :=
2294                 Ultimate_Extending_Project_Of (Arguments_Project);
2295
2296               --  If building a dynamic or relocatable library, compile with
2297               --  PIC option, if it exists.
2298
2299               if Arguments_Project.Library
2300                 and then Arguments_Project.Library_Kind /= Static
2301               then
2302                  declare
2303                     PIC : constant String := MLib.Tgt.PIC_Option;
2304                  begin
2305                     if PIC /= "" then
2306                        Add_Arguments ((1 => new String'(PIC)));
2307                     end if;
2308                  end;
2309               end if;
2310
2311               --  We now look for package Compiler and get the switches from
2312               --  this package.
2313
2314               Compiler_Package :=
2315                 Prj.Util.Value_Of
2316                   (Name        => Name_Compiler,
2317                    In_Packages => Arguments_Project.Decl.Packages,
2318                    Shared      => Project_Tree.Shared);
2319
2320               if Compiler_Package /= No_Package then
2321
2322                  --  If package Gnatmake.Compiler exists, we get the specific
2323                  --  switches for the current source, or the global switches,
2324                  --  if any.
2325
2326                  Switches :=
2327                    Switches_Of
2328                      (Source_File => Source_File,
2329                       Project     => Arguments_Project,
2330                       In_Package  => Compiler_Package,
2331                       Allow_ALI   => False);
2332
2333               end if;
2334
2335               case Switches.Kind is
2336
2337                  --  We have a list of switches. We add these switches,
2338                  --  plus the saved gcc switches.
2339
2340                  when List =>
2341                     declare
2342                        Current : String_List_Id := Switches.Values;
2343                        Element : String_Element;
2344                        Number  : Natural := 0;
2345
2346                     begin
2347                        while Current /= Nil_String loop
2348                           Element := Project_Tree.Shared.String_Elements.
2349                                        Table (Current);
2350                           Number  := Number + 1;
2351                           Current := Element.Next;
2352                        end loop;
2353
2354                        declare
2355                           New_Args : Argument_List (1 .. Number);
2356                           Last_New : Natural := 0;
2357                           Dir_Path : constant String := Get_Name_String
2358                             (Arguments_Project.Directory.Display_Name);
2359
2360                        begin
2361                           Current := Switches.Values;
2362
2363                           for Index in New_Args'Range loop
2364                              Element := Project_Tree.Shared.String_Elements.
2365                                           Table (Current);
2366                              Get_Name_String (Element.Value);
2367
2368                              if Name_Len > 0 then
2369                                 Last_New := Last_New + 1;
2370                                 New_Args (Last_New) :=
2371                                   new String'(Name_Buffer (1 .. Name_Len));
2372                                 Ensure_Absolute_Path
2373                                   (New_Args (Last_New),
2374                                    Do_Fail              => Make_Failed'Access,
2375                                    Parent               => Dir_Path,
2376                                    Including_Non_Switch => False);
2377                              end if;
2378
2379                              Current := Element.Next;
2380                           end loop;
2381
2382                           Add_Arguments
2383                             (Configuration_Pragmas_Switch (Arguments_Project)
2384                              & New_Args (1 .. Last_New)
2385                              & The_Saved_Gcc_Switches.all);
2386                        end;
2387                     end;
2388
2389                     --  We have a single switch. We add this switch,
2390                     --  plus the saved gcc switches.
2391
2392                  when Single =>
2393                     Get_Name_String (Switches.Value);
2394
2395                     declare
2396                        New_Args : Argument_List :=
2397                                     (1 => new String'
2398                                            (Name_Buffer (1 .. Name_Len)));
2399                        Dir_Path : constant String :=
2400                                     Get_Name_String
2401                                       (Arguments_Project.
2402                                        Directory.Display_Name);
2403
2404                     begin
2405                        Ensure_Absolute_Path
2406                          (New_Args (1),
2407                           Do_Fail              => Make_Failed'Access,
2408                           Parent               => Dir_Path,
2409                           Including_Non_Switch => False);
2410                        Add_Arguments
2411                          (Configuration_Pragmas_Switch (Arguments_Project) &
2412                           New_Args & The_Saved_Gcc_Switches.all);
2413                     end;
2414
2415                     --  We have no switches from Gnatmake.Compiler.
2416                     --  We add the saved gcc switches.
2417
2418                  when Undefined =>
2419                     Add_Arguments
2420                       (Configuration_Pragmas_Switch (Arguments_Project) &
2421                        The_Saved_Gcc_Switches.all);
2422               end case;
2423            end if;
2424         end;
2425      end if;
2426
2427      --  Set Output_Is_Object, depending if there is a -S switch.
2428      --  If the bind step is not performed, and there is a -S switch,
2429      --  then we will not check for a valid object file.
2430
2431      Check_For_S_Switch;
2432   end Collect_Arguments;
2433
2434   ---------------------
2435   -- Compile_Sources --
2436   ---------------------
2437
2438   procedure Compile_Sources
2439     (Main_Source           : File_Name_Type;
2440      Args                  : Argument_List;
2441      First_Compiled_File   : out File_Name_Type;
2442      Most_Recent_Obj_File  : out File_Name_Type;
2443      Most_Recent_Obj_Stamp : out Time_Stamp_Type;
2444      Main_Unit             : out Boolean;
2445      Compilation_Failures  : out Natural;
2446      Main_Index            : Int      := 0;
2447      Check_Readonly_Files  : Boolean  := False;
2448      Do_Not_Execute        : Boolean  := False;
2449      Force_Compilations    : Boolean  := False;
2450      Keep_Going            : Boolean  := False;
2451      In_Place_Mode         : Boolean  := False;
2452      Initialize_ALI_Data   : Boolean  := True;
2453      Max_Process           : Positive := 1)
2454   is
2455      Mfile            : Natural := No_Mapping_File;
2456      Mapping_File_Arg : String_Access;
2457      --  Info on the mapping file
2458
2459      Need_To_Check_Standard_Library : Boolean :=
2460                                         (Check_Readonly_Files or Must_Compile)
2461                                           and not Unique_Compile;
2462
2463      procedure Add_Process
2464        (Pid           : Process_Id;
2465         Sfile         : File_Name_Type;
2466         Afile         : File_Name_Type;
2467         Uname         : Unit_Name_Type;
2468         Full_Lib_File : File_Name_Type;
2469         Lib_File_Attr : File_Attributes;
2470         Mfile         : Natural := No_Mapping_File);
2471      --  Adds process Pid to the current list of outstanding compilation
2472      --  processes and record the full name of the source file Sfile that
2473      --  we are compiling, the name of its library file Afile and the
2474      --  name of its unit Uname. If Mfile is not equal to No_Mapping_File,
2475      --  it is the index of the mapping file used during compilation in the
2476      --  array The_Mapping_File_Names.
2477
2478      procedure Await_Compile
2479        (Data  : out Compilation_Data;
2480         OK    : out Boolean);
2481      --  Awaits that an outstanding compilation process terminates. When it
2482      --  does set Data to the information registered for the corresponding
2483      --  call to Add_Process. Note that this time stamp can be used to check
2484      --  whether the compilation did generate an object file. OK is set to
2485      --  True if the compilation succeeded. Data could be No_Compilation_Data
2486      --  if there was no compilation to wait for.
2487
2488      function Bad_Compilation_Count return Natural;
2489      --  Returns the number of compilation failures
2490
2491      procedure Check_Standard_Library;
2492      --  Check if s-stalib.adb needs to be compiled
2493
2494      procedure Collect_Arguments_And_Compile
2495        (Full_Source_File : File_Name_Type;
2496         Lib_File         : File_Name_Type;
2497         Source_Index     : Int;
2498         Pid              : out Process_Id;
2499         Process_Created  : out Boolean);
2500      --  Collect arguments from project file (if any) and compile. If no
2501      --  compilation was attempted, Processed_Created is set to False, and the
2502      --  value of Pid is unknown.
2503
2504      function Compile
2505        (Project      : Project_Id;
2506         S            : File_Name_Type;
2507         L            : File_Name_Type;
2508         Source_Index : Int;
2509         Args         : Argument_List) return Process_Id;
2510      --  Compiles S using Args. If S is a GNAT predefined source "-gnatpg" is
2511      --  added to Args. Non blocking call. L corresponds to the expected
2512      --  library file name. Process_Id of the process spawned to execute the
2513      --  compilation.
2514
2515      type ALI_Project is record
2516         ALI      : ALI_Id;
2517         Project : Project_Id;
2518      end record;
2519
2520      package Good_ALI is new Table.Table (
2521        Table_Component_Type => ALI_Project,
2522        Table_Index_Type     => Natural,
2523        Table_Low_Bound      => 1,
2524        Table_Initial        => 50,
2525        Table_Increment      => 100,
2526        Table_Name           => "Make.Good_ALI");
2527      --  Contains the set of valid ALI files that have not yet been scanned
2528
2529      function Good_ALI_Present return Boolean;
2530      --  Returns True if any ALI file was recorded in the previous set
2531
2532      procedure Get_Mapping_File (Project : Project_Id);
2533      --  Get a mapping file name. If there is one to be reused, reuse it.
2534      --  Otherwise, create a new mapping file.
2535
2536      function Get_Next_Good_ALI return ALI_Project;
2537      --  Returns the next good ALI_Id record
2538
2539      procedure Record_Failure
2540        (File  : File_Name_Type;
2541         Unit  : Unit_Name_Type;
2542         Found : Boolean := True);
2543      --  Records in the previous table that the compilation for File failed.
2544      --  If Found is False then the compilation of File failed because we
2545      --  could not find it. Records also Unit when possible.
2546
2547      procedure Record_Good_ALI (A : ALI_Id; Project : Project_Id);
2548      --  Records in the previous set the Id of an ALI file
2549
2550      function Must_Exit_Because_Of_Error return Boolean;
2551      --  Return True if there were errors and the user decided to exit in such
2552      --  a case. This waits for any outstanding compilation.
2553
2554      function Start_Compile_If_Possible (Args : Argument_List) return Boolean;
2555      --  Check if there is more work that we can do (i.e. the Queue is non
2556      --  empty). If there is, do it only if we have not yet used up all the
2557      --  available processes.
2558      --  Returns True if we should exit the main loop
2559
2560      procedure Wait_For_Available_Slot;
2561      --  Check if we should wait for a compilation to finish. This is the case
2562      --  if all the available processes are busy compiling sources or there is
2563      --  nothing else to do (that is the Q is empty and there are no good ALIs
2564      --  to process).
2565
2566      procedure Fill_Queue_From_ALI_Files;
2567      --  Check if we recorded good ALI files. If yes process them now in the
2568      --  order in which they have been recorded. There are two occasions in
2569      --  which we record good ali files. The first is in phase 1 when, after
2570      --  scanning an existing ALI file we realize it is up-to-date, the second
2571      --  instance is after a successful compilation.
2572
2573      -----------------
2574      -- Add_Process --
2575      -----------------
2576
2577      procedure Add_Process
2578        (Pid           : Process_Id;
2579         Sfile         : File_Name_Type;
2580         Afile         : File_Name_Type;
2581         Uname         : Unit_Name_Type;
2582         Full_Lib_File : File_Name_Type;
2583         Lib_File_Attr : File_Attributes;
2584         Mfile         : Natural := No_Mapping_File)
2585      is
2586         OC1 : constant Positive := Outstanding_Compiles + 1;
2587
2588      begin
2589         pragma Assert (OC1 <= Max_Process);
2590         pragma Assert (Pid /= Invalid_Pid);
2591
2592         Running_Compile (OC1) :=
2593           (Pid              => Pid,
2594            Full_Source_File => Sfile,
2595            Lib_File         => Afile,
2596            Full_Lib_File    => Full_Lib_File,
2597            Lib_File_Attr    => Lib_File_Attr,
2598            Source_Unit      => Uname,
2599            Mapping_File     => Mfile,
2600            Project          => Arguments_Project);
2601
2602         Outstanding_Compiles := OC1;
2603
2604         if Arguments_Project /= No_Project then
2605            Queue.Set_Obj_Dir_Busy (Arguments_Project.Object_Directory.Name);
2606         end if;
2607      end Add_Process;
2608
2609      --------------------
2610      -- Await_Compile --
2611      -------------------
2612
2613      procedure Await_Compile
2614        (Data : out Compilation_Data;
2615         OK   : out Boolean)
2616      is
2617         Pid       : Process_Id;
2618         Project   : Project_Id;
2619         Comp_Data : Project_Compilation_Access;
2620
2621      begin
2622         pragma Assert (Outstanding_Compiles > 0);
2623
2624         Data := No_Compilation_Data;
2625         OK   := False;
2626
2627         Wait_Process (Pid, OK);
2628
2629         if Pid = Invalid_Pid then
2630            return;
2631         end if;
2632
2633         --  Look into the running compilation processes for this PID
2634
2635         for J in Running_Compile'First .. Outstanding_Compiles loop
2636            if Pid = Running_Compile (J).Pid then
2637               Data    := Running_Compile (J);
2638               Project := Running_Compile (J).Project;
2639
2640               if Project /= No_Project then
2641                  Queue.Set_Obj_Dir_Free (Project.Object_Directory.Name);
2642               end if;
2643
2644               --  If a mapping file was used by this compilation, get its file
2645               --  name for reuse by a subsequent compilation.
2646
2647               if Running_Compile (J).Mapping_File /= No_Mapping_File then
2648                  Comp_Data :=
2649                    Project_Compilation_Htable.Get
2650                      (Project_Compilation, Project);
2651                  Comp_Data.Last_Free_Indexes :=
2652                    Comp_Data.Last_Free_Indexes + 1;
2653                  Comp_Data.Free_Mapping_File_Indexes
2654                    (Comp_Data.Last_Free_Indexes) :=
2655                    Running_Compile (J).Mapping_File;
2656               end if;
2657
2658               --  To actually remove this Pid and related info from
2659               --  Running_Compile replace its entry with the last valid
2660               --  entry in Running_Compile.
2661
2662               if J = Outstanding_Compiles then
2663                  null;
2664               else
2665                  Running_Compile (J) :=
2666                    Running_Compile (Outstanding_Compiles);
2667               end if;
2668
2669               Outstanding_Compiles := Outstanding_Compiles - 1;
2670               exit;
2671            end if;
2672         end loop;
2673
2674         --  If the PID was not found, return with OK set to False
2675
2676         if Data = No_Compilation_Data then
2677            OK := False;
2678         end if;
2679      end Await_Compile;
2680
2681      ---------------------------
2682      -- Bad_Compilation_Count --
2683      ---------------------------
2684
2685      function Bad_Compilation_Count return Natural is
2686      begin
2687         return Bad_Compilation.Last - Bad_Compilation.First + 1;
2688      end Bad_Compilation_Count;
2689
2690      ----------------------------
2691      -- Check_Standard_Library --
2692      ----------------------------
2693
2694      procedure Check_Standard_Library is
2695      begin
2696         Need_To_Check_Standard_Library := False;
2697
2698         if not Targparm.Suppress_Standard_Library_On_Target then
2699            declare
2700               Sfile  : File_Name_Type;
2701               Add_It : Boolean := True;
2702
2703            begin
2704               Name_Len := 0;
2705               Add_Str_To_Name_Buffer (Standard_Library_Package_Body_Name);
2706               Sfile := Name_Enter;
2707
2708               --  If we have a special runtime, we add the standard
2709               --  library only if we can find it.
2710
2711               if RTS_Switch then
2712                  Add_It := Full_Source_Name (Sfile) /= No_File;
2713               end if;
2714
2715               if Add_It then
2716                  if not Queue.Insert
2717                           ((Format  => Format_Gnatmake,
2718                             File    => Sfile,
2719                             Unit    => No_Unit_Name,
2720                             Project => No_Project,
2721                             Index   => 0,
2722                             Sid     => No_Source))
2723                  then
2724                     if Is_In_Obsoleted (Sfile) then
2725                        Executable_Obsolete := True;
2726                     end if;
2727                  end if;
2728               end if;
2729            end;
2730         end if;
2731      end Check_Standard_Library;
2732
2733      -----------------------------------
2734      -- Collect_Arguments_And_Compile --
2735      -----------------------------------
2736
2737      procedure Collect_Arguments_And_Compile
2738        (Full_Source_File : File_Name_Type;
2739         Lib_File         : File_Name_Type;
2740         Source_Index     : Int;
2741         Pid              : out Process_Id;
2742         Process_Created  : out Boolean) is
2743      begin
2744         Process_Created := False;
2745
2746         --  If we use mapping file (-P or -C switches), then get one
2747
2748         if Create_Mapping_File then
2749            Get_Mapping_File (Arguments_Project);
2750         end if;
2751
2752         --  If the source is part of a project file, we set the ADA_*_PATHs,
2753         --  check for an eventual library project, and use the full path.
2754
2755         if Arguments_Project /= No_Project then
2756            if not Arguments_Project.Externally_Built
2757              or else Must_Compile
2758            then
2759               Prj.Env.Set_Ada_Paths
2760                 (Arguments_Project,
2761                  Project_Tree,
2762                  Including_Libraries => True,
2763                  Include_Path        => Use_Include_Path_File);
2764
2765               if not Unique_Compile
2766                 and then MLib.Tgt.Support_For_Libraries /= Prj.None
2767               then
2768                  declare
2769                     Prj : constant Project_Id :=
2770                             Ultimate_Extending_Project_Of (Arguments_Project);
2771
2772                  begin
2773                     if Prj.Library
2774                       and then (not Prj.Externally_Built or else Must_Compile)
2775                       and then not Prj.Need_To_Build_Lib
2776                     then
2777                        --  Add to the Q all sources of the project that have
2778                        --  not been marked.
2779
2780                        Insert_Project_Sources
2781                          (The_Project  => Prj,
2782                           All_Projects => False,
2783                           Into_Q       => True);
2784
2785                        --  Now mark the project as processed
2786
2787                        Prj.Need_To_Build_Lib := True;
2788                     end if;
2789                  end;
2790               end if;
2791
2792               Pid :=
2793                 Compile
2794                   (Project       => Arguments_Project,
2795                    S             => File_Name_Type (Arguments_Path_Name),
2796                    L             => Lib_File,
2797                    Source_Index  => Source_Index,
2798                    Args          => Arguments (1 .. Last_Argument));
2799               Process_Created := True;
2800            end if;
2801
2802         else
2803            --  If this is a source outside of any project file, make sure it
2804            --  will be compiled in object directory of the main project file.
2805
2806            Pid :=
2807              Compile
2808                (Project        => Main_Project,
2809                 S              => Full_Source_File,
2810                 L              => Lib_File,
2811                 Source_Index   => Source_Index,
2812                 Args           => Arguments (1 .. Last_Argument));
2813            Process_Created := True;
2814         end if;
2815      end Collect_Arguments_And_Compile;
2816
2817      -------------
2818      -- Compile --
2819      -------------
2820
2821      function Compile
2822        (Project      : Project_Id;
2823         S            : File_Name_Type;
2824         L            : File_Name_Type;
2825         Source_Index : Int;
2826         Args         : Argument_List) return Process_Id
2827      is
2828         Comp_Args : Argument_List (Args'First .. Args'Last + 10);
2829         Comp_Next : Integer := Args'First;
2830         Comp_Last : Integer;
2831         Arg_Index : Integer;
2832
2833         function Ada_File_Name (Name : File_Name_Type) return Boolean;
2834         --  Returns True if Name is the name of an ada source file
2835         --  (i.e. suffix is .ads or .adb)
2836
2837         -------------------
2838         -- Ada_File_Name --
2839         -------------------
2840
2841         function Ada_File_Name (Name : File_Name_Type) return Boolean is
2842         begin
2843            Get_Name_String (Name);
2844            return
2845              Name_Len > 4
2846                and then Name_Buffer (Name_Len - 3 .. Name_Len - 1) = ".ad"
2847                and then (Name_Buffer (Name_Len) = 'b'
2848                            or else
2849                          Name_Buffer (Name_Len) = 's');
2850         end Ada_File_Name;
2851
2852      --  Start of processing for Compile
2853
2854      begin
2855         Enter_Into_Obsoleted (S);
2856
2857         --  By default, Syntax_Only is False
2858
2859         Syntax_Only := False;
2860
2861         for J in Args'Range loop
2862            if Args (J).all = "-gnats" then
2863
2864               --  If we compile with -gnats, the bind step and the link step
2865               --  are inhibited. Also, we set Syntax_Only to True, so that
2866               --  we don't fail when we don't find the ALI file, after
2867               --  compilation.
2868
2869               Do_Bind_Step := False;
2870               Do_Link_Step := False;
2871               Syntax_Only  := True;
2872
2873            elsif Args (J).all = "-gnatc" then
2874
2875               --  If we compile with -gnatc, the bind step and the link step
2876               --  are inhibited. We set Syntax_Only to False for the case when
2877               --  -gnats was previously specified.
2878
2879               Do_Bind_Step := False;
2880               Do_Link_Step := False;
2881               Syntax_Only  := False;
2882            end if;
2883         end loop;
2884
2885         Comp_Args (Comp_Next) := new String'("-gnatea");
2886         Comp_Next := Comp_Next + 1;
2887
2888         Comp_Args (Comp_Next) := Comp_Flag;
2889         Comp_Next := Comp_Next + 1;
2890
2891         --  Optimize the simple case where the gcc command line looks like
2892         --     gcc -c -I. ... -I- file.adb
2893         --  into
2894         --     gcc -c ... file.adb
2895
2896         if Args (Args'First).all = "-I" & Normalized_CWD
2897           and then Args (Args'Last).all = "-I-"
2898           and then S = Strip_Directory (S)
2899         then
2900            Comp_Last := Comp_Next + Args'Length - 3;
2901            Arg_Index := Args'First + 1;
2902
2903         else
2904            Comp_Last := Comp_Next + Args'Length - 1;
2905            Arg_Index := Args'First;
2906         end if;
2907
2908         --  Make a deep copy of the arguments, because Normalize_Arguments
2909         --  may deallocate some arguments. Also strip target specific -mxxx
2910         --  switches in CodePeer mode.
2911
2912         declare
2913            Index : Natural;
2914            Last  : constant Natural := Comp_Last;
2915
2916         begin
2917            Index := Comp_Next;
2918            for J in Comp_Next .. Last loop
2919               declare
2920                  Str : String renames Args (Arg_Index).all;
2921               begin
2922                  if CodePeer_Mode
2923                    and then Str'Length > 2
2924                    and then Str (Str'First .. Str'First + 1) = "-m"
2925                  then
2926                     Comp_Last := Comp_Last - 1;
2927                  else
2928                     Comp_Args (Index) := new String'(Str);
2929                     Index := Index + 1;
2930                  end if;
2931               end;
2932
2933               Arg_Index := Arg_Index + 1;
2934            end loop;
2935         end;
2936
2937         --  Set -gnatpg for predefined files (for this purpose the renamings
2938         --  such as Text_IO do not count as predefined). Note that we strip
2939         --  the directory name from the source file name because the call to
2940         --  Fname.Is_Predefined_File_Name cannot deal with directory prefixes.
2941
2942         declare
2943            Fname : constant File_Name_Type := Strip_Directory (S);
2944
2945         begin
2946            if Is_Predefined_File_Name (Fname, False) then
2947               if Check_Readonly_Files or else Must_Compile then
2948                  Comp_Args (Comp_Args'First + 2 .. Comp_Last + 1) :=
2949                    Comp_Args (Comp_Args'First + 1 .. Comp_Last);
2950                  Comp_Last := Comp_Last + 1;
2951                  Comp_Args (Comp_Args'First + 1) := GNAT_Flag;
2952
2953               else
2954                  Make_Failed
2955                    ("not allowed to compile """ &
2956                     Get_Name_String (Fname) &
2957                     """; use -a switch, or use the compiler directly with "
2958                     & "the ""-gnatg"" switch");
2959               end if;
2960            end if;
2961         end;
2962
2963         --  Now check if the file name has one of the suffixes familiar to
2964         --  the gcc driver. If this is not the case then add the ada flag
2965         --  "-x ada".
2966         --  Append systematically "-x adascil" in CodePeer mode instead, to
2967         --  force the use of gnat1scil instead of gnat1.
2968
2969         if CodePeer_Mode then
2970            Comp_Last := Comp_Last + 1;
2971            Comp_Args (Comp_Last) := Ada_Flag_1;
2972            Comp_Last := Comp_Last + 1;
2973            Comp_Args (Comp_Last) := AdaSCIL_Flag;
2974
2975         elsif not Ada_File_Name (S) and then not Targparm.AAMP_On_Target then
2976            Comp_Last := Comp_Last + 1;
2977            Comp_Args (Comp_Last) := Ada_Flag_1;
2978            Comp_Last := Comp_Last + 1;
2979            Comp_Args (Comp_Last) := Ada_Flag_2;
2980         end if;
2981
2982         if Source_Index /= 0 then
2983            declare
2984               Num : constant String := Source_Index'Img;
2985            begin
2986               Comp_Last := Comp_Last + 1;
2987               Comp_Args (Comp_Last) :=
2988                 new String'("-gnateI" & Num (Num'First + 1 .. Num'Last));
2989            end;
2990         end if;
2991
2992         if Source_Index /= 0
2993           or else L /= Strip_Directory (L)
2994           or else Object_Directory_Path /= null
2995         then
2996            --  Build -o argument
2997
2998            Get_Name_String (L);
2999
3000            for J in reverse 1 .. Name_Len loop
3001               if Name_Buffer (J) = '.' then
3002                  Name_Len := J + Object_Suffix'Length - 1;
3003                  Name_Buffer (J .. Name_Len) := Object_Suffix;
3004                  exit;
3005               end if;
3006            end loop;
3007
3008            Comp_Last := Comp_Last + 1;
3009            Comp_Args (Comp_Last) := Output_Flag;
3010            Comp_Last := Comp_Last + 1;
3011
3012            --  If an object directory was specified, prepend the object file
3013            --  name with this object directory.
3014
3015            if Object_Directory_Path /= null then
3016               Comp_Args (Comp_Last) :=
3017                 new String'(Object_Directory_Path.all &
3018                               Name_Buffer (1 .. Name_Len));
3019
3020            else
3021               Comp_Args (Comp_Last) :=
3022                 new String'(Name_Buffer (1 .. Name_Len));
3023            end if;
3024         end if;
3025
3026         if Create_Mapping_File and then Mapping_File_Arg /= null then
3027            Comp_Last := Comp_Last + 1;
3028            Comp_Args (Comp_Last) := new String'(Mapping_File_Arg.all);
3029         end if;
3030
3031         Get_Name_String (S);
3032
3033         Comp_Last := Comp_Last + 1;
3034         Comp_Args (Comp_Last) := new String'(Name_Buffer (1 .. Name_Len));
3035
3036         --  Change to object directory of the project file, if necessary
3037
3038         if Project /= No_Project then
3039            Change_To_Object_Directory (Project);
3040         end if;
3041
3042         GNAT.OS_Lib.Normalize_Arguments (Comp_Args (Args'First .. Comp_Last));
3043
3044         Comp_Last := Comp_Last + 1;
3045         Comp_Args (Comp_Last) := new String'("-gnatez");
3046
3047         Display (Gcc.all, Comp_Args (Args'First .. Comp_Last));
3048
3049         if Gcc_Path = null then
3050            Make_Failed ("error, unable to locate " & Gcc.all);
3051         end if;
3052
3053         return
3054           GNAT.OS_Lib.Non_Blocking_Spawn
3055             (Gcc_Path.all, Comp_Args (Args'First .. Comp_Last));
3056      end Compile;
3057
3058      -------------------------------
3059      -- Fill_Queue_From_ALI_Files --
3060      -------------------------------
3061
3062      procedure Fill_Queue_From_ALI_Files is
3063         ALI_P        : ALI_Project;
3064         ALI          : ALI_Id;
3065         Source_Index : Int;
3066         Sfile        : File_Name_Type;
3067         Sid          : Prj.Source_Id;
3068         Uname        : Unit_Name_Type;
3069         Unit_Name    : Name_Id;
3070         Uid          : Prj.Unit_Index;
3071
3072      begin
3073         while Good_ALI_Present loop
3074            ALI_P        := Get_Next_Good_ALI;
3075            ALI          := ALI_P.ALI;
3076            Source_Index := Unit_Index_Of (ALIs.Table (ALI_P.ALI).Afile);
3077
3078            --  If we are processing the library file corresponding to the
3079            --  main source file check if this source can be a main unit.
3080
3081            if ALIs.Table (ALI).Sfile = Main_Source
3082              and then Source_Index = Main_Index
3083            then
3084               Main_Unit := ALIs.Table (ALI).Main_Program /= None;
3085            end if;
3086
3087            --  The following adds the standard library (s-stalib) to the list
3088            --  of files to be handled by gnatmake: this file and any files it
3089            --  depends on are always included in every bind, even if they are
3090            --  not in the explicit dependency list. Of course, it is not added
3091            --  if Suppress_Standard_Library is True.
3092
3093            --  However, to avoid annoying output about s-stalib.ali being read
3094            --  only, when "-v" is used, we add the standard library only when
3095            --  "-a" is used.
3096
3097            if Need_To_Check_Standard_Library then
3098               Check_Standard_Library;
3099            end if;
3100
3101            --  Now insert in the Q the unmarked source files (i.e. those which
3102            --  have never been inserted in the Q and hence never considered).
3103            --  Only do that if Unique_Compile is False.
3104
3105            if not Unique_Compile then
3106               for J in
3107                 ALIs.Table (ALI).First_Unit .. ALIs.Table (ALI).Last_Unit
3108               loop
3109                  for K in
3110                    Units.Table (J).First_With .. Units.Table (J).Last_With
3111                  loop
3112                     Sfile := Withs.Table (K).Sfile;
3113                     Uname := Withs.Table (K).Uname;
3114                     Sid   := No_Source;
3115
3116                     --  If project files are used, find the proper source to
3117                     --  compile in case Sfile is the spec but there is a body.
3118
3119                     if Main_Project /= No_Project then
3120                        Get_Name_String (Uname);
3121                        Name_Len  := Name_Len - 2;
3122                        Unit_Name := Name_Find;
3123                        Uid :=
3124                          Units_Htable.Get (Project_Tree.Units_HT, Unit_Name);
3125
3126                        if Uid /= Prj.No_Unit_Index then
3127                           if Uid.File_Names (Impl) /= null
3128                             and then not Uid.File_Names (Impl).Locally_Removed
3129                           then
3130                              Sfile        := Uid.File_Names (Impl).File;
3131                              Source_Index := Uid.File_Names (Impl).Index;
3132                              Sid          := Uid.File_Names (Impl);
3133
3134                           elsif Uid.File_Names (Spec) /= null
3135                             and then not Uid.File_Names (Spec).Locally_Removed
3136                           then
3137                              Sfile        := Uid.File_Names (Spec).File;
3138                              Source_Index := Uid.File_Names (Spec).Index;
3139                              Sid          := Uid.File_Names (Spec);
3140                           end if;
3141                        end if;
3142                     end if;
3143
3144                     Dependencies.Append ((ALIs.Table (ALI).Sfile, Sfile));
3145
3146                     if Is_In_Obsoleted (Sfile) then
3147                        Executable_Obsolete := True;
3148                     end if;
3149
3150                     if Sfile = No_File then
3151                        Debug_Msg ("Skipping generic:", Withs.Table (K).Uname);
3152
3153                     else
3154                        Source_Index := Unit_Index_Of (Withs.Table (K).Afile);
3155
3156                        if not (Check_Readonly_Files or Must_Compile)
3157                          and then Is_Internal_File_Name (Sfile, False)
3158                        then
3159                           Debug_Msg ("Skipping internal file:", Sfile);
3160
3161                        else
3162                           Queue.Insert
3163                             ((Format  => Format_Gnatmake,
3164                               File    => Sfile,
3165                               Project => ALI_P.Project,
3166                               Unit    => Withs.Table (K).Uname,
3167                               Index   => Source_Index,
3168                               Sid     => Sid));
3169                        end if;
3170                     end if;
3171                  end loop;
3172               end loop;
3173            end if;
3174         end loop;
3175      end Fill_Queue_From_ALI_Files;
3176
3177      ----------------------
3178      -- Get_Mapping_File --
3179      ----------------------
3180
3181      procedure Get_Mapping_File (Project : Project_Id) is
3182         Data : Project_Compilation_Access;
3183
3184      begin
3185         Data := Project_Compilation_Htable.Get (Project_Compilation, Project);
3186
3187         --  If there is a mapping file ready to be reused, reuse it
3188
3189         if Data.Last_Free_Indexes > 0 then
3190            Mfile := Data.Free_Mapping_File_Indexes (Data.Last_Free_Indexes);
3191            Data.Last_Free_Indexes := Data.Last_Free_Indexes - 1;
3192
3193         --  Otherwise, create and initialize a new one
3194
3195         else
3196            Init_Mapping_File
3197              (Project => Project, Data => Data.all, File_Index => Mfile);
3198         end if;
3199
3200         --  Put the name in the mapping file argument for the invocation
3201         --  of the compiler.
3202
3203         Free (Mapping_File_Arg);
3204         Mapping_File_Arg :=
3205           new String'("-gnatem=" &
3206                       Get_Name_String (Data.Mapping_File_Names (Mfile)));
3207      end Get_Mapping_File;
3208
3209      -----------------------
3210      -- Get_Next_Good_ALI --
3211      -----------------------
3212
3213      function Get_Next_Good_ALI return ALI_Project is
3214         ALIP : ALI_Project;
3215
3216      begin
3217         pragma Assert (Good_ALI_Present);
3218         ALIP := Good_ALI.Table (Good_ALI.Last);
3219         Good_ALI.Decrement_Last;
3220         return ALIP;
3221      end Get_Next_Good_ALI;
3222
3223      ----------------------
3224      -- Good_ALI_Present --
3225      ----------------------
3226
3227      function Good_ALI_Present return Boolean is
3228      begin
3229         return Good_ALI.First <= Good_ALI.Last;
3230      end Good_ALI_Present;
3231
3232      --------------------------------
3233      -- Must_Exit_Because_Of_Error --
3234      --------------------------------
3235
3236      function Must_Exit_Because_Of_Error return Boolean is
3237         Data    : Compilation_Data;
3238         Success : Boolean;
3239
3240      begin
3241         if Bad_Compilation_Count > 0 and then not Keep_Going then
3242            while Outstanding_Compiles > 0 loop
3243               Await_Compile (Data, Success);
3244
3245               if not Success then
3246                  Record_Failure (Data.Full_Source_File, Data.Source_Unit);
3247               end if;
3248            end loop;
3249
3250            return True;
3251         end if;
3252
3253         return False;
3254      end Must_Exit_Because_Of_Error;
3255
3256      --------------------
3257      -- Record_Failure --
3258      --------------------
3259
3260      procedure Record_Failure
3261        (File  : File_Name_Type;
3262         Unit  : Unit_Name_Type;
3263         Found : Boolean := True)
3264      is
3265      begin
3266         Bad_Compilation.Increment_Last;
3267         Bad_Compilation.Table (Bad_Compilation.Last) := (File, Unit, Found);
3268      end Record_Failure;
3269
3270      ---------------------
3271      -- Record_Good_ALI --
3272      ---------------------
3273
3274      procedure Record_Good_ALI (A : ALI_Id; Project : Project_Id) is
3275      begin
3276         Good_ALI.Increment_Last;
3277         Good_ALI.Table (Good_ALI.Last) := (A, Project);
3278      end Record_Good_ALI;
3279
3280      -------------------------------
3281      -- Start_Compile_If_Possible --
3282      -------------------------------
3283
3284      function Start_Compile_If_Possible
3285        (Args : Argument_List) return Boolean
3286      is
3287         In_Lib_Dir      : Boolean;
3288         Need_To_Compile : Boolean;
3289         Pid             : Process_Id := Invalid_Pid;
3290         Process_Created : Boolean;
3291
3292         Source           : Queue.Source_Info;
3293         Full_Source_File : File_Name_Type := No_File;
3294         Source_File_Attr : aliased File_Attributes;
3295         --  The full name of the source file and its attributes (size, ...)
3296
3297         Lib_File      : File_Name_Type;
3298         Full_Lib_File : File_Name_Type := No_File;
3299         Lib_File_Attr : aliased File_Attributes;
3300         Read_Only     : Boolean := False;
3301         ALI           : ALI_Id;
3302         --  The ALI file and its attributes (size, stamp, ...)
3303
3304         Obj_File  : File_Name_Type;
3305         Obj_Stamp : Time_Stamp_Type;
3306         --  The object file
3307
3308         Found : Boolean;
3309
3310      begin
3311         if not Queue.Is_Virtually_Empty and then
3312            Outstanding_Compiles < Max_Process
3313         then
3314            Queue.Extract (Found, Source);
3315
3316            --  If it is a source in a project, first look for the ALI file
3317            --  in the object directory. When the project is extending another
3318            --  the ALI file may not be found, but the source does not
3319            --  necessarily need to be compiled, as it may already be up to
3320            --  date in the project being extended. In this case, look for an
3321            --  ALI file in all the object directories, as is done when
3322            --  gnatmake is not invoked with a project file.
3323
3324            if Source.Sid /= No_Source then
3325               Initialize_Source_Record (Source.Sid);
3326               Full_Source_File :=
3327                 File_Name_Type (Source.Sid.Path.Display_Name);
3328               Lib_File      := Source.Sid.Dep_Name;
3329               Full_Lib_File := File_Name_Type (Source.Sid.Dep_Path);
3330               Lib_File_Attr := Unknown_Attributes;
3331
3332               if Full_Lib_File /= No_File then
3333                  declare
3334                     FLF : constant String :=
3335                       Get_Name_String (Full_Lib_File) & ASCII.NUL;
3336                  begin
3337                     if not Is_Regular_File
3338                       (FLF'Address, Lib_File_Attr'Access)
3339                     then
3340                        Full_Lib_File := No_File;
3341                     end if;
3342                  end;
3343               end if;
3344            end if;
3345
3346            if Full_Lib_File = No_File then
3347               Osint.Full_Source_Name
3348                 (Source.File,
3349                  Full_File => Full_Source_File,
3350                  Attr      => Source_File_Attr'Access);
3351
3352               Lib_File := Osint.Lib_File_Name (Source.File, Source.Index);
3353
3354               Osint.Full_Lib_File_Name
3355                 (Lib_File,
3356                  Lib_File => Full_Lib_File,
3357                  Attr     => Lib_File_Attr);
3358            end if;
3359
3360            --  If source has already been compiled, executable is obsolete
3361
3362            if Is_In_Obsoleted (Source.File) then
3363               Executable_Obsolete := True;
3364            end if;
3365
3366            In_Lib_Dir := Full_Lib_File /= No_File
3367                          and then In_Ada_Lib_Dir (Full_Lib_File);
3368
3369            --  Since the following requires a system call, we precompute it
3370            --  when needed.
3371
3372            if not In_Lib_Dir then
3373               if Full_Lib_File /= No_File
3374                 and then not (Check_Readonly_Files or else Must_Compile)
3375               then
3376                  Get_Name_String (Full_Lib_File);
3377                  Name_Buffer (Name_Len + 1) := ASCII.NUL;
3378                  Read_Only := not Is_Writable_File
3379                    (Name_Buffer'Address, Lib_File_Attr'Access);
3380               else
3381                  Read_Only := False;
3382               end if;
3383            end if;
3384
3385            --  If the library file is an Ada library skip it
3386
3387            if In_Lib_Dir then
3388               Verbose_Msg
3389                 (Lib_File,
3390                  "is in an Ada library",
3391                  Prefix => "  ",
3392                  Minimum_Verbosity => Opt.High);
3393
3394               --  If the library file is a read-only library skip it, but only
3395               --  if, when using project files, this library file is in the
3396               --  right object directory (a read-only ALI file in the object
3397               --  directory of a project being extended must not be skipped).
3398
3399            elsif Read_Only
3400              and then Is_In_Object_Directory (Source.File, Full_Lib_File)
3401            then
3402               Verbose_Msg
3403                 (Lib_File,
3404                  "is a read-only library",
3405                  Prefix => "  ",
3406                  Minimum_Verbosity => Opt.High);
3407
3408               --  The source file that we are checking cannot be located
3409
3410            elsif Full_Source_File = No_File then
3411               Record_Failure (Source.File, Source.Unit, False);
3412
3413               --  Source and library files can be located but are internal
3414               --  files.
3415
3416            elsif not (Check_Readonly_Files or else Must_Compile)
3417              and then Full_Lib_File /= No_File
3418              and then Is_Internal_File_Name (Source.File, False)
3419            then
3420               if Force_Compilations then
3421                  Fail
3422                    ("not allowed to compile """ &
3423                     Get_Name_String (Source.File) &
3424                     """; use -a switch, or use the compiler directly with "
3425                     & "the ""-gnatg"" switch");
3426               end if;
3427
3428               Verbose_Msg
3429                 (Lib_File,
3430                  "is an internal library",
3431                  Prefix => "  ",
3432                  Minimum_Verbosity => Opt.High);
3433
3434               --  The source file that we are checking can be located
3435
3436            else
3437               Collect_Arguments
3438                  (Source.File, Source.File = Main_Source, Args);
3439
3440               --  Do nothing if project of source is externally built
3441
3442               if Arguments_Project = No_Project
3443                 or else not Arguments_Project.Externally_Built
3444                 or else Must_Compile
3445               then
3446                  --  Don't waste any time if we have to recompile anyway
3447
3448                  Obj_Stamp       := Empty_Time_Stamp;
3449                  Need_To_Compile := Force_Compilations;
3450
3451                  if not Force_Compilations then
3452                     Check (Source_File    => Source.File,
3453                            Is_Main_Source => Source.File = Main_Source,
3454                            The_Args       => Args,
3455                            Lib_File       => Lib_File,
3456                            Full_Lib_File  => Full_Lib_File,
3457                            Lib_File_Attr  => Lib_File_Attr'Access,
3458                            Read_Only      => Read_Only,
3459                            ALI            => ALI,
3460                            O_File         => Obj_File,
3461                            O_Stamp        => Obj_Stamp);
3462                     Need_To_Compile := (ALI = No_ALI_Id);
3463                  end if;
3464
3465                  if not Need_To_Compile then
3466
3467                     --  The ALI file is up-to-date; record its Id
3468
3469                     Record_Good_ALI (ALI, Arguments_Project);
3470
3471                     --  Record the time stamp of the most recent object
3472                     --  file as long as no (re)compilations are needed.
3473
3474                     if First_Compiled_File = No_File
3475                       and then (Most_Recent_Obj_File = No_File
3476                                  or else Obj_Stamp > Most_Recent_Obj_Stamp)
3477                     then
3478                        Most_Recent_Obj_File  := Obj_File;
3479                        Most_Recent_Obj_Stamp := Obj_Stamp;
3480                     end if;
3481
3482                  else
3483                     --  Check that switch -x has been used if a source outside
3484                     --  of project files need to be compiled.
3485
3486                     if Main_Project /= No_Project
3487                       and then Arguments_Project = No_Project
3488                       and then not External_Unit_Compilation_Allowed
3489                     then
3490                        Make_Failed ("external source ("
3491                                     & Get_Name_String (Source.File)
3492                                     & ") is not part of any project;"
3493                                     & " cannot be compiled without"
3494                                     & " gnatmake switch -x");
3495                     end if;
3496
3497                     --  Is this the first file we have to compile?
3498
3499                     if First_Compiled_File = No_File then
3500                        First_Compiled_File  := Full_Source_File;
3501                        Most_Recent_Obj_File := No_File;
3502
3503                        if Do_Not_Execute then
3504
3505                           --  Exit the main loop
3506
3507                           return True;
3508                        end if;
3509                     end if;
3510
3511                     --  Compute where the ALI file must be generated in
3512                     --  In_Place_Mode (this does not require to know the
3513                     --  location of the object directory).
3514
3515                     if In_Place_Mode then
3516                        if Full_Lib_File = No_File then
3517
3518                           --  If the library file was not found, then save
3519                           --  the library file near the source file.
3520
3521                           Lib_File :=
3522                             Osint.Lib_File_Name
3523                               (Full_Source_File, Source.Index);
3524                           Full_Lib_File := Lib_File;
3525
3526                        else
3527                           --  If the library file was found, then save the
3528                           --  library file in the same place.
3529
3530                           Lib_File := Full_Lib_File;
3531                        end if;
3532                     end if;
3533
3534                     --  Start the compilation and record it. We can do this
3535                     --  because there is at least one free process. This might
3536                     --  change the current directory.
3537
3538                     Collect_Arguments_And_Compile
3539                       (Full_Source_File => Full_Source_File,
3540                        Lib_File         => Lib_File,
3541                        Source_Index     => Source.Index,
3542                        Pid              => Pid,
3543                        Process_Created  => Process_Created);
3544
3545                     --  Compute where the ALI file will be generated (for
3546                     --  cases that might require to know the current
3547                     --  directory). The current directory might be changed
3548                     --  when compiling other files so we cannot rely on it
3549                     --  being the same to find the resulting ALI file.
3550
3551                     if not In_Place_Mode then
3552
3553                        --  Compute the expected location of the ALI file. This
3554                        --  can be from several places:
3555                        --    -i => in place mode. In such a case,
3556                        --          Full_Lib_File has already been set above
3557                        --    -D => if specified
3558                        --    or defaults in current dir
3559                        --  We could simply use a call similar to
3560                        --     Osint.Full_Lib_File_Name (Lib_File)
3561                        --  but that involves system calls and is thus slower
3562
3563                        if Object_Directory_Path /= null then
3564                           Name_Len := 0;
3565                           Add_Str_To_Name_Buffer (Object_Directory_Path.all);
3566                           Add_Str_To_Name_Buffer (Get_Name_String (Lib_File));
3567                           Full_Lib_File := Name_Find;
3568
3569                        else
3570                           if Project_Of_Current_Object_Directory /=
3571                             No_Project
3572                           then
3573                              Get_Name_String
3574                                (Project_Of_Current_Object_Directory
3575                                 .Object_Directory.Display_Name);
3576                              Add_Str_To_Name_Buffer
3577                                (Get_Name_String (Lib_File));
3578                              Full_Lib_File := Name_Find;
3579
3580                           else
3581                              Full_Lib_File := Lib_File;
3582                           end if;
3583                        end if;
3584
3585                     end if;
3586
3587                     Lib_File_Attr := Unknown_Attributes;
3588
3589                     --  Make sure we could successfully start the compilation
3590
3591                     if Process_Created then
3592                        if Pid = Invalid_Pid then
3593                           Record_Failure (Full_Source_File, Source.Unit);
3594                        else
3595                           Add_Process
3596                             (Pid           => Pid,
3597                              Sfile         => Full_Source_File,
3598                              Afile         => Lib_File,
3599                              Uname         => Source.Unit,
3600                              Mfile         => Mfile,
3601                              Full_Lib_File => Full_Lib_File,
3602                              Lib_File_Attr => Lib_File_Attr);
3603                        end if;
3604                     end if;
3605                  end if;
3606               end if;
3607            end if;
3608         end if;
3609         return False;
3610      end Start_Compile_If_Possible;
3611
3612      -----------------------------
3613      -- Wait_For_Available_Slot --
3614      -----------------------------
3615
3616      procedure Wait_For_Available_Slot is
3617         Compilation_OK : Boolean;
3618         Text           : Text_Buffer_Ptr;
3619         ALI            : ALI_Id;
3620         Data           : Compilation_Data;
3621
3622      begin
3623         if Outstanding_Compiles = Max_Process
3624           or else (Queue.Is_Virtually_Empty
3625                     and then not Good_ALI_Present
3626                     and then Outstanding_Compiles > 0)
3627         then
3628            Await_Compile (Data, Compilation_OK);
3629
3630            if not Compilation_OK then
3631               Record_Failure (Data.Full_Source_File, Data.Source_Unit);
3632            end if;
3633
3634            if Compilation_OK or else Keep_Going then
3635
3636               --  Re-read the updated library file
3637
3638               declare
3639                  Saved_Object_Consistency : constant Boolean :=
3640                                               Check_Object_Consistency;
3641
3642               begin
3643                  --  If compilation was not OK, or if output is not an object
3644                  --  file and we don't do the bind step, don't check for
3645                  --  object consistency.
3646
3647                  Check_Object_Consistency :=
3648                    Check_Object_Consistency
3649                      and Compilation_OK
3650                      and (Output_Is_Object or Do_Bind_Step);
3651
3652                  Text :=
3653                    Read_Library_Info_From_Full
3654                      (Data.Full_Lib_File, Data.Lib_File_Attr'Access);
3655
3656                  --  Restore Check_Object_Consistency to its initial value
3657
3658                  Check_Object_Consistency := Saved_Object_Consistency;
3659               end;
3660
3661               --  If an ALI file was generated by this compilation, scan the
3662               --  ALI file and record it.
3663
3664               --  If the scan fails, a previous ali file is inconsistent with
3665               --  the unit just compiled.
3666
3667               if Text /= null then
3668                  ALI :=
3669                    Scan_ALI
3670                      (Data.Lib_File, Text, Ignore_ED => False, Err => True);
3671
3672                  if ALI = No_ALI_Id then
3673
3674                     --  Record a failure only if not already done
3675
3676                     if Compilation_OK then
3677                        Inform
3678                          (Data.Lib_File,
3679                           "incompatible ALI file, please recompile");
3680                        Record_Failure
3681                          (Data.Full_Source_File, Data.Source_Unit);
3682                     end if;
3683
3684                  else
3685                     Record_Good_ALI (ALI, Data.Project);
3686                  end if;
3687
3688                  Free (Text);
3689
3690               --  If we could not read the ALI file that was just generated
3691               --  then there could be a problem reading either the ALI or the
3692               --  corresponding object file (if Check_Object_Consistency is
3693               --  set Read_Library_Info checks that the time stamp of the
3694               --  object file is more recent than that of the ALI). However,
3695               --  we record a failure only if not already done.
3696
3697               else
3698                  if Compilation_OK and not Syntax_Only then
3699                     Inform
3700                       (Data.Lib_File,
3701                        "WARNING: ALI or object file not found after compile");
3702
3703                     if not Is_Regular_File
3704                              (Get_Name_String (Name_Id (Data.Full_Lib_File)))
3705                     then
3706                        Inform (Data.Full_Lib_File, "not found");
3707                     end if;
3708
3709                     Record_Failure (Data.Full_Source_File, Data.Source_Unit);
3710                  end if;
3711               end if;
3712            end if;
3713         end if;
3714      end Wait_For_Available_Slot;
3715
3716   --  Start of processing for Compile_Sources
3717
3718   begin
3719      pragma Assert (Args'First = 1);
3720
3721      Outstanding_Compiles := 0;
3722      Running_Compile := new Comp_Data_Arr (1 .. Max_Process);
3723
3724      --  Package and Queue initializations
3725
3726      Good_ALI.Init;
3727
3728      if Initialize_ALI_Data then
3729         Initialize_ALI;
3730         Initialize_ALI_Source;
3731      end if;
3732
3733      --  The following two flags affect the behavior of ALI.Set_Source_Table.
3734      --  We set Check_Source_Files to True to ensure that source file time
3735      --  stamps are checked, and we set All_Sources to False to avoid checking
3736      --  the presence of the source files listed in the source dependency
3737      --  section of an ali file (which would be a mistake since the ali file
3738      --  may be obsolete).
3739
3740      Check_Source_Files := True;
3741      All_Sources        := False;
3742
3743      Queue.Insert
3744        ((Format  => Format_Gnatmake,
3745          File    => Main_Source,
3746          Project => Main_Project,
3747          Unit    => No_Unit_Name,
3748          Index   => Main_Index,
3749          Sid     => No_Source));
3750
3751      First_Compiled_File   := No_File;
3752      Most_Recent_Obj_File  := No_File;
3753      Most_Recent_Obj_Stamp := Empty_Time_Stamp;
3754      Main_Unit             := False;
3755
3756      --  Keep looping until there is no more work to do (the Q is empty)
3757      --  and all the outstanding compilations have terminated.
3758
3759      Make_Loop :
3760      while not Queue.Is_Empty or else Outstanding_Compiles > 0 loop
3761         exit Make_Loop when Must_Exit_Because_Of_Error;
3762         exit Make_Loop when Start_Compile_If_Possible (Args);
3763
3764         Wait_For_Available_Slot;
3765
3766         --  ??? Should be done as soon as we add a Good_ALI, wouldn't it avoid
3767         --  the need for a list of good ALI?
3768
3769         Fill_Queue_From_ALI_Files;
3770
3771         if Display_Compilation_Progress then
3772            Write_Str ("completed ");
3773            Write_Int (Int (Queue.Processed));
3774            Write_Str (" out of ");
3775            Write_Int (Int (Queue.Size));
3776            Write_Str (" (");
3777            Write_Int (Int ((Queue.Processed * 100) / Queue.Size));
3778            Write_Str ("%)...");
3779            Write_Eol;
3780         end if;
3781      end loop Make_Loop;
3782
3783      Compilation_Failures := Bad_Compilation_Count;
3784
3785      --  Compilation is finished
3786
3787      --  Delete any temporary configuration pragma file
3788
3789      if not Keep_Temporary_Files then
3790         Delete_Temp_Config_Files (Project_Tree);
3791      end if;
3792   end Compile_Sources;
3793
3794   ----------------------------------
3795   -- Configuration_Pragmas_Switch --
3796   ----------------------------------
3797
3798   function Configuration_Pragmas_Switch
3799     (For_Project : Project_Id) return Argument_List
3800   is
3801      The_Packages : Package_Id;
3802      Gnatmake     : Package_Id;
3803      Compiler     : Package_Id;
3804
3805      Global_Attribute : Variable_Value := Nil_Variable_Value;
3806      Local_Attribute  : Variable_Value := Nil_Variable_Value;
3807
3808      Global_Attribute_Present : Boolean := False;
3809      Local_Attribute_Present  : Boolean := False;
3810
3811      Result : Argument_List (1 .. 3);
3812      Last   : Natural := 0;
3813
3814   begin
3815      Prj.Env.Create_Config_Pragmas_File
3816        (For_Project, Project_Tree);
3817
3818      if For_Project.Config_File_Name /= No_Path then
3819         Temporary_Config_File := For_Project.Config_File_Temp;
3820         Last := 1;
3821         Result (1) :=
3822           new String'
3823             ("-gnatec=" & Get_Name_String (For_Project.Config_File_Name));
3824
3825      else
3826         Temporary_Config_File := False;
3827      end if;
3828
3829      --  Check for attribute Builder'Global_Configuration_Pragmas
3830
3831      The_Packages := Main_Project.Decl.Packages;
3832      Gnatmake :=
3833        Prj.Util.Value_Of
3834          (Name        => Name_Builder,
3835           In_Packages => The_Packages,
3836           Shared      => Project_Tree.Shared);
3837
3838      if Gnatmake /= No_Package then
3839         Global_Attribute := Prj.Util.Value_Of
3840           (Variable_Name => Name_Global_Configuration_Pragmas,
3841            In_Variables  => Project_Tree.Shared.Packages.Table
3842                               (Gnatmake).Decl.Attributes,
3843            Shared        => Project_Tree.Shared);
3844         Global_Attribute_Present :=
3845           Global_Attribute /= Nil_Variable_Value
3846           and then Get_Name_String (Global_Attribute.Value) /= "";
3847
3848         if Global_Attribute_Present then
3849            declare
3850               Path : constant String :=
3851                        Absolute_Path
3852                          (Path_Name_Type (Global_Attribute.Value),
3853                           Global_Attribute.Project);
3854            begin
3855               if not Is_Regular_File (Path) then
3856                  if Debug.Debug_Flag_F then
3857                     Make_Failed
3858                       ("cannot find configuration pragmas file "
3859                        & File_Name (Path));
3860                  else
3861                     Make_Failed
3862                       ("cannot find configuration pragmas file " & Path);
3863                  end if;
3864               end if;
3865
3866               Last := Last + 1;
3867               Result (Last) := new String'("-gnatec=" &  Path);
3868            end;
3869         end if;
3870      end if;
3871
3872      --  Check for attribute Compiler'Local_Configuration_Pragmas
3873
3874      The_Packages := For_Project.Decl.Packages;
3875      Compiler :=
3876        Prj.Util.Value_Of
3877          (Name        => Name_Compiler,
3878           In_Packages => The_Packages,
3879           Shared      => Project_Tree.Shared);
3880
3881      if Compiler /= No_Package then
3882         Local_Attribute := Prj.Util.Value_Of
3883           (Variable_Name => Name_Local_Configuration_Pragmas,
3884            In_Variables  => Project_Tree.Shared.Packages.Table
3885                               (Compiler).Decl.Attributes,
3886            Shared        => Project_Tree.Shared);
3887         Local_Attribute_Present :=
3888           Local_Attribute /= Nil_Variable_Value
3889           and then Get_Name_String (Local_Attribute.Value) /= "";
3890
3891         if Local_Attribute_Present then
3892            declare
3893               Path : constant String :=
3894                        Absolute_Path
3895                          (Path_Name_Type (Local_Attribute.Value),
3896                           Local_Attribute.Project);
3897            begin
3898               if not Is_Regular_File (Path) then
3899                  if Debug.Debug_Flag_F then
3900                     Make_Failed
3901                       ("cannot find configuration pragmas file "
3902                        & File_Name (Path));
3903
3904                  else
3905                     Make_Failed
3906                       ("cannot find configuration pragmas file " & Path);
3907                  end if;
3908               end if;
3909
3910               Last := Last + 1;
3911               Result (Last) := new String'("-gnatec=" & Path);
3912            end;
3913         end if;
3914      end if;
3915
3916      return Result (1 .. Last);
3917   end Configuration_Pragmas_Switch;
3918
3919   ---------------
3920   -- Debug_Msg --
3921   ---------------
3922
3923   procedure Debug_Msg (S : String; N : Name_Id) is
3924   begin
3925      if Debug.Debug_Flag_W then
3926         Write_Str ("   ... ");
3927         Write_Str (S);
3928         Write_Str (" ");
3929         Write_Name (N);
3930         Write_Eol;
3931      end if;
3932   end Debug_Msg;
3933
3934   procedure Debug_Msg (S : String; N : File_Name_Type) is
3935   begin
3936      Debug_Msg (S, Name_Id (N));
3937   end Debug_Msg;
3938
3939   procedure Debug_Msg (S : String; N : Unit_Name_Type) is
3940   begin
3941      Debug_Msg (S, Name_Id (N));
3942   end Debug_Msg;
3943
3944   -------------
3945   -- Display --
3946   -------------
3947
3948   procedure Display (Program : String; Args : Argument_List) is
3949   begin
3950      pragma Assert (Args'First = 1);
3951
3952      if Display_Executed_Programs then
3953         Write_Str (Program);
3954
3955         for J in Args'Range loop
3956
3957            --  Never display -gnatea nor -gnatez
3958
3959            if Args (J).all /= "-gnatea"
3960                 and then
3961               Args (J).all /= "-gnatez"
3962            then
3963               --  Do not display the mapping file argument automatically
3964               --  created when using a project file.
3965
3966               if Main_Project = No_Project
3967                 or else Opt.Keep_Temporary_Files
3968                 or else Args (J)'Length < 8
3969                 or else
3970                   Args (J) (Args (J)'First .. Args (J)'First + 6) /= "-gnatem"
3971               then
3972                  --  When -dn is not specified, do not display the config
3973                  --  pragmas switch (-gnatec) for the temporary file created
3974                  --  by the project manager (always the first -gnatec switch).
3975                  --  Reset Temporary_Config_File to False so that the eventual
3976                  --  other -gnatec switches will be displayed.
3977
3978                  if not Opt.Keep_Temporary_Files
3979                    and then Temporary_Config_File
3980                    and then Args (J)'Length > 7
3981                    and then Args (J) (Args (J)'First .. Args (J)'First + 6) =
3982                                                                    "-gnatec"
3983                  then
3984                     Temporary_Config_File := False;
3985
3986                     --  Do not display the -F=mapping_file switch for gnatbind
3987                     --  if -dn is not specified.
3988
3989                  elsif Opt.Keep_Temporary_Files
3990                    or else Args (J)'Length < 4
3991                    or else
3992                      Args (J) (Args (J)'First .. Args (J)'First + 2) /= "-F="
3993                  then
3994                     Write_Str (" ");
3995
3996                     --  If -df is used, only display file names, not path
3997                     --  names.
3998
3999                     if Debug.Debug_Flag_F then
4000                        declare
4001                           Equal_Pos : Natural;
4002
4003                        begin
4004                           Equal_Pos := Args (J)'First - 1;
4005                           for K in Args (J)'Range loop
4006                              if Args (J) (K) = '=' then
4007                                 Equal_Pos := K;
4008                                 exit;
4009                              end if;
4010                           end loop;
4011
4012                           if Is_Absolute_Path
4013                             (Args (J) (Equal_Pos + 1 .. Args (J)'Last))
4014                           then
4015                              Write_Str
4016                                (Args (J) (Args (J)'First .. Equal_Pos));
4017                              Write_Str
4018                                (File_Name
4019                                   (Args (J)
4020                                    (Equal_Pos + 1 .. Args (J)'Last)));
4021
4022                           else
4023                              Write_Str (Args (J).all);
4024                           end if;
4025                        end;
4026
4027                     else
4028                        Write_Str (Args (J).all);
4029                     end if;
4030                  end if;
4031               end if;
4032            end if;
4033         end loop;
4034
4035         Write_Eol;
4036      end if;
4037   end Display;
4038
4039   ----------------------
4040   -- Display_Commands --
4041   ----------------------
4042
4043   procedure Display_Commands (Display : Boolean := True) is
4044   begin
4045      Display_Executed_Programs := Display;
4046   end Display_Commands;
4047
4048   --------------------------
4049   -- Enter_Into_Obsoleted --
4050   --------------------------
4051
4052   procedure Enter_Into_Obsoleted (F : File_Name_Type) is
4053      Name  : constant String := Get_Name_String (F);
4054      First : Natural;
4055      F2    : File_Name_Type;
4056
4057   begin
4058      First := Name'Last;
4059      while First > Name'First
4060        and then not Is_Directory_Separator (Name (First - 1))
4061      loop
4062         First := First - 1;
4063      end loop;
4064
4065      if First /= Name'First then
4066         Name_Len := 0;
4067         Add_Str_To_Name_Buffer (Name (First .. Name'Last));
4068         F2 := Name_Find;
4069
4070      else
4071         F2 := F;
4072      end if;
4073
4074      Debug_Msg ("New entry in Obsoleted table:", F2);
4075      Obsoleted.Set (F2, True);
4076   end Enter_Into_Obsoleted;
4077
4078   ---------------
4079   -- Globalize --
4080   ---------------
4081
4082   procedure Globalize (Success : out Boolean) is
4083      Quiet_Str       : aliased String := "-quiet";
4084      Globalizer_Args : constant Argument_List :=
4085                          (1 => Quiet_Str'Unchecked_Access);
4086      Previous_Dir    : String_Access;
4087
4088      procedure Globalize_Dir (Dir : String);
4089      --  Call CodePeer globalizer on Dir
4090
4091      -------------------
4092      -- Globalize_Dir --
4093      -------------------
4094
4095      procedure Globalize_Dir (Dir : String) is
4096         Result : Boolean;
4097      begin
4098         if Previous_Dir = null or else Dir /= Previous_Dir.all then
4099            Free (Previous_Dir);
4100            Previous_Dir := new String'(Dir);
4101            Change_Dir (Dir);
4102            GNAT.OS_Lib.Spawn (Globalizer_Path.all, Globalizer_Args, Result);
4103            Success := Success and Result;
4104         end if;
4105      end Globalize_Dir;
4106
4107      procedure Globalize_Dirs is new
4108        Prj.Env.For_All_Object_Dirs (Globalize_Dir);
4109
4110   --  Start of procedure Globalize
4111
4112   begin
4113      Success := True;
4114      Display (Globalizer, Globalizer_Args);
4115
4116      if Globalizer_Path = null then
4117         Make_Failed ("error, unable to locate " & Globalizer);
4118      end if;
4119
4120      if Main_Project = No_Project then
4121         GNAT.OS_Lib.Spawn (Globalizer_Path.all, Globalizer_Args, Success);
4122      else
4123         Globalize_Dirs (Main_Project, Project_Tree);
4124      end if;
4125   end Globalize;
4126
4127   -------------------
4128   -- Linking_Phase --
4129   -------------------
4130
4131   procedure Linking_Phase
4132     (Non_Std_Executable : Boolean := False;
4133      Executable         : File_Name_Type := No_File;
4134      Main_ALI_File      : File_Name_Type)
4135   is
4136      Linker_Switches_Last : constant Integer := Linker_Switches.Last;
4137      Path_Option          : constant String_Access :=
4138                               MLib.Linker_Library_Path_Option;
4139      Libraries_Present    : Boolean := False;
4140      Current              : Natural;
4141      Proj2                : Project_Id;
4142      Depth                : Natural;
4143      Proj1                : Project_List;
4144
4145   begin
4146      if not Run_Path_Option then
4147         Linker_Switches.Increment_Last;
4148         Linker_Switches.Table (Linker_Switches.Last) :=
4149           new String'("-R");
4150      end if;
4151
4152      if Main_Project /= No_Project then
4153         Library_Paths.Set_Last (0);
4154         Library_Projs.Init;
4155
4156         if MLib.Tgt.Support_For_Libraries /= Prj.None then
4157
4158            --  Check for library projects
4159
4160            Proj1 := Project_Tree.Projects;
4161            while Proj1 /= null loop
4162               if Proj1.Project /= Main_Project
4163                 and then Proj1.Project.Library
4164               then
4165                  --  Add this project to table Library_Projs
4166
4167                  Libraries_Present := True;
4168                  Depth := Proj1.Project.Depth;
4169                  Library_Projs.Increment_Last;
4170                  Current := Library_Projs.Last;
4171
4172                  --  Any project with a greater depth should be after this
4173                  --  project in the list.
4174
4175                  while Current > 1 loop
4176                     Proj2 := Library_Projs.Table (Current - 1);
4177                     exit when Proj2.Depth <= Depth;
4178                     Library_Projs.Table (Current) := Proj2;
4179                     Current := Current - 1;
4180                  end loop;
4181
4182                  Library_Projs.Table (Current) := Proj1.Project;
4183
4184                  --  If it is not a static library and path option is set, add
4185                  --  it to the Library_Paths table.
4186
4187                  if Proj1.Project.Library_Kind /= Static
4188                    and then Proj1.Project.Extended_By = No_Project
4189                    and then Path_Option /= null
4190                  then
4191                     Library_Paths.Increment_Last;
4192                     Library_Paths.Table (Library_Paths.Last) :=
4193                       new String'
4194                         (Get_Name_String
4195                              (Proj1.Project.Library_Dir.Display_Name));
4196                  end if;
4197               end if;
4198
4199               Proj1 := Proj1.Next;
4200            end loop;
4201
4202            for Index in 1 .. Library_Projs.Last loop
4203               if Library_Projs.Table (Index).Extended_By = No_Project then
4204                  if Library_Projs.Table (Index).Library_Kind = Static then
4205                     Linker_Switches.Increment_Last;
4206                     Linker_Switches.Table (Linker_Switches.Last) :=
4207                       new String'
4208                         (Get_Name_String
4209                              (Library_Projs.Table
4210                                   (Index).Library_Dir.Display_Name) &
4211                          "lib" &
4212                          Get_Name_String
4213                            (Library_Projs.Table (Index).Library_Name) &
4214                          "." &
4215                          MLib.Tgt.Archive_Ext);
4216
4217                  else
4218                     --  Add the -L switch
4219
4220                     Linker_Switches.Increment_Last;
4221                     Linker_Switches.Table (Linker_Switches.Last) :=
4222                       new String'("-L" &
4223                         Get_Name_String (Library_Projs.Table (Index).
4224                                            Library_Dir.Display_Name));
4225
4226                     --  Add the -l switch
4227
4228                     Linker_Switches.Increment_Last;
4229                     Linker_Switches.Table (Linker_Switches.Last) :=
4230                       new String'("-l" &
4231                         Get_Name_String
4232                           (Library_Projs.Table (Index).Library_Name));
4233                  end if;
4234               end if;
4235            end loop;
4236         end if;
4237
4238         if Libraries_Present then
4239
4240            --  If Path_Option is not null, create the switch ("-Wl,-rpath,"
4241            --  or equivalent) with all the non-static library dirs plus the
4242            --  standard GNAT library dir. We do that only if Run_Path_Option
4243            --  is True (not disabled by -R switch).
4244
4245            if Run_Path_Option and then Path_Option /= null then
4246               declare
4247                  Option  : String_Access;
4248                  Length  : Natural := Path_Option'Length;
4249                  Current : Natural;
4250
4251               begin
4252                  if MLib.Separate_Run_Path_Options then
4253
4254                     --  We are going to create one switch of the form
4255                     --  "-Wl,-rpath,dir_N" for each directory to
4256                     --  consider.
4257
4258                     --  One switch for each library directory
4259
4260                     for Index in
4261                       Library_Paths.First .. Library_Paths.Last
4262                     loop
4263                        Linker_Switches.Increment_Last;
4264                        Linker_Switches.Table (Linker_Switches.Last) :=
4265                          new String'
4266                            (Path_Option.all &
4267                             Library_Paths.Table (Index).all);
4268                     end loop;
4269
4270                     --  One switch for the standard GNAT library dir
4271
4272                     Linker_Switches.Increment_Last;
4273                     Linker_Switches.Table (Linker_Switches.Last) :=
4274                       new String'(Path_Option.all & MLib.Utl.Lib_Directory);
4275
4276                  else
4277                     --  We are going to create one switch of the form
4278                     --  "-Wl,-rpath,dir_1:dir_2:dir_3"
4279
4280                     for Index in Library_Paths.First .. Library_Paths.Last
4281                     loop
4282                        --  Add the length of the library dir plus one for the
4283                        --  directory separator.
4284
4285                        Length :=
4286                          Length + Library_Paths.Table (Index)'Length + 1;
4287                     end loop;
4288
4289                     --  Finally, add the length of the standard GNAT
4290                     --  library dir.
4291
4292                     Length := Length + MLib.Utl.Lib_Directory'Length;
4293                     Option := new String (1 .. Length);
4294                     Option (1 .. Path_Option'Length) := Path_Option.all;
4295                     Current := Path_Option'Length;
4296
4297                     --  Put each library dir followed by a dir
4298                     --  separator.
4299
4300                     for Index in Library_Paths.First .. Library_Paths.Last
4301                     loop
4302                        Option
4303                          (Current + 1 ..
4304                             Current + Library_Paths.Table (Index)'Length) :=
4305                          Library_Paths.Table (Index).all;
4306                        Current :=
4307                          Current + Library_Paths.Table (Index)'Length + 1;
4308                        Option (Current) := Path_Separator;
4309                     end loop;
4310
4311                     --  Finally put the standard GNAT library dir
4312
4313                     Option
4314                       (Current + 1 ..
4315                          Current + MLib.Utl.Lib_Directory'Length) :=
4316                         MLib.Utl.Lib_Directory;
4317
4318                     --  And add the switch to the linker switches
4319
4320                     Linker_Switches.Increment_Last;
4321                     Linker_Switches.Table (Linker_Switches.Last) := Option;
4322                  end if;
4323               end;
4324            end if;
4325         end if;
4326
4327         --  Put the object directories in ADA_OBJECTS_PATH
4328
4329         Prj.Env.Set_Ada_Paths
4330           (Main_Project,
4331            Project_Tree,
4332            Including_Libraries => False,
4333            Include_Path        => False);
4334
4335         --  Check for attributes Linker'Linker_Options in projects other than
4336         --  the main project
4337
4338         declare
4339            Linker_Options : constant String_List :=
4340              Linker_Options_Switches
4341                (Main_Project,
4342                 Do_Fail => Make_Failed'Access,
4343                 In_Tree => Project_Tree);
4344         begin
4345            for Option in Linker_Options'Range loop
4346               Linker_Switches.Increment_Last;
4347               Linker_Switches.Table (Linker_Switches.Last) :=
4348                 Linker_Options (Option);
4349            end loop;
4350         end;
4351      end if;
4352
4353      if CodePeer_Mode then
4354         Linker_Switches.Increment_Last;
4355         Linker_Switches.Table (Linker_Switches.Last) :=
4356           new String'(CodePeer_Mode_String);
4357      end if;
4358
4359      --  Add switch -M to gnatlink if builder switch --create-map-file
4360      --  has been specified.
4361
4362      if Map_File /= null then
4363         Linker_Switches.Increment_Last;
4364         Linker_Switches.Table (Linker_Switches.Last) :=
4365           new String'("-M" & Map_File.all);
4366      end if;
4367
4368      declare
4369         Args : Argument_List
4370                  (Linker_Switches.First .. Linker_Switches.Last + 2);
4371
4372         Last_Arg : Integer := Linker_Switches.First - 1;
4373         Skip     : Boolean := False;
4374
4375      begin
4376         --  Get all the linker switches
4377
4378         for J in Linker_Switches.First .. Linker_Switches.Last loop
4379            if Skip then
4380               Skip := False;
4381
4382            elsif Non_Std_Executable
4383              and then Linker_Switches.Table (J).all = "-o"
4384            then
4385               Skip := True;
4386
4387               --  Here we capture and duplicate the linker argument. We
4388               --  need to do the duplication since the arguments will get
4389               --  normalized. Not doing so will result in calling normalized
4390               --  two times for the same set of arguments if gnatmake is
4391               --  passed multiple mains. This can result in the wrong
4392               --  argument being passed to the linker.
4393
4394            else
4395               Last_Arg := Last_Arg + 1;
4396               Args (Last_Arg) := new String'(Linker_Switches.Table (J).all);
4397            end if;
4398         end loop;
4399
4400         --  If need be, add the -o switch
4401
4402         if Non_Std_Executable then
4403            Last_Arg := Last_Arg + 1;
4404            Args (Last_Arg) := new String'("-o");
4405            Last_Arg := Last_Arg + 1;
4406            Args (Last_Arg) := new String'(Get_Name_String (Executable));
4407         end if;
4408
4409         --  And invoke the linker
4410
4411         declare
4412            Success : Boolean := False;
4413
4414         begin
4415            --  If gnatmake was invoked with --subdirs and no project file,
4416            --  put the executable in the subdirectory specified.
4417
4418            if Prj.Subdirs /= null and then Main_Project = No_Project then
4419               Change_Dir (Object_Directory_Path.all);
4420            end if;
4421
4422            Link (Main_ALI_File,
4423                  Link_With_Shared_Libgcc.all &
4424                  Args (Args'First .. Last_Arg),
4425                  Success);
4426
4427            if Success then
4428               Successful_Links.Increment_Last;
4429               Successful_Links.Table (Successful_Links.Last) := Main_ALI_File;
4430
4431            elsif Osint.Number_Of_Files = 1 or else not Keep_Going then
4432               Make_Failed ("*** link failed.");
4433
4434            else
4435               Set_Standard_Error;
4436               Write_Line ("*** link failed");
4437
4438               if Commands_To_Stdout then
4439                  Set_Standard_Output;
4440               end if;
4441
4442               Failed_Links.Increment_Last;
4443               Failed_Links.Table (Failed_Links.Last) := Main_ALI_File;
4444            end if;
4445         end;
4446      end;
4447
4448      Linker_Switches.Set_Last (Linker_Switches_Last);
4449   end Linking_Phase;
4450
4451   -------------------
4452   -- Binding_Phase --
4453   -------------------
4454
4455   procedure Binding_Phase
4456     (Stand_Alone_Libraries : Boolean := False;
4457      Main_ALI_File         : File_Name_Type)
4458   is
4459      Args : Argument_List (Binder_Switches.First .. Binder_Switches.Last + 2);
4460      --  The arguments for the invocation of gnatbind
4461
4462      Last_Arg : Natural := Binder_Switches.Last;
4463      --  Index of the last argument in Args
4464
4465      Shared_Libs : Boolean := False;
4466      --  Set to True when there are shared library project files or
4467      --  when gnatbind is invoked with -shared.
4468
4469      Proj : Project_List;
4470
4471      Mapping_Path : Path_Name_Type := No_Path;
4472      --  The path name of the mapping file
4473
4474   begin
4475      --  Check if there are shared libraries, so that gnatbind is called with
4476      --  -shared. Check also if gnatbind is called with -shared, so that
4477      --  gnatlink is called with -shared-libgcc ensuring that the shared
4478      --  version of libgcc will be used.
4479
4480      if Main_Project /= No_Project
4481        and then MLib.Tgt.Support_For_Libraries /= Prj.None
4482      then
4483         Proj := Project_Tree.Projects;
4484         while Proj /= null loop
4485            if Proj.Project.Library
4486              and then Proj.Project.Library_Kind /= Static
4487            then
4488               Shared_Libs := True;
4489               Bind_Shared := Shared_Switch'Access;
4490               exit;
4491            end if;
4492
4493            Proj := Proj.Next;
4494         end loop;
4495      end if;
4496
4497      --  Check now for switch -shared
4498
4499      if not Shared_Libs then
4500         for J in Binder_Switches.First .. Last_Arg loop
4501            if Binder_Switches.Table (J).all = "-shared" then
4502               Shared_Libs := True;
4503               exit;
4504            end if;
4505         end loop;
4506      end if;
4507
4508      --  If shared libraries present, invoke gnatlink with
4509      --  -shared-libgcc.
4510
4511      if Shared_Libs then
4512         Link_With_Shared_Libgcc := Shared_Libgcc_Switch'Access;
4513      end if;
4514
4515      --  Get all the binder switches
4516
4517      for J in Binder_Switches.First .. Last_Arg loop
4518         Args (J) := Binder_Switches.Table (J);
4519      end loop;
4520
4521      if Stand_Alone_Libraries then
4522         Last_Arg := Last_Arg + 1;
4523         Args (Last_Arg) := Force_Elab_Flags_String'Access;
4524      end if;
4525
4526      if CodePeer_Mode then
4527         Last_Arg := Last_Arg + 1;
4528         Args (Last_Arg) := CodePeer_Mode_String'Access;
4529      end if;
4530
4531      if Main_Project /= No_Project then
4532
4533         --  Put all the source directories in ADA_INCLUDE_PATH, and all the
4534         --  object directories in ADA_OBJECTS_PATH.
4535
4536         Prj.Env.Set_Ada_Paths
4537           (Project             => Main_Project,
4538            In_Tree             => Project_Tree,
4539            Including_Libraries => True,
4540            Include_Path        => Use_Include_Path_File);
4541
4542         --  If switch -C was specified, create a binder mapping file
4543
4544         if Create_Mapping_File then
4545            Mapping_Path := Create_Binder_Mapping_File (Project_Tree);
4546
4547            if Mapping_Path /= No_Path then
4548               Last_Arg := Last_Arg + 1;
4549               Args (Last_Arg) :=
4550                 new String'("-F=" & Get_Name_String (Mapping_Path));
4551            end if;
4552         end if;
4553      end if;
4554
4555      --  If gnatmake was invoked with --subdirs and no project file, put the
4556      --  binder generated files in the subdirectory specified.
4557
4558      if Main_Project = No_Project and then Prj.Subdirs /= null then
4559         Change_Dir (Object_Directory_Path.all);
4560      end if;
4561
4562      begin
4563         Bind (Main_ALI_File,
4564               Bind_Shared.all & Args (Args'First .. Last_Arg));
4565
4566      exception
4567         when others =>
4568
4569            --  Delete the temporary mapping file if one was created
4570
4571            if Mapping_Path /= No_Path then
4572               Delete_Temporary_File (Project_Tree.Shared, Mapping_Path);
4573            end if;
4574
4575            --  And reraise the exception
4576
4577            raise;
4578      end;
4579
4580      --  If -dn was not specified, delete the temporary mapping file
4581      --  if one was created.
4582
4583      if Mapping_Path /= No_Path then
4584         Delete_Temporary_File (Project_Tree.Shared, Mapping_Path);
4585      end if;
4586   end Binding_Phase;
4587
4588   -------------------
4589   -- Library_Phase --
4590   -------------------
4591
4592   procedure Library_Phase
4593     (Stand_Alone_Libraries : in out Boolean;
4594      Library_Rebuilt       : in out Boolean)
4595   is
4596      Depth   : Natural;
4597      Current : Natural;
4598      Proj1   : Project_List;
4599
4600      procedure Add_To_Library_Projs (Proj : Project_Id);
4601      --  Add project Project to table Library_Projs in decreasing depth order
4602
4603      --------------------------
4604      -- Add_To_Library_Projs --
4605      --------------------------
4606
4607      procedure Add_To_Library_Projs (Proj : Project_Id) is
4608         Prj : Project_Id;
4609
4610      begin
4611         Library_Projs.Increment_Last;
4612         Depth := Proj.Depth;
4613
4614         --  Put the projects in decreasing depth order, so that
4615         --  if libA depends on libB, libB is first in order.
4616
4617         Current := Library_Projs.Last;
4618         while Current > 1 loop
4619            Prj := Library_Projs.Table (Current - 1);
4620            exit when Prj.Depth >= Depth;
4621            Library_Projs.Table (Current) := Prj;
4622            Current := Current - 1;
4623         end loop;
4624
4625         Library_Projs.Table (Current) := Proj;
4626      end Add_To_Library_Projs;
4627
4628   --  Start of processing for Library_Phase
4629
4630   begin
4631      Library_Projs.Init;
4632
4633      --  Put in Library_Projs table all library project file ids when the
4634      --  library need to be rebuilt.
4635
4636      Proj1 := Project_Tree.Projects;
4637      while Proj1 /= null loop
4638         if Proj1.Project.Extended_By = No_Project then
4639            if Proj1.Project.Standalone_Library /= No then
4640               Stand_Alone_Libraries := True;
4641            end if;
4642
4643            if Proj1.Project.Library then
4644               MLib.Prj.Check_Library
4645                 (Proj1.Project, Project_Tree);
4646            end if;
4647
4648            if Proj1.Project.Need_To_Build_Lib then
4649               Add_To_Library_Projs (Proj1.Project);
4650            end if;
4651         end if;
4652
4653         Proj1 := Proj1.Next;
4654      end loop;
4655
4656      --  Check if importing libraries should be regenerated
4657      --  because at least an imported library will be
4658      --  regenerated or is more recent.
4659
4660      Proj1 := Project_Tree.Projects;
4661      while Proj1 /= null loop
4662         if Proj1.Project.Library
4663           and then Proj1.Project.Extended_By = No_Project
4664           and then Proj1.Project.Library_Kind /= Static
4665           and then not Proj1.Project.Need_To_Build_Lib
4666           and then not Proj1.Project.Externally_Built
4667         then
4668            declare
4669               List    : Project_List;
4670               Proj2   : Project_Id;
4671               Rebuild : Boolean := False;
4672
4673               Lib_Timestamp1 : constant Time_Stamp_Type :=
4674                                  Proj1.Project.Library_TS;
4675
4676            begin
4677               List := Proj1.Project.All_Imported_Projects;
4678               while List /= null loop
4679                  Proj2 := List.Project;
4680
4681                  if Proj2.Library then
4682                     if Proj2.Need_To_Build_Lib
4683                       or else
4684                         (Lib_Timestamp1 < Proj2.Library_TS)
4685                     then
4686                        Rebuild := True;
4687                        exit;
4688                     end if;
4689                  end if;
4690
4691                  List := List.Next;
4692               end loop;
4693
4694               if Rebuild then
4695                  Proj1.Project.Need_To_Build_Lib := True;
4696                  Add_To_Library_Projs (Proj1.Project);
4697               end if;
4698            end;
4699         end if;
4700
4701         Proj1 := Proj1.Next;
4702      end loop;
4703
4704      --  Reset the flags Need_To_Build_Lib for the next main, to avoid
4705      --  rebuilding libraries uselessly.
4706
4707      Proj1 := Project_Tree.Projects;
4708      while Proj1 /= null loop
4709         Proj1.Project.Need_To_Build_Lib := False;
4710         Proj1 := Proj1.Next;
4711      end loop;
4712
4713      --  Build the libraries, if any need to be built
4714
4715      for J in 1 .. Library_Projs.Last loop
4716         Library_Rebuilt := True;
4717
4718         --  If a library is rebuilt, then executables are obsolete
4719
4720         Executable_Obsolete := True;
4721
4722         MLib.Prj.Build_Library
4723           (For_Project   => Library_Projs.Table (J),
4724            In_Tree       => Project_Tree,
4725            Gnatbind      => Gnatbind.all,
4726            Gnatbind_Path => Gnatbind_Path,
4727            Gcc           => Gcc.all,
4728            Gcc_Path      => Gcc_Path);
4729      end loop;
4730   end Library_Phase;
4731
4732   -----------------------
4733   -- Compilation_Phase --
4734   -----------------------
4735
4736   procedure Compilation_Phase
4737     (Main_Source_File           : File_Name_Type;
4738      Current_Main_Index         : Int := 0;
4739      Total_Compilation_Failures : in out Natural;
4740      Stand_Alone_Libraries      : in out Boolean;
4741      Executable                 : File_Name_Type := No_File;
4742      Is_Last_Main               : Boolean;
4743      Stop_Compile               : out Boolean)
4744   is
4745      Args                : Argument_List (1 .. Gcc_Switches.Last);
4746      First_Compiled_File : File_Name_Type;
4747      Youngest_Obj_File   : File_Name_Type;
4748      Youngest_Obj_Stamp  : Time_Stamp_Type;
4749
4750      Is_Main_Unit : Boolean;
4751      --  Set True by Compile_Sources if Main_Source_File can be a main unit
4752
4753      Compilation_Failures : Natural;
4754
4755      Executable_Stamp : Time_Stamp_Type;
4756
4757      Library_Rebuilt : Boolean := False;
4758
4759   begin
4760      Stop_Compile := False;
4761
4762      for J in 1 .. Gcc_Switches.Last loop
4763         Args (J) := Gcc_Switches.Table (J);
4764      end loop;
4765
4766      --  Now we invoke Compile_Sources for the current main
4767
4768      Compile_Sources
4769        (Main_Source           => Main_Source_File,
4770         Args                  => Args,
4771         First_Compiled_File   => First_Compiled_File,
4772         Most_Recent_Obj_File  => Youngest_Obj_File,
4773         Most_Recent_Obj_Stamp => Youngest_Obj_Stamp,
4774         Main_Unit             => Is_Main_Unit,
4775         Main_Index            => Current_Main_Index,
4776         Compilation_Failures  => Compilation_Failures,
4777         Check_Readonly_Files  => Check_Readonly_Files,
4778         Do_Not_Execute        => Do_Not_Execute,
4779         Force_Compilations    => Force_Compilations,
4780         In_Place_Mode         => In_Place_Mode,
4781         Keep_Going            => Keep_Going,
4782         Initialize_ALI_Data   => True,
4783         Max_Process           => Saved_Maximum_Processes);
4784
4785      if Verbose_Mode then
4786         Write_Str ("End of compilation");
4787         Write_Eol;
4788      end if;
4789
4790      Total_Compilation_Failures :=
4791        Total_Compilation_Failures + Compilation_Failures;
4792
4793      if Total_Compilation_Failures /= 0 then
4794         Stop_Compile := True;
4795         return;
4796      end if;
4797
4798      --  Regenerate libraries, if there are any and if object files have been
4799      --  regenerated. Note that we skip this in CodePeer mode because we don't
4800      --  need libraries in this case, and more importantly, the object files
4801      --  may not be present.
4802
4803      if Main_Project /= No_Project
4804        and then not CodePeer_Mode
4805        and then MLib.Tgt.Support_For_Libraries /= Prj.None
4806        and then (Do_Bind_Step
4807                   or Unique_Compile_All_Projects
4808                   or not Compile_Only)
4809        and then (Do_Link_Step or Is_Last_Main)
4810      then
4811         Library_Phase
4812           (Stand_Alone_Libraries => Stand_Alone_Libraries,
4813            Library_Rebuilt       => Library_Rebuilt);
4814      end if;
4815
4816      if List_Dependencies then
4817         if First_Compiled_File /= No_File then
4818            Inform
4819              (First_Compiled_File,
4820               "must be recompiled. Can't generate dependence list.");
4821         else
4822            List_Depend;
4823         end if;
4824
4825      elsif First_Compiled_File = No_File
4826        and then not Do_Bind_Step
4827        and then not Quiet_Output
4828        and then not Library_Rebuilt
4829        and then Osint.Number_Of_Files = 1
4830      then
4831         Inform (Msg => "objects up to date.");
4832         Stop_Compile := True;
4833         return;
4834
4835      elsif Do_Not_Execute and then First_Compiled_File /= No_File then
4836         Write_Name (First_Compiled_File);
4837         Write_Eol;
4838      end if;
4839
4840      --  Stop after compile step if any of:
4841
4842      --    1) -n (Do_Not_Execute) specified
4843
4844      --    2) -M (List_Dependencies) specified (also sets
4845      --       Do_Not_Execute above, so this is probably superfluous).
4846
4847      --    3) -c (Compile_Only) specified, but not -b (Bind_Only)
4848
4849      --    4) Made unit cannot be a main unit
4850
4851      if ((Do_Not_Execute
4852            or List_Dependencies
4853            or not Do_Bind_Step
4854            or not Is_Main_Unit)
4855          and not No_Main_Subprogram
4856          and not Build_Bind_And_Link_Full_Project)
4857        or Unique_Compile
4858      then
4859         Stop_Compile := True;
4860         return;
4861      end if;
4862
4863      --  If the objects were up-to-date check if the executable file is also
4864      --  up-to-date. For now always bind and link on the JVM since there is
4865      --  currently no simple way to check whether objects are up to date wrt
4866      --  the executable. Same in CodePeer mode where there is no executable.
4867
4868      if Targparm.VM_Target /= JVM_Target
4869        and then not CodePeer_Mode
4870        and then First_Compiled_File = No_File
4871      then
4872         Executable_Stamp := File_Stamp (Executable);
4873
4874         if not Executable_Obsolete then
4875            Executable_Obsolete := Youngest_Obj_Stamp > Executable_Stamp;
4876         end if;
4877
4878         if not Executable_Obsolete then
4879            for Index in reverse 1 .. Dependencies.Last loop
4880               if Is_In_Obsoleted (Dependencies.Table (Index).Depends_On) then
4881                  Enter_Into_Obsoleted (Dependencies.Table (Index).This);
4882               end if;
4883            end loop;
4884
4885            Executable_Obsolete := Is_In_Obsoleted (Main_Source_File);
4886            Dependencies.Init;
4887         end if;
4888
4889         if not Executable_Obsolete then
4890
4891            --  If no Ada object files obsolete the executable, check
4892            --  for younger or missing linker files.
4893
4894            Check_Linker_Options
4895              (Executable_Stamp,
4896               Youngest_Obj_File,
4897               Youngest_Obj_Stamp);
4898
4899            Executable_Obsolete := Youngest_Obj_File /= No_File;
4900         end if;
4901
4902         --  Check if any library file is more recent than the
4903         --  executable: there may be an externally built library
4904         --  file that has been modified.
4905
4906         if not Executable_Obsolete and then Main_Project /= No_Project then
4907            declare
4908               Proj1 : Project_List;
4909
4910            begin
4911               Proj1 := Project_Tree.Projects;
4912               while Proj1 /= null loop
4913                  if Proj1.Project.Library
4914                    and then Proj1.Project.Library_TS > Executable_Stamp
4915                  then
4916                     Executable_Obsolete := True;
4917                     Youngest_Obj_Stamp := Proj1.Project.Library_TS;
4918                     Name_Len := 0;
4919                     Add_Str_To_Name_Buffer ("library ");
4920                     Add_Str_To_Name_Buffer
4921                       (Get_Name_String (Proj1.Project.Library_Name));
4922                     Youngest_Obj_File := Name_Find;
4923                     exit;
4924                  end if;
4925
4926                  Proj1 := Proj1.Next;
4927               end loop;
4928            end;
4929         end if;
4930
4931         --  Return if the executable is up to date and otherwise
4932         --  motivate the relink/rebind.
4933
4934         if not Executable_Obsolete then
4935            if not Quiet_Output then
4936               Inform (Executable, "up to date.");
4937            end if;
4938
4939            Stop_Compile := True;
4940            return;
4941         end if;
4942
4943         if Executable_Stamp (1) = ' ' then
4944            if not No_Main_Subprogram then
4945               Verbose_Msg (Executable, "missing.", Prefix => "  ");
4946            end if;
4947
4948         elsif Youngest_Obj_Stamp (1) = ' ' then
4949            Verbose_Msg
4950              (Youngest_Obj_File, "missing.",  Prefix => "  ");
4951
4952         elsif Youngest_Obj_Stamp > Executable_Stamp then
4953            Verbose_Msg
4954              (Youngest_Obj_File,
4955               "(" & String (Youngest_Obj_Stamp) & ") newer than",
4956               Executable,
4957               "(" & String (Executable_Stamp) & ")");
4958
4959         else
4960            Verbose_Msg
4961              (Executable, "needs to be rebuilt", Prefix => "  ");
4962
4963         end if;
4964      end if;
4965   end Compilation_Phase;
4966
4967   ----------------------------------------
4968   -- Resolve_Relative_Names_In_Switches --
4969   ----------------------------------------
4970
4971   procedure Resolve_Relative_Names_In_Switches (Current_Work_Dir : String) is
4972   begin
4973      --  If a relative path output file has been specified, we add the
4974      --  exec directory.
4975
4976      for J in reverse 1 .. Saved_Linker_Switches.Last - 1 loop
4977         if Saved_Linker_Switches.Table (J).all = Output_Flag.all then
4978            declare
4979               Exec_File_Name : constant String :=
4980                                  Saved_Linker_Switches.Table (J + 1).all;
4981
4982            begin
4983               if not Is_Absolute_Path (Exec_File_Name) then
4984                  Get_Name_String (Main_Project.Exec_Directory.Display_Name);
4985                  Add_Str_To_Name_Buffer (Exec_File_Name);
4986                  Saved_Linker_Switches.Table (J + 1) :=
4987                    new String'(Name_Buffer (1 .. Name_Len));
4988               end if;
4989            end;
4990
4991            exit;
4992         end if;
4993      end loop;
4994
4995      --  If we are using a project file, for relative paths we add the
4996      --  current working directory for any relative path on the command
4997      --  line and the project directory, for any relative path in the
4998      --  project file.
4999
5000      declare
5001         Dir_Path : constant String :=
5002                      Get_Name_String (Main_Project.Directory.Display_Name);
5003      begin
5004         for J in 1 .. Binder_Switches.Last loop
5005            Ensure_Absolute_Path
5006              (Binder_Switches.Table (J),
5007               Do_Fail => Make_Failed'Access,
5008               Parent => Dir_Path, For_Gnatbind => True);
5009         end loop;
5010
5011         for J in 1 .. Saved_Binder_Switches.Last loop
5012            Ensure_Absolute_Path
5013              (Saved_Binder_Switches.Table (J),
5014               Do_Fail             => Make_Failed'Access,
5015               Parent              => Current_Work_Dir,
5016               For_Gnatbind        => True);
5017         end loop;
5018
5019         for J in 1 .. Linker_Switches.Last loop
5020            Ensure_Absolute_Path
5021              (Linker_Switches.Table (J),
5022               Parent  => Dir_Path,
5023               Do_Fail => Make_Failed'Access);
5024         end loop;
5025
5026         for J in 1 .. Saved_Linker_Switches.Last loop
5027            Ensure_Absolute_Path
5028              (Saved_Linker_Switches.Table (J),
5029               Do_Fail => Make_Failed'Access,
5030               Parent  => Current_Work_Dir);
5031         end loop;
5032
5033         for J in 1 .. Gcc_Switches.Last loop
5034            Ensure_Absolute_Path
5035              (Gcc_Switches.Table (J),
5036               Do_Fail              => Make_Failed'Access,
5037               Parent               => Dir_Path,
5038               Including_Non_Switch => False);
5039         end loop;
5040
5041         for J in 1 .. Saved_Gcc_Switches.Last loop
5042            Ensure_Absolute_Path
5043              (Saved_Gcc_Switches.Table (J),
5044               Parent               => Current_Work_Dir,
5045               Do_Fail              => Make_Failed'Access,
5046               Including_Non_Switch => False);
5047         end loop;
5048      end;
5049   end Resolve_Relative_Names_In_Switches;
5050
5051   -----------------------------------
5052   -- Queue_Library_Project_Sources --
5053   -----------------------------------
5054
5055   procedure Queue_Library_Project_Sources is
5056   begin
5057      if not Unique_Compile
5058        and then MLib.Tgt.Support_For_Libraries /= Prj.None
5059      then
5060         declare
5061            Proj : Project_List;
5062
5063         begin
5064            Proj := Project_Tree.Projects;
5065            while Proj /= null loop
5066               if Proj.Project.Library then
5067                  Proj.Project.Need_To_Build_Lib :=
5068                    not MLib.Tgt.Library_Exists_For
5069                          (Proj.Project, Project_Tree)
5070                    and then not Proj.Project.Externally_Built;
5071
5072                  if Proj.Project.Need_To_Build_Lib then
5073
5074                     --  If there is no object directory, then it will be
5075                     --  impossible to build the library, so fail immediately.
5076
5077                     if Proj.Project.Object_Directory = No_Path_Information
5078                     then
5079                        Make_Failed
5080                          ("no object files to build library for"
5081                           & " project """
5082                           & Get_Name_String (Proj.Project.Name)
5083                           & """");
5084                        Proj.Project.Need_To_Build_Lib := False;
5085
5086                     else
5087                        if Verbose_Mode then
5088                           Write_Str
5089                             ("Library file does not exist for "
5090                              & "project """);
5091                           Write_Str
5092                             (Get_Name_String (Proj.Project.Name));
5093                           Write_Line ("""");
5094                        end if;
5095
5096                        Insert_Project_Sources
5097                          (The_Project  => Proj.Project,
5098                           All_Projects => False,
5099                           Into_Q       => True);
5100                     end if;
5101                  end if;
5102               end if;
5103
5104               Proj := Proj.Next;
5105            end loop;
5106         end;
5107      end if;
5108   end Queue_Library_Project_Sources;
5109
5110   ------------------------
5111   -- Compute_Executable --
5112   ------------------------
5113
5114   procedure Compute_Executable
5115     (Main_Source_File   : File_Name_Type;
5116      Executable         : out File_Name_Type;
5117      Non_Std_Executable : out Boolean)
5118   is
5119   begin
5120      Executable          := No_File;
5121      Non_Std_Executable  :=
5122        Targparm.Executable_Extension_On_Target /= No_Name;
5123
5124      --  Look inside the linker switches to see if the name of the final
5125      --  executable program was specified.
5126
5127      for J in reverse Linker_Switches.First .. Linker_Switches.Last loop
5128         if Linker_Switches.Table (J).all = Output_Flag.all then
5129            pragma Assert (J < Linker_Switches.Last);
5130
5131            --  We cannot specify a single executable for several main
5132            --  subprograms
5133
5134            if Osint.Number_Of_Files > 1 then
5135               Fail ("cannot specify a single executable for several mains");
5136            end if;
5137
5138            Name_Len := 0;
5139            Add_Str_To_Name_Buffer (Linker_Switches.Table (J + 1).all);
5140            Executable := Name_Enter;
5141
5142            Verbose_Msg (Executable, "final executable");
5143         end if;
5144      end loop;
5145
5146      --  If the name of the final executable program was not specified then
5147      --  construct it from the main input file.
5148
5149      if Executable = No_File then
5150         if Main_Project = No_Project then
5151            Executable := Executable_Name (Strip_Suffix (Main_Source_File));
5152
5153         else
5154            --  If we are using a project file, we attempt to remove the body
5155            --  (or spec) termination of the main subprogram. We find it the
5156            --  naming scheme of the project file. This avoids generating an
5157            --  executable "main.2" for a main subprogram "main.2.ada", when
5158            --  the body termination is ".2.ada".
5159
5160            Executable :=
5161              Prj.Util.Executable_Of
5162                (Main_Project, Project_Tree.Shared,
5163                 Main_Source_File, Main_Index);
5164         end if;
5165      end if;
5166
5167      if Main_Project /= No_Project
5168        and then Main_Project.Exec_Directory /= No_Path_Information
5169      then
5170         declare
5171            Exec_File_Name : constant String := Get_Name_String (Executable);
5172         begin
5173            if not Is_Absolute_Path (Exec_File_Name) then
5174               Get_Name_String (Main_Project.Exec_Directory.Display_Name);
5175               Add_Str_To_Name_Buffer (Exec_File_Name);
5176               Executable := Name_Find;
5177            end if;
5178
5179            Non_Std_Executable := True;
5180         end;
5181      end if;
5182   end Compute_Executable;
5183
5184   -------------------------------
5185   -- Compute_Switches_For_Main --
5186   -------------------------------
5187
5188   procedure Compute_Switches_For_Main
5189     (Main_Source_File  : in out File_Name_Type;
5190      Root_Environment  : in out Prj.Tree.Environment;
5191      Compute_Builder   : Boolean;
5192      Current_Work_Dir  : String)
5193   is
5194      function Add_Global_Switches
5195        (Switch      : String;
5196         For_Lang    : Name_Id;
5197         For_Builder : Boolean;
5198         Has_Global_Compilation_Switches : Boolean) return Boolean;
5199      --  Handles builder and global compilation switches, as read from the
5200      --  project file.
5201
5202      -------------------------
5203      -- Add_Global_Switches --
5204      -------------------------
5205
5206      function Add_Global_Switches
5207        (Switch      : String;
5208         For_Lang    : Name_Id;
5209         For_Builder : Boolean;
5210         Has_Global_Compilation_Switches : Boolean) return Boolean
5211      is
5212         pragma Unreferenced (For_Lang);
5213
5214      begin
5215         if For_Builder then
5216            Program_Args := None;
5217            Switch_May_Be_Passed_To_The_Compiler :=
5218              not Has_Global_Compilation_Switches;
5219            Scan_Make_Arg (Root_Environment, Switch, And_Save => False);
5220
5221            return Gnatmake_Switch_Found
5222              or else Switch_May_Be_Passed_To_The_Compiler;
5223         else
5224            Add_Switch (Switch, Compiler, And_Save => False);
5225            return True;
5226         end if;
5227      end Add_Global_Switches;
5228
5229      procedure Do_Compute_Builder_Switches
5230      is new Makeutl.Compute_Builder_Switches (Add_Global_Switches);
5231
5232   --  Start of processing for Compute_Switches_For_Main
5233
5234   begin
5235      if Main_Project /= No_Project then
5236         declare
5237            Main_Source_File_Name : constant String :=
5238                                      Get_Name_String (Main_Source_File);
5239
5240            Main_Unit_File_Name   : constant String :=
5241              Prj.Env.File_Name_Of_Library_Unit_Body
5242                (Name              => Main_Source_File_Name,
5243                 Project           => Main_Project,
5244                 In_Tree           => Project_Tree,
5245                 Main_Project_Only => not Unique_Compile);
5246
5247            The_Packages : constant Package_Id := Main_Project.Decl.Packages;
5248
5249            Binder_Package : constant Prj.Package_Id :=
5250                               Prj.Util.Value_Of
5251                                 (Name        => Name_Binder,
5252                                  In_Packages => The_Packages,
5253                                  Shared      => Project_Tree.Shared);
5254
5255            Linker_Package : constant Prj.Package_Id :=
5256                               Prj.Util.Value_Of
5257                                 (Name        => Name_Linker,
5258                                  In_Packages => The_Packages,
5259                                  Shared      => Project_Tree.Shared);
5260
5261         begin
5262            --  We fail if we cannot find the main source file
5263
5264            if Main_Unit_File_Name = "" then
5265               Make_Failed ('"' & Main_Source_File_Name
5266                            & """ is not a unit of project "
5267                            & Project_File_Name.all & ".");
5268            end if;
5269
5270            --  Remove any directory information from the main source file
5271            --  file name.
5272
5273            declare
5274               Pos : Natural := Main_Unit_File_Name'Last;
5275
5276            begin
5277               loop
5278                  exit when Pos < Main_Unit_File_Name'First
5279                    or else Main_Unit_File_Name (Pos) = Directory_Separator;
5280                  Pos := Pos - 1;
5281               end loop;
5282
5283               Name_Len := Main_Unit_File_Name'Last - Pos;
5284
5285               Name_Buffer (1 .. Name_Len) :=
5286                 Main_Unit_File_Name (Pos + 1 .. Main_Unit_File_Name'Last);
5287
5288               Main_Source_File := Name_Find;
5289
5290               --  We only output the main source file if there is only one
5291
5292               if Verbose_Mode and then Osint.Number_Of_Files = 1 then
5293                  Write_Str ("Main source file: """);
5294                  Write_Str (Main_Unit_File_Name
5295                             (Pos + 1 .. Main_Unit_File_Name'Last));
5296                  Write_Line (""".");
5297               end if;
5298            end;
5299
5300            if Compute_Builder then
5301               Do_Compute_Builder_Switches
5302                 (Project_Tree     => Project_Tree,
5303                  Env              => Root_Environment,
5304                  Main_Project     => Main_Project,
5305                  Only_For_Lang    => Name_Ada);
5306
5307               Resolve_Relative_Names_In_Switches
5308                 (Current_Work_Dir => Current_Work_Dir);
5309
5310               --  Record current last switch index for tables Binder_Switches
5311               --  and Linker_Switches, so that these tables may be reset
5312               --  before each main, before adding switches from the project
5313               --  file and from the command line.
5314
5315               Last_Binder_Switch := Binder_Switches.Last;
5316               Last_Linker_Switch := Linker_Switches.Last;
5317
5318            else
5319               --  Reset the tables Binder_Switches and Linker_Switches
5320
5321               Binder_Switches.Set_Last (Last_Binder_Switch);
5322               Linker_Switches.Set_Last (Last_Linker_Switch);
5323            end if;
5324
5325            --  We now deal with the binder and linker switches. If no project
5326            --  file is used, there is nothing to do because the binder and
5327            --  linker switches are the same for all mains.
5328
5329            --  Add binder switches from the project file for the first main
5330
5331            if Do_Bind_Step and then Binder_Package /= No_Package then
5332               if Verbose_Mode then
5333                  Write_Str ("Adding binder switches for """);
5334                  Write_Str (Main_Unit_File_Name);
5335                  Write_Line (""".");
5336               end if;
5337
5338               Add_Switches
5339                 (Env               => Root_Environment,
5340                  File_Name         => Main_Unit_File_Name,
5341                  The_Package       => Binder_Package,
5342                  Program           => Binder);
5343            end if;
5344
5345            --  Add linker switches from the project file for the first main
5346
5347            if Do_Link_Step and then Linker_Package /= No_Package then
5348               if Verbose_Mode then
5349                  Write_Str ("Adding linker switches for""");
5350                  Write_Str (Main_Unit_File_Name);
5351                  Write_Line (""".");
5352               end if;
5353
5354               Add_Switches
5355                 (Env               => Root_Environment,
5356                  File_Name         => Main_Unit_File_Name,
5357                  The_Package       => Linker_Package,
5358                  Program           => Linker);
5359            end if;
5360
5361            --  As we are using a project file, for relative paths we add the
5362            --  current working directory for any relative path on the command
5363            --  line and the project directory, for any relative path in the
5364            --  project file.
5365
5366            declare
5367               Dir_Path : constant String :=
5368                 Get_Name_String (Main_Project.Directory.Display_Name);
5369
5370            begin
5371               for J in Last_Binder_Switch + 1 .. Binder_Switches.Last loop
5372                  Ensure_Absolute_Path
5373                    (Binder_Switches.Table (J),
5374                     Do_Fail => Make_Failed'Access,
5375                     Parent  => Dir_Path, For_Gnatbind => True);
5376               end loop;
5377
5378               for J in Last_Linker_Switch + 1 .. Linker_Switches.Last loop
5379                  Ensure_Absolute_Path
5380                    (Linker_Switches.Table (J),
5381                     Parent  => Dir_Path,
5382                     Do_Fail => Make_Failed'Access);
5383               end loop;
5384            end;
5385         end;
5386
5387      else
5388         if not Compute_Builder then
5389
5390            --  Reset the tables Binder_Switches and Linker_Switches
5391
5392            Binder_Switches.Set_Last (Last_Binder_Switch);
5393            Linker_Switches.Set_Last (Last_Linker_Switch);
5394         end if;
5395      end if;
5396
5397      Check_Steps;
5398
5399      if Compute_Builder then
5400         Display_Commands (not Quiet_Output);
5401      end if;
5402
5403      --  We now put in the Binder_Switches and Linker_Switches tables, the
5404      --  binder and linker switches of the command line that have been put in
5405      --  the Saved_ tables. If a project file was used, then the command line
5406      --  switches will follow the project file switches.
5407
5408      for J in 1 .. Saved_Binder_Switches.Last loop
5409         Add_Switch
5410           (Saved_Binder_Switches.Table (J),
5411            Binder,
5412            And_Save => False);
5413      end loop;
5414
5415      for J in 1 .. Saved_Linker_Switches.Last loop
5416         Add_Switch
5417           (Saved_Linker_Switches.Table (J),
5418            Linker,
5419            And_Save => False);
5420      end loop;
5421   end Compute_Switches_For_Main;
5422
5423   --------------
5424   -- Gnatmake --
5425   --------------
5426
5427   procedure Gnatmake is
5428      Main_Source_File : File_Name_Type;
5429      --  The source file containing the main compilation unit
5430
5431      Total_Compilation_Failures : Natural := 0;
5432
5433      Main_ALI_File : File_Name_Type;
5434      --  The ali file corresponding to Main_Source_File
5435
5436      Executable : File_Name_Type := No_File;
5437      --  The file name of an executable
5438
5439      Non_Std_Executable : Boolean := False;
5440      --  Non_Std_Executable is set to True when there is a possibility that
5441      --  the linker will not choose the correct executable file name.
5442
5443      Current_Work_Dir : constant String_Access :=
5444                                    new String'(Get_Current_Dir);
5445      --  The current working directory, used to modify some relative path
5446      --  switches on the command line when a project file is used.
5447
5448      Current_Main_Index : Int := 0;
5449      --  If not zero, the index of the current main unit in its source file
5450
5451      Is_First_Main : Boolean;
5452      --  Whether we are processing the first main
5453
5454      Stand_Alone_Libraries : Boolean := False;
5455      --  Set to True when there are Stand-Alone Libraries, so that gnatbind
5456      --  is invoked with the -F switch to force checking of elaboration flags.
5457
5458      Project_Node_Tree : Project_Node_Tree_Ref;
5459
5460      Stop_Compile : Boolean;
5461
5462      Discard : Boolean;
5463      pragma Warnings (Off, Discard);
5464
5465      procedure Check_Mains;
5466      --  Check that the main subprograms do exist and that they all
5467      --  belong to the same project file.
5468
5469      -----------------
5470      -- Check_Mains --
5471      -----------------
5472
5473      procedure Check_Mains is
5474         Real_Main_Project : Project_Id := No_Project;
5475         Info              : Main_Info;
5476         Proj              : Project_Id;
5477
5478      begin
5479         if Mains.Number_Of_Mains (Project_Tree) = 0
5480           and then not Unique_Compile
5481         then
5482            Mains.Fill_From_Project (Main_Project, Project_Tree);
5483         end if;
5484
5485         Mains.Complete_Mains
5486           (Root_Environment.Flags, Main_Project, Project_Tree);
5487
5488         --  If we have multiple mains on the command line, they need not
5489         --  belong to the root project, but they must all belong to the same
5490         --  project.
5491
5492         if not Unique_Compile then
5493            Mains.Reset;
5494            loop
5495               Info := Mains.Next_Main;
5496               exit when Info = No_Main_Info;
5497
5498               Proj := Ultimate_Extending_Project_Of (Info.Project);
5499
5500               if Real_Main_Project = No_Project then
5501                  Real_Main_Project := Proj;
5502               elsif Real_Main_Project /= Proj then
5503                  Make_Failed
5504                    ("""" & Get_Name_String (Info.File) &
5505                     """ is not a source of project " &
5506                     Get_Name_String (Real_Main_Project.Name));
5507               end if;
5508            end loop;
5509
5510            if Real_Main_Project /= No_Project then
5511               Main_Project := Real_Main_Project;
5512            end if;
5513
5514            Debug_Output ("After checking mains, main project is",
5515                          Main_Project.Name);
5516
5517         else
5518            --  For all mains on the command line, make sure they were in
5519            --  osint. In particular, if the user has specified a multi-unit
5520            --  source file, the call to Complete_Mains will have expanded
5521            --  the list of mains to all its units, and we must now put them
5522            --  back on the command line.
5523            --  ??? This will not be necessary when gnatmake shares the same
5524            --  queue as gprbuild and processes the file directly on the queue.
5525
5526            Mains.Reset;
5527            loop
5528               Info := Mains.Next_Main;
5529               exit when Info = No_Main_Info;
5530
5531               if Info.Index /= 0 then
5532                  Debug_Output ("Add to command line index="
5533                                & Info.Index'Img, Name_Id (Info.File));
5534                  Osint.Add_File (Get_Name_String (Info.File), Info.Index);
5535               end if;
5536            end loop;
5537         end if;
5538      end Check_Mains;
5539
5540   --  Start of processing for Gnatmake
5541
5542   --  This body is very long, should be broken down???
5543
5544   begin
5545      Install_Int_Handler (Sigint_Intercepted'Access);
5546
5547      Do_Compile_Step := True;
5548      Do_Bind_Step    := True;
5549      Do_Link_Step    := True;
5550
5551      Obsoleted.Reset;
5552
5553      Make.Initialize (Project_Node_Tree, Root_Environment);
5554
5555      Bind_Shared := No_Shared_Switch'Access;
5556      Link_With_Shared_Libgcc := No_Shared_Libgcc_Switch'Access;
5557
5558      Failed_Links.Set_Last (0);
5559      Successful_Links.Set_Last (0);
5560
5561      --  Special case when switch -B was specified
5562
5563      if Build_Bind_And_Link_Full_Project then
5564
5565         --  When switch -B is specified, there must be a project file
5566
5567         if Main_Project = No_Project then
5568            Make_Failed ("-B cannot be used without a project file");
5569
5570         --  No main program may be specified on the command line
5571
5572         elsif Osint.Number_Of_Files /= 0 then
5573            Make_Failed
5574              ("-B cannot be used with a main specified on the command line");
5575
5576         --  And the project file cannot be a library project file
5577
5578         elsif Main_Project.Library then
5579            Make_Failed ("-B cannot be used for a library project file");
5580
5581         else
5582            No_Main_Subprogram := True;
5583            Insert_Project_Sources
5584              (The_Project  => Main_Project,
5585               All_Projects => Unique_Compile_All_Projects,
5586               Into_Q       => False);
5587
5588            --  If there are no sources to compile, we fail
5589
5590            if Osint.Number_Of_Files = 0 then
5591               Make_Failed ("no sources to compile");
5592            end if;
5593
5594            --  Specify -n for gnatbind and add the ALI files of all the
5595            --  sources, except the one which is a fake main subprogram: this
5596            --  is the one for the binder generated file and it will be
5597            --  transmitted to gnatlink. These sources are those that are in
5598            --  the queue.
5599
5600            Add_Switch ("-n", Binder, And_Save => True);
5601
5602            for J in 1 .. Queue.Size loop
5603               Add_Switch
5604                 (Get_Name_String (Lib_File_Name (Queue.Element (J))),
5605                  Binder, And_Save => True);
5606            end loop;
5607         end if;
5608
5609      elsif Main_Index /= 0 and then Osint.Number_Of_Files > 1 then
5610         Make_Failed ("cannot specify several mains with a multi-unit index");
5611
5612      elsif Main_Project /= No_Project then
5613
5614         --  If the main project file is a library project file, main(s) cannot
5615         --  be specified on the command line.
5616
5617         if Osint.Number_Of_Files /= 0 then
5618            if Main_Project.Library
5619              and then not Unique_Compile
5620              and then ((not Make_Steps) or else Bind_Only or else Link_Only)
5621            then
5622               Make_Failed
5623                 ("cannot specify a main program "
5624                  & "on the command line for a library project file");
5625            end if;
5626
5627         --  If no mains have been specified on the command line, and we are
5628         --  using a project file, we either find the main(s) in attribute Main
5629         --  of the main project, or we put all the sources of the project file
5630         --  as mains.
5631
5632         else
5633            if Main_Index /= 0 then
5634               Make_Failed ("cannot specify a multi-unit index but no main "
5635                            & "on the command line");
5636            end if;
5637
5638            declare
5639               Value : String_List_Id := Main_Project.Mains;
5640
5641            begin
5642               --  The attribute Main is an empty list or not specified, or
5643               --  else gnatmake was invoked with the switch "-u".
5644
5645               if Value = Prj.Nil_String or else Unique_Compile then
5646                  if not Make_Steps
5647                    or Compile_Only
5648                    or not Main_Project.Library
5649                  then
5650                     --  First make sure that the binder and the linker will
5651                     --  not be invoked.
5652
5653                     Do_Bind_Step := False;
5654                     Do_Link_Step := False;
5655
5656                     --  Put all the sources in the queue
5657
5658                     No_Main_Subprogram := True;
5659                     Insert_Project_Sources
5660                       (The_Project  => Main_Project,
5661                        All_Projects => Unique_Compile_All_Projects,
5662                        Into_Q       => False);
5663
5664                     --  If no sources to compile, then there is nothing to do
5665
5666                     if Osint.Number_Of_Files = 0 then
5667                        if not Quiet_Output then
5668                           Osint.Write_Program_Name;
5669                           Write_Line (": no sources to compile");
5670                        end if;
5671
5672                        Finish_Program (Project_Tree, E_Success);
5673                     end if;
5674                  end if;
5675
5676               else
5677                  --  The attribute Main is not an empty list. Put all the main
5678                  --  subprograms in the list as if they were specified on the
5679                  --  command line. However, if attribute Languages includes a
5680                  --  language other than Ada, only include the Ada mains; if
5681                  --  there is no Ada main, compile all sources of the project.
5682
5683                  declare
5684                     Languages : constant Variable_Value :=
5685                                   Prj.Util.Value_Of
5686                                     (Name_Languages,
5687                                      Main_Project.Decl.Attributes,
5688                                      Project_Tree.Shared);
5689
5690                     Current : String_List_Id;
5691                     Element : String_Element;
5692
5693                     Foreign_Language  : Boolean := False;
5694                     At_Least_One_Main : Boolean := False;
5695
5696                  begin
5697                     --  First, determine if there is a foreign language in
5698                     --  attribute Languages.
5699
5700                     if not Languages.Default then
5701                        Current := Languages.Values;
5702                        Look_For_Foreign :
5703                        while Current /= Nil_String loop
5704                           Element := Project_Tree.Shared.String_Elements.
5705                                        Table (Current);
5706                           Get_Name_String (Element.Value);
5707                           To_Lower (Name_Buffer (1 .. Name_Len));
5708
5709                           if Name_Buffer (1 .. Name_Len) /= "ada" then
5710                              Foreign_Language := True;
5711                              exit Look_For_Foreign;
5712                           end if;
5713
5714                           Current := Element.Next;
5715                        end loop Look_For_Foreign;
5716                     end if;
5717
5718                     --  Then, find all mains, or if there is a foreign
5719                     --  language, all the Ada mains.
5720
5721                     while Value /= Prj.Nil_String loop
5722                        --  To know if a main is an Ada main, get its project.
5723                        --  It should be the project specified on the command
5724                        --  line.
5725
5726                        Get_Name_String
5727                          (Project_Tree.Shared.String_Elements.Table
5728                             (Value).Value);
5729
5730                        declare
5731                           Main_Name : constant String :=
5732                                         Get_Name_String
5733                                           (Project_Tree.Shared.
5734                                             String_Elements.
5735                                               Table (Value).Value);
5736
5737                           Proj : constant Project_Id :=
5738                                    Prj.Env.Project_Of
5739                                     (Main_Name, Main_Project, Project_Tree);
5740
5741                        begin
5742                           if Proj = Main_Project then
5743                              At_Least_One_Main := True;
5744                              Osint.Add_File
5745                                (Get_Name_String
5746                                   (Project_Tree.Shared.String_Elements.Table
5747                                      (Value).Value),
5748                                 Index =>
5749                                   Project_Tree.Shared.String_Elements.Table
5750                                     (Value).Index);
5751
5752                           elsif not Foreign_Language then
5753                              Make_Failed
5754                                ("""" & Main_Name &
5755                                 """ is not a source of project " &
5756                                 Get_Name_String (Main_Project.Display_Name));
5757                           end if;
5758                        end;
5759
5760                        Value := Project_Tree.Shared.String_Elements.Table
5761                                   (Value).Next;
5762                     end loop;
5763
5764                     --  If we did not get any main, it means that all mains
5765                     --  in attribute Mains are in a foreign language and -B
5766                     --  was not specified to gnatmake; so, we fail.
5767
5768                     if not At_Least_One_Main then
5769                        Make_Failed
5770                          ("no Ada mains, use -B to build foreign main");
5771                     end if;
5772                  end;
5773
5774               end if;
5775            end;
5776         end if;
5777
5778         --  Check that each main on the command line is a source of a
5779         --  project file and, if there are several mains, each of them
5780         --  is a source of the same project file.
5781
5782         Check_Mains;
5783      end if;
5784
5785      if Verbose_Mode then
5786         Write_Eol;
5787         Display_Version ("GNATMAKE", "1992");
5788      end if;
5789
5790      if Osint.Number_Of_Files = 0 then
5791         if Main_Project /= No_Project and then Main_Project.Library then
5792            if Do_Bind_Step and then Main_Project.Standalone_Library = No then
5793               Make_Failed ("only stand-alone libraries may be bound");
5794            end if;
5795
5796            --  Add the default search directories to be able to find libgnat
5797
5798            Osint.Add_Default_Search_Dirs;
5799
5800            --  And bind and or link the library
5801
5802            MLib.Prj.Build_Library
5803              (For_Project   => Main_Project,
5804               In_Tree       => Project_Tree,
5805               Gnatbind      => Gnatbind.all,
5806               Gnatbind_Path => Gnatbind_Path,
5807               Gcc           => Gcc.all,
5808               Gcc_Path      => Gcc_Path,
5809               Bind          => Bind_Only,
5810               Link          => Link_Only);
5811
5812            Finish_Program (Project_Tree, E_Success);
5813
5814         else
5815            --  Call Get_Target_Parameters to ensure that VM_Target and
5816            --  AAMP_On_Target get set before calling Usage.
5817
5818            Targparm.Get_Target_Parameters;
5819
5820            --  Output usage information if no argument on the command line
5821
5822            if Argument_Count = 0 then
5823               Usage;
5824            else
5825               Try_Help;
5826            end if;
5827
5828            Finish_Program (Project_Tree, E_Success);
5829         end if;
5830      end if;
5831
5832      --  Get the first executable.
5833      --  ??? This needs to be done early, because Osint.Next_Main_File also
5834      --  initializes the primary search directory, used below to initialize
5835      --  the "-I" parameter
5836
5837      Main_Source_File := Next_Main_Source;  --  No directory information
5838
5839      --  If -M was specified, behave as if -n was specified
5840
5841      if List_Dependencies then
5842         Do_Not_Execute := True;
5843      end if;
5844
5845      Add_Switch ("-I-", Compiler, And_Save => True);
5846
5847      if Main_Project = No_Project then
5848         if Look_In_Primary_Dir then
5849            Add_Switch
5850              ("-I" &
5851               Normalize_Directory_Name
5852                 (Get_Primary_Src_Search_Directory.all).all,
5853                  Compiler,
5854                  Append_Switch => False,
5855                  And_Save      => False);
5856
5857         end if;
5858
5859      else
5860         --  If we use a project file, we have already checked that a main
5861         --  specified on the command line with directory information has the
5862         --  path name corresponding to a correct source in the project tree.
5863         --  So, we don't need the directory information to be taken into
5864         --  account by Find_File, and in fact it may lead to take the wrong
5865         --  sources for other compilation units, when there are extending
5866         --  projects.
5867
5868         Look_In_Primary_Dir := False;
5869      end if;
5870
5871      --  If the user wants a program without a main subprogram, add the
5872      --  appropriate switch to the binder.
5873
5874      if No_Main_Subprogram then
5875         Add_Switch ("-z", Binder, And_Save => True);
5876      end if;
5877
5878      if Main_Project /= No_Project then
5879
5880         if Main_Project.Object_Directory /= No_Path_Information then
5881
5882            --  Change current directory to object directory of main project
5883
5884            Project_Of_Current_Object_Directory := No_Project;
5885            Change_To_Object_Directory (Main_Project);
5886         end if;
5887
5888         --  Source file lookups should be cached for efficiency. Source files
5889         --  are not supposed to change.
5890
5891         Osint.Source_File_Data (Cache => True);
5892
5893         Queue_Library_Project_Sources;
5894      end if;
5895
5896      --  The combination of -f -u and one or several mains on the command line
5897      --  implies -a.
5898
5899      if Force_Compilations
5900        and then Unique_Compile
5901        and then not Unique_Compile_All_Projects
5902        and then Main_On_Command_Line
5903      then
5904         Must_Compile := True;
5905      end if;
5906
5907      if Main_Project /= No_Project
5908        and then not Must_Compile
5909        and then Main_Project.Externally_Built
5910      then
5911         Make_Failed
5912           ("nothing to do for a main project that is externally built");
5913      end if;
5914
5915      --  If no project file is used, we just put the gcc switches
5916      --  from the command line in the Gcc_Switches table.
5917
5918      if Main_Project = No_Project then
5919         for J in 1 .. Saved_Gcc_Switches.Last loop
5920            Add_Switch
5921              (Saved_Gcc_Switches.Table (J), Compiler, And_Save => False);
5922         end loop;
5923
5924      else
5925         --  If there is a project, put the command line gcc switches in the
5926         --  variable The_Saved_Gcc_Switches. They are going to be used later
5927         --  in procedure Compile_Sources.
5928
5929         The_Saved_Gcc_Switches :=
5930           new Argument_List (1 .. Saved_Gcc_Switches.Last + 1);
5931
5932         for J in 1 .. Saved_Gcc_Switches.Last loop
5933            The_Saved_Gcc_Switches (J) := Saved_Gcc_Switches.Table (J);
5934         end loop;
5935
5936         --  We never use gnat.adc when a project file is used
5937
5938         The_Saved_Gcc_Switches (The_Saved_Gcc_Switches'Last) := No_gnat_adc;
5939      end if;
5940
5941      --  If there was a --GCC, --GNATBIND or --GNATLINK switch on the command
5942      --  line, then we have to use it, even if there was another switch in
5943      --  the project file.
5944
5945      if Saved_Gcc /= null then
5946         Gcc := Saved_Gcc;
5947      end if;
5948
5949      if Saved_Gnatbind /= null then
5950         Gnatbind := Saved_Gnatbind;
5951      end if;
5952
5953      if Saved_Gnatlink /= null then
5954         Gnatlink := Saved_Gnatlink;
5955      end if;
5956
5957      Bad_Compilation.Init;
5958
5959      --  If project files are used, create the mapping of all the sources, so
5960      --  that the correct paths will be found. Otherwise, if there is a file
5961      --  which is not a source with the same name in a source directory this
5962      --  file may be incorrectly found.
5963
5964      if Main_Project /= No_Project then
5965         Prj.Env.Create_Mapping (Project_Tree);
5966      end if;
5967
5968      --  Here is where the make process is started
5969
5970      Queue.Initialize
5971        (Main_Project /= No_Project and then One_Compilation_Per_Obj_Dir);
5972
5973      Is_First_Main := True;
5974
5975      Multiple_Main_Loop : for N_File in 1 .. Osint.Number_Of_Files loop
5976         if Current_File_Index /= No_Index then
5977            Main_Index := Current_File_Index;
5978         end if;
5979
5980         Current_Main_Index := Main_Index;
5981
5982         if Current_Main_Index = 0
5983           and then Unique_Compile
5984           and then Main_Project /= No_Project
5985         then
5986            --  If this is a multi-unit source, do not compile it as is (ie
5987            --  without specifying which unit to compile)
5988            --  Insert_Project_Sources has added each of the unit separately.
5989
5990            declare
5991               Source : constant Prj.Source_Id := Find_Source
5992                 (In_Tree   => Project_Tree,
5993                  Project   => Main_Project,
5994                  Base_Name => Main_Source_File,
5995                  Index     => Current_Main_Index,
5996                  In_Imported_Only => True);
5997            begin
5998               if Source /= No_Source and then Source.Index /= 0 then
5999                  goto Next_Main;
6000               end if;
6001            end;
6002         end if;
6003
6004         Compute_Switches_For_Main
6005           (Main_Source_File,
6006            Root_Environment,
6007            Compute_Builder  => Is_First_Main,
6008            Current_Work_Dir => Current_Work_Dir.all);
6009
6010         if Is_First_Main then
6011
6012            --  Put the default source dirs in the source path only now, so
6013            --  that we take the correct ones in the case where --RTS= is
6014            --  specified in the Builder switches.
6015
6016            Osint.Add_Default_Search_Dirs;
6017
6018            --  Get the target parameters, which are only needed for a couple
6019            --  of cases in gnatmake. Protect against an exception, such as the
6020            --  case of system.ads missing from the library, and fail
6021            --  gracefully.
6022
6023            begin
6024               Targparm.Get_Target_Parameters;
6025            exception
6026               when Unrecoverable_Error =>
6027                  Make_Failed ("*** make failed.");
6028            end;
6029
6030            --  Special processing for VM targets
6031
6032            if Targparm.VM_Target /= No_VM then
6033
6034               --  Set proper processing commands
6035
6036               case Targparm.VM_Target is
6037                  when Targparm.JVM_Target =>
6038
6039                     --  Do not check for an object file (".o") when compiling
6040                     --  to JVM machine since ".class" files are generated
6041                     --  instead.
6042
6043                     Check_Object_Consistency := False;
6044
6045                     --  Do not modify Gcc is --GCC= was specified
6046
6047                     if Gcc = Original_Gcc then
6048                        Gcc := new String'("jvm-gnatcompile");
6049                     end if;
6050
6051                  when Targparm.CLI_Target =>
6052                     --  Do not modify Gcc is --GCC= was specified
6053
6054                     if Gcc = Original_Gcc then
6055                        Gcc := new String'("dotnet-gnatcompile");
6056                     end if;
6057
6058                  when Targparm.No_VM =>
6059                     raise Program_Error;
6060               end case;
6061            end if;
6062
6063            Gcc_Path       := GNAT.OS_Lib.Locate_Exec_On_Path (Gcc.all);
6064            Gnatbind_Path  := GNAT.OS_Lib.Locate_Exec_On_Path (Gnatbind.all);
6065            Gnatlink_Path  := GNAT.OS_Lib.Locate_Exec_On_Path (Gnatlink.all);
6066
6067            --  If we have specified -j switch both from the project file
6068            --  and on the command line, the one from the command line takes
6069            --  precedence.
6070
6071            if Saved_Maximum_Processes = 0 then
6072               Saved_Maximum_Processes := Maximum_Processes;
6073            end if;
6074
6075            if Debug.Debug_Flag_M then
6076               Write_Line ("Maximum number of simultaneous compilations =" &
6077                           Saved_Maximum_Processes'Img);
6078            end if;
6079
6080            --  Allocate as many temporary mapping file names as the maximum
6081            --  number of compilations processed, for each possible project.
6082
6083            declare
6084               Data : Project_Compilation_Access;
6085               Proj : Project_List;
6086
6087            begin
6088               Proj := Project_Tree.Projects;
6089               while Proj /= null loop
6090                  Data :=
6091                    new Project_Compilation_Data'
6092                      (Mapping_File_Names        =>
6093                         new Temp_Path_Names (1 .. Saved_Maximum_Processes),
6094                       Last_Mapping_File_Names   => 0,
6095                       Free_Mapping_File_Indexes =>
6096                         new Free_File_Indexes (1 .. Saved_Maximum_Processes),
6097                       Last_Free_Indexes         => 0);
6098
6099                  Project_Compilation_Htable.Set
6100                    (Project_Compilation, Proj.Project, Data);
6101                  Proj := Proj.Next;
6102               end loop;
6103
6104               Data :=
6105                 new Project_Compilation_Data'
6106                   (Mapping_File_Names        =>
6107                      new Temp_Path_Names (1 .. Saved_Maximum_Processes),
6108                    Last_Mapping_File_Names   => 0,
6109                    Free_Mapping_File_Indexes =>
6110                      new Free_File_Indexes (1 .. Saved_Maximum_Processes),
6111                    Last_Free_Indexes         => 0);
6112
6113               Project_Compilation_Htable.Set
6114                 (Project_Compilation, No_Project, Data);
6115            end;
6116
6117            Is_First_Main := False;
6118         end if;
6119
6120         Executable_Obsolete := False;
6121
6122         Compute_Executable
6123           (Main_Source_File   => Main_Source_File,
6124            Executable         => Executable,
6125            Non_Std_Executable => Non_Std_Executable);
6126
6127         if Do_Compile_Step then
6128            Compilation_Phase
6129              (Main_Source_File           => Main_Source_File,
6130               Current_Main_Index         => Current_Main_Index,
6131               Total_Compilation_Failures => Total_Compilation_Failures,
6132               Stand_Alone_Libraries      => Stand_Alone_Libraries,
6133               Executable                 => Executable,
6134               Is_Last_Main               => N_File = Osint.Number_Of_Files,
6135               Stop_Compile               => Stop_Compile);
6136
6137            if Stop_Compile then
6138               if Total_Compilation_Failures /= 0 then
6139                  if Keep_Going then
6140                     goto Next_Main;
6141
6142                  else
6143                     List_Bad_Compilations;
6144                     Report_Compilation_Failed;
6145                  end if;
6146
6147               elsif Osint.Number_Of_Files = 1 then
6148                  exit Multiple_Main_Loop;
6149               else
6150                  goto Next_Main;
6151               end if;
6152            end if;
6153         end if;
6154
6155         --  For binding and linking, we need to be in the object directory of
6156         --  the main project.
6157
6158         if Main_Project /= No_Project then
6159            Change_To_Object_Directory (Main_Project);
6160         end if;
6161
6162         --  If we are here, it means that we need to rebuilt the current main,
6163         --  so we set Executable_Obsolete to True to make sure that subsequent
6164         --  mains will be rebuilt.
6165
6166         Main_ALI_In_Place_Mode_Step : declare
6167            ALI_File : File_Name_Type;
6168            Src_File : File_Name_Type;
6169
6170         begin
6171            Src_File      := Strip_Directory (Main_Source_File);
6172            ALI_File      := Lib_File_Name (Src_File, Current_Main_Index);
6173            Main_ALI_File := Full_Lib_File_Name (ALI_File);
6174
6175            --  When In_Place_Mode, the library file can be located in the
6176            --  Main_Source_File directory which may not be present in the
6177            --  library path. If it is not present then use the corresponding
6178            --  library file name.
6179
6180            if Main_ALI_File = No_File and then In_Place_Mode then
6181               Get_Name_String (Get_Directory (Full_Source_Name (Src_File)));
6182               Get_Name_String_And_Append (ALI_File);
6183               Main_ALI_File := Name_Find;
6184               Main_ALI_File := Full_Lib_File_Name (Main_ALI_File);
6185            end if;
6186
6187            if Main_ALI_File = No_File then
6188               Make_Failed ("could not find the main ALI file");
6189            end if;
6190         end Main_ALI_In_Place_Mode_Step;
6191
6192         if Do_Bind_Step then
6193            Binding_Phase
6194              (Stand_Alone_Libraries => Stand_Alone_Libraries,
6195               Main_ALI_File         => Main_ALI_File);
6196         end if;
6197
6198         if Do_Link_Step then
6199            Linking_Phase
6200              (Non_Std_Executable => Non_Std_Executable,
6201               Executable         => Executable,
6202               Main_ALI_File      => Main_ALI_File);
6203         end if;
6204
6205         --  We go to here when we skip the bind and link steps
6206
6207         <<Next_Main>>
6208
6209         Queue.Remove_Marks;
6210
6211         if N_File < Osint.Number_Of_Files then
6212            Main_Source_File := Next_Main_Source;  --  No directory information
6213         end if;
6214      end loop Multiple_Main_Loop;
6215
6216      if CodePeer_Mode then
6217         declare
6218            Success : Boolean := False;
6219         begin
6220            Globalize (Success);
6221
6222            if not Success then
6223               Set_Standard_Error;
6224               Write_Str ("*** globalize failed.");
6225
6226               if Commands_To_Stdout then
6227                  Set_Standard_Output;
6228               end if;
6229            end if;
6230         end;
6231      end if;
6232
6233      if Failed_Links.Last > 0 then
6234         for Index in 1 .. Successful_Links.Last loop
6235            Write_Str ("Linking of """);
6236            Write_Str (Get_Name_String (Successful_Links.Table (Index)));
6237            Write_Line (""" succeeded.");
6238         end loop;
6239
6240         Set_Standard_Error;
6241
6242         for Index in 1 .. Failed_Links.Last loop
6243            Write_Str ("Linking of """);
6244            Write_Str (Get_Name_String (Failed_Links.Table (Index)));
6245            Write_Line (""" failed.");
6246         end loop;
6247
6248         if Commands_To_Stdout then
6249            Set_Standard_Output;
6250         end if;
6251
6252         if Total_Compilation_Failures = 0 then
6253            Report_Compilation_Failed;
6254         end if;
6255      end if;
6256
6257      if Total_Compilation_Failures /= 0 then
6258         List_Bad_Compilations;
6259         Report_Compilation_Failed;
6260      end if;
6261
6262      Finish_Program (Project_Tree, E_Success);
6263
6264   exception
6265      when X : others =>
6266         Set_Standard_Error;
6267         Write_Line (Exception_Information (X));
6268         Make_Failed ("INTERNAL ERROR. Please report.");
6269   end Gnatmake;
6270
6271   ----------
6272   -- Hash --
6273   ----------
6274
6275   function Hash (F : File_Name_Type) return Header_Num is
6276   begin
6277      return Header_Num (1 + F mod Max_Header);
6278   end Hash;
6279
6280   --------------------
6281   -- In_Ada_Lib_Dir --
6282   --------------------
6283
6284   function In_Ada_Lib_Dir (File : File_Name_Type) return Boolean is
6285      D : constant File_Name_Type := Get_Directory (File);
6286      B : constant Byte           := Get_Name_Table_Byte (D);
6287   begin
6288      return (B and Ada_Lib_Dir) /= 0;
6289   end In_Ada_Lib_Dir;
6290
6291   -----------------------
6292   -- Init_Mapping_File --
6293   -----------------------
6294
6295   procedure Init_Mapping_File
6296     (Project    : Project_Id;
6297      Data       : in out Project_Compilation_Data;
6298      File_Index : in out Natural)
6299   is
6300      FD     : File_Descriptor;
6301      Status : Boolean;
6302      --  For call to Close
6303
6304   begin
6305      --  Increase the index of the last mapping file for this project
6306
6307      Data.Last_Mapping_File_Names := Data.Last_Mapping_File_Names + 1;
6308
6309      --  If there is a project file, call Create_Mapping_File with
6310      --  the project id.
6311
6312      if Project /= No_Project then
6313         Prj.Env.Create_Mapping_File
6314           (Project,
6315            In_Tree  => Project_Tree,
6316            Language => Name_Ada,
6317            Name     => Data.Mapping_File_Names
6318                          (Data.Last_Mapping_File_Names));
6319
6320      --  Otherwise, just create an empty file
6321
6322      else
6323         Tempdir.Create_Temp_File
6324           (FD, Data.Mapping_File_Names (Data.Last_Mapping_File_Names));
6325
6326         if FD = Invalid_FD then
6327            Make_Failed ("disk full");
6328         else
6329            Record_Temp_File
6330              (Project_Tree.Shared,
6331               Data.Mapping_File_Names (Data.Last_Mapping_File_Names));
6332         end if;
6333
6334         Close (FD, Status);
6335
6336         if not Status then
6337            Make_Failed ("disk full");
6338         end if;
6339      end if;
6340
6341      --  And return the index of the newly created file
6342
6343      File_Index := Data.Last_Mapping_File_Names;
6344   end Init_Mapping_File;
6345
6346   ----------------
6347   -- Initialize --
6348   ----------------
6349
6350   procedure Initialize
6351      (Project_Node_Tree : out Project_Node_Tree_Ref;
6352       Env               : out Prj.Tree.Environment)
6353   is
6354      procedure Check_Version_And_Help is
6355        new Check_Version_And_Help_G (Makeusg);
6356
6357   --  Start of processing for Initialize
6358
6359   begin
6360      --  Prepare the project's tree, since this is used to hold external
6361      --  references, project path and other attributes that can be impacted by
6362      --  the command line switches
6363
6364      Prj.Tree.Initialize (Env, Gnatmake_Flags);
6365
6366      Project_Node_Tree := new Project_Node_Tree_Data;
6367      Prj.Tree.Initialize (Project_Node_Tree);
6368
6369      --  Override default initialization of Check_Object_Consistency since
6370      --  this is normally False for GNATBIND, but is True for GNATMAKE since
6371      --  we do not need to check source consistency again once GNATMAKE has
6372      --  looked at the sources to check.
6373
6374      Check_Object_Consistency := True;
6375
6376      --  Package initializations (the order of calls is important here)
6377
6378      Output.Set_Standard_Error;
6379
6380      Gcc_Switches.Init;
6381      Binder_Switches.Init;
6382      Linker_Switches.Init;
6383
6384      Csets.Initialize;
6385      Snames.Initialize;
6386      Stringt.Initialize;
6387
6388      Prj.Initialize (Project_Tree);
6389
6390      Dependencies.Init;
6391
6392      RTS_Specified := null;
6393      N_M_Switch := 0;
6394
6395      Mains.Delete;
6396
6397      --  Add the directory where gnatmake is invoked in front of the path,
6398      --  if gnatmake is invoked from a bin directory or with directory
6399      --  information.
6400
6401      declare
6402         Prefix  : constant String := Executable_Prefix_Path;
6403         Command : constant String := Command_Name;
6404
6405      begin
6406         if Prefix'Length > 0 then
6407            declare
6408               PATH : constant String :=
6409                        Prefix & Directory_Separator & "bin" & Path_Separator
6410                        & Getenv ("PATH").all;
6411            begin
6412               Setenv ("PATH", PATH);
6413            end;
6414
6415         else
6416            for Index in reverse Command'Range loop
6417               if Command (Index) = Directory_Separator then
6418                  declare
6419                     Absolute_Dir : constant String :=
6420                                      Normalize_Pathname
6421                                        (Command (Command'First .. Index));
6422                     PATH         : constant String :=
6423                                      Absolute_Dir &
6424                                      Path_Separator &
6425                                      Getenv ("PATH").all;
6426                  begin
6427                     Setenv ("PATH", PATH);
6428                  end;
6429
6430                  exit;
6431               end if;
6432            end loop;
6433         end if;
6434      end;
6435
6436      --  Scan the switches and arguments
6437
6438      --  First, scan to detect --version and/or --help
6439
6440      Check_Version_And_Help ("GNATMAKE", "1995");
6441
6442      --  Scan again the switch and arguments, now that we are sure that they
6443      --  do not include --version or --help.
6444
6445      Scan_Args : for Next_Arg in 1 .. Argument_Count loop
6446         Scan_Make_Arg (Env, Argument (Next_Arg), And_Save => True);
6447      end loop Scan_Args;
6448
6449      if N_M_Switch > 0 and RTS_Specified = null then
6450         Process_Multilib (Env);
6451      end if;
6452
6453      if Commands_To_Stdout then
6454         Set_Standard_Output;
6455      end if;
6456
6457      if Usage_Requested then
6458         Usage;
6459      end if;
6460
6461      --  Add the default project search directories now, after the directories
6462      --  that have been specified by switches -aP<dir>.
6463
6464      Prj.Env.Initialize_Default_Project_Path
6465        (Env.Project_Path, Target_Name => Sdefault.Target_Name.all);
6466
6467      --  Test for trailing -P switch
6468
6469      if Project_File_Name_Present and then Project_File_Name = null then
6470         Make_Failed ("project file name missing after -P");
6471
6472      --  Test for trailing -o switch
6473
6474      elsif Output_File_Name_Present and then not Output_File_Name_Seen then
6475         Make_Failed ("output file name missing after -o");
6476
6477      --  Test for trailing -D switch
6478
6479      elsif Object_Directory_Present and then not Object_Directory_Seen then
6480         Make_Failed ("object directory missing after -D");
6481      end if;
6482
6483      --  Test for simultaneity of -i and -D
6484
6485      if Object_Directory_Path /= null and then In_Place_Mode then
6486         Make_Failed ("-i and -D cannot be used simultaneously");
6487      end if;
6488
6489      --  Warn about 'gnatmake -P'
6490
6491      if Project_File_Name /= null then
6492         Write_Line
6493           ("warning: gnatmake -P is obsolete and will not be available "
6494            & "in the next release; use gprbuild instead");
6495      end if;
6496
6497      --  If --subdirs= is specified, but not -P, this is equivalent to -D,
6498      --  except that the directory is created if it does not exist.
6499
6500      if Prj.Subdirs /= null and then Project_File_Name = null then
6501         if Object_Directory_Path /= null then
6502            Make_Failed ("--subdirs and -D cannot be used simultaneously");
6503
6504         elsif In_Place_Mode then
6505            Make_Failed ("--subdirs and -i cannot be used simultaneously");
6506
6507         else
6508            if not Is_Directory (Prj.Subdirs.all) then
6509               begin
6510                  Ada.Directories.Create_Path (Prj.Subdirs.all);
6511               exception
6512                  when others =>
6513                     Make_Failed ("unable to create object directory " &
6514                                  Prj.Subdirs.all);
6515               end;
6516            end if;
6517
6518            Object_Directory_Present := True;
6519
6520            declare
6521               Argv : constant String (1 .. Prj.Subdirs'Length) :=
6522                        Prj.Subdirs.all;
6523            begin
6524               Scan_Make_Arg (Env, Argv, And_Save => False);
6525            end;
6526         end if;
6527      end if;
6528
6529      --  Deal with -C= switch
6530
6531      if Gnatmake_Mapping_File /= null then
6532
6533         --  First, check compatibility with other switches
6534
6535         if Project_File_Name /= null then
6536            Make_Failed ("-C= switch is not compatible with -P switch");
6537
6538         elsif Saved_Maximum_Processes > 1 then
6539            Make_Failed ("-C= switch is not compatible with -jnnn switch");
6540         end if;
6541
6542         Fmap.Initialize (Gnatmake_Mapping_File.all);
6543         Add_Switch
6544           ("-gnatem=" & Gnatmake_Mapping_File.all,
6545            Compiler,
6546            And_Save => True);
6547      end if;
6548
6549      if Project_File_Name /= null then
6550
6551         --  A project file was specified by a -P switch
6552
6553         if Verbose_Mode then
6554            Write_Eol;
6555            Write_Str ("Parsing project file """);
6556            Write_Str (Project_File_Name.all);
6557            Write_Str (""".");
6558            Write_Eol;
6559         end if;
6560
6561         --  Avoid looking in the current directory for ALI files
6562
6563         --  Look_In_Primary_Dir := False;
6564
6565         --  Set the project parsing verbosity to whatever was specified
6566         --  by a possible -vP switch.
6567
6568         Prj.Pars.Set_Verbosity (To => Current_Verbosity);
6569
6570         --  Parse the project file.
6571         --  If there is an error, Main_Project will still be No_Project.
6572
6573         Prj.Pars.Parse
6574           (Project           => Main_Project,
6575            In_Tree           => Project_Tree,
6576            Project_File_Name => Project_File_Name.all,
6577            Packages_To_Check => Packages_To_Check_By_Gnatmake,
6578            Env               => Env,
6579            In_Node_Tree      => Project_Node_Tree);
6580
6581         --  The parsing of project files may have changed the current output
6582
6583         if Commands_To_Stdout then
6584            Set_Standard_Output;
6585         else
6586            Set_Standard_Error;
6587         end if;
6588
6589         if Main_Project = No_Project then
6590            Make_Failed
6591              ("""" & Project_File_Name.all & """ processing failed");
6592         end if;
6593
6594         if Main_Project.Qualifier = Aggregate then
6595            Make_Failed ("aggregate projects are not supported");
6596
6597         elsif Aggregate_Libraries_In (Project_Tree) then
6598            Make_Failed ("aggregate library projects are not supported");
6599         end if;
6600
6601         Create_Mapping_File := True;
6602
6603         if Verbose_Mode then
6604            Write_Eol;
6605            Write_Str ("Parsing of project file """);
6606            Write_Str (Project_File_Name.all);
6607            Write_Str (""" is finished.");
6608            Write_Eol;
6609         end if;
6610
6611         --  We add the source directories and the object directories to the
6612         --  search paths.
6613
6614         --  ??? Why do we need these search directories, we already know the
6615         --  locations from parsing the project, except for the runtime which
6616         --  has its own directories anyway
6617
6618         Add_Source_Directories (Main_Project, Project_Tree);
6619         Add_Object_Directories (Main_Project, Project_Tree);
6620
6621         Recursive_Compute_Depth (Main_Project);
6622         Compute_All_Imported_Projects (Main_Project, Project_Tree);
6623
6624      else
6625
6626         Osint.Add_Default_Search_Dirs;
6627
6628         --  Source file lookups should be cached for efficiency. Source files
6629         --  are not supposed to change. However, we do that now only if no
6630         --  project file is used; if a project file is used, we do it just
6631         --  after changing the directory to the object directory.
6632
6633         Osint.Source_File_Data (Cache => True);
6634
6635         --  Read gnat.adc file to initialize Fname.UF
6636
6637         Fname.UF.Initialize;
6638
6639         if Config_File then
6640            begin
6641               Fname.SF.Read_Source_File_Name_Pragmas;
6642
6643            exception
6644               when Err : SFN_Scan.Syntax_Error_In_GNAT_ADC =>
6645                  Make_Failed (Exception_Message (Err));
6646            end;
6647         end if;
6648      end if;
6649
6650      --  Make sure no project object directory is recorded
6651
6652      Project_Of_Current_Object_Directory := No_Project;
6653
6654      if Debug.Debug_Flag_N then
6655         Opt.Keep_Temporary_Files := True;
6656      end if;
6657   end Initialize;
6658
6659   ----------------------------
6660   -- Insert_Project_Sources --
6661   ----------------------------
6662
6663   procedure Insert_Project_Sources
6664     (The_Project  : Project_Id;
6665      All_Projects : Boolean;
6666      Into_Q       : Boolean)
6667   is
6668      Put_In_Q : Boolean := Into_Q;
6669      Unit     : Unit_Index;
6670      Sfile    : File_Name_Type;
6671      Sid      : Prj.Source_Id;
6672      Index    : Int;
6673      Project  : Project_Id;
6674
6675   begin
6676      --  Loop through all the sources in the project files
6677
6678      Unit := Units_Htable.Get_First (Project_Tree.Units_HT);
6679      while Unit /= null loop
6680         Sfile   := No_File;
6681         Sid     := No_Source;
6682         Index   := 0;
6683         Project := No_Project;
6684
6685         --  If there is a source for the body, and the body has not been
6686         --  locally removed.
6687
6688         if Unit.File_Names (Impl) /= null
6689           and then not Unit.File_Names (Impl).Locally_Removed
6690         then
6691            --  And it is a source for the specified project
6692
6693            if All_Projects
6694              or else
6695                Is_Extending (The_Project, Unit.File_Names (Impl).Project)
6696            then
6697               Project := Unit.File_Names (Impl).Project;
6698
6699               --  If we don't have a spec, we cannot consider the source
6700               --  if it is a subunit.
6701
6702               if Unit.File_Names (Spec) = null then
6703                  declare
6704                     Src_Ind : Source_File_Index;
6705
6706                     --  Here we are cheating a little bit: we don't want to
6707                     --  use Sinput.L, because it depends on the GNAT tree
6708                     --  (Atree, Sinfo, ...). So, we pretend that it is a
6709                     --  project file, and we use Sinput.P.
6710
6711                     --  Source_File_Is_Subunit is just scanning through the
6712                     --  file until it finds one of the reserved words
6713                     --  separate, procedure, function, generic or package.
6714                     --  Fortunately, these Ada reserved words are also
6715                     --  reserved for project files.
6716
6717                  begin
6718                     Src_Ind := Sinput.P.Load_Project_File
6719                                  (Get_Name_String
6720                                   (Unit.File_Names (Impl).Path.Display_Name));
6721
6722                     --  If it is a subunit, discard it
6723
6724                     if Sinput.P.Source_File_Is_Subunit (Src_Ind) then
6725                        Sfile := No_File;
6726                        Index := 0;
6727                        Sid   := No_Source;
6728                     else
6729                        Sfile := Unit.File_Names (Impl).Display_File;
6730                        Index := Unit.File_Names (Impl).Index;
6731                        Sid   := Unit.File_Names (Impl);
6732                     end if;
6733                  end;
6734
6735               else
6736                  Sfile := Unit.File_Names (Impl).Display_File;
6737                  Index := Unit.File_Names (Impl).Index;
6738                  Sid   := Unit.File_Names (Impl);
6739               end if;
6740            end if;
6741
6742         elsif Unit.File_Names (Spec) /= null
6743           and then not Unit.File_Names (Spec).Locally_Removed
6744           and then
6745             (All_Projects
6746               or else
6747                 Is_Extending (The_Project, Unit.File_Names (Spec).Project))
6748         then
6749            --  If there is no source for the body, but there is one for the
6750            --  spec which has not been locally removed, then we take this one.
6751
6752            Sfile := Unit.File_Names (Spec).Display_File;
6753            Index := Unit.File_Names (Spec).Index;
6754            Sid   := Unit.File_Names (Spec);
6755            Project := Unit.File_Names (Spec).Project;
6756         end if;
6757
6758         --  For the first source inserted into the Q, we need to initialize
6759         --  the Q, but not for the subsequent sources.
6760
6761         Queue.Initialize
6762                 (Main_Project /= No_Project and then
6763                  One_Compilation_Per_Obj_Dir);
6764
6765         if Sfile /= No_File then
6766            Queue.Insert
6767              ((Format   => Format_Gnatmake,
6768                File     => Sfile,
6769                Project  => Project,
6770                Unit     => No_Unit_Name,
6771                Index    => Index,
6772                Sid      => Sid));
6773         end if;
6774
6775         if not Put_In_Q and then Sfile /= No_File then
6776
6777            --  If Put_In_Q is False, we add the source as if it were specified
6778            --  on the command line, and we set Put_In_Q to True, so that the
6779            --  following sources will only be put in the queue. The source is
6780            --  already in the Q, but we need at least one fake main to call
6781            --  Compile_Sources.
6782
6783            if Verbose_Mode then
6784               Write_Str ("Adding """);
6785               Write_Str (Get_Name_String (Sfile));
6786               Write_Line (""" as if on the command line");
6787            end if;
6788
6789            Osint.Add_File (Get_Name_String (Sfile), Index);
6790            Put_In_Q := True;
6791         end if;
6792
6793         Unit := Units_Htable.Get_Next (Project_Tree.Units_HT);
6794      end loop;
6795   end Insert_Project_Sources;
6796
6797   ---------------------
6798   -- Is_In_Obsoleted --
6799   ---------------------
6800
6801   function Is_In_Obsoleted (F : File_Name_Type) return Boolean is
6802   begin
6803      if F = No_File then
6804         return False;
6805
6806      else
6807         declare
6808            Name  : constant String := Get_Name_String (F);
6809            First : Natural;
6810            F2    : File_Name_Type;
6811
6812         begin
6813            First := Name'Last;
6814            while First > Name'First
6815              and then not Is_Directory_Separator (Name (First - 1))
6816            loop
6817               First := First - 1;
6818            end loop;
6819
6820            if First /= Name'First then
6821               Name_Len := 0;
6822               Add_Str_To_Name_Buffer (Name (First .. Name'Last));
6823               F2 := Name_Find;
6824
6825            else
6826               F2 := F;
6827            end if;
6828
6829            return Obsoleted.Get (F2);
6830         end;
6831      end if;
6832   end Is_In_Obsoleted;
6833
6834   ----------------------------
6835   -- Is_In_Object_Directory --
6836   ----------------------------
6837
6838   function Is_In_Object_Directory
6839     (Source_File   : File_Name_Type;
6840      Full_Lib_File : File_Name_Type) return Boolean
6841   is
6842   begin
6843      --  There is something to check only when using project files. Otherwise,
6844      --  this function returns True (last line of the function).
6845
6846      if Main_Project /= No_Project then
6847         declare
6848            Source_File_Name : constant String :=
6849                                 Get_Name_String (Source_File);
6850            Saved_Verbosity  : constant Verbosity := Current_Verbosity;
6851            Project          : Project_Id         := No_Project;
6852
6853            Path_Name : Path_Name_Type := No_Path;
6854            pragma Warnings (Off, Path_Name);
6855
6856         begin
6857            --  Call Get_Reference to know the ultimate extending project of
6858            --  the source. Call it with verbosity default to avoid verbose
6859            --  messages.
6860
6861            Current_Verbosity := Default;
6862            Prj.Env.Get_Reference
6863              (Source_File_Name => Source_File_Name,
6864               Project          => Project,
6865               In_Tree          => Project_Tree,
6866               Path             => Path_Name);
6867            Current_Verbosity := Saved_Verbosity;
6868
6869            --  If this source is in a project, check that the ALI file is in
6870            --  its object directory. If it is not, return False, so that the
6871            --  ALI file will not be skipped.
6872
6873            if Project /= No_Project then
6874               declare
6875                  Object_Directory : constant String :=
6876                                       Normalize_Pathname
6877                                        (Get_Name_String
6878                                         (Project.
6879                                            Object_Directory.Display_Name));
6880
6881                  Olast : Natural := Object_Directory'Last;
6882
6883                  Lib_File_Directory : constant String :=
6884                                         Normalize_Pathname (Dir_Name
6885                                           (Get_Name_String (Full_Lib_File)));
6886
6887                  Llast : Natural := Lib_File_Directory'Last;
6888
6889               begin
6890                  --  For directories, Normalize_Pathname may or may not put
6891                  --  a directory separator at the end, depending on its input.
6892                  --  Remove any last directory separator before comparison.
6893                  --  Returns True only if the two directories are the same.
6894
6895                  if Object_Directory (Olast) = Directory_Separator then
6896                     Olast := Olast - 1;
6897                  end if;
6898
6899                  if Lib_File_Directory (Llast) = Directory_Separator then
6900                     Llast := Llast - 1;
6901                  end if;
6902
6903                  return Object_Directory (Object_Directory'First .. Olast) =
6904                        Lib_File_Directory (Lib_File_Directory'First .. Llast);
6905               end;
6906            end if;
6907         end;
6908      end if;
6909
6910      --  When the source is not in a project file, always return True
6911
6912      return True;
6913   end Is_In_Object_Directory;
6914
6915   ----------
6916   -- Link --
6917   ----------
6918
6919   procedure Link
6920     (ALI_File : File_Name_Type;
6921      Args     : Argument_List;
6922      Success  : out Boolean)
6923   is
6924      Link_Args : Argument_List (1 .. Args'Length + 1);
6925
6926   begin
6927      Get_Name_String (ALI_File);
6928      Link_Args (1) := new String'(Name_Buffer (1 .. Name_Len));
6929
6930      Link_Args (2 .. Args'Length + 1) :=  Args;
6931
6932      GNAT.OS_Lib.Normalize_Arguments (Link_Args);
6933
6934      Display (Gnatlink.all, Link_Args);
6935
6936      if Gnatlink_Path = null then
6937         Make_Failed ("error, unable to locate " & Gnatlink.all);
6938      end if;
6939
6940      GNAT.OS_Lib.Spawn (Gnatlink_Path.all, Link_Args, Success);
6941   end Link;
6942
6943   ---------------------------
6944   -- List_Bad_Compilations --
6945   ---------------------------
6946
6947   procedure List_Bad_Compilations is
6948   begin
6949      if not No_Exit_Message then
6950         for J in Bad_Compilation.First .. Bad_Compilation.Last loop
6951            if Bad_Compilation.Table (J).File = No_File then
6952               null;
6953            elsif not Bad_Compilation.Table (J).Found then
6954               Inform (Bad_Compilation.Table (J).File, "not found");
6955            else
6956               Inform (Bad_Compilation.Table (J).File, "compilation error");
6957            end if;
6958         end loop;
6959      end if;
6960   end List_Bad_Compilations;
6961
6962   -----------------
6963   -- List_Depend --
6964   -----------------
6965
6966   procedure List_Depend is
6967      Lib_Name  : File_Name_Type;
6968      Obj_Name  : File_Name_Type;
6969      Src_Name  : File_Name_Type;
6970
6971      Len       : Natural;
6972      Line_Pos  : Natural;
6973      Line_Size : constant := 77;
6974
6975   begin
6976      Set_Standard_Output;
6977
6978      for A in ALIs.First .. ALIs.Last loop
6979         Lib_Name := ALIs.Table (A).Afile;
6980
6981         --  We have to provide the full library file name in In_Place_Mode
6982
6983         if In_Place_Mode then
6984            Lib_Name := Full_Lib_File_Name (Lib_Name);
6985         end if;
6986
6987         Obj_Name := Object_File_Name (Lib_Name);
6988         Write_Name (Obj_Name);
6989         Write_Str (" :");
6990
6991         Get_Name_String (Obj_Name);
6992         Len := Name_Len;
6993         Line_Pos := Len + 2;
6994
6995         for D in ALIs.Table (A).First_Sdep .. ALIs.Table (A).Last_Sdep loop
6996            Src_Name := Sdep.Table (D).Sfile;
6997
6998            if Is_Internal_File_Name (Src_Name)
6999              and then not Check_Readonly_Files
7000            then
7001               null;
7002            else
7003               if not Quiet_Output then
7004                  Src_Name := Full_Source_Name (Src_Name);
7005               end if;
7006
7007               Get_Name_String (Src_Name);
7008               Len := Name_Len;
7009
7010               if Line_Pos + Len + 1 > Line_Size then
7011                  Write_Str (" \");
7012                  Write_Eol;
7013                  Line_Pos := 0;
7014               end if;
7015
7016               Line_Pos := Line_Pos + Len + 1;
7017
7018               Write_Str (" ");
7019               Write_Name (Src_Name);
7020            end if;
7021         end loop;
7022
7023         Write_Eol;
7024      end loop;
7025
7026      if not Commands_To_Stdout then
7027         Set_Standard_Error;
7028      end if;
7029   end List_Depend;
7030
7031   -----------------
7032   -- Make_Failed --
7033   -----------------
7034
7035   procedure Make_Failed (S : String) is
7036   begin
7037      Fail_Program (Project_Tree, S);
7038   end Make_Failed;
7039
7040   --------------------
7041   -- Mark_Directory --
7042   --------------------
7043
7044   procedure Mark_Directory
7045     (Dir             : String;
7046      Mark            : Lib_Mark_Type;
7047      On_Command_Line : Boolean)
7048   is
7049      N : Name_Id;
7050      B : Byte;
7051
7052      function Base_Directory return String;
7053      --  If Dir comes from the command line, empty string (relative paths are
7054      --  resolved with respect to the current directory), else return the main
7055      --  project's directory.
7056
7057      --------------------
7058      -- Base_Directory --
7059      --------------------
7060
7061      function Base_Directory return String is
7062      begin
7063         if On_Command_Line then
7064            return "";
7065         else
7066            return Get_Name_String (Main_Project.Directory.Display_Name);
7067         end if;
7068      end Base_Directory;
7069
7070      Real_Path : constant String := Normalize_Pathname (Dir, Base_Directory);
7071
7072   --  Start of processing for Mark_Directory
7073
7074   begin
7075      Name_Len := 0;
7076
7077      if Real_Path'Length = 0 then
7078         Add_Str_To_Name_Buffer (Dir);
7079
7080      else
7081         Add_Str_To_Name_Buffer (Real_Path);
7082      end if;
7083
7084      --  Last character is supposed to be a directory separator
7085
7086      if not Is_Directory_Separator (Name_Buffer (Name_Len)) then
7087         Add_Char_To_Name_Buffer (Directory_Separator);
7088      end if;
7089
7090      --  Add flags to the already existing flags
7091
7092      N := Name_Find;
7093      B := Get_Name_Table_Byte (N);
7094      Set_Name_Table_Byte (N, B or Mark);
7095   end Mark_Directory;
7096
7097   ----------------------
7098   -- Process_Multilib --
7099   ----------------------
7100
7101   procedure Process_Multilib (Env : in out Prj.Tree.Environment) is
7102      Output_FD         : File_Descriptor;
7103      Output_Name       : String_Access;
7104      Arg_Index         : Natural := 0;
7105      Success           : Boolean := False;
7106      Return_Code       : Integer := 0;
7107      Multilib_Gcc_Path : String_Access;
7108      Multilib_Gcc      : String_Access;
7109      N_Read            : Integer := 0;
7110      Line              : String (1 .. 1000);
7111      Args              : Argument_List (1 .. N_M_Switch + 1);
7112
7113   begin
7114      pragma Assert (N_M_Switch > 0 and RTS_Specified = null);
7115
7116      --  In case we detected a multilib switch and the user has not
7117      --  manually specified a specific RTS we emulate the following command:
7118      --  gnatmake $FLAGS --RTS=$(gcc -print-multi-directory $FLAGS)
7119
7120      --  First select the flags which might have an impact on multilib
7121      --  processing. Note that this is an heuristic selection and it
7122      --  will need to be maintained over time. The condition has to
7123      --  be kept synchronized with N_M_Switch counting in Scan_Make_Arg.
7124
7125      for Next_Arg in 1 .. Argument_Count loop
7126         declare
7127            Argv : constant String := Argument (Next_Arg);
7128
7129         begin
7130            if Argv'Length > 2
7131              and then Argv (1) = '-'
7132              and then Argv (2) = 'm'
7133              and then Argv /= "-margs"
7134
7135              --  Ignore -mieee to avoid spawning an extra gcc in this case
7136
7137              and then Argv /= "-mieee"
7138            then
7139               Arg_Index := Arg_Index + 1;
7140               Args (Arg_Index) := new String'(Argv);
7141            end if;
7142         end;
7143      end loop;
7144
7145      pragma Assert (Arg_Index = N_M_Switch);
7146
7147      Args (Args'Last) := new String'("-print-multi-directory");
7148
7149      --  Call the GCC driver with the collected flags and save its
7150      --  output. Alternate design would be to link in gnatmake the
7151      --  relevant part of the GCC driver.
7152
7153      if Saved_Gcc /= null then
7154         Multilib_Gcc := Saved_Gcc;
7155      else
7156         Multilib_Gcc := Gcc;
7157      end if;
7158
7159      Multilib_Gcc_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Multilib_Gcc.all);
7160
7161      Create_Temp_Output_File (Output_FD, Output_Name);
7162
7163      if Output_FD = Invalid_FD then
7164         return;
7165      end if;
7166
7167      GNAT.OS_Lib.Spawn
7168        (Multilib_Gcc_Path.all, Args, Output_FD, Return_Code, False);
7169      Close (Output_FD);
7170
7171      if Return_Code /= 0 then
7172         return;
7173      end if;
7174
7175      --  Parse the GCC driver output which is a single line, removing CR/LF
7176
7177      Output_FD := Open_Read (Output_Name.all, Binary);
7178
7179      if Output_FD = Invalid_FD then
7180         return;
7181      end if;
7182
7183      N_Read := Read (Output_FD, Line (1)'Address, Line'Length);
7184      Close (Output_FD);
7185      Delete_File (Output_Name.all, Success);
7186
7187      for J in reverse 1 .. N_Read loop
7188         if Line (J) = ASCII.CR or else Line (J) = ASCII.LF then
7189            N_Read := N_Read - 1;
7190         else
7191            exit;
7192         end if;
7193      end loop;
7194
7195      --  In case the standard RTS is selected do nothing
7196
7197      if N_Read = 0 or else Line (1 .. N_Read) = "." then
7198         return;
7199      end if;
7200
7201      --  Otherwise add -margs --RTS=output
7202
7203      Scan_Make_Arg (Env, "-margs", And_Save => True);
7204      Scan_Make_Arg (Env, "--RTS=" & Line (1 .. N_Read), And_Save => True);
7205   end Process_Multilib;
7206
7207   -----------------------------
7208   -- Recursive_Compute_Depth --
7209   -----------------------------
7210
7211   procedure Recursive_Compute_Depth (Project : Project_Id) is
7212      use Project_Boolean_Htable;
7213      Seen : Project_Boolean_Htable.Instance := Project_Boolean_Htable.Nil;
7214
7215      procedure Recurse (Prj : Project_Id; Depth : Natural);
7216      --  Recursive procedure that does the work, keeping track of the depth
7217
7218      -------------
7219      -- Recurse --
7220      -------------
7221
7222      procedure Recurse (Prj : Project_Id; Depth : Natural) is
7223         List : Project_List;
7224         Proj : Project_Id;
7225
7226      begin
7227         if Prj.Depth >= Depth or else Get (Seen, Prj) then
7228            return;
7229         end if;
7230
7231         --  We need a test to avoid infinite recursions with limited withs:
7232         --  If we have A -> B -> A, then when set level of A to n, we try and
7233         --  set level of B to n+1, and then level of A to n + 2, ...
7234
7235         Set (Seen, Prj, True);
7236
7237         Prj.Depth := Depth;
7238
7239         --  Visit each imported project
7240
7241         List := Prj.Imported_Projects;
7242         while List /= null loop
7243            Proj := List.Project;
7244            List := List.Next;
7245            Recurse (Prj => Proj, Depth => Depth + 1);
7246         end loop;
7247
7248         --  We again allow changing the depth of this project later on if it
7249         --  is in fact imported by a lower-level project.
7250
7251         Set (Seen, Prj, False);
7252      end Recurse;
7253
7254      Proj : Project_List;
7255
7256   --  Start of processing for Recursive_Compute_Depth
7257
7258   begin
7259      Proj := Project_Tree.Projects;
7260      while Proj /= null loop
7261         Proj.Project.Depth := 0;
7262         Proj := Proj.Next;
7263      end loop;
7264
7265      Recurse (Project, Depth => 1);
7266      Reset (Seen);
7267   end Recursive_Compute_Depth;
7268
7269   -------------------------------
7270   -- Report_Compilation_Failed --
7271   -------------------------------
7272
7273   procedure Report_Compilation_Failed is
7274   begin
7275      Fail_Program (Project_Tree, "");
7276   end Report_Compilation_Failed;
7277
7278   ------------------------
7279   -- Sigint_Intercepted --
7280   ------------------------
7281
7282   procedure Sigint_Intercepted is
7283      SIGINT  : constant := 2;
7284
7285   begin
7286      Set_Standard_Error;
7287      Write_Line ("*** Interrupted ***");
7288
7289      --  Send SIGINT to all outstanding compilation processes spawned
7290
7291      for J in 1 .. Outstanding_Compiles loop
7292         Kill (Running_Compile (J).Pid, SIGINT, 1);
7293      end loop;
7294
7295      Finish_Program (Project_Tree, E_No_Compile);
7296   end Sigint_Intercepted;
7297
7298   -------------------
7299   -- Scan_Make_Arg --
7300   -------------------
7301
7302   procedure Scan_Make_Arg
7303     (Env               : in out Prj.Tree.Environment;
7304      Argv              : String;
7305      And_Save          : Boolean)
7306   is
7307      Success : Boolean;
7308
7309   begin
7310      Gnatmake_Switch_Found := True;
7311
7312      pragma Assert (Argv'First = 1);
7313
7314      if Argv'Length = 0 then
7315         return;
7316      end if;
7317
7318      --  If the previous switch has set the Project_File_Name_Present flag
7319      --  (that is we have seen a -P alone), then the next argument is the name
7320      --  of the project file.
7321
7322      if Project_File_Name_Present and then Project_File_Name = null then
7323         if Argv (1) = '-' then
7324            Make_Failed ("project file name missing after -P");
7325
7326         else
7327            Project_File_Name_Present := False;
7328            Project_File_Name := new String'(Argv);
7329         end if;
7330
7331      --  If the previous switch has set the Output_File_Name_Present flag
7332      --  (that is we have seen a -o), then the next argument is the name of
7333      --  the output executable.
7334
7335      elsif Output_File_Name_Present
7336        and then not Output_File_Name_Seen
7337      then
7338         Output_File_Name_Seen := True;
7339
7340         if Argv (1) = '-' then
7341            Make_Failed ("output file name missing after -o");
7342
7343         else
7344            Add_Switch ("-o", Linker, And_Save => And_Save);
7345            Add_Switch (Executable_Name (Argv), Linker, And_Save => And_Save);
7346         end if;
7347
7348      --  If the previous switch has set the Object_Directory_Present flag
7349      --  (that is we have seen a -D), then the next argument is the path name
7350      --  of the object directory.
7351
7352      elsif Object_Directory_Present
7353        and then not Object_Directory_Seen
7354      then
7355         Object_Directory_Seen := True;
7356
7357         if Argv (1) = '-' then
7358            Make_Failed ("object directory path name missing after -D");
7359
7360         elsif not Is_Directory (Argv) then
7361            Make_Failed ("cannot find object directory """ & Argv & """");
7362
7363         else
7364            --  Record the object directory. Make sure it ends with a directory
7365            --  separator.
7366
7367            declare
7368               Norm : constant String := Normalize_Pathname (Argv);
7369
7370            begin
7371               if Norm (Norm'Last) = Directory_Separator then
7372                  Object_Directory_Path := new String'(Norm);
7373               else
7374                  Object_Directory_Path :=
7375                    new String'(Norm & Directory_Separator);
7376               end if;
7377
7378               Add_Lib_Search_Dir (Norm);
7379
7380               --  Specify the object directory to the binder
7381
7382               Add_Switch ("-aO" & Norm, Binder, And_Save => And_Save);
7383            end;
7384
7385         end if;
7386
7387      --  Then check if we are dealing with -cargs/-bargs/-largs/-margs. These
7388      --  options are taken as is when found in package Compiler, Binder or
7389      --  Linker of the main project file.
7390
7391      elsif (And_Save or else Program_Args = None)
7392        and then (Argv = "-bargs" or else
7393                  Argv = "-cargs" or else
7394                  Argv = "-largs" or else
7395                  Argv = "-margs")
7396      then
7397         case Argv (2) is
7398            when 'c' => Program_Args := Compiler;
7399            when 'b' => Program_Args := Binder;
7400            when 'l' => Program_Args := Linker;
7401            when 'm' => Program_Args := None;
7402
7403            when others =>
7404               raise Program_Error;
7405         end case;
7406
7407      --  A special test is needed for the -o switch within a -largs since that
7408      --  is another way to specify the name of the final executable.
7409
7410      elsif Program_Args = Linker and then Argv = "-o" then
7411         Make_Failed
7412           ("switch -o not allowed within a -largs. Use -o directly.");
7413
7414      --  Check to see if we are reading switches after a -cargs, -bargs or
7415      --  -largs switch. If so, save it.
7416
7417      elsif Program_Args /= None then
7418
7419         --  Check to see if we are reading -I switches in order to take into
7420         --  account in the src & lib search directories.
7421
7422         if Argv'Length > 2 and then Argv (1 .. 2) = "-I" then
7423            if Argv (3 .. Argv'Last) = "-" then
7424               Look_In_Primary_Dir := False;
7425
7426            elsif Program_Args = Compiler then
7427               if Argv (3 .. Argv'Last) /= "-" then
7428                  Add_Source_Search_Dir (Argv (3 .. Argv'Last), And_Save);
7429               end if;
7430
7431            elsif Program_Args = Binder then
7432               Add_Library_Search_Dir (Argv (3 .. Argv'Last), And_Save);
7433            end if;
7434         end if;
7435
7436         Add_Switch (Argv, Program_Args, And_Save => And_Save);
7437
7438         --  Make sure that all significant switches -m on the command line
7439         --  are counted.
7440
7441         if Argv'Length > 2
7442           and then Argv (1 .. 2) = "-m"
7443           and then Argv /= "-mieee"
7444         then
7445            N_M_Switch := N_M_Switch + 1;
7446         end if;
7447
7448      --  Handle non-default compiler, binder, linker, and handle --RTS switch
7449
7450      elsif Argv'Length > 2 and then Argv (1 .. 2) = "--" then
7451         if Argv'Length > 6
7452           and then Argv (1 .. 6) = "--GCC="
7453         then
7454            declare
7455               Program_Args : constant Argument_List_Access :=
7456                                Argument_String_To_List
7457                                  (Argv (7 .. Argv'Last));
7458
7459            begin
7460               if And_Save then
7461                  Saved_Gcc := new String'(Program_Args.all (1).all);
7462               else
7463                  Gcc := new String'(Program_Args.all (1).all);
7464               end if;
7465
7466               for J in 2 .. Program_Args.all'Last loop
7467                  Add_Switch
7468                    (Program_Args.all (J).all, Compiler, And_Save => And_Save);
7469               end loop;
7470            end;
7471
7472         elsif Argv'Length > 11
7473           and then Argv (1 .. 11) = "--GNATBIND="
7474         then
7475            declare
7476               Program_Args : constant Argument_List_Access :=
7477                                Argument_String_To_List
7478                                  (Argv (12 .. Argv'Last));
7479
7480            begin
7481               if And_Save then
7482                  Saved_Gnatbind := new String'(Program_Args.all (1).all);
7483               else
7484                  Gnatbind := new String'(Program_Args.all (1).all);
7485               end if;
7486
7487               for J in 2 .. Program_Args.all'Last loop
7488                  Add_Switch
7489                    (Program_Args.all (J).all, Binder, And_Save => And_Save);
7490               end loop;
7491            end;
7492
7493         elsif Argv'Length > 11
7494           and then Argv (1 .. 11) = "--GNATLINK="
7495         then
7496            declare
7497               Program_Args : constant Argument_List_Access :=
7498                                Argument_String_To_List
7499                                  (Argv (12 .. Argv'Last));
7500            begin
7501               if And_Save then
7502                  Saved_Gnatlink := new String'(Program_Args.all (1).all);
7503               else
7504                  Gnatlink := new String'(Program_Args.all (1).all);
7505               end if;
7506
7507               for J in 2 .. Program_Args.all'Last loop
7508                  Add_Switch (Program_Args.all (J).all, Linker);
7509               end loop;
7510            end;
7511
7512         elsif Argv'Length >= 5 and then
7513           Argv (1 .. 5) = "--RTS"
7514         then
7515            Add_Switch (Argv, Compiler, And_Save => And_Save);
7516            Add_Switch (Argv, Binder,   And_Save => And_Save);
7517
7518            if Argv'Length <= 6 or else Argv (6) /= '=' then
7519               Make_Failed ("missing path for --RTS");
7520
7521            else
7522               --  Check that this is the first time we see this switch or
7523               --  if it is not the first time, the same path is specified.
7524
7525               if RTS_Specified = null then
7526                  RTS_Specified := new String'(Argv (7 .. Argv'Last));
7527
7528               elsif RTS_Specified.all /= Argv (7 .. Argv'Last) then
7529                  Make_Failed ("--RTS cannot be specified multiple times");
7530               end if;
7531
7532               --  Valid --RTS switch
7533
7534               No_Stdinc := True;
7535               No_Stdlib := True;
7536               RTS_Switch := True;
7537
7538               declare
7539                  Src_Path_Name : constant String_Ptr :=
7540                                    Get_RTS_Search_Dir
7541                                      (Argv (7 .. Argv'Last), Include);
7542
7543                  Lib_Path_Name : constant String_Ptr :=
7544                                    Get_RTS_Search_Dir
7545                                      (Argv (7 .. Argv'Last), Objects);
7546
7547               begin
7548                  if Src_Path_Name /= null
7549                    and then Lib_Path_Name /= null
7550                  then
7551                     --  Set RTS_*_Path_Name variables, so that correct direct-
7552                     --  ories will be set when Osint.Add_Default_Search_Dirs
7553                     --  is called later.
7554
7555                     RTS_Src_Path_Name := Src_Path_Name;
7556                     RTS_Lib_Path_Name := Lib_Path_Name;
7557
7558                  elsif Src_Path_Name = null
7559                    and then Lib_Path_Name = null
7560                  then
7561                     Make_Failed ("RTS path not valid: missing "
7562                                  & "adainclude and adalib directories");
7563
7564                  elsif Src_Path_Name = null then
7565                     Make_Failed ("RTS path not valid: missing adainclude "
7566                                  & "directory");
7567
7568                  elsif  Lib_Path_Name = null then
7569                     Make_Failed ("RTS path not valid: missing adalib "
7570                                  & "directory");
7571                  end if;
7572               end;
7573            end if;
7574
7575         elsif Argv'Length > Source_Info_Option'Length and then
7576           Argv (1 .. Source_Info_Option'Length) = Source_Info_Option
7577         then
7578            Project_Tree.Source_Info_File_Name :=
7579              new String'(Argv (Source_Info_Option'Length + 1 .. Argv'Last));
7580
7581         elsif Argv'Length >= 8 and then
7582           Argv (1 .. 8) = "--param="
7583         then
7584            Add_Switch (Argv, Compiler, And_Save => And_Save);
7585            Add_Switch (Argv, Linker,   And_Save => And_Save);
7586
7587         elsif Argv = Create_Map_File_Switch then
7588            Map_File := new String'("");
7589
7590         elsif Argv'Length > Create_Map_File_Switch'Length + 1
7591           and then
7592             Argv (1 .. Create_Map_File_Switch'Length) = Create_Map_File_Switch
7593           and then
7594             Argv (Create_Map_File_Switch'Length + 1) = '='
7595         then
7596            Map_File :=
7597              new String'
7598                (Argv (Create_Map_File_Switch'Length + 2 .. Argv'Last));
7599
7600         else
7601            Scan_Make_Switches (Env, Argv, Success);
7602         end if;
7603
7604      --  If we have seen a regular switch process it
7605
7606      elsif Argv (1) = '-' then
7607         if Argv'Length = 1 then
7608            Make_Failed ("switch character cannot be followed by a blank");
7609
7610         --  Incorrect switches that should start with "--"
7611
7612         elsif     (Argv'Length > 5  and then Argv (1 .. 5) = "-RTS=")
7613           or else (Argv'Length > 5  and then Argv (1 .. 5) = "-GCC=")
7614           or else (Argv'Length > 8  and then Argv (1 .. 7) = "-param=")
7615           or else (Argv'Length > 10 and then Argv (1 .. 10) = "-GNATLINK=")
7616           or else (Argv'Length > 10 and then Argv (1 .. 10) = "-GNATBIND=")
7617         then
7618            Make_Failed ("option " & Argv & " should start with '--'");
7619
7620         --  -I-
7621
7622         elsif Argv (2 .. Argv'Last) = "I-" then
7623            Look_In_Primary_Dir := False;
7624
7625         --  Forbid  -?-  or  -??-  where ? is any character
7626
7627         elsif (Argv'Length = 3 and then Argv (3) = '-')
7628           or else (Argv'Length = 4 and then Argv (4) = '-')
7629         then
7630            Make_Failed
7631              ("trailing ""-"" at the end of " & Argv & " forbidden.");
7632
7633         --  -Idir
7634
7635         elsif Argv (2) = 'I' then
7636            Add_Source_Search_Dir  (Argv (3 .. Argv'Last), And_Save);
7637            Add_Library_Search_Dir (Argv (3 .. Argv'Last), And_Save);
7638            Add_Switch (Argv, Compiler, And_Save => And_Save);
7639            Add_Switch (Argv, Binder,   And_Save => And_Save);
7640
7641         --  -aIdir (to gcc this is like a -I switch)
7642
7643         elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aI" then
7644            Add_Source_Search_Dir (Argv (4 .. Argv'Last), And_Save);
7645            Add_Switch
7646              ("-I" & Argv (4 .. Argv'Last), Compiler, And_Save => And_Save);
7647            Add_Switch (Argv, Binder, And_Save => And_Save);
7648
7649         --  -aOdir
7650
7651         elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aO" then
7652            Add_Library_Search_Dir (Argv (4 .. Argv'Last), And_Save);
7653            Add_Switch (Argv, Binder, And_Save => And_Save);
7654
7655         --  -aLdir (to gnatbind this is like a -aO switch)
7656
7657         elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aL" then
7658            Mark_Directory (Argv (4 .. Argv'Last), Ada_Lib_Dir, And_Save);
7659            Add_Library_Search_Dir (Argv (4 .. Argv'Last), And_Save);
7660            Add_Switch
7661              ("-aO" & Argv (4 .. Argv'Last), Binder, And_Save => And_Save);
7662
7663         --  -aamp_target=...
7664
7665         elsif Argv'Length >= 13 and then Argv (2 .. 13) = "aamp_target=" then
7666            Add_Switch (Argv, Compiler, And_Save => And_Save);
7667
7668            --  Set the aamp_target environment variable so that the binder and
7669            --  linker will use the proper target library. This is consistent
7670            --  with how things work when -aamp_target is passed on the command
7671            --  line to gnaampmake.
7672
7673            Setenv ("aamp_target", Argv (14 .. Argv'Last));
7674
7675         --  -Adir (to gnatbind this is like a -aO switch, to gcc like a -I)
7676
7677         elsif Argv (2) = 'A' then
7678            Mark_Directory (Argv (3 .. Argv'Last), Ada_Lib_Dir, And_Save);
7679            Add_Source_Search_Dir  (Argv (3 .. Argv'Last), And_Save);
7680            Add_Library_Search_Dir (Argv (3 .. Argv'Last), And_Save);
7681            Add_Switch
7682              ("-I"  & Argv (3 .. Argv'Last), Compiler, And_Save => And_Save);
7683            Add_Switch
7684              ("-aO" & Argv (3 .. Argv'Last), Binder,   And_Save => And_Save);
7685
7686         --  -Ldir
7687
7688         elsif Argv (2) = 'L' then
7689            Add_Switch (Argv, Linker, And_Save => And_Save);
7690
7691         --  For -gxxx, -pg, -mxxx, -fxxx, -Oxxx, pass the switch to both the
7692         --  compiler and the linker (except for -gnatxxx which is only for the
7693         --  compiler). Some of the -mxxx (for example -m64) and -fxxx (for
7694         --  example -ftest-coverage for gcov) need to be used when compiling
7695         --  the binder generated files, and using all these gcc switches for
7696         --  them should not be a problem. Pass -Oxxx to the linker for LTO.
7697
7698         elsif
7699           (Argv (2) = 'g' and then (Argv'Last < 5
7700                                       or else Argv (2 .. 5) /= "gnat"))
7701             or else Argv (2 .. Argv'Last) = "pg"
7702             or else (Argv (2) = 'm' and then Argv'Last > 2)
7703             or else (Argv (2) = 'f' and then Argv'Last > 2)
7704             or else Argv (2) = 'O'
7705         then
7706            Add_Switch (Argv, Compiler, And_Save => And_Save);
7707            Add_Switch (Argv, Linker,   And_Save => And_Save);
7708
7709            --  The following condition has to be kept synchronized with
7710            --  the Process_Multilib one.
7711
7712            if Argv (2) = 'm'
7713              and then Argv /= "-mieee"
7714            then
7715               N_M_Switch := N_M_Switch + 1;
7716            end if;
7717
7718         --  -C=<mapping file>
7719
7720         elsif Argv'Last > 2 and then Argv (2) = 'C' then
7721            if And_Save then
7722               if Argv (3) /= '=' or else Argv'Last <= 3 then
7723                  Make_Failed ("illegal switch " & Argv);
7724               end if;
7725
7726               Gnatmake_Mapping_File := new String'(Argv (4 .. Argv'Last));
7727            end if;
7728
7729         --  -D
7730
7731         elsif Argv'Last = 2 and then Argv (2) = 'D' then
7732            if Project_File_Name /= null then
7733               Make_Failed
7734                 ("-D cannot be used in conjunction with a project file");
7735
7736            else
7737               Scan_Make_Switches (Env, Argv, Success);
7738            end if;
7739
7740         --  -d
7741
7742         elsif Argv (2) = 'd' and then Argv'Last = 2 then
7743            Display_Compilation_Progress := True;
7744
7745         --  -i
7746
7747         elsif Argv'Last = 2 and then Argv (2) = 'i' then
7748            if Project_File_Name /= null then
7749               Make_Failed
7750                 ("-i cannot be used in conjunction with a project file");
7751            else
7752               Scan_Make_Switches (Env, Argv, Success);
7753            end if;
7754
7755         --  -j (need to save the result)
7756
7757         elsif Argv (2) = 'j' then
7758            Scan_Make_Switches (Env, Argv, Success);
7759
7760            if And_Save then
7761               Saved_Maximum_Processes := Maximum_Processes;
7762            end if;
7763
7764         --  -m
7765
7766         elsif Argv (2) = 'm' and then Argv'Last = 2 then
7767            Minimal_Recompilation := True;
7768
7769         --  -u
7770
7771         elsif Argv (2) = 'u' and then Argv'Last = 2 then
7772            Unique_Compile := True;
7773            Compile_Only   := True;
7774            Do_Bind_Step   := False;
7775            Do_Link_Step   := False;
7776
7777         --  -U
7778
7779         elsif Argv (2) = 'U'
7780           and then Argv'Last = 2
7781         then
7782            Unique_Compile_All_Projects := True;
7783            Unique_Compile := True;
7784            Compile_Only   := True;
7785            Do_Bind_Step   := False;
7786            Do_Link_Step   := False;
7787
7788         --  -Pprj or -P prj (only once, and only on the command line)
7789
7790         elsif Argv (2) = 'P' then
7791            if Project_File_Name /= null then
7792               Make_Failed ("cannot have several project files specified");
7793
7794            elsif Object_Directory_Path /= null then
7795               Make_Failed
7796                 ("-D cannot be used in conjunction with a project file");
7797
7798            elsif In_Place_Mode then
7799               Make_Failed
7800                 ("-i cannot be used in conjunction with a project file");
7801
7802            elsif not And_Save then
7803
7804               --  It could be a tool other than gnatmake (e.g. gnatdist)
7805               --  or a -P switch inside a project file.
7806
7807               Fail
7808                 ("either the tool is not ""project-aware"" or "
7809                  & "a project file is specified inside a project file");
7810
7811            elsif Argv'Last = 2 then
7812
7813               --  -P is used alone: the project file name is the next option
7814
7815               Project_File_Name_Present := True;
7816
7817            else
7818               Project_File_Name := new String'(Argv (3 .. Argv'Last));
7819            end if;
7820
7821         --  -vPx  (verbosity of the parsing of the project files)
7822
7823         elsif Argv'Length >= 3 and then Argv (2 .. 3) = "vP" then
7824            if Argv'Last /= 4 or else Argv (4) not in '0' .. '2' then
7825               Make_Failed
7826                 ("invalid verbosity level " & Argv (4 .. Argv'Last));
7827
7828            elsif And_Save then
7829               case Argv (4) is
7830                  when '0' =>
7831                     Current_Verbosity := Prj.Default;
7832                  when '1' =>
7833                     Current_Verbosity := Prj.Medium;
7834                  when '2' =>
7835                     Current_Verbosity := Prj.High;
7836                  when others =>
7837                     null;
7838               end case;
7839            end if;
7840
7841         --  -Xext=val  (External assignment)
7842
7843         elsif Argv (2) = 'X'
7844           and then Is_External_Assignment (Env, Argv)
7845         then
7846            --  Is_External_Assignment has side effects when it returns True
7847
7848            null;
7849
7850         --  If -gnath is present, then generate the usage information right
7851         --  now and do not pass this option on to the compiler calls.
7852
7853         elsif Argv = "-gnath" then
7854            Usage;
7855
7856         --  If -gnatc is specified, make sure the bind and link steps are not
7857         --  executed.
7858
7859         elsif Argv'Length >= 6 and then Argv (2 .. 6) = "gnatc" then
7860
7861            --  If -gnatc is specified, make sure the bind and link steps are
7862            --  not executed.
7863
7864            Add_Switch (Argv, Compiler, And_Save => And_Save);
7865            Operating_Mode           := Check_Semantics;
7866            Check_Object_Consistency := False;
7867
7868            --  Except in CodePeer mode (set by -gnatcC), where we do want to
7869            --  call bind/link in CodePeer mode (-P switch).
7870
7871            if Argv'Last >= 7 and then Argv (7) = 'C' then
7872               CodePeer_Mode := True;
7873            else
7874               Compile_Only := True;
7875               Do_Bind_Step := False;
7876               Do_Link_Step := False;
7877            end if;
7878
7879         --  If -gnatA is specified, make sure that gnat.adc is never read
7880
7881         elsif Argv'Length >= 6 and then Argv (2 .. 6) = "gnatA" then
7882            Add_Switch (Argv, Compiler, And_Save => And_Save);
7883            Opt.Config_File := False;
7884
7885         elsif Argv (2 .. Argv'Last) = "nostdlib" then
7886
7887            --  Pass -nstdlib to gnatbind and gnatlink
7888
7889            No_Stdlib := True;
7890            Add_Switch (Argv, Binder, And_Save => And_Save);
7891            Add_Switch (Argv, Linker, And_Save => And_Save);
7892
7893         elsif Argv (2 .. Argv'Last) = "nostdinc" then
7894
7895            --  Pass -nostdinc to the Compiler and to gnatbind
7896
7897            No_Stdinc := True;
7898            Add_Switch (Argv, Compiler, And_Save => And_Save);
7899            Add_Switch (Argv, Binder,   And_Save => And_Save);
7900
7901         --  All other switches are processed by Scan_Make_Switches. If the
7902         --  call returns with Gnatmake_Switch_Found = False, then the switch
7903         --  is passed to the compiler.
7904
7905         else
7906            Scan_Make_Switches (Env, Argv, Gnatmake_Switch_Found);
7907
7908            if not Gnatmake_Switch_Found then
7909               Add_Switch (Argv, Compiler, And_Save => And_Save);
7910            end if;
7911         end if;
7912
7913      --  If not a switch it must be a file name
7914
7915      else
7916         if And_Save then
7917            Main_On_Command_Line := True;
7918         end if;
7919
7920         Add_File (Argv);
7921         Mains.Add_Main (Argv);
7922      end if;
7923   end Scan_Make_Arg;
7924
7925   -----------------
7926   -- Switches_Of --
7927   -----------------
7928
7929   function Switches_Of
7930     (Source_File      : File_Name_Type;
7931      Project          : Project_Id;
7932      In_Package       : Package_Id;
7933      Allow_ALI        : Boolean) return Variable_Value
7934   is
7935      Switches : Variable_Value;
7936      Is_Default : Boolean;
7937
7938   begin
7939      Makeutl.Get_Switches
7940        (Source_File  => Source_File,
7941         Source_Lang  => Name_Ada,
7942         Source_Prj   => Project,
7943         Pkg_Name     => Project_Tree.Shared.Packages.Table (In_Package).Name,
7944         Project_Tree => Project_Tree,
7945         Value        => Switches,
7946         Is_Default   => Is_Default,
7947         Test_Without_Suffix => True,
7948         Check_ALI_Suffix => Allow_ALI);
7949      return Switches;
7950   end Switches_Of;
7951
7952   -----------
7953   -- Usage --
7954   -----------
7955
7956   procedure Usage is
7957   begin
7958      if Usage_Needed then
7959         Usage_Needed := False;
7960         Makeusg;
7961      end if;
7962   end Usage;
7963
7964begin
7965   --  Make sure that in case of failure, the temp files will be deleted
7966
7967   Prj.Com.Fail    := Make_Failed'Access;
7968   MLib.Fail       := Make_Failed'Access;
7969end Make;
7970