1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                             G N A T L I N K                              --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1996-2018, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26--  Gnatlink usage: please consult the gnat documentation
27
28with ALI;      use ALI;
29with Csets;
30with Gnatvsn;  use Gnatvsn;
31with Indepsw;  use Indepsw;
32with Namet;    use Namet;
33with Opt;
34with Osint;    use Osint;
35with Output;   use Output;
36with Snames;
37with Switch;   use Switch;
38with System;   use System;
39with Table;
40with Targparm;
41with Types;
42
43with Ada.Command_Line; use Ada.Command_Line;
44with Ada.Exceptions;   use Ada.Exceptions;
45
46with System.OS_Lib; use System.OS_Lib;
47with System.CRTL;
48
49with Interfaces.C_Streams; use Interfaces.C_Streams;
50with Interfaces.C.Strings; use Interfaces.C.Strings;
51
52procedure Gnatlink is
53   pragma Ident (Gnatvsn.Gnat_Static_Version_String);
54
55   Shared_Libgcc_String : constant String := "-shared-libgcc";
56   Shared_Libgcc        : constant String_Access :=
57                            new String'(Shared_Libgcc_String);
58   --  Used to invoke gcc when the binder is invoked with -shared
59
60   Static_Libgcc_String : constant String := "-static-libgcc";
61   Static_Libgcc        : constant String_Access :=
62                            new String'(Static_Libgcc_String);
63   --  Used to invoke gcc when shared libs are not used
64
65   package Gcc_Linker_Options is new Table.Table (
66     Table_Component_Type => String_Access,
67     Table_Index_Type     => Integer,
68     Table_Low_Bound      => 1,
69     Table_Initial        => 20,
70     Table_Increment      => 100,
71     Table_Name           => "Gnatlink.Gcc_Linker_Options");
72   --  Comments needed ???
73
74   package Libpath is new Table.Table (
75     Table_Component_Type => Character,
76     Table_Index_Type     => Integer,
77     Table_Low_Bound      => 1,
78     Table_Initial        => 4096,
79     Table_Increment      => 100,
80     Table_Name           => "Gnatlink.Libpath");
81   --  Comments needed ???
82
83   package Linker_Options is new Table.Table (
84     Table_Component_Type => String_Access,
85     Table_Index_Type     => Integer,
86     Table_Low_Bound      => 1,
87     Table_Initial        => 20,
88     Table_Increment      => 100,
89     Table_Name           => "Gnatlink.Linker_Options");
90   --  Comments needed ???
91
92   package Linker_Objects is new Table.Table (
93     Table_Component_Type => String_Access,
94     Table_Index_Type     => Integer,
95     Table_Low_Bound      => 1,
96     Table_Initial        => 20,
97     Table_Increment      => 100,
98     Table_Name           => "Gnatlink.Linker_Objects");
99   --  This table collects the objects file to be passed to the linker. In the
100   --  case where the linker command line is too long then programs objects
101   --  are put on the Response_File_Objects table. Note that the binder object
102   --  file and the user's objects remain in this table. This is very
103   --  important because on the GNU linker command line the -L switch is not
104   --  used to look for objects files but -L switch is used to look for
105   --  objects listed in the response file. This is not a problem with the
106   --  applications objects as they are specified with a full name.
107
108   package Response_File_Objects is new Table.Table (
109     Table_Component_Type => String_Access,
110     Table_Index_Type     => Integer,
111     Table_Low_Bound      => 1,
112     Table_Initial        => 20,
113     Table_Increment      => 100,
114     Table_Name           => "Gnatlink.Response_File_Objects");
115   --  This table collects the objects file that are to be put in the response
116   --  file. Only application objects are collected there (see details in
117   --  Linker_Objects table comments)
118
119   package Binder_Options_From_ALI is new Table.Table (
120     Table_Component_Type => String_Access,
121     Table_Index_Type     => Integer,
122     Table_Low_Bound      => 1, -- equals low bound of Argument_List for Spawn
123     Table_Initial        => 20,
124     Table_Increment      => 100,
125     Table_Name           => "Gnatlink.Binder_Options_From_ALI");
126   --  This table collects the switches from the ALI file of the main
127   --  subprogram.
128
129   package Binder_Options is new Table.Table (
130     Table_Component_Type => String_Access,
131     Table_Index_Type     => Integer,
132     Table_Low_Bound      => 1, -- equals low bound of Argument_List for Spawn
133     Table_Initial        => 20,
134     Table_Increment      => 100,
135     Table_Name           => "Gnatlink.Binder_Options");
136   --  This table collects the arguments to be passed to compile the binder
137   --  generated file.
138
139   Gcc : String_Access := Program_Name ("gcc", "gnatlink");
140
141   Read_Mode : constant String := "r" & ASCII.NUL;
142
143   Begin_Info : constant String := "--  BEGIN Object file/option list";
144   End_Info   : constant String := "--  END Object file/option list   ";
145
146   Gcc_Path             : String_Access;
147   Linker_Path          : String_Access;
148   Output_File_Name     : String_Access;
149   Ali_File_Name        : String_Access;
150   Binder_Spec_Src_File : String_Access;
151   Binder_Body_Src_File : String_Access;
152   Binder_Ali_File      : String_Access;
153   Binder_Obj_File      : String_Access;
154
155   Base_Command_Name    : String_Access;
156
157   Target_Debuggable_Suffix : String_Access;
158
159   Tname    : Temp_File_Name;
160   Tname_FD : File_Descriptor := Invalid_FD;
161   --  Temporary file used by linker to pass list of object files on
162   --  certain systems with limitations on size of arguments.
163
164   Debug_Flag_Present : Boolean := False;
165   Verbose_Mode       : Boolean := False;
166   Very_Verbose_Mode  : Boolean := False;
167
168   Standard_Gcc : Boolean := True;
169
170   Compile_Bind_File : Boolean := True;
171   --  Set to False if bind file is not to be compiled
172
173   Create_Map_File : Boolean := False;
174   --  Set to True by switch -M. The map file name is derived from
175   --  the ALI file name (mainprog.ali => mainprog.map).
176
177   Object_List_File_Supported : Boolean;
178   for Object_List_File_Supported'Size use Character'Size;
179   pragma Import
180     (C, Object_List_File_Supported, "__gnat_objlist_file_supported");
181   --  Predicate indicating whether the linker has an option whereby the
182   --  names of object files can be passed to the linker in a file.
183
184   Object_File_Option_Ptr : Interfaces.C.Strings.chars_ptr;
185   pragma Import (C, Object_File_Option_Ptr, "__gnat_object_file_option");
186   --  Pointer to a string representing the linker option which specifies
187   --  the response file.
188
189   Object_File_Option : constant String := Value (Object_File_Option_Ptr);
190   --  The linker option which specifies the response file as a string
191
192   Using_GNU_response_file : constant Boolean :=
193     Object_File_Option'Length > 0
194       and then Object_File_Option (Object_File_Option'Last) = '@';
195   --  Whether a GNU response file is used
196
197   Object_List_File_Required : Boolean := False;
198   --  Set to True to force generation of a response file
199
200   Shared_Libgcc_Default : Character;
201   for Shared_Libgcc_Default'Size use Character'Size;
202   pragma Import
203     (C, Shared_Libgcc_Default, "__gnat_shared_libgcc_default");
204   --  Indicates wether libgcc should be statically linked (use 'T') or
205   --  dynamically linked (use 'H') by default.
206
207   function Base_Name (File_Name : String) return String;
208   --  Return just the file name part without the extension (if present)
209
210   procedure Check_Existing_Executable (File_Name : String);
211   --  Delete any existing executable to avoid accidentally updating the target
212   --  of a symbolic link, but produce a Fatail_Error if File_Name matches any
213   --  of the source file names. This avoids overwriting of extensionless
214   --  source files by accident on systems where executables do not have
215   --  extensions.
216
217   procedure Delete (Name : String);
218   --  Wrapper to unlink as status is ignored by this application
219
220   procedure Error_Msg (Message : String);
221   --  Output the error or warning Message
222
223   procedure Exit_With_Error (Error : String);
224   --  Output Error and exit program with a fatal condition
225
226   procedure Process_Args;
227   --  Go through all the arguments and build option tables
228
229   procedure Process_Binder_File (Name : String);
230   --  Reads the binder file and extracts linker arguments
231
232   procedure Usage;
233   --  Display usage
234
235   procedure Write_Header;
236   --  Show user the program name, version and copyright
237
238   procedure Write_Usage;
239   --  Show user the program options
240
241   ---------------
242   -- Base_Name --
243   ---------------
244
245   function Base_Name (File_Name : String) return String is
246      Findex1 : Natural;
247      Findex2 : Natural;
248
249   begin
250      Findex1 := File_Name'First;
251
252      --  The file might be specified by a full path name. However,
253      --  we want the path to be stripped away.
254
255      for J in reverse File_Name'Range loop
256         if Is_Directory_Separator (File_Name (J)) then
257            Findex1 := J + 1;
258            exit;
259         end if;
260      end loop;
261
262      Findex2 := File_Name'Last;
263      while Findex2 > Findex1 and then File_Name (Findex2) /=  '.' loop
264         Findex2 := Findex2 - 1;
265      end loop;
266
267      if Findex2 = Findex1 then
268         Findex2 := File_Name'Last + 1;
269      end if;
270
271      return File_Name (Findex1 .. Findex2 - 1);
272   end Base_Name;
273
274   -------------------------------
275   -- Check_Existing_Executable --
276   -------------------------------
277
278   procedure Check_Existing_Executable (File_Name : String) is
279      Ename : String := File_Name;
280      Efile : File_Name_Type;
281      Sfile : File_Name_Type;
282
283   begin
284      Canonical_Case_File_Name (Ename);
285      Name_Len := 0;
286      Add_Str_To_Name_Buffer (Ename);
287      Efile := Name_Find;
288
289      for J in Units.Table'First .. Units.Last loop
290         Sfile := Units.Table (J).Sfile;
291         if Sfile = Efile then
292            Exit_With_Error
293              ("executable name """ & File_Name & """ matches "
294               & "source file name """ & Get_Name_String (Sfile) & """");
295         end if;
296      end loop;
297
298      Delete (File_Name);
299   end Check_Existing_Executable;
300
301   ------------
302   -- Delete --
303   ------------
304
305   procedure Delete (Name : String) is
306      Status : int;
307      pragma Unreferenced (Status);
308   begin
309      Status := unlink (Name'Address);
310      --  Is it really right to ignore an error here ???
311   end Delete;
312
313   ---------------
314   -- Error_Msg --
315   ---------------
316
317   procedure Error_Msg (Message : String) is
318   begin
319      Write_Str (Base_Command_Name.all);
320      Write_Str (": ");
321      Write_Str (Message);
322      Write_Eol;
323   end Error_Msg;
324
325   ---------------------
326   -- Exit_With_Error --
327   ---------------------
328
329   procedure Exit_With_Error (Error : String) is
330   begin
331      Error_Msg (Error);
332      Exit_Program (E_Fatal);
333   end Exit_With_Error;
334
335   ------------------
336   -- Process_Args --
337   ------------------
338
339   procedure Process_Args is
340      Next_Arg : Integer;
341
342      Skip_Next : Boolean := False;
343      --  Set to true if the next argument is to be added into the list of
344      --  linker's argument without parsing it.
345
346      procedure Check_Version_And_Help is new Check_Version_And_Help_G (Usage);
347
348      --  Start of processing for Process_Args
349
350   begin
351      --  First, check for --version and --help
352
353      Check_Version_And_Help ("GNATLINK", "1996");
354
355      --  Loop through arguments of gnatlink command
356
357      Next_Arg := 1;
358      loop
359         exit when Next_Arg > Argument_Count;
360
361         Process_One_Arg : declare
362            Arg : constant String := Argument (Next_Arg);
363
364         begin
365            --  Case of argument which is a switch
366
367            --  We definitely need section by section comments here ???
368
369            if Skip_Next then
370
371               --  This argument must not be parsed, just add it to the
372               --  list of linker's options.
373
374               Skip_Next := False;
375
376               Linker_Options.Increment_Last;
377               Linker_Options.Table (Linker_Options.Last) :=
378                 new String'(Arg);
379
380            elsif Arg'Length /= 0 and then Arg (1) = '-' then
381               if Arg'Length > 4 and then Arg (2 .. 5) = "gnat" then
382                  Exit_With_Error
383                    ("invalid switch: """ & Arg & """ (gnat not needed here)");
384               end if;
385
386               if Arg = "-Xlinker" then
387
388                  --  Next argument should be sent directly to the linker.
389                  --  We do not want to parse it here.
390
391                  Skip_Next := True;
392
393                  Linker_Options.Increment_Last;
394                  Linker_Options.Table (Linker_Options.Last) :=
395                    new String'(Arg);
396
397               elsif Arg (2) = 'g'
398                 and then (Arg'Length < 5 or else Arg (2 .. 5) /= "gnat")
399               then
400                  Debug_Flag_Present := True;
401
402                  Linker_Options.Increment_Last;
403                  Linker_Options.Table (Linker_Options.Last) :=
404                   new String'(Arg);
405
406                  Binder_Options.Increment_Last;
407                  Binder_Options.Table (Binder_Options.Last) :=
408                    Linker_Options.Table (Linker_Options.Last);
409
410               elsif Arg'Length >= 3 and then Arg (2) = 'M' then
411                  declare
412                     Switches : String_List_Access;
413
414                  begin
415                     Convert (Map_File, Arg (3 .. Arg'Last), Switches);
416
417                     if Switches /= null then
418                        for J in Switches'Range loop
419                           Linker_Options.Increment_Last;
420                           Linker_Options.Table (Linker_Options.Last) :=
421                             Switches (J);
422                        end loop;
423                     end if;
424                  end;
425
426               elsif Arg'Length = 2 then
427                  case Arg (2) is
428                     when 'f' =>
429                        if Object_List_File_Supported then
430                           Object_List_File_Required := True;
431                        else
432                           Exit_With_Error
433                             ("Object list file not supported on this target");
434                        end if;
435
436                     when 'M' =>
437                        Create_Map_File := True;
438
439                     when 'n' =>
440                        Compile_Bind_File := False;
441
442                     when 'o' =>
443                        Next_Arg := Next_Arg + 1;
444
445                        if Next_Arg > Argument_Count then
446                           Exit_With_Error ("Missing argument for -o");
447                        end if;
448
449                        Output_File_Name :=
450                          new String'(Executable_Name
451                                        (Argument (Next_Arg),
452                                         Only_If_No_Suffix => True));
453
454                     when 'P' =>
455                        Opt.CodePeer_Mode := True;
456
457                     when 'R' =>
458                        Opt.Run_Path_Option := False;
459
460                     when 'v' =>
461
462                        --  Support "double" verbose mode.  Second -v
463                        --  gets sent to the linker and binder phases.
464
465                        if Verbose_Mode then
466                           Very_Verbose_Mode := True;
467
468                           Linker_Options.Increment_Last;
469                           Linker_Options.Table (Linker_Options.Last) :=
470                            new String'(Arg);
471
472                           Binder_Options.Increment_Last;
473                           Binder_Options.Table (Binder_Options.Last) :=
474                             Linker_Options.Table (Linker_Options.Last);
475
476                        else
477                           Verbose_Mode := True;
478
479                        end if;
480
481                     when others =>
482                        Linker_Options.Increment_Last;
483                        Linker_Options.Table (Linker_Options.Last) :=
484                         new String'(Arg);
485
486                  end case;
487
488               elsif Arg (2) = 'B' then
489                  Linker_Options.Increment_Last;
490                  Linker_Options.Table (Linker_Options.Last) :=
491                    new String'(Arg);
492
493                  Binder_Options.Increment_Last;
494                  Binder_Options.Table (Binder_Options.Last) :=
495                    Linker_Options.Table (Linker_Options.Last);
496
497               elsif Arg'Length >= 7 and then Arg (1 .. 7) = "--LINK=" then
498                  if Arg'Length = 7 then
499                     Exit_With_Error ("Missing argument for --LINK=");
500                  end if;
501
502                  declare
503                     L_Args : constant Argument_List_Access :=
504                               Argument_String_To_List (Arg (8 .. Arg'Last));
505                  begin
506                     --  The linker program is the first argument
507
508                     Linker_Path :=
509                      System.OS_Lib.Locate_Exec_On_Path (L_Args.all (1).all);
510
511                     if Linker_Path = null then
512                        Exit_With_Error
513                          ("Could not locate linker: " & L_Args.all (1).all);
514                     end if;
515
516                     --  The other arguments are passed as-is to the linker
517                     --  and override those coming from --GCC= if any.
518
519                     if L_Args.all'Last >= 2 then
520                        Gcc_Linker_Options.Set_Last (0);
521                     end if;
522
523                     for J in 2 .. L_Args.all'Last loop
524                        Gcc_Linker_Options.Increment_Last;
525                        Gcc_Linker_Options.Table
526                          (Gcc_Linker_Options.Last) :=
527                                             new String'(L_Args.all (J).all);
528                     end loop;
529                  end;
530
531               elsif Arg'Length >= 6 and then Arg (1 .. 6) = "--GCC=" then
532                  if Arg'Length = 6 then
533                     Exit_With_Error ("Missing argument for --GCC=");
534                  end if;
535
536                  declare
537                     Program_Args : constant Argument_List_Access :=
538                                      Argument_String_To_List
539                                                 (Arg (7 .. Arg'Last));
540
541                  begin
542                     if Program_Args.all (1).all /= Gcc.all then
543                        Gcc := new String'(Program_Args.all (1).all);
544                        Standard_Gcc := False;
545                     end if;
546
547                     --  Set appropriate flags for switches passed
548
549                     for J in 2 .. Program_Args.all'Last loop
550                        declare
551                           Arg : constant String := Program_Args.all (J).all;
552                           AF  : constant Integer := Arg'First;
553
554                        begin
555                           if Arg'Length /= 0 and then Arg (AF) = '-' then
556                              if Arg (AF + 1) = 'g'
557                                and then (Arg'Length = 2
558                                  or else Arg (AF + 2) in '0' .. '3'
559                                  or else Arg (AF + 2 .. Arg'Last) = "coff")
560                              then
561                                 Debug_Flag_Present := True;
562                              end if;
563                           end if;
564
565                           --  Add directory to source search dirs so that
566                           --  Get_Target_Parameters can find system.ads
567
568                           if Arg (AF .. AF + 1) = "-I"
569                             and then Arg'Length > 2
570                           then
571                              Add_Src_Search_Dir (Arg (AF + 2 .. Arg'Last));
572                           end if;
573
574                           --  Pass to gcc for compiling binder generated file
575                           --  No use passing libraries, it will just generate
576                           --  a warning
577
578                           if not (Arg (AF .. AF + 1) = "-l"
579                             or else Arg (AF .. AF + 1) = "-L")
580                           then
581                              Binder_Options.Increment_Last;
582                              Binder_Options.Table (Binder_Options.Last) :=
583                                new String'(Arg);
584                           end if;
585
586                           --  Pass to gcc for linking program
587
588                           Gcc_Linker_Options.Increment_Last;
589                           Gcc_Linker_Options.Table
590                             (Gcc_Linker_Options.Last) := new String'(Arg);
591                        end;
592                     end loop;
593                  end;
594
595               --  Send all multi-character switches not recognized as
596               --  a special case by gnatlink to the linker/loader stage.
597
598               else
599                  Linker_Options.Increment_Last;
600                  Linker_Options.Table (Linker_Options.Last) :=
601                    new String'(Arg);
602               end if;
603
604            --  Here if argument is a file name rather than a switch
605
606            else
607               --  If explicit ali file, capture it
608
609               if Arg'Length > 4
610                 and then Arg (Arg'Last - 3 .. Arg'Last) = ".ali"
611               then
612                  if Ali_File_Name = null then
613                     Ali_File_Name := new String'(Arg);
614                  else
615                     Exit_With_Error ("cannot handle more than one ALI file");
616                  end if;
617
618               --  If target object file, record object file
619
620               elsif Arg'Length > Get_Target_Object_Suffix.all'Length
621                 and then Arg
622                   (Arg'Last -
623                    Get_Target_Object_Suffix.all'Length + 1 .. Arg'Last)
624                   = Get_Target_Object_Suffix.all
625               then
626                  Linker_Objects.Increment_Last;
627                  Linker_Objects.Table (Linker_Objects.Last) :=
628                    new String'(Arg);
629
630               --  If host object file, record object file
631
632               elsif Arg'Length > Get_Object_Suffix.all'Length
633                 and then Arg
634                   (Arg'Last - Get_Object_Suffix.all'Length + 1 .. Arg'Last)
635                                                = Get_Object_Suffix.all
636               then
637                  Linker_Objects.Increment_Last;
638                  Linker_Objects.Table (Linker_Objects.Last) :=
639                    new String'(Arg);
640
641               --  If corresponding ali file exists, capture it
642
643               elsif Ali_File_Name = null
644                 and then Is_Regular_File (Arg & ".ali")
645               then
646                  Ali_File_Name := new String'(Arg & ".ali");
647
648               --  Otherwise assume this is a linker options entry, but
649               --  see below for interesting adjustment to this assumption.
650
651               else
652                  Linker_Options.Increment_Last;
653                  Linker_Options.Table (Linker_Options.Last) :=
654                    new String'(Arg);
655               end if;
656            end if;
657         end Process_One_Arg;
658
659         Next_Arg := Next_Arg + 1;
660      end loop;
661
662      --  Compile the bind file with warnings suppressed, because
663      --  otherwise the with of the main program may cause junk warnings.
664
665      Binder_Options.Increment_Last;
666      Binder_Options.Table (Binder_Options.Last) := new String'("-gnatws");
667
668      --  If we did not get an ali file at all, and we had at least one
669      --  linker option, then assume that was the intended ali file after
670      --  all, so that we get a nicer message later on.
671
672      if Ali_File_Name = null
673        and then Linker_Options.Last >= Linker_Options.First
674      then
675         Ali_File_Name :=
676           new String'(Linker_Options.Table (Linker_Options.First).all
677                       & ".ali");
678      end if;
679   end Process_Args;
680
681   -------------------------
682   -- Process_Binder_File --
683   -------------------------
684
685   procedure Process_Binder_File (Name : String) is
686      Fd : FILEs;
687      --  Binder file's descriptor
688
689      Link_Bytes : Integer := 0;
690      --  Projected number of bytes for the linker command line
691
692      Link_Max : Integer;
693      pragma Import (C, Link_Max, "__gnat_link_max");
694      --  Maximum number of bytes on the command line supported by the OS
695      --  linker. Passed this limit the response file mechanism must be used
696      --  if supported.
697
698      Next_Line : String (1 .. 1000);
699      --  Current line value
700
701      Nlast  : Integer;
702      Nfirst : Integer;
703      --  Current line slice (the slice does not contain line terminator)
704
705      Last : Integer;
706      --  Current line last character for shared libraries (without version)
707
708      Objs_Begin : Integer := 0;
709      --  First object file index in Linker_Objects table
710
711      Objs_End : Integer := 0;
712      --  Last object file index in Linker_Objects table
713
714      Status : int;
715      pragma Warnings (Off, Status);
716      --  Used for various Interfaces.C_Streams calls
717
718      Closing_Status : Boolean;
719      pragma Warnings (Off, Closing_Status);
720      --  For call to Close
721
722      GNAT_Static : Boolean := False;
723      --  Save state of -static option
724
725      GNAT_Shared : Boolean := False;
726      --  Save state of -shared option
727
728      Xlinker_Was_Previous : Boolean := False;
729      --  Indicate that "-Xlinker" was the option preceding the current option.
730      --  If True, then the current option is never suppressed.
731
732      --  Rollback data
733
734      --  These data items are used to store current binder file context. The
735      --  context is composed of the file descriptor position and the current
736      --  line together with the slice indexes (first and last position) for
737      --  this line. The rollback data are used by the Store_File_Context and
738      --  Rollback_File_Context routines below. The file context mechanism
739      --  interact only with the Get_Next_Line call. For example:
740
741      --     Store_File_Context;
742      --     Get_Next_Line;
743      --     Rollback_File_Context;
744      --     Get_Next_Line;
745
746      --  Both Get_Next_Line calls above will read the exact same data from
747      --  the file. In other words, Next_Line, Nfirst and Nlast variables
748      --  will be set with the exact same values.
749
750      RB_File_Pos  : long;                -- File position
751      RB_Next_Line : String (1 .. 1000);  -- Current line content
752      RB_Nlast     : Integer;             -- Slice last index
753      RB_Nfirst    : Integer;             -- Slice first index
754
755      Run_Path_Option_Ptr : Interfaces.C.Strings.chars_ptr;
756      pragma Import (C, Run_Path_Option_Ptr, "__gnat_run_path_option");
757      --  Pointer to string representing the native linker option which
758      --  specifies the path where the dynamic loader should find shared
759      --  libraries. Equal to null string if this system doesn't support it.
760
761      Libgcc_Subdir_Ptr : Interfaces.C.Strings.chars_ptr;
762      pragma Import (C, Libgcc_Subdir_Ptr, "__gnat_default_libgcc_subdir");
763      --  Pointer to string indicating the installation subdirectory where
764      --  a default shared libgcc might be found.
765
766      Object_Library_Ext_Ptr : Interfaces.C.Strings.chars_ptr;
767      pragma Import
768        (C, Object_Library_Ext_Ptr, "__gnat_object_library_extension");
769      --  Pointer to string specifying the default extension for
770      --  object libraries, e.g. Unix uses ".a".
771
772      Separate_Run_Path_Options : Boolean;
773      for Separate_Run_Path_Options'Size use Character'Size;
774      pragma Import
775        (C, Separate_Run_Path_Options, "__gnat_separate_run_path_options");
776      --  Whether separate rpath options should be emitted for each directory
777
778      procedure Get_Next_Line;
779      --  Read the next line from the binder file without the line
780      --  terminator.
781
782      function Index (S, Pattern : String) return Natural;
783      --  Return the last occurrence of Pattern in S, or 0 if none
784
785      procedure Store_File_Context;
786      --  Store current file context, Fd position and current line data.
787      --  The file context is stored into the rollback data above (RB_*).
788      --  Store_File_Context can be called at any time, only the last call
789      --  will be used (i.e. this routine overwrites the file context).
790
791      procedure Rollback_File_Context;
792      --  Restore file context from rollback data. This routine must be called
793      --  after Store_File_Context. The binder file context will be restored
794      --  with the data stored by the last Store_File_Context call.
795
796      procedure Write_RF (S : String);
797      --  Write a string to the response file and check if it was successful.
798      --  Fail the program if it was not successful (disk full).
799
800      -------------------
801      -- Get_Next_Line --
802      -------------------
803
804      procedure Get_Next_Line is
805         Fchars : chars;
806
807      begin
808         Fchars := fgets (Next_Line'Address, Next_Line'Length, Fd);
809
810         if Fchars = System.Null_Address then
811            Exit_With_Error ("Error reading binder output");
812         end if;
813
814         Nfirst := Next_Line'First;
815         Nlast := Nfirst;
816         while Nlast <= Next_Line'Last
817           and then Next_Line (Nlast) /= ASCII.LF
818           and then Next_Line (Nlast) /= ASCII.CR
819         loop
820            Nlast := Nlast + 1;
821         end loop;
822
823         Nlast := Nlast - 1;
824      end Get_Next_Line;
825
826      -----------
827      -- Index --
828      -----------
829
830      function Index (S, Pattern : String) return Natural is
831         Len : constant Natural := Pattern'Length;
832
833      begin
834         for J in reverse S'First .. S'Last - Len + 1 loop
835            if Pattern = S (J .. J + Len - 1) then
836               return J;
837            end if;
838         end loop;
839
840         return 0;
841      end Index;
842
843      ---------------------------
844      -- Rollback_File_Context --
845      ---------------------------
846
847      procedure Rollback_File_Context is
848      begin
849         Next_Line := RB_Next_Line;
850         Nfirst    := RB_Nfirst;
851         Nlast     := RB_Nlast;
852         Status    := fseek (Fd, RB_File_Pos, Interfaces.C_Streams.SEEK_SET);
853
854         if Status = -1 then
855            Exit_With_Error ("Error setting file position");
856         end if;
857      end Rollback_File_Context;
858
859      ------------------------
860      -- Store_File_Context --
861      ------------------------
862
863      procedure Store_File_Context is
864         use type System.CRTL.long;
865
866      begin
867         RB_Next_Line := Next_Line;
868         RB_Nfirst    := Nfirst;
869         RB_Nlast     := Nlast;
870         RB_File_Pos  := ftell (Fd);
871
872         if RB_File_Pos = -1 then
873            Exit_With_Error ("Error getting file position");
874         end if;
875      end Store_File_Context;
876
877      --------------
878      -- Write_RF --
879      --------------
880
881      procedure Write_RF (S : String) is
882         Success    : Boolean            := True;
883         Back_Slash : constant Character := '\';
884
885      begin
886         --  If a GNU response file is used, space and backslash need to be
887         --  escaped because they are interpreted as a string separator and
888         --  an escape character respectively by the underlying mechanism.
889         --  On the other hand, quote and double-quote are not escaped since
890         --  they are interpreted as string delimiters on both sides.
891
892         if Using_GNU_response_file then
893            for J in S'Range loop
894               if S (J) = ' ' or else S (J) = '\' then
895                  if Write (Tname_FD, Back_Slash'Address, 1) /= 1 then
896                     Success := False;
897                  end if;
898               end if;
899
900               if Write (Tname_FD, S (J)'Address, 1) /= 1 then
901                  Success := False;
902               end if;
903            end loop;
904
905         else
906            if Write (Tname_FD, S'Address, S'Length) /= S'Length then
907               Success := False;
908            end if;
909         end if;
910
911         if Write (Tname_FD, ASCII.LF'Address, 1) /= 1 then
912            Success := False;
913         end if;
914
915         if not Success then
916            Exit_With_Error ("Error generating response file: disk full");
917         end if;
918      end Write_RF;
919
920   --  Start of processing for Process_Binder_File
921
922   begin
923      Fd := fopen (Name'Address, Read_Mode'Address);
924
925      if Fd = NULL_Stream then
926         Exit_With_Error ("Failed to open binder output");
927      end if;
928
929      --  Skip up to the Begin Info line
930
931      loop
932         Get_Next_Line;
933         exit when Next_Line (Nfirst .. Nlast) = Begin_Info;
934      end loop;
935
936      loop
937         Get_Next_Line;
938
939         --  Go to end when end line is reached (this will happen in
940         --  High_Integrity_Mode where no -L switches are generated)
941
942         exit when Next_Line (Nfirst .. Nlast) = End_Info;
943
944         Next_Line (Nfirst .. Nlast - 8) := Next_Line (Nfirst + 8 .. Nlast);
945         Nlast := Nlast - 8;
946
947         --  Go to next section when switches are reached
948
949         exit when Next_Line (1) = '-';
950
951         --  Otherwise we have another object file to collect
952
953         Linker_Objects.Increment_Last;
954
955         --  Mark the positions of first and last object files in case they
956         --  need to be placed with a named file on systems having linker
957         --  line limitations.
958
959         if Objs_Begin = 0 then
960            Objs_Begin := Linker_Objects.Last;
961         end if;
962
963         Linker_Objects.Table (Linker_Objects.Last) :=
964           new String'(Next_Line (Nfirst .. Nlast));
965
966         --  Nlast - Nfirst + 1, for the size, plus one for the space between
967         --  each arguments.
968
969         Link_Bytes := Link_Bytes + Nlast - Nfirst + 2;
970      end loop;
971
972      Objs_End := Linker_Objects.Last;
973
974      --  Continue to compute the Link_Bytes, the linker options are part of
975      --  command line length.
976
977      Store_File_Context;
978
979      while Next_Line (Nfirst .. Nlast) /= End_Info loop
980         Link_Bytes := Link_Bytes + Nlast - Nfirst + 2;
981         Get_Next_Line;
982      end loop;
983
984      Rollback_File_Context;
985
986      --  On systems that have limitations on handling very long linker lines
987      --  we make use of the system linker option which takes a list of object
988      --  file names from a file instead of the command line itself. What we do
989      --  is to replace the list of object files by the special linker option
990      --  which then reads the object file list from a file instead. The option
991      --  to read from a file instead of the command line is only triggered if
992      --  a conservative threshold is passed.
993
994      if Object_List_File_Required
995        or else (Object_List_File_Supported
996                   and then Link_Bytes > Link_Max)
997      then
998         --  Create a temporary file containing the Ada user object files
999         --  needed by the link. This list is taken from the bind file and is
1000         --  output one object per line for maximal compatibility with linkers
1001         --  supporting this option.
1002
1003         Create_Temp_File (Tname_FD, Tname);
1004
1005         --  ??? File descriptor should be checked to not be Invalid_FD.
1006         --  ??? Status of Write and Close operations should be checked, and
1007         --  failure should occur if a status is wrong.
1008
1009         for J in Objs_Begin .. Objs_End loop
1010            Write_RF (Linker_Objects.Table (J).all);
1011
1012            Response_File_Objects.Increment_Last;
1013            Response_File_Objects.Table (Response_File_Objects.Last) :=
1014              Linker_Objects.Table (J);
1015         end loop;
1016
1017         Close (Tname_FD, Closing_Status);
1018
1019         --  Add the special objects list file option together with the name
1020         --  of the temporary file (removing the null character) to the objects
1021         --  file table.
1022
1023         Linker_Objects.Table (Objs_Begin) :=
1024           new String'(Object_File_Option &
1025                       Tname (Tname'First .. Tname'Last - 1));
1026
1027         --  The slots containing these object file names are then removed
1028         --  from the objects table so they do not appear in the link. They are
1029         --  removed by moving up the linker options and non-Ada object files
1030         --  appearing after the Ada object list in the table.
1031
1032         declare
1033            N : Integer;
1034
1035         begin
1036            N := Objs_End - Objs_Begin + 1;
1037
1038            for J in Objs_End + 1 .. Linker_Objects.Last loop
1039               Linker_Objects.Table (J - N + 1) := Linker_Objects.Table (J);
1040            end loop;
1041
1042            Linker_Objects.Set_Last (Linker_Objects.Last - N + 1);
1043         end;
1044      end if;
1045
1046      --  Process switches and options
1047
1048      if Next_Line (Nfirst .. Nlast) /= End_Info then
1049         Xlinker_Was_Previous := False;
1050
1051         loop
1052            if Xlinker_Was_Previous
1053              or else Next_Line (Nfirst .. Nlast) = "-Xlinker"
1054            then
1055               Linker_Options.Increment_Last;
1056               Linker_Options.Table (Linker_Options.Last) :=
1057                 new String'(Next_Line (Nfirst .. Nlast));
1058
1059            elsif Next_Line (Nfirst .. Nlast) = "-static" then
1060               GNAT_Static := True;
1061
1062            elsif Next_Line (Nfirst .. Nlast) = "-shared" then
1063               GNAT_Shared := True;
1064
1065            --  Add binder options only if not already set on the command line.
1066            --  This rule is a way to control the linker options order.
1067
1068            else
1069               if Nlast > Nfirst + 2 and then
1070                 Next_Line (Nfirst .. Nfirst + 1) = "-L"
1071               then
1072                  --  Construct a library search path for use later to locate
1073                  --  static gnatlib libraries.
1074
1075                  if Libpath.Last > 1 then
1076                     Libpath.Increment_Last;
1077                     Libpath.Table (Libpath.Last) := Path_Separator;
1078                  end if;
1079
1080                  for I in Nfirst + 2 .. Nlast loop
1081                     Libpath.Increment_Last;
1082                     Libpath.Table (Libpath.Last) := Next_Line (I);
1083                  end loop;
1084
1085                  Linker_Options.Increment_Last;
1086
1087                  Linker_Options.Table (Linker_Options.Last) :=
1088                    new String'(Next_Line (Nfirst .. Nlast));
1089
1090               elsif Next_Line (Nfirst .. Nlast) = "-lgnarl"
1091                 or else Next_Line (Nfirst .. Nlast) = "-lgnat"
1092                 or else
1093                   Next_Line
1094                     (1 .. Natural'Min (Nlast, 8 + Library_Version'Length)) =
1095                       Shared_Lib ("gnarl")
1096                 or else
1097                   Next_Line
1098                     (1 .. Natural'Min (Nlast, 7 + Library_Version'Length)) =
1099                       Shared_Lib ("gnat")
1100               then
1101                  --  If it is a shared library, remove the library version.
1102                  --  We will be looking for the static version of the library
1103                  --  as it is in the same directory as the shared version.
1104
1105                  if Next_Line (Nlast - Library_Version'Length + 1 .. Nlast) =
1106                       Library_Version
1107                  then
1108                     --  Set Last to point to last character before the
1109                     --  library version.
1110
1111                     Last := Nlast - Library_Version'Length - 1;
1112                  else
1113                     Last := Nlast;
1114                  end if;
1115
1116                  --  Given a Gnat standard library, search the library path to
1117                  --  find the library location.
1118
1119                  --  Shouldn't we abstract a proc here, we are getting awfully
1120                  --  heavily nested ???
1121
1122                  declare
1123                     File_Path : String_Access;
1124
1125                     Object_Lib_Extension : constant String :=
1126                       Value (Object_Library_Ext_Ptr);
1127
1128                     File_Name : constant String := "lib" &
1129                       Next_Line (Nfirst + 2 .. Last) & Object_Lib_Extension;
1130
1131                     Run_Path_Opt : constant String :=
1132                       Value (Run_Path_Option_Ptr);
1133
1134                     GCC_Index          : Natural;
1135                     Run_Path_Opt_Index : Natural := 0;
1136
1137                  begin
1138                     File_Path :=
1139                       Locate_Regular_File (File_Name,
1140                         String (Libpath.Table (1 .. Libpath.Last)));
1141
1142                     if File_Path /= null then
1143                        if GNAT_Static then
1144
1145                           --  If static gnatlib found, explicitly specify to
1146                           --  overcome possible linker default usage of shared
1147                           --  version.
1148
1149                           Linker_Options.Increment_Last;
1150
1151                           Linker_Options.Table (Linker_Options.Last) :=
1152                             new String'(File_Path.all);
1153
1154                        elsif GNAT_Shared then
1155                           if Opt.Run_Path_Option then
1156
1157                              --  If shared gnatlib desired, add appropriate
1158                              --  system specific switch so that it can be
1159                              --  located at runtime.
1160
1161                              if Run_Path_Opt'Length /= 0 then
1162
1163                                 --  Output the system specific linker command
1164                                 --  that allows the image activator to find
1165                                 --  the shared library at runtime. Also add
1166                                 --  path to find libgcc_s.so, if relevant.
1167
1168                                 declare
1169                                    Path : String (1 .. File_Path'Length + 15);
1170
1171                                    Path_Last : constant Natural :=
1172                                                  File_Path'Length;
1173
1174                                 begin
1175                                    Path (1 .. File_Path'Length) :=
1176                                      File_Path.all;
1177
1178                                 --  To find the location of the shared version
1179                                 --  of libgcc, we look for "gcc-lib" in the
1180                                 --  path of the library. However, this
1181                                 --  subdirectory is no longer present in
1182                                 --  recent versions of GCC. So, we look for
1183                                 --  the last subdirectory "lib" in the path.
1184
1185                                    GCC_Index :=
1186                                      Index (Path (1 .. Path_Last), "gcc-lib");
1187
1188                                    if GCC_Index /= 0 then
1189
1190                                       --  The shared version of libgcc is
1191                                       --  located in the parent directory.
1192
1193                                       GCC_Index := GCC_Index - 1;
1194
1195                                    else
1196                                       GCC_Index :=
1197                                         Index
1198                                           (Path (1 .. Path_Last),
1199                                            "/lib/");
1200
1201                                       if GCC_Index = 0 then
1202                                          GCC_Index :=
1203                                            Index (Path (1 .. Path_Last),
1204                                                   Directory_Separator & "lib"
1205                                                   & Directory_Separator);
1206                                       end if;
1207
1208                                       --  If we have found a "lib" subdir in
1209                                       --  the path to libgnat, the possible
1210                                       --  shared libgcc of interest by default
1211                                       --  is in libgcc_subdir at the same
1212                                       --  level.
1213
1214                                       if GCC_Index /= 0 then
1215                                          declare
1216                                             Subdir : constant String :=
1217                                               Value (Libgcc_Subdir_Ptr);
1218                                          begin
1219                                             Path
1220                                               (GCC_Index + 1 ..
1221                                                GCC_Index + Subdir'Length) :=
1222                                               Subdir;
1223                                             GCC_Index :=
1224                                               GCC_Index + Subdir'Length;
1225                                          end;
1226                                       end if;
1227                                    end if;
1228
1229                                 --  Look for an eventual run_path_option in
1230                                 --  the linker switches.
1231
1232                                    if Separate_Run_Path_Options then
1233                                       Linker_Options.Increment_Last;
1234                                       Linker_Options.Table
1235                                         (Linker_Options.Last) :=
1236                                           new String'
1237                                             (Run_Path_Opt
1238                                              & File_Path
1239                                                (1 .. File_Path'Length
1240                                                 - File_Name'Length));
1241
1242                                       if GCC_Index /= 0 then
1243                                          Linker_Options.Increment_Last;
1244                                          Linker_Options.Table
1245                                            (Linker_Options.Last) :=
1246                                            new String'
1247                                              (Run_Path_Opt
1248                                               & Path (1 .. GCC_Index));
1249                                       end if;
1250
1251                                    else
1252                                       for J in reverse
1253                                         1 .. Linker_Options.Last
1254                                       loop
1255                                          if Linker_Options.Table (J) /= null
1256                                            and then
1257                                              Linker_Options.Table (J)'Length
1258                                                        > Run_Path_Opt'Length
1259                                            and then
1260                                              Linker_Options.Table (J)
1261                                                (1 .. Run_Path_Opt'Length) =
1262                                                                 Run_Path_Opt
1263                                          then
1264                                             --  We have found an already
1265                                             --  specified run_path_option:
1266                                             --  we will add to this
1267                                             --  switch, because only one
1268                                             --  run_path_option should be
1269                                             --  specified.
1270
1271                                             Run_Path_Opt_Index := J;
1272                                             exit;
1273                                          end if;
1274                                       end loop;
1275
1276                                       --  If there is no run_path_option, we
1277                                       --  need to add one.
1278
1279                                       if Run_Path_Opt_Index = 0 then
1280                                          Linker_Options.Increment_Last;
1281                                       end if;
1282
1283                                       if GCC_Index = 0 then
1284                                          if Run_Path_Opt_Index = 0 then
1285                                             Linker_Options.Table
1286                                               (Linker_Options.Last) :=
1287                                                 new String'
1288                                                   (Run_Path_Opt
1289                                                    & File_Path
1290                                                      (1 .. File_Path'Length
1291                                                       - File_Name'Length));
1292
1293                                          else
1294                                             Linker_Options.Table
1295                                               (Run_Path_Opt_Index) :=
1296                                                 new String'
1297                                                   (Linker_Options.Table
1298                                                     (Run_Path_Opt_Index).all
1299                                                    & Path_Separator
1300                                                    & File_Path
1301                                                      (1 .. File_Path'Length
1302                                                       - File_Name'Length));
1303                                          end if;
1304
1305                                       else
1306                                          if Run_Path_Opt_Index = 0 then
1307                                             Linker_Options.Table
1308                                               (Linker_Options.Last) :=
1309                                                 new String'
1310                                                   (Run_Path_Opt
1311                                                    & File_Path
1312                                                      (1 .. File_Path'Length
1313                                                       - File_Name'Length)
1314                                                    & Path_Separator
1315                                                    & Path (1 .. GCC_Index));
1316
1317                                          else
1318                                             Linker_Options.Table
1319                                               (Run_Path_Opt_Index) :=
1320                                                 new String'
1321                                                   (Linker_Options.Table
1322                                                     (Run_Path_Opt_Index).all
1323                                                    & Path_Separator
1324                                                    & File_Path
1325                                                      (1 .. File_Path'Length
1326                                                       - File_Name'Length)
1327                                                    & Path_Separator
1328                                                    & Path (1 .. GCC_Index));
1329                                          end if;
1330                                       end if;
1331                                    end if;
1332                                 end;
1333                              end if;
1334                           end if;
1335
1336                           --  Then we add the appropriate -l switch
1337
1338                           Linker_Options.Increment_Last;
1339                           Linker_Options.Table (Linker_Options.Last) :=
1340                             new String'(Next_Line (Nfirst .. Nlast));
1341                        end if;
1342
1343                     else
1344                        --  If gnatlib library not found, then add it anyway in
1345                        --  case some other mechanism may find it.
1346
1347                        Linker_Options.Increment_Last;
1348                        Linker_Options.Table (Linker_Options.Last) :=
1349                          new String'(Next_Line (Nfirst .. Nlast));
1350                     end if;
1351                  end;
1352               else
1353                  Linker_Options.Increment_Last;
1354                  Linker_Options.Table (Linker_Options.Last) :=
1355                    new String'(Next_Line (Nfirst .. Nlast));
1356               end if;
1357            end if;
1358
1359            Xlinker_Was_Previous := Next_Line (Nfirst .. Nlast) = "-Xlinker";
1360
1361            Get_Next_Line;
1362            exit when Next_Line (Nfirst .. Nlast) = End_Info;
1363
1364            Next_Line (Nfirst .. Nlast - 8) := Next_Line (Nfirst + 8 .. Nlast);
1365            Nlast := Nlast - 8;
1366         end loop;
1367      end if;
1368
1369      --  If -shared was specified, invoke gcc with -shared-libgcc
1370
1371      if GNAT_Shared then
1372         Linker_Options.Increment_Last;
1373         Linker_Options.Table (Linker_Options.Last) := Shared_Libgcc;
1374      end if;
1375
1376      Status := fclose (Fd);
1377   end Process_Binder_File;
1378
1379   -----------
1380   -- Usage --
1381   -----------
1382
1383   procedure Usage is
1384   begin
1385      Write_Str ("Usage: ");
1386      Write_Str (Base_Command_Name.all);
1387      Write_Str (" switches mainprog.ali [non-Ada-objects] [linker-options]");
1388      Write_Eol;
1389      Write_Eol;
1390      Write_Line ("  mainprog.ali   the ALI file of the main program");
1391      Write_Eol;
1392      Write_Eol;
1393      Display_Usage_Version_And_Help;
1394      Write_Line ("  -f    Force object file list to be generated");
1395      Write_Line ("  -g    Compile binder source file with debug information");
1396      Write_Line ("  -n    Do not compile the binder source file");
1397      Write_Line ("  -P    Process files for use by CodePeer");
1398      Write_Line ("  -R    Do not use a run_path_option");
1399      Write_Line ("  -v    Verbose mode");
1400      Write_Line ("  -v -v Very verbose mode");
1401      Write_Eol;
1402      Write_Line ("  -o nam     Use 'nam' as the name of the executable");
1403      Write_Line ("  -Bdir      Load compiler executables from dir");
1404
1405      if Is_Supported (Map_File) then
1406         Write_Line ("  -Mmap      Create map file map");
1407         Write_Line ("  -M         Create map file mainprog.map");
1408      end if;
1409
1410      Write_Line ("  --GCC=comp Use 'comp' as the compiler rather than 'gcc'");
1411      Write_Line ("  --LINK=lnk Use 'lnk' as the linker rather than 'gcc'");
1412      Write_Eol;
1413      Write_Line ("  [non-Ada-objects]  list of non Ada object files");
1414      Write_Line ("  [linker-options]   other options for the linker");
1415   end Usage;
1416
1417   ------------------
1418   -- Write_Header --
1419   ------------------
1420
1421   procedure Write_Header is
1422   begin
1423      if Verbose_Mode then
1424         Write_Eol;
1425         Display_Version ("GNATLINK", "1995");
1426      end if;
1427   end Write_Header;
1428
1429   -----------------
1430   -- Write_Usage --
1431   -----------------
1432
1433   procedure Write_Usage is
1434   begin
1435      Write_Header;
1436      Usage;
1437   end Write_Usage;
1438
1439--  Start of processing for Gnatlink
1440
1441begin
1442   --  Add the directory where gnatlink is invoked in front of the path, if
1443   --  gnatlink is invoked with directory information.
1444
1445   declare
1446      Command : constant String := Command_Name;
1447   begin
1448      for Index in reverse Command'Range loop
1449         if Command (Index) = Directory_Separator then
1450            declare
1451               Absolute_Dir : constant String :=
1452                 Normalize_Pathname
1453                   (Command (Command'First .. Index));
1454
1455               PATH : constant String :=
1456                 Absolute_Dir &
1457                 Path_Separator &
1458                 Getenv ("PATH").all;
1459
1460            begin
1461               Setenv ("PATH", PATH);
1462            end;
1463
1464            exit;
1465         end if;
1466      end loop;
1467   end;
1468
1469   Base_Command_Name := new String'(Base_Name (Command_Name));
1470   Process_Args;
1471
1472   if Argument_Count = 0
1473     or else (Verbose_Mode and then Argument_Count = 1)
1474   then
1475      Write_Usage;
1476      Exit_Program (E_Fatal);
1477   end if;
1478
1479   --  Initialize packages to be used
1480
1481   Csets.Initialize;
1482   Snames.Initialize;
1483
1484   --  We always compile with -c
1485
1486   Binder_Options_From_ALI.Increment_Last;
1487   Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1488     new String'("-c");
1489
1490   if Ali_File_Name = null then
1491      Exit_With_Error ("no ali file given for link");
1492   end if;
1493
1494   if not Is_Regular_File (Ali_File_Name.all) then
1495      Exit_With_Error (Ali_File_Name.all & " not found");
1496   end if;
1497
1498   --  Read the ALI file of the main subprogram if the binder generated file
1499   --  needs to be compiled and no --GCC= switch has been specified. Fetch the
1500   --  back end switches from this ALI file and use these switches to compile
1501   --  the binder generated file
1502
1503   if Compile_Bind_File and then Standard_Gcc then
1504      Initialize_ALI;
1505      Name_Len := Ali_File_Name'Length;
1506      Name_Buffer (1 .. Name_Len) := Ali_File_Name.all;
1507
1508      declare
1509         use Types;
1510         F : constant File_Name_Type := Name_Find;
1511         T : Text_Buffer_Ptr;
1512         A : ALI_Id;
1513
1514      begin
1515         --  Load the ALI file
1516
1517         T := Read_Library_Info (F, True);
1518
1519         --  Read it. Note that we ignore errors, since we only want very
1520         --  limited information from the ali file, and likely a slightly
1521         --  wrong version will be just fine, though in normal operation
1522         --  we don't expect this to happen.
1523
1524         A := Scan_ALI
1525               (F,
1526                T,
1527                Ignore_ED     => False,
1528                Err           => False,
1529                Ignore_Errors => True);
1530
1531         if A /= No_ALI_Id then
1532            for
1533              Index in Units.Table (ALIs.Table (A).First_Unit).First_Arg ..
1534                       Units.Table (ALIs.Table (A).First_Unit).Last_Arg
1535            loop
1536               --  Do not compile with the front end switches. However, --RTS
1537               --  is to be dealt with specially because it needs to be passed
1538               --  to compile the file generated by the binder.
1539
1540               declare
1541                  Arg : String_Ptr renames Args.Table (Index);
1542               begin
1543                  if not Is_Front_End_Switch (Arg.all) then
1544                     Binder_Options_From_ALI.Increment_Last;
1545                     Binder_Options_From_ALI.Table
1546                       (Binder_Options_From_ALI.Last) := String_Access (Arg);
1547
1548                     --  GNAT doesn't support GCC's multilib mechanism when it
1549                     --  is configured with --disable-libada. This means that,
1550                     --  when a multilib switch is used to request a particular
1551                     --  compilation mode, the corresponding --RTS switch must
1552                     --  also be specified. It is convenient to eliminate the
1553                     --  redundancy by keying the compilation mode on a single
1554                     --  switch, namely --RTS, and have the compiler reinstate
1555                     --  the multilib switch (see gcc-interface/lang-specs.h).
1556                     --  This switch must be passed to the driver at link time.
1557
1558                     if Arg'Length = 5
1559                       and then Arg (Arg'First + 1 .. Arg'First + 4) = "mrtp"
1560                     then
1561                        Linker_Options.Increment_Last;
1562                        Linker_Options.Table
1563                          (Linker_Options.Last) := String_Access (Arg);
1564                     end if;
1565
1566                  elsif Arg'Length > 5
1567                    and then Arg (Arg'First + 2 .. Arg'First + 5) = "RTS="
1568                  then
1569                     Binder_Options_From_ALI.Increment_Last;
1570                     Binder_Options_From_ALI.Table
1571                       (Binder_Options_From_ALI.Last) := String_Access (Arg);
1572
1573                     --  Set the RTS_*_Path_Name variables, so that
1574                     --  the correct directories will be set when
1575                     --  Osint.Add_Default_Search_Dirs will be called later.
1576
1577                     Opt.RTS_Src_Path_Name :=
1578                       Get_RTS_Search_Dir
1579                         (Arg (Arg'First + 6 .. Arg'Last), Include);
1580
1581                     Opt.RTS_Lib_Path_Name :=
1582                       Get_RTS_Search_Dir
1583                         (Arg (Arg'First + 6 .. Arg'Last), Objects);
1584                  end if;
1585               end;
1586            end loop;
1587         end if;
1588      end;
1589   end if;
1590
1591   --  Get target parameters
1592
1593   Osint.Add_Default_Search_Dirs;
1594   Targparm.Get_Target_Parameters;
1595
1596   --  Compile the bind file with the following switches:
1597
1598   --    -gnatA   stops reading gnat.adc, since we don't know what
1599   --             pragmas would work, and we do not need it anyway.
1600
1601   --    -gnatWb  allows brackets coding for wide characters
1602
1603   --    -gnatiw  allows wide characters in identifiers. This is needed
1604   --             because bindgen uses brackets encoding for all upper
1605   --             half and wide characters in identifier names.
1606
1607   --  In addition, in CodePeer mode compile with -x adascil -gnatcC
1608
1609   Binder_Options_From_ALI.Increment_Last;
1610   Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1611        new String'("-gnatA");
1612   Binder_Options_From_ALI.Increment_Last;
1613   Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1614        new String'("-gnatWb");
1615   Binder_Options_From_ALI.Increment_Last;
1616   Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1617        new String'("-gnatiw");
1618
1619   if Opt.CodePeer_Mode then
1620      Binder_Options_From_ALI.Increment_Last;
1621      Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1622        new String'("-x");
1623      Binder_Options_From_ALI.Increment_Last;
1624      Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1625        new String'("adascil");
1626      Binder_Options_From_ALI.Increment_Last;
1627      Binder_Options_From_ALI.Table (Binder_Options_From_ALI.Last) :=
1628        new String'("-gnatcC");
1629   end if;
1630
1631   --  Locate all the necessary programs and verify required files are present
1632
1633   Gcc_Path := System.OS_Lib.Locate_Exec_On_Path (Gcc.all);
1634
1635   if Gcc_Path = null then
1636      Exit_With_Error ("Couldn't locate " & Gcc.all);
1637   end if;
1638
1639   if Linker_Path = null then
1640      Linker_Path := Gcc_Path;
1641   end if;
1642
1643   Write_Header;
1644
1645   Target_Debuggable_Suffix := Get_Target_Debuggable_Suffix;
1646
1647   --  If no output name specified, then use the base name of .ali file name
1648
1649   if Output_File_Name = null then
1650      Output_File_Name :=
1651        new String'(Base_Name (Ali_File_Name.all)
1652                      & Target_Debuggable_Suffix.all);
1653   end if;
1654
1655   Linker_Options.Increment_Last;
1656   Linker_Options.Table (Linker_Options.Last) := new String'("-o");
1657
1658   Linker_Options.Increment_Last;
1659   Linker_Options.Table (Linker_Options.Last) :=
1660     new String'(Output_File_Name.all);
1661
1662   Check_Existing_Executable (Output_File_Name.all);
1663
1664   --  Warn if main program is called "test", as that may be a built-in command
1665   --  on Unix. On non-Unix systems executables have a suffix, so the warning
1666   --  will not appear. However, do not warn in the case of a cross compiler.
1667
1668   --  Assume this is a cross tool if the executable name is not gnatlink.
1669   --  Note that the executable name is also gnatlink on windows, but in that
1670   --  case the output file name will be test.exe rather than test.
1671
1672   if Base_Command_Name.all = "gnatlink"
1673     and then Output_File_Name.all = "test"
1674   then
1675      Error_Msg ("warning: executable name """ & Output_File_Name.all
1676                 & """ may conflict with shell command");
1677   end if;
1678
1679   --  Special warnings for worrisome file names on windows
1680
1681   --  Recent versions of Windows by default cause privilege escalation if an
1682   --  executable file name contains substrings "install", "setup", "update"
1683   --  or "patch". A console application will typically fail to load as a
1684   --  result, so we should warn the user.
1685
1686   Bad_File_Names_On_Windows : declare
1687      FN : String := Output_File_Name.all;
1688
1689      procedure Check_File_Name (S : String);
1690      --  Warn if file name has the substring S
1691
1692      procedure Check_File_Name (S : String) is
1693      begin
1694         for J in 1 .. FN'Length - (S'Length - 1) loop
1695            if FN (J .. J + (S'Length - 1)) = S then
1696               Error_Msg
1697                 ("warning: executable file name """ & Output_File_Name.all
1698                  & """ contains substring """ & S & '"');
1699               Error_Msg
1700                 ("admin privileges may be required to run this file");
1701            end if;
1702         end loop;
1703      end Check_File_Name;
1704
1705   --  Start of processing for Bad_File_Names_On_Windows
1706
1707   begin
1708      for J in FN'Range loop
1709            FN (J) := Csets.Fold_Lower (FN (J));
1710      end loop;
1711
1712      --  For now we detect Windows by its executable suffix of .exe
1713
1714      if Target_Debuggable_Suffix.all = ".exe" then
1715         Check_File_Name ("install");
1716         Check_File_Name ("setup");
1717         Check_File_Name ("update");
1718         Check_File_Name ("patch");
1719      end if;
1720   end Bad_File_Names_On_Windows;
1721
1722   --  If -M switch was specified, add the switches to create the map file
1723
1724   if Create_Map_File then
1725      declare
1726         Map_Name : constant String := Base_Name (Ali_File_Name.all) & ".map";
1727         Switches : String_List_Access;
1728
1729      begin
1730         Convert (Map_File, Map_Name, Switches);
1731
1732         if Switches /= null then
1733            for J in Switches'Range loop
1734               Linker_Options.Increment_Last;
1735               Linker_Options.Table (Linker_Options.Last) := Switches (J);
1736            end loop;
1737         end if;
1738      end;
1739   end if;
1740
1741   --  Perform consistency checks
1742
1743   --  Transform the .ali file name into the binder output file name
1744
1745   Make_Binder_File_Names : declare
1746      Fname     : constant String  := Base_Name (Ali_File_Name.all);
1747      Fname_Len : Integer := Fname'Length;
1748
1749      function Get_Maximum_File_Name_Length return Integer;
1750      pragma Import (C, Get_Maximum_File_Name_Length,
1751                        "__gnat_get_maximum_file_name_length");
1752
1753      Maximum_File_Name_Length : constant Integer :=
1754                                   Get_Maximum_File_Name_Length;
1755
1756      Bind_File_Prefix : Types.String_Ptr;
1757      --  Contains prefix used for bind files
1758
1759   begin
1760      --  Set prefix
1761
1762      Bind_File_Prefix := new String'("b~");
1763
1764      --  If the length of the binder file becomes too long due to
1765      --  the addition of the "b?" prefix, then truncate it.
1766
1767      if Maximum_File_Name_Length > 0 then
1768         while Fname_Len >
1769                 Maximum_File_Name_Length - Bind_File_Prefix.all'Length
1770         loop
1771            Fname_Len := Fname_Len - 1;
1772         end loop;
1773      end if;
1774
1775      declare
1776         Fnam : constant String :=
1777                  Bind_File_Prefix.all &
1778                    Fname (Fname'First .. Fname'First + Fname_Len - 1);
1779
1780      begin
1781         Binder_Spec_Src_File := new String'(Fnam & ".ads");
1782         Binder_Body_Src_File := new String'(Fnam & ".adb");
1783         Binder_Ali_File      := new String'(Fnam & ".ali");
1784
1785         Binder_Obj_File := new String'(Fnam & Get_Target_Object_Suffix.all);
1786      end;
1787
1788      if Fname_Len /= Fname'Length then
1789         Binder_Options.Increment_Last;
1790         Binder_Options.Table (Binder_Options.Last) := new String'("-o");
1791         Binder_Options.Increment_Last;
1792         Binder_Options.Table (Binder_Options.Last) := Binder_Obj_File;
1793      end if;
1794   end Make_Binder_File_Names;
1795
1796   Process_Binder_File (Binder_Body_Src_File.all & ASCII.NUL);
1797
1798   --  Compile the binder file. This is fast, so we always do it, unless
1799   --  specifically told not to by the -n switch
1800
1801   if Compile_Bind_File then
1802      Bind_Step : declare
1803         Success : Boolean;
1804
1805         Args : Argument_List
1806                 (1 .. Binder_Options_From_ALI.Last + Binder_Options.Last + 1);
1807
1808      begin
1809         for J in 1 .. Binder_Options_From_ALI.Last loop
1810            Args (J) := Binder_Options_From_ALI.Table (J);
1811         end loop;
1812
1813         for J in 1 .. Binder_Options.Last loop
1814            Args (Binder_Options_From_ALI.Last + J) :=
1815              Binder_Options.Table (J);
1816         end loop;
1817
1818         --  Use the full path of the binder generated source, so that it is
1819         --  guaranteed that the debugger will find this source, even with
1820         --  STABS.
1821
1822         Args (Args'Last) :=
1823           new String'(Normalize_Pathname (Binder_Body_Src_File.all));
1824
1825         if Verbose_Mode then
1826            Write_Str (Base_Name (Gcc_Path.all));
1827
1828            for J in Args'Range loop
1829               Write_Str (" ");
1830               Write_Str (Args (J).all);
1831            end loop;
1832
1833            Write_Eol;
1834         end if;
1835
1836         System.OS_Lib.Spawn (Gcc_Path.all, Args, Success);
1837
1838         if not Success then
1839            Exit_Program (E_Fatal);
1840         end if;
1841      end Bind_Step;
1842   end if;
1843
1844   --  In CodePeer mode, there's nothing left to do after the binder file has
1845   --  been compiled.
1846
1847   if Opt.CodePeer_Mode then
1848      if Tname_FD /= Invalid_FD then
1849         Delete (Tname);
1850      end if;
1851
1852      return;
1853   end if;
1854
1855   --  Now, actually link the program
1856
1857   Link_Step : declare
1858      Num_Args : Natural :=
1859        (Linker_Options.Last - Linker_Options.First + 1) +
1860        (Gcc_Linker_Options.Last - Gcc_Linker_Options.First + 1) +
1861        (Linker_Objects.Last - Linker_Objects.First + 1);
1862      Stack_Op : Boolean := False;
1863
1864   begin
1865      --  Remove duplicate stack size setting from the Linker_Options table.
1866      --  The stack setting option "-Xlinker --stack=R,C" can be found
1867      --  in one line when set by a pragma Linker_Options or in two lines
1868      --  ("-Xlinker" then "--stack=R,C") when set on the command line. We
1869      --  also check for the "-Wl,--stack=R" style option.
1870
1871      --  We must remove the second stack setting option instance because
1872      --  the one on the command line will always be the first one. And any
1873      --  subsequent stack setting option will overwrite the previous one.
1874      --  This is done especially for GNAT/NT where we set the stack size
1875      --  for tasking programs by a pragma in the NT specific tasking
1876      --  package System.Task_Primitives.Operations.
1877
1878      --  Note: This is not a FOR loop that runs from Linker_Options.First
1879      --  to Linker_Options.Last, since operations within the loop can
1880      --  modify the length of the table.
1881
1882      Clean_Link_Option_Set : declare
1883         J                  : Natural;
1884         Shared_Libgcc_Seen : Boolean := False;
1885         Static_Libgcc_Seen : Boolean := False;
1886
1887      begin
1888         J := Linker_Options.First;
1889         while J <= Linker_Options.Last loop
1890            if Linker_Options.Table (J).all = "-Xlinker"
1891              and then J < Linker_Options.Last
1892              and then Linker_Options.Table (J + 1)'Length > 8
1893              and then Linker_Options.Table (J + 1) (1 .. 8) = "--stack="
1894            then
1895               if Stack_Op then
1896                  Linker_Options.Table (J .. Linker_Options.Last - 2) :=
1897                    Linker_Options.Table (J + 2 .. Linker_Options.Last);
1898                  Linker_Options.Decrement_Last;
1899                  Linker_Options.Decrement_Last;
1900                  Num_Args := Num_Args - 2;
1901
1902               else
1903                  Stack_Op := True;
1904               end if;
1905            end if;
1906
1907            --  Remove duplicate -shared-libgcc switches
1908
1909            if Linker_Options.Table (J).all = Shared_Libgcc_String then
1910               if Shared_Libgcc_Seen then
1911                  Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1912                    Linker_Options.Table (J + 1 .. Linker_Options.Last);
1913                  Linker_Options.Decrement_Last;
1914                  Num_Args := Num_Args - 1;
1915
1916               else
1917                  Shared_Libgcc_Seen := True;
1918               end if;
1919            end if;
1920
1921            --  Remove duplicate -static-libgcc switches
1922
1923            if Linker_Options.Table (J).all = Static_Libgcc_String then
1924               if Static_Libgcc_Seen then
1925                  Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1926                    Linker_Options.Table (J + 1 .. Linker_Options.Last);
1927                  Linker_Options.Decrement_Last;
1928                  Num_Args := Num_Args - 1;
1929
1930               else
1931                  Static_Libgcc_Seen := True;
1932               end if;
1933            end if;
1934
1935            --  Here we just check for a canonical form that matches the
1936            --  pragma Linker_Options set in the NT runtime.
1937
1938            if (Linker_Options.Table (J)'Length > 17
1939                and then Linker_Options.Table (J) (1 .. 17) =
1940                  "-Xlinker --stack=")
1941              or else
1942                (Linker_Options.Table (J)'Length > 12
1943                 and then Linker_Options.Table (J) (1 .. 12) =
1944                       "-Wl,--stack=")
1945            then
1946               if Stack_Op then
1947                  Linker_Options.Table (J .. Linker_Options.Last - 1) :=
1948                    Linker_Options.Table (J + 1 .. Linker_Options.Last);
1949                  Linker_Options.Decrement_Last;
1950                  Num_Args := Num_Args - 1;
1951
1952               else
1953                  Stack_Op := True;
1954               end if;
1955            end if;
1956
1957            J := J + 1;
1958         end loop;
1959
1960         if Linker_Path = Gcc_Path then
1961
1962            --  For systems where the default is to link statically with
1963            --  libgcc, if gcc is not called with -shared-libgcc, call it
1964            --  with -static-libgcc, as there are some platforms where one
1965            --  of these two switches is compulsory to link.
1966            --  Don't push extra switches if we already saw one.
1967
1968            if Shared_Libgcc_Default = 'T'
1969              and then not Shared_Libgcc_Seen
1970              and then not Static_Libgcc_Seen
1971            then
1972               Linker_Options.Increment_Last;
1973               Linker_Options.Table (Linker_Options.Last) := Static_Libgcc;
1974               Num_Args := Num_Args + 1;
1975            end if;
1976
1977            --  Likewise, the reverse.
1978
1979            if Shared_Libgcc_Default = 'H'
1980              and then not Static_Libgcc_Seen
1981              and then not Shared_Libgcc_Seen
1982            then
1983               Linker_Options.Increment_Last;
1984               Linker_Options.Table (Linker_Options.Last) := Shared_Libgcc;
1985               Num_Args := Num_Args + 1;
1986            end if;
1987         end if;
1988      end Clean_Link_Option_Set;
1989
1990      --  Prepare arguments for call to linker
1991
1992      Call_Linker : declare
1993         Success  : Boolean;
1994         Args     : Argument_List (1 .. Num_Args + 1);
1995         Index    : Integer := Args'First;
1996
1997      begin
1998         Args (Index) := Binder_Obj_File;
1999
2000         --  Add the object files and any -largs libraries
2001
2002         for J in Linker_Objects.First .. Linker_Objects.Last loop
2003            Index := Index + 1;
2004            Args (Index) := Linker_Objects.Table (J);
2005         end loop;
2006
2007         --  Add the linker options from the binder file
2008
2009         for J in Linker_Options.First .. Linker_Options.Last loop
2010            Index := Index + 1;
2011            Args (Index) := Linker_Options.Table (J);
2012         end loop;
2013
2014         --  Finally add the libraries from the --GCC= switch
2015
2016         for J in Gcc_Linker_Options.First .. Gcc_Linker_Options.Last loop
2017            Index := Index + 1;
2018            Args (Index) := Gcc_Linker_Options.Table (J);
2019         end loop;
2020
2021         if Verbose_Mode then
2022            Write_Str (Linker_Path.all);
2023
2024            for J in Args'Range loop
2025               Write_Str (" ");
2026               Write_Str (Args (J).all);
2027            end loop;
2028
2029            Write_Eol;
2030
2031            --  If we are on very verbose mode (-v -v) and a response file
2032            --  is used we display its content.
2033
2034            if Very_Verbose_Mode and then Tname_FD /= Invalid_FD then
2035               Write_Eol;
2036               Write_Str ("Response file (" &
2037                            Tname (Tname'First .. Tname'Last - 1) &
2038                            ") content : ");
2039               Write_Eol;
2040
2041               for J in
2042                 Response_File_Objects.First .. Response_File_Objects.Last
2043               loop
2044                  Write_Str (Response_File_Objects.Table (J).all);
2045                  Write_Eol;
2046               end loop;
2047
2048               Write_Eol;
2049            end if;
2050         end if;
2051
2052         System.OS_Lib.Spawn (Linker_Path.all, Args, Success);
2053
2054         --  Delete the temporary file used in conjunction with linking if one
2055         --  was created. See Process_Bind_File for details.
2056
2057         if Tname_FD /= Invalid_FD then
2058            Delete (Tname);
2059         end if;
2060
2061         if not Success then
2062            Error_Msg ("error when calling " & Linker_Path.all);
2063            Exit_Program (E_Fatal);
2064         end if;
2065      end Call_Linker;
2066   end Link_Step;
2067
2068   --  Only keep the binder output file and it's associated object
2069   --  file if compiling with the -g option.  These files are only
2070   --  useful if debugging.
2071
2072   if not Debug_Flag_Present then
2073      Delete (Binder_Ali_File.all & ASCII.NUL);
2074      Delete (Binder_Spec_Src_File.all & ASCII.NUL);
2075      Delete (Binder_Body_Src_File.all & ASCII.NUL);
2076      Delete (Binder_Obj_File.all & ASCII.NUL);
2077   end if;
2078
2079   Exit_Program (E_Success);
2080
2081exception
2082   when X : others =>
2083      Write_Line (Exception_Information (X));
2084      Exit_With_Error ("INTERNAL ERROR. Please report");
2085end Gnatlink;
2086