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