Don't bfd_check_format if not needed
[external/binutils.git] / ld / ldfile.c
1 /* Linker file opening and searching.
2    Copyright (C) 1991-2015 Free Software Foundation, Inc.
3
4    This file is part of the GNU Binutils.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
19    MA 02110-1301, USA.  */
20
21 #include "sysdep.h"
22 #include "bfd.h"
23 #include "bfdlink.h"
24 #include "safe-ctype.h"
25 #include "ld.h"
26 #include "ldmisc.h"
27 #include "ldexp.h"
28 #include "ldlang.h"
29 #include "ldfile.h"
30 #include "ldmain.h"
31 #include <ldgram.h>
32 #include "ldlex.h"
33 #include "ldemul.h"
34 #include "libiberty.h"
35 #include "filenames.h"
36 #ifdef ENABLE_PLUGINS
37 #include "plugin-api.h"
38 #include "plugin.h"
39 #endif /* ENABLE_PLUGINS */
40
41 bfd_boolean  ldfile_assumed_script = FALSE;
42 const char * ldfile_output_machine_name = "";
43 unsigned long ldfile_output_machine;
44 enum bfd_architecture ldfile_output_architecture;
45 search_dirs_type * search_head;
46
47 #ifdef VMS
48 static char * slash = "";
49 #else
50 #if defined (_WIN32) && ! defined (__CYGWIN32__)
51 static char * slash = "\\";
52 #else
53 static char * slash = "/";
54 #endif
55 #endif
56
57 typedef struct search_arch
58 {
59   char *name;
60   struct search_arch *next;
61 } search_arch_type;
62
63 static search_dirs_type **search_tail_ptr = &search_head;
64 static search_arch_type *search_arch_head;
65 static search_arch_type **search_arch_tail_ptr = &search_arch_head;
66
67 /* Test whether a pathname, after canonicalization, is the same or a
68    sub-directory of the sysroot directory.  */
69
70 static bfd_boolean
71 is_sysrooted_pathname (const char *name)
72 {
73   char *realname;
74   int len;
75   bfd_boolean result;
76
77   if (ld_canon_sysroot == NULL)
78     return FALSE;
79
80   realname = lrealpath (name);
81   len = strlen (realname);
82   result = FALSE;
83   if (len > ld_canon_sysroot_len
84       && IS_DIR_SEPARATOR (realname[ld_canon_sysroot_len]))
85     {
86       realname[ld_canon_sysroot_len] = '\0';
87       result = FILENAME_CMP (ld_canon_sysroot, realname) == 0;
88     }
89
90   free (realname);
91   return result;
92 }
93
94 /* Adds NAME to the library search path.
95    Makes a copy of NAME using xmalloc().  */
96
97 void
98 ldfile_add_library_path (const char *name, bfd_boolean cmdline)
99 {
100   search_dirs_type *new_dirs;
101
102   if (!cmdline && config.only_cmd_line_lib_dirs)
103     return;
104
105   new_dirs = (search_dirs_type *) xmalloc (sizeof (search_dirs_type));
106   new_dirs->next = NULL;
107   new_dirs->cmdline = cmdline;
108   *search_tail_ptr = new_dirs;
109   search_tail_ptr = &new_dirs->next;
110
111   /* If a directory is marked as honoring sysroot, prepend the sysroot path
112      now.  */
113   if (name[0] == '=')
114     new_dirs->name = concat (ld_sysroot, name + 1, (const char *) NULL);
115   else
116     new_dirs->name = xstrdup (name);
117 }
118
119 /* Try to open a BFD for a lang_input_statement.  */
120
121 bfd_boolean
122 ldfile_try_open_bfd (const char *attempt,
123                      lang_input_statement_type *entry)
124 {
125   entry->the_bfd = bfd_openr (attempt, entry->target);
126
127   if (verbose)
128     {
129       if (entry->the_bfd == NULL)
130         info_msg (_("attempt to open %s failed\n"), attempt);
131       else
132         info_msg (_("attempt to open %s succeeded\n"), attempt);
133     }
134
135   if (entry->the_bfd == NULL)
136     {
137       if (bfd_get_error () == bfd_error_invalid_target)
138         einfo (_("%F%P: invalid BFD target `%s'\n"), entry->target);
139       return FALSE;
140     }
141
142   /* Linker needs to decompress sections.  */
143   entry->the_bfd->flags |= BFD_DECOMPRESS;
144
145   /* If we are searching for this file, see if the architecture is
146      compatible with the output file.  If it isn't, keep searching.
147      If we can't open the file as an object file, stop the search
148      here.  If we are statically linking, ensure that we don't link
149      a dynamic object.
150
151      In the code below, it's OK to exit early if the check fails,
152      closing the checked BFD and returning FALSE, but if the BFD
153      checks out compatible, do not exit early returning TRUE, or
154      the plugins will not get a chance to claim the file.  */
155
156   if (entry->flags.search_dirs || !entry->flags.dynamic)
157     {
158       bfd *check;
159
160       if (bfd_check_format (entry->the_bfd, bfd_archive))
161         check = bfd_openr_next_archived_file (entry->the_bfd, NULL);
162       else
163         check = entry->the_bfd;
164
165       if (check != NULL)
166         {
167           if (! bfd_check_format (check, bfd_object))
168             {
169               if (check == entry->the_bfd
170                   && entry->flags.search_dirs
171                   && bfd_get_error () == bfd_error_file_not_recognized
172                   && ! ldemul_unrecognized_file (entry))
173                 {
174                   int token, skip = 0;
175                   char *arg, *arg1, *arg2, *arg3;
176                   extern FILE *yyin;
177
178                   /* Try to interpret the file as a linker script.  */
179                   ldfile_open_command_file (attempt);
180
181                   ldfile_assumed_script = TRUE;
182                   parser_input = input_selected;
183                   ldlex_both ();
184                   token = INPUT_SCRIPT;
185                   while (token != 0)
186                     {
187                       switch (token)
188                         {
189                         case OUTPUT_FORMAT:
190                           if ((token = yylex ()) != '(')
191                             continue;
192                           if ((token = yylex ()) != NAME)
193                             continue;
194                           arg1 = yylval.name;
195                           arg2 = NULL;
196                           arg3 = NULL;
197                           token = yylex ();
198                           if (token == ',')
199                             {
200                               if ((token = yylex ()) != NAME)
201                                 {
202                                   free (arg1);
203                                   continue;
204                                 }
205                               arg2 = yylval.name;
206                               if ((token = yylex ()) != ','
207                                   || (token = yylex ()) != NAME)
208                                 {
209                                   free (arg1);
210                                   free (arg2);
211                                   continue;
212                                 }
213                               arg3 = yylval.name;
214                               token = yylex ();
215                             }
216                           if (token == ')')
217                             {
218                               switch (command_line.endian)
219                                 {
220                                 default:
221                                 case ENDIAN_UNSET:
222                                   arg = arg1; break;
223                                 case ENDIAN_BIG:
224                                   arg = arg2 ? arg2 : arg1; break;
225                                 case ENDIAN_LITTLE:
226                                   arg = arg3 ? arg3 : arg1; break;
227                                 }
228                               if (strcmp (arg, lang_get_output_target ()) != 0)
229                                 skip = 1;
230                             }
231                           free (arg1);
232                           if (arg2) free (arg2);
233                           if (arg3) free (arg3);
234                           break;
235                         case NAME:
236                         case LNAME:
237                         case VERS_IDENTIFIER:
238                         case VERS_TAG:
239                           free (yylval.name);
240                           break;
241                         case INT:
242                           if (yylval.bigint.str)
243                             free (yylval.bigint.str);
244                           break;
245                         }
246                       token = yylex ();
247                     }
248                   ldlex_popstate ();
249                   ldfile_assumed_script = FALSE;
250                   fclose (yyin);
251                   yyin = NULL;
252                   if (skip)
253                     {
254                       if (command_line.warn_search_mismatch)
255                         einfo (_("%P: skipping incompatible %s "
256                                  "when searching for %s\n"),
257                                attempt, entry->local_sym_name);
258                       bfd_close (entry->the_bfd);
259                       entry->the_bfd = NULL;
260                       return FALSE;
261                     }
262                 }
263               goto success;
264             }
265
266           if (!entry->flags.dynamic && (entry->the_bfd->flags & DYNAMIC) != 0)
267             {
268               einfo (_("%F%P: attempted static link of dynamic object `%s'\n"),
269                      attempt);
270               bfd_close (entry->the_bfd);
271               entry->the_bfd = NULL;
272               return FALSE;
273             }
274
275           if (entry->flags.search_dirs
276               && !bfd_arch_get_compatible (check, link_info.output_bfd,
277                                            command_line.accept_unknown_input_arch)
278               /* XCOFF archives can have 32 and 64 bit objects.  */
279               && ! (bfd_get_flavour (check) == bfd_target_xcoff_flavour
280                     && bfd_get_flavour (link_info.output_bfd) == bfd_target_xcoff_flavour
281                     && bfd_check_format (entry->the_bfd, bfd_archive)))
282             {
283               if (command_line.warn_search_mismatch)
284                 einfo (_("%P: skipping incompatible %s "
285                          "when searching for %s\n"),
286                        attempt, entry->local_sym_name);
287               bfd_close (entry->the_bfd);
288               entry->the_bfd = NULL;
289               return FALSE;
290             }
291         }
292     }
293 success:
294 #ifdef ENABLE_PLUGINS
295   /* If plugins are active, they get first chance to claim
296      any successfully-opened input file.  We skip archives
297      here; the plugin wants us to offer it the individual
298      members when we enumerate them, not the whole file.  We
299      also ignore corefiles, because that's just weird.  It is
300      a needed side-effect of calling  bfd_check_format with
301      bfd_object that it sets the bfd's arch and mach, which
302      will be needed when and if we want to bfd_create a new
303      one using this one as a template.  */
304   if (link_info.lto_plugin_active
305       && !no_more_claiming
306       && bfd_check_format (entry->the_bfd, bfd_object))
307     plugin_maybe_claim (entry);
308 #endif /* ENABLE_PLUGINS */
309
310   /* It opened OK, the format checked out, and the plugins have had
311      their chance to claim it, so this is success.  */
312   return TRUE;
313 }
314
315 /* Search for and open the file specified by ENTRY.  If it is an
316    archive, use ARCH, LIB and SUFFIX to modify the file name.  */
317
318 bfd_boolean
319 ldfile_open_file_search (const char *arch,
320                          lang_input_statement_type *entry,
321                          const char *lib,
322                          const char *suffix)
323 {
324   search_dirs_type *search;
325
326   /* If this is not an archive, try to open it in the current
327      directory first.  */
328   if (! entry->flags.maybe_archive)
329     {
330       if (entry->flags.sysrooted && IS_ABSOLUTE_PATH (entry->filename))
331         {
332           char *name = concat (ld_sysroot, entry->filename,
333                                (const char *) NULL);
334           if (ldfile_try_open_bfd (name, entry))
335             {
336               entry->filename = name;
337               return TRUE;
338             }
339           free (name);
340         }
341       else if (ldfile_try_open_bfd (entry->filename, entry))
342         return TRUE;
343
344       if (IS_ABSOLUTE_PATH (entry->filename))
345         return FALSE;
346     }
347
348   for (search = search_head; search != NULL; search = search->next)
349     {
350       char *string;
351
352       if (entry->flags.dynamic && ! link_info.relocatable)
353         {
354           if (ldemul_open_dynamic_archive (arch, search, entry))
355             return TRUE;
356         }
357
358       if (entry->flags.maybe_archive && !entry->flags.full_name_provided)
359         string = concat (search->name, slash, lib, entry->filename,
360                          arch, suffix, (const char *) NULL);
361       else
362         string = concat (search->name, slash, entry->filename,
363                          (const char *) 0);
364
365       if (ldfile_try_open_bfd (string, entry))
366         {
367           entry->filename = string;
368           return TRUE;
369         }
370
371       free (string);
372     }
373
374   return FALSE;
375 }
376
377 /* Open the input file specified by ENTRY.
378    PR 4437: Do not stop on the first missing file, but
379    continue processing other input files in case there
380    are more errors to report.  */
381
382 void
383 ldfile_open_file (lang_input_statement_type *entry)
384 {
385   if (entry->the_bfd != NULL)
386     return;
387
388   if (! entry->flags.search_dirs)
389     {
390       if (ldfile_try_open_bfd (entry->filename, entry))
391         return;
392
393       if (filename_cmp (entry->filename, entry->local_sym_name) != 0)
394         einfo (_("%P: cannot find %s (%s): %E\n"),
395                entry->filename, entry->local_sym_name);
396       else
397         einfo (_("%P: cannot find %s: %E\n"), entry->local_sym_name);
398
399       entry->flags.missing_file = TRUE;
400       input_flags.missing_file = TRUE;
401     }
402   else
403     {
404       search_arch_type *arch;
405       bfd_boolean found = FALSE;
406
407       /* Try to open <filename><suffix> or lib<filename><suffix>.a */
408       for (arch = search_arch_head; arch != NULL; arch = arch->next)
409         {
410           found = ldfile_open_file_search (arch->name, entry, "lib", ".a");
411           if (found)
412             break;
413 #ifdef VMS
414           found = ldfile_open_file_search (arch->name, entry, ":lib", ".a");
415           if (found)
416             break;
417 #endif
418           found = ldemul_find_potential_libraries (arch->name, entry);
419           if (found)
420             break;
421         }
422
423       /* If we have found the file, we don't need to search directories
424          again.  */
425       if (found)
426         entry->flags.search_dirs = FALSE;
427       else
428         {
429           if (entry->flags.sysrooted
430                && ld_sysroot
431                && IS_ABSOLUTE_PATH (entry->local_sym_name))
432             einfo (_("%P: cannot find %s inside %s\n"),
433                    entry->local_sym_name, ld_sysroot);
434           else
435             einfo (_("%P: cannot find %s\n"), entry->local_sym_name);
436           entry->flags.missing_file = TRUE;
437           input_flags.missing_file = TRUE;
438         }
439     }
440 }
441
442 /* Try to open NAME.  */
443
444 static FILE *
445 try_open (const char *name, bfd_boolean *sysrooted)
446 {
447   FILE *result;
448
449   result = fopen (name, "r");
450
451   if (result != NULL)
452     *sysrooted = is_sysrooted_pathname (name);
453
454   if (verbose)
455     {
456       if (result == NULL)
457         info_msg (_("cannot find script file %s\n"), name);
458       else
459         info_msg (_("opened script file %s\n"), name);
460     }
461
462   return result;
463 }
464
465 /* Return TRUE iff directory DIR contains an "ldscripts" subdirectory.  */
466
467 static bfd_boolean
468 check_for_scripts_dir (char *dir)
469 {
470   char *buf;
471   struct stat s;
472   bfd_boolean res;
473
474   buf = concat (dir, "/ldscripts", (const char *) NULL);
475   res = stat (buf, &s) == 0 && S_ISDIR (s.st_mode);
476   free (buf);
477   return res;
478 }
479
480 /* Return the default directory for finding script files.
481    We look for the "ldscripts" directory in:
482
483    SCRIPTDIR (passed from Makefile)
484              (adjusted according to the current location of the binary)
485    the dir where this program is (for using it from the build tree).  */
486
487 static char *
488 find_scripts_dir (void)
489 {
490   char *dir;
491
492   dir = make_relative_prefix (program_name, BINDIR, SCRIPTDIR);
493   if (dir)
494     {
495       if (check_for_scripts_dir (dir))
496         return dir;
497       free (dir);
498     }
499
500   dir = make_relative_prefix (program_name, TOOLBINDIR, SCRIPTDIR);
501   if (dir)
502     {
503       if (check_for_scripts_dir (dir))
504         return dir;
505       free (dir);
506     }
507
508   /* Look for "ldscripts" in the dir where our binary is.  */
509   dir = make_relative_prefix (program_name, ".", ".");
510   if (dir)
511     {
512       if (check_for_scripts_dir (dir))
513         return dir;
514       free (dir);
515     }
516
517   return NULL;
518 }
519
520 /* If DEFAULT_ONLY is false, try to open NAME; if that fails, look for
521    it in directories specified with -L, then in the default script
522    directory.  If DEFAULT_ONLY is true, the search is restricted to
523    the default script location.  */
524
525 static FILE *
526 ldfile_find_command_file (const char *name,
527                           bfd_boolean default_only,
528                           bfd_boolean *sysrooted)
529 {
530   search_dirs_type *search;
531   FILE *result = NULL;
532   char *path;
533   static search_dirs_type *script_search;
534
535   if (!default_only)
536     {
537       /* First try raw name.  */
538       result = try_open (name, sysrooted);
539       if (result != NULL)
540         return result;
541     }
542
543   if (!script_search)
544     {
545       char *script_dir = find_scripts_dir ();
546       if (script_dir)
547         {
548           search_dirs_type **save_tail_ptr = search_tail_ptr;
549           search_tail_ptr = &script_search;
550           ldfile_add_library_path (script_dir, TRUE);
551           search_tail_ptr = save_tail_ptr;
552         }
553     }
554
555   /* Temporarily append script_search to the path list so that the
556      paths specified with -L will be searched first.  */
557   *search_tail_ptr = script_search;
558
559   /* Try now prefixes.  */
560   for (search = default_only ? script_search : search_head;
561        search != NULL;
562        search = search->next)
563     {
564       path = concat (search->name, slash, name, (const char *) NULL);
565       result = try_open (path, sysrooted);
566       free (path);
567       if (result)
568         break;
569     }
570
571   /* Restore the original path list.  */
572   *search_tail_ptr = NULL;
573
574   return result;
575 }
576
577 /* Open command file NAME.  */
578
579 static void
580 ldfile_open_command_file_1 (const char *name, bfd_boolean default_only)
581 {
582   FILE *ldlex_input_stack;
583   bfd_boolean sysrooted;
584
585   ldlex_input_stack = ldfile_find_command_file (name, default_only, &sysrooted);
586
587   if (ldlex_input_stack == NULL)
588     {
589       bfd_set_error (bfd_error_system_call);
590       einfo (_("%P%F: cannot open linker script file %s: %E\n"), name);
591       return;
592     }
593
594   lex_push_file (ldlex_input_stack, name, sysrooted);
595
596   lineno = 1;
597
598   saved_script_handle = ldlex_input_stack;
599 }
600
601 /* Open command file NAME in the current directory, -L directories,
602    the default script location, in that order.  */
603
604 void
605 ldfile_open_command_file (const char *name)
606 {
607   ldfile_open_command_file_1 (name, FALSE);
608 }
609
610 /* Open command file NAME at the default script location.  */
611
612 void
613 ldfile_open_default_command_file (const char *name)
614 {
615   ldfile_open_command_file_1 (name, TRUE);
616 }
617
618 void
619 ldfile_add_arch (const char *in_name)
620 {
621   char *name = xstrdup (in_name);
622   search_arch_type *new_arch = (search_arch_type *)
623       xmalloc (sizeof (search_arch_type));
624
625   ldfile_output_machine_name = in_name;
626
627   new_arch->name = name;
628   new_arch->next = NULL;
629   while (*name)
630     {
631       *name = TOLOWER (*name);
632       name++;
633     }
634   *search_arch_tail_ptr = new_arch;
635   search_arch_tail_ptr = &new_arch->next;
636
637 }
638
639 /* Set the output architecture.  */
640
641 void
642 ldfile_set_output_arch (const char *string, enum bfd_architecture defarch)
643 {
644   const bfd_arch_info_type *arch = bfd_scan_arch (string);
645
646   if (arch)
647     {
648       ldfile_output_architecture = arch->arch;
649       ldfile_output_machine = arch->mach;
650       ldfile_output_machine_name = arch->printable_name;
651     }
652   else if (defarch != bfd_arch_unknown)
653     ldfile_output_architecture = defarch;
654   else
655     einfo (_("%P%F: cannot represent machine `%s'\n"), string);
656 }