1/* Plugin control for the GNU linker.
2   Copyright (C) 2010-2017 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 "libiberty.h"
23#include "bfd.h"
24#include "bfdlink.h"
25#include "bfdver.h"
26#include "ld.h"
27#include "ldmain.h"
28#include "ldmisc.h"
29#include "ldexp.h"
30#include "ldlang.h"
31#include "ldfile.h"
32#include "plugin-api.h"
33#include "../bfd/plugin.h"
34#include "plugin.h"
35#include "elf-bfd.h"
36#if HAVE_MMAP
37# include <sys/mman.h>
38# ifndef MAP_FAILED
39#  define MAP_FAILED ((void *) -1)
40# endif
41# ifndef PROT_READ
42#  define PROT_READ 0
43# endif
44# ifndef MAP_PRIVATE
45#  define MAP_PRIVATE 0
46# endif
47#endif
48#include <errno.h>
49#if !(defined(errno) || defined(_MSC_VER) && defined(_INC_ERRNO))
50extern int errno;
51#endif
52#if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
53#include <windows.h>
54#endif
55
56/* Report plugin symbols.  */
57bfd_boolean report_plugin_symbols;
58
59/* The suffix to append to the name of the real (claimed) object file
60   when generating a dummy BFD to hold the IR symbols sent from the
61   plugin.  For cosmetic use only; appears in maps, crefs etc.  */
62#define IRONLY_SUFFIX " (symbol from plugin)"
63
64/* Stores a single argument passed to a plugin.  */
65typedef struct plugin_arg
66{
67  struct plugin_arg *next;
68  const char *arg;
69} plugin_arg_t;
70
71/* Holds all details of a single plugin.  */
72typedef struct plugin
73{
74  /* Next on the list of plugins, or NULL at end of chain.  */
75  struct plugin *next;
76  /* The argument string given to --plugin.  */
77  const char *name;
78  /* The shared library handle returned by dlopen.  */
79  void *dlhandle;
80  /* The list of argument string given to --plugin-opt.  */
81  plugin_arg_t *args;
82  /* Number of args in the list, for convenience.  */
83  size_t n_args;
84  /* The plugin's event handlers.  */
85  ld_plugin_claim_file_handler claim_file_handler;
86  ld_plugin_all_symbols_read_handler all_symbols_read_handler;
87  ld_plugin_cleanup_handler cleanup_handler;
88  /* TRUE if the cleanup handlers have been called.  */
89  bfd_boolean cleanup_done;
90} plugin_t;
91
92typedef struct view_buffer
93{
94  char *addr;
95  size_t filesize;
96  off_t offset;
97} view_buffer_t;
98
99/* The internal version of struct ld_plugin_input_file with a BFD
100   pointer.  */
101typedef struct plugin_input_file
102{
103  bfd *abfd;
104  view_buffer_t view_buffer;
105  char *name;
106  int fd;
107  bfd_boolean use_mmap;
108  off_t offset;
109  off_t filesize;
110} plugin_input_file_t;
111
112/* The master list of all plugins.  */
113static plugin_t *plugins_list = NULL;
114
115/* We keep a tail pointer for easy linking on the end.  */
116static plugin_t **plugins_tail_chain_ptr = &plugins_list;
117
118/* The last plugin added to the list, for receiving args.  */
119static plugin_t *last_plugin = NULL;
120
121/* The tail of the arg chain of the last plugin added to the list.  */
122static plugin_arg_t **last_plugin_args_tail_chain_ptr = NULL;
123
124/* The plugin which is currently having a callback executed.  */
125static plugin_t *called_plugin = NULL;
126
127/* Last plugin to cause an error, if any.  */
128static const char *error_plugin = NULL;
129
130/* State of linker "notice" interface before we poked at it.  */
131static bfd_boolean orig_notice_all;
132
133/* Original linker callbacks, and the plugin version.  */
134static const struct bfd_link_callbacks *orig_callbacks;
135static struct bfd_link_callbacks plugin_callbacks;
136
137/* Set at all symbols read time, to avoid recursively offering the plugin
138   its own newly-added input files and libs to claim.  */
139bfd_boolean no_more_claiming = FALSE;
140
141#if HAVE_MMAP && HAVE_GETPAGESIZE
142/* Page size used by mmap.  */
143static off_t plugin_pagesize;
144#endif
145
146/* List of tags to set in the constant leading part of the tv array. */
147static const enum ld_plugin_tag tv_header_tags[] =
148{
149  LDPT_MESSAGE,
150  LDPT_API_VERSION,
151  LDPT_GNU_LD_VERSION,
152  LDPT_LINKER_OUTPUT,
153  LDPT_OUTPUT_NAME,
154  LDPT_REGISTER_CLAIM_FILE_HOOK,
155  LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK,
156  LDPT_REGISTER_CLEANUP_HOOK,
157  LDPT_ADD_SYMBOLS,
158  LDPT_GET_INPUT_FILE,
159  LDPT_GET_VIEW,
160  LDPT_RELEASE_INPUT_FILE,
161  LDPT_GET_SYMBOLS,
162  LDPT_GET_SYMBOLS_V2,
163  LDPT_ADD_INPUT_FILE,
164  LDPT_ADD_INPUT_LIBRARY,
165  LDPT_SET_EXTRA_LIBRARY_PATH
166};
167
168/* How many entries in the constant leading part of the tv array.  */
169static const size_t tv_header_size = ARRAY_SIZE (tv_header_tags);
170
171/* Forward references.  */
172static bfd_boolean plugin_notice (struct bfd_link_info *,
173				  struct bfd_link_hash_entry *,
174				  struct bfd_link_hash_entry *,
175				  bfd *, asection *, bfd_vma, flagword);
176
177static const bfd_target * plugin_object_p (bfd *);
178
179#if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
180
181#define RTLD_NOW 0	/* Dummy value.  */
182
183static void *
184dlopen (const char *file, int mode ATTRIBUTE_UNUSED)
185{
186  return LoadLibrary (file);
187}
188
189static void *
190dlsym (void *handle, const char *name)
191{
192  return GetProcAddress (handle, name);
193}
194
195static int
196dlclose (void *handle)
197{
198  FreeLibrary (handle);
199  return 0;
200}
201
202#endif /* !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)  */
203
204#ifndef HAVE_DLFCN_H
205static const char *
206dlerror (void)
207{
208  return "";
209}
210#endif
211
212/* Helper function for exiting with error status.  */
213static int
214set_plugin_error (const char *plugin)
215{
216  error_plugin = plugin;
217  return -1;
218}
219
220/* Test if an error occurred.  */
221static bfd_boolean
222plugin_error_p (void)
223{
224  return error_plugin != NULL;
225}
226
227/* Return name of plugin which caused an error if any.  */
228const char *
229plugin_error_plugin (void)
230{
231  return error_plugin ? error_plugin : _("<no plugin>");
232}
233
234/* Handle -plugin arg: find and load plugin, or return error.  */
235void
236plugin_opt_plugin (const char *plugin)
237{
238  plugin_t *newplug;
239  plugin_t *curplug = plugins_list;
240
241  newplug = xmalloc (sizeof *newplug);
242  memset (newplug, 0, sizeof *newplug);
243  newplug->name = plugin;
244  newplug->dlhandle = dlopen (plugin, RTLD_NOW);
245  if (!newplug->dlhandle)
246    einfo (_("%P%F: %s: error loading plugin: %s\n"), plugin, dlerror ());
247
248  /* Check if plugin has been loaded already.  */
249  while (curplug)
250    {
251      if (newplug->dlhandle == curplug->dlhandle)
252	{
253	  einfo (_("%P: %s: duplicated plugin\n"), plugin);
254	  free (newplug);
255	  return;
256	}
257      curplug = curplug->next;
258    }
259
260  /* Chain on end, so when we run list it is in command-line order.  */
261  *plugins_tail_chain_ptr = newplug;
262  plugins_tail_chain_ptr = &newplug->next;
263
264  /* Record it as current plugin for receiving args.  */
265  last_plugin = newplug;
266  last_plugin_args_tail_chain_ptr = &newplug->args;
267}
268
269/* Accumulate option arguments for last-loaded plugin, or return
270   error if none.  */
271int
272plugin_opt_plugin_arg (const char *arg)
273{
274  plugin_arg_t *newarg;
275
276  if (!last_plugin)
277    return set_plugin_error (_("<no plugin>"));
278
279  /* Ignore -pass-through= from GCC driver.  */
280  if (*arg == '-')
281    {
282      const char *p = arg + 1;
283
284      if (*p == '-')
285	++p;
286      if (strncmp (p, "pass-through=", 13) == 0)
287	return 0;
288    }
289
290  newarg = xmalloc (sizeof *newarg);
291  newarg->arg = arg;
292  newarg->next = NULL;
293
294  /* Chain on end to preserve command-line order.  */
295  *last_plugin_args_tail_chain_ptr = newarg;
296  last_plugin_args_tail_chain_ptr = &newarg->next;
297  last_plugin->n_args++;
298  return 0;
299}
300
301/* Generate a dummy BFD to represent an IR file, for any callers of
302   plugin_call_claim_file to use as the handle in the ld_plugin_input_file
303   struct that they build to pass in.  The BFD is initially writable, so
304   that symbols can be added to it; it must be made readable after the
305   add_symbols hook has been called so that it can be read when linking.  */
306static bfd *
307plugin_get_ir_dummy_bfd (const char *name, bfd *srctemplate)
308{
309  bfd *abfd;
310  bfd_boolean bfd_plugin_target;
311
312  bfd_use_reserved_id = 1;
313  bfd_plugin_target = bfd_plugin_target_p (srctemplate->xvec);
314  abfd = bfd_create (concat (name, IRONLY_SUFFIX, (const char *) NULL),
315		     bfd_plugin_target ? link_info.output_bfd : srctemplate);
316  if (abfd != NULL)
317    {
318      abfd->flags |= BFD_LINKER_CREATED | BFD_PLUGIN;
319      if (!bfd_make_writable (abfd))
320	goto report_error;
321      if (!bfd_plugin_target)
322	{
323	  bfd_set_arch_info (abfd, bfd_get_arch_info (srctemplate));
324	  bfd_set_gp_size (abfd, bfd_get_gp_size (srctemplate));
325	  if (!bfd_copy_private_bfd_data (srctemplate, abfd))
326	    goto report_error;
327	}
328	{
329	  flagword flags;
330
331	  /* Create section to own the symbols.  */
332	  flags = (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
333		   | SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_EXCLUDE);
334	  if (bfd_make_section_anyway_with_flags (abfd, ".text", flags))
335	    return abfd;
336	}
337    }
338report_error:
339  einfo (_("could not create dummy IR bfd: %F%E\n"));
340  return NULL;
341}
342
343/* Check if the BFD passed in is an IR dummy object file.  */
344static inline bfd_boolean
345is_ir_dummy_bfd (const bfd *abfd)
346{
347  /* ABFD can sometimes legitimately be NULL, e.g. when called from one
348     of the linker callbacks for a symbol in the *ABS* or *UND* sections.  */
349  return abfd != NULL && (abfd->flags & BFD_PLUGIN) != 0;
350}
351
352/* Helpers to convert between BFD and GOLD symbol formats.  */
353static enum ld_plugin_status
354asymbol_from_plugin_symbol (bfd *abfd, asymbol *asym,
355			    const struct ld_plugin_symbol *ldsym)
356{
357  flagword flags = BSF_NO_FLAGS;
358  struct bfd_section *section;
359
360  asym->the_bfd = abfd;
361  asym->name = (ldsym->version
362		? concat (ldsym->name, "@", ldsym->version, (const char *) NULL)
363		: ldsym->name);
364  asym->value = 0;
365  switch (ldsym->def)
366    {
367    case LDPK_WEAKDEF:
368      flags = BSF_WEAK;
369      /* FALLTHRU */
370    case LDPK_DEF:
371      flags |= BSF_GLOBAL;
372      if (ldsym->comdat_key)
373	{
374	  char *name = concat (".gnu.linkonce.t.", ldsym->comdat_key,
375			       (const char *) NULL);
376	  section = bfd_get_section_by_name (abfd, name);
377	  if (section != NULL)
378	    free (name);
379	  else
380	    {
381	      flagword sflags;
382
383	      sflags = (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
384			| SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_EXCLUDE
385			| SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD);
386	      section = bfd_make_section_anyway_with_flags (abfd, name, sflags);
387	      if (section == NULL)
388		return LDPS_ERR;
389	    }
390	}
391      else
392	section = bfd_get_section_by_name (abfd, ".text");
393      break;
394
395    case LDPK_WEAKUNDEF:
396      flags = BSF_WEAK;
397      /* FALLTHRU */
398    case LDPK_UNDEF:
399      section = bfd_und_section_ptr;
400      break;
401
402    case LDPK_COMMON:
403      flags = BSF_GLOBAL;
404      section = bfd_com_section_ptr;
405      asym->value = ldsym->size;
406      /* For ELF targets, set alignment of common symbol to 1.  */
407      if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
408	{
409	  ((elf_symbol_type *) asym)->internal_elf_sym.st_shndx = SHN_COMMON;
410	  ((elf_symbol_type *) asym)->internal_elf_sym.st_value = 1;
411	}
412      break;
413
414    default:
415      return LDPS_ERR;
416    }
417  asym->flags = flags;
418  asym->section = section;
419
420  /* Visibility only applies on ELF targets.  */
421  if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
422    {
423      elf_symbol_type *elfsym = elf_symbol_from (abfd, asym);
424      unsigned char visibility;
425
426      if (!elfsym)
427	einfo (_("%P%F: %s: non-ELF symbol in ELF BFD!\n"), asym->name);
428      switch (ldsym->visibility)
429	{
430	default:
431	  einfo (_("%P%F: unknown ELF symbol visibility: %d!\n"),
432		 ldsym->visibility);
433	  return LDPS_ERR;
434
435	case LDPV_DEFAULT:
436	  visibility = STV_DEFAULT;
437	  break;
438	case LDPV_PROTECTED:
439	  visibility = STV_PROTECTED;
440	  break;
441	case LDPV_INTERNAL:
442	  visibility = STV_INTERNAL;
443	  break;
444	case LDPV_HIDDEN:
445	  visibility = STV_HIDDEN;
446	  break;
447	}
448      elfsym->internal_elf_sym.st_other
449	= (visibility | (elfsym->internal_elf_sym.st_other
450			 & ~ELF_ST_VISIBILITY (-1)));
451    }
452
453  return LDPS_OK;
454}
455
456/* Register a claim-file handler.  */
457static enum ld_plugin_status
458register_claim_file (ld_plugin_claim_file_handler handler)
459{
460  ASSERT (called_plugin);
461  called_plugin->claim_file_handler = handler;
462  return LDPS_OK;
463}
464
465/* Register an all-symbols-read handler.  */
466static enum ld_plugin_status
467register_all_symbols_read (ld_plugin_all_symbols_read_handler handler)
468{
469  ASSERT (called_plugin);
470  called_plugin->all_symbols_read_handler = handler;
471  return LDPS_OK;
472}
473
474/* Register a cleanup handler.  */
475static enum ld_plugin_status
476register_cleanup (ld_plugin_cleanup_handler handler)
477{
478  ASSERT (called_plugin);
479  called_plugin->cleanup_handler = handler;
480  return LDPS_OK;
481}
482
483/* Add symbols from a plugin-claimed input file.  */
484static enum ld_plugin_status
485add_symbols (void *handle, int nsyms, const struct ld_plugin_symbol *syms)
486{
487  asymbol **symptrs;
488  plugin_input_file_t *input = handle;
489  bfd *abfd = input->abfd;
490  int n;
491
492  ASSERT (called_plugin);
493  symptrs = xmalloc (nsyms * sizeof *symptrs);
494  for (n = 0; n < nsyms; n++)
495    {
496      enum ld_plugin_status rv;
497      asymbol *bfdsym;
498
499      bfdsym = bfd_make_empty_symbol (abfd);
500      symptrs[n] = bfdsym;
501      rv = asymbol_from_plugin_symbol (abfd, bfdsym, syms + n);
502      if (rv != LDPS_OK)
503	return rv;
504    }
505  bfd_set_symtab (abfd, symptrs, nsyms);
506  return LDPS_OK;
507}
508
509/* Get the input file information with an open (possibly re-opened)
510   file descriptor.  */
511static enum ld_plugin_status
512get_input_file (const void *handle, struct ld_plugin_input_file *file)
513{
514  const plugin_input_file_t *input = handle;
515
516  ASSERT (called_plugin);
517
518  file->name = input->name;
519  file->offset = input->offset;
520  file->filesize = input->filesize;
521  file->handle = (void *) handle;
522
523  return LDPS_OK;
524}
525
526/* Get view of the input file.  */
527static enum ld_plugin_status
528get_view (const void *handle, const void **viewp)
529{
530  plugin_input_file_t *input = (plugin_input_file_t *) handle;
531  char *buffer;
532  size_t size = input->filesize;
533  off_t offset = input->offset;
534#if HAVE_MMAP && HAVE_GETPAGESIZE
535  off_t bias;
536#endif
537
538  ASSERT (called_plugin);
539
540  /* FIXME: einfo should support %lld.  */
541  if ((off_t) size != input->filesize)
542    einfo (_("%P%F: unsupported input file size: %s (%ld bytes)\n"),
543	   input->name, (long) input->filesize);
544
545  /* Check the cached view buffer.  */
546  if (input->view_buffer.addr != NULL
547      && input->view_buffer.filesize == size
548      && input->view_buffer.offset == offset)
549    {
550      *viewp = input->view_buffer.addr;
551      return LDPS_OK;
552    }
553
554  input->view_buffer.filesize = size;
555  input->view_buffer.offset = offset;
556
557#if HAVE_MMAP
558# if HAVE_GETPAGESIZE
559  bias = offset % plugin_pagesize;
560  offset -= bias;
561  size += bias;
562# endif
563  buffer = mmap (NULL, size, PROT_READ, MAP_PRIVATE, input->fd, offset);
564  if (buffer != MAP_FAILED)
565    {
566      input->use_mmap = TRUE;
567# if HAVE_GETPAGESIZE
568      buffer += bias;
569# endif
570    }
571  else
572#endif
573    {
574      char *p;
575
576      input->use_mmap = FALSE;
577
578      if (lseek (input->fd, offset, SEEK_SET) < 0)
579	return LDPS_ERR;
580
581      buffer = bfd_alloc (input->abfd, size);
582      if (buffer == NULL)
583	return LDPS_ERR;
584
585      p = buffer;
586      do
587	{
588	  ssize_t got = read (input->fd, p, size);
589	  if (got == 0)
590	    break;
591	  else if (got > 0)
592	    {
593	      p += got;
594	      size -= got;
595	    }
596	  else if (errno != EINTR)
597	    return LDPS_ERR;
598	}
599      while (size > 0);
600    }
601
602  input->view_buffer.addr = buffer;
603  *viewp = buffer;
604
605  return LDPS_OK;
606}
607
608/* Release the input file.  */
609static enum ld_plugin_status
610release_input_file (const void *handle)
611{
612  plugin_input_file_t *input = (plugin_input_file_t *) handle;
613  ASSERT (called_plugin);
614  if (input->fd != -1)
615    {
616      close (input->fd);
617      input->fd = -1;
618    }
619  return LDPS_OK;
620}
621
622/* Return TRUE if a defined symbol might be reachable from outside the
623   universe of claimed objects.  */
624static inline bfd_boolean
625is_visible_from_outside (struct ld_plugin_symbol *lsym,
626			 struct bfd_link_hash_entry *blhe)
627{
628  struct bfd_sym_chain *sym;
629
630  if (bfd_link_relocatable (&link_info))
631    return TRUE;
632  if (link_info.export_dynamic || bfd_link_dll (&link_info))
633    {
634      /* Check if symbol is hidden by version script.  */
635      if (bfd_hide_sym_by_version (link_info.version_info,
636				   blhe->root.string))
637	return FALSE;
638      /* Only ELF symbols really have visibility.  */
639      if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
640	{
641	  struct elf_link_hash_entry *el = (struct elf_link_hash_entry *)blhe;
642	  int vis = ELF_ST_VISIBILITY (el->other);
643	  return vis == STV_DEFAULT || vis == STV_PROTECTED;
644	}
645      /* On non-ELF targets, we can safely make inferences by considering
646	 what visibility the plugin would have liked to apply when it first
647	 sent us the symbol.  During ELF symbol processing, visibility only
648	 ever becomes more restrictive, not less, when symbols are merged,
649	 so this is a conservative estimate; it may give false positives,
650	 declaring something visible from outside when it in fact would
651	 not have been, but this will only lead to missed optimisation
652	 opportunities during LTRANS at worst; it will not give false
653	 negatives, which can lead to the disastrous conclusion that the
654	 related symbol is IRONLY.  (See GCC PR46319 for an example.)  */
655      return (lsym->visibility == LDPV_DEFAULT
656	      || lsym->visibility == LDPV_PROTECTED);
657    }
658
659  for (sym = &entry_symbol; sym != NULL; sym = sym->next)
660    if (sym->name
661	&& strcmp (sym->name, blhe->root.string) == 0)
662      return TRUE;
663
664  return FALSE;
665}
666
667/* Get the symbol resolution info for a plugin-claimed input file.  */
668static enum ld_plugin_status
669get_symbols (const void *handle, int nsyms, struct ld_plugin_symbol *syms,
670	     int def_ironly_exp)
671{
672  const plugin_input_file_t *input = handle;
673  const bfd *abfd = (const bfd *) input->abfd;
674  int n;
675
676  ASSERT (called_plugin);
677  for (n = 0; n < nsyms; n++)
678    {
679      struct bfd_link_hash_entry *blhe;
680      asection *owner_sec;
681      int res;
682
683      if (syms[n].def != LDPK_UNDEF)
684	blhe = bfd_link_hash_lookup (link_info.hash, syms[n].name,
685				     FALSE, FALSE, TRUE);
686      else
687	blhe = bfd_wrapped_link_hash_lookup (link_info.output_bfd, &link_info,
688					     syms[n].name, FALSE, FALSE, TRUE);
689      if (!blhe)
690	{
691	  /* The plugin is called to claim symbols in an archive element
692	     from plugin_object_p.  But those symbols aren't needed to
693	     create output.  They are defined and referenced only within
694	     IR.  */
695	  switch (syms[n].def)
696	    {
697	    default:
698	      abort ();
699	    case LDPK_UNDEF:
700	    case LDPK_WEAKUNDEF:
701	      res = LDPR_UNDEF;
702	      break;
703	    case LDPK_DEF:
704	    case LDPK_WEAKDEF:
705	    case LDPK_COMMON:
706	      res = LDPR_PREVAILING_DEF_IRONLY;
707	      break;
708	    }
709	  goto report_symbol;
710	}
711
712      /* Determine resolution from blhe type and symbol's original type.  */
713      if (blhe->type == bfd_link_hash_undefined
714	  || blhe->type == bfd_link_hash_undefweak)
715	{
716	  res = LDPR_UNDEF;
717	  goto report_symbol;
718	}
719      if (blhe->type != bfd_link_hash_defined
720	  && blhe->type != bfd_link_hash_defweak
721	  && blhe->type != bfd_link_hash_common)
722	{
723	  /* We should not have a new, indirect or warning symbol here.  */
724	  einfo ("%P%F: %s: plugin symbol table corrupt (sym type %d)\n",
725		 called_plugin->name, blhe->type);
726	}
727
728      /* Find out which section owns the symbol.  Since it's not undef,
729	 it must have an owner; if it's not a common symbol, both defs
730	 and weakdefs keep it in the same place. */
731      owner_sec = (blhe->type == bfd_link_hash_common
732		   ? blhe->u.c.p->section
733		   : blhe->u.def.section);
734
735
736      /* If it was originally undefined or common, then it has been
737	 resolved; determine how.  */
738      if (syms[n].def == LDPK_UNDEF
739	  || syms[n].def == LDPK_WEAKUNDEF
740	  || syms[n].def == LDPK_COMMON)
741	{
742	  if (owner_sec->owner == link_info.output_bfd)
743	    res = LDPR_RESOLVED_EXEC;
744	  else if (owner_sec->owner == abfd)
745	    res = LDPR_PREVAILING_DEF_IRONLY;
746	  else if (is_ir_dummy_bfd (owner_sec->owner))
747	    res = LDPR_RESOLVED_IR;
748	  else if (owner_sec->owner != NULL
749		   && (owner_sec->owner->flags & DYNAMIC) != 0)
750	    res = LDPR_RESOLVED_DYN;
751	  else
752	    res = LDPR_RESOLVED_EXEC;
753	}
754
755      /* Was originally def, or weakdef.  Does it prevail?  If the
756	 owner is the original dummy bfd that supplied it, then this
757	 is the definition that has prevailed.  */
758      else if (owner_sec->owner == link_info.output_bfd)
759	res = LDPR_PREEMPTED_REG;
760      else if (owner_sec->owner == abfd)
761	res = LDPR_PREVAILING_DEF_IRONLY;
762
763      /* Was originally def, weakdef, or common, but has been pre-empted.  */
764      else if (is_ir_dummy_bfd (owner_sec->owner))
765	res = LDPR_PREEMPTED_IR;
766      else
767	res = LDPR_PREEMPTED_REG;
768
769      if (res == LDPR_PREVAILING_DEF_IRONLY)
770	{
771	  /* We need to know if the sym is referenced from non-IR files.  Or
772	     even potentially-referenced, perhaps in a future final link if
773	     this is a partial one, perhaps dynamically at load-time if the
774	     symbol is externally visible.  */
775	  if (blhe->non_ir_ref)
776	    res = LDPR_PREVAILING_DEF;
777	  else if (is_visible_from_outside (&syms[n], blhe))
778	    res = def_ironly_exp;
779	}
780
781    report_symbol:
782      syms[n].resolution = res;
783      if (report_plugin_symbols)
784	einfo (_("%P: %B: symbol `%s' "
785		 "definition: %d, visibility: %d, resolution: %d\n"),
786	       abfd, syms[n].name,
787	       syms[n].def, syms[n].visibility, res);
788    }
789  return LDPS_OK;
790}
791
792static enum ld_plugin_status
793get_symbols_v1 (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
794{
795  return get_symbols (handle, nsyms, syms, LDPR_PREVAILING_DEF);
796}
797
798static enum ld_plugin_status
799get_symbols_v2 (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
800{
801  return get_symbols (handle, nsyms, syms, LDPR_PREVAILING_DEF_IRONLY_EXP);
802}
803
804/* Add a new (real) input file generated by a plugin.  */
805static enum ld_plugin_status
806add_input_file (const char *pathname)
807{
808  lang_input_statement_type *is;
809
810  ASSERT (called_plugin);
811  is = lang_add_input_file (xstrdup (pathname), lang_input_file_is_file_enum,
812			    NULL);
813  if (!is)
814    return LDPS_ERR;
815  is->flags.lto_output = 1;
816  return LDPS_OK;
817}
818
819/* Add a new (real) library required by a plugin.  */
820static enum ld_plugin_status
821add_input_library (const char *pathname)
822{
823  lang_input_statement_type *is;
824
825  ASSERT (called_plugin);
826  is = lang_add_input_file (xstrdup (pathname), lang_input_file_is_l_enum,
827			    NULL);
828  if (!is)
829    return LDPS_ERR;
830  is->flags.lto_output = 1;
831  return LDPS_OK;
832}
833
834/* Set the extra library path to be used by libraries added via
835   add_input_library.  */
836static enum ld_plugin_status
837set_extra_library_path (const char *path)
838{
839  ASSERT (called_plugin);
840  ldfile_add_library_path (xstrdup (path), FALSE);
841  return LDPS_OK;
842}
843
844/* Issue a diagnostic message from a plugin.  */
845static enum ld_plugin_status
846message (int level, const char *format, ...)
847{
848  va_list args;
849  va_start (args, format);
850
851  switch (level)
852    {
853    case LDPL_INFO:
854      vfinfo (stdout, format, args, FALSE);
855      putchar ('\n');
856      break;
857    case LDPL_WARNING:
858      {
859	char *newfmt = concat ("%P: warning: ", format, "\n",
860			       (const char *) NULL);
861	vfinfo (stdout, newfmt, args, TRUE);
862	free (newfmt);
863      }
864      break;
865    case LDPL_FATAL:
866    case LDPL_ERROR:
867    default:
868      {
869	char *newfmt = concat (level == LDPL_FATAL ? "%P%F" : "%P%X",
870			       ": error: ", format, "\n",
871			       (const char *) NULL);
872	fflush (stdout);
873	vfinfo (stderr, newfmt, args, TRUE);
874	fflush (stderr);
875	free (newfmt);
876      }
877      break;
878    }
879
880  va_end (args);
881  return LDPS_OK;
882}
883
884/* Helper to size leading part of tv array and set it up. */
885static void
886set_tv_header (struct ld_plugin_tv *tv)
887{
888  size_t i;
889
890  /* Version info.  */
891  static const unsigned int major = (unsigned)(BFD_VERSION / 100000000UL);
892  static const unsigned int minor = (unsigned)(BFD_VERSION / 1000000UL) % 100;
893
894  for (i = 0; i < tv_header_size; i++)
895    {
896      tv[i].tv_tag = tv_header_tags[i];
897#define TVU(x) tv[i].tv_u.tv_ ## x
898      switch (tv[i].tv_tag)
899	{
900	case LDPT_MESSAGE:
901	  TVU(message) = message;
902	  break;
903	case LDPT_API_VERSION:
904	  TVU(val) = LD_PLUGIN_API_VERSION;
905	  break;
906	case LDPT_GNU_LD_VERSION:
907	  TVU(val) = major * 100 + minor;
908	  break;
909	case LDPT_LINKER_OUTPUT:
910	  TVU(val) = (bfd_link_relocatable (&link_info) ? LDPO_REL
911		      : bfd_link_pde (&link_info) ? LDPO_EXEC
912		      : bfd_link_pie (&link_info) ? LDPO_PIE
913		      : LDPO_DYN);
914	  break;
915	case LDPT_OUTPUT_NAME:
916	  TVU(string) = output_filename;
917	  break;
918	case LDPT_REGISTER_CLAIM_FILE_HOOK:
919	  TVU(register_claim_file) = register_claim_file;
920	  break;
921	case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
922	  TVU(register_all_symbols_read) = register_all_symbols_read;
923	  break;
924	case LDPT_REGISTER_CLEANUP_HOOK:
925	  TVU(register_cleanup) = register_cleanup;
926	  break;
927	case LDPT_ADD_SYMBOLS:
928	  TVU(add_symbols) = add_symbols;
929	  break;
930	case LDPT_GET_INPUT_FILE:
931	  TVU(get_input_file) = get_input_file;
932	  break;
933	case LDPT_GET_VIEW:
934	  TVU(get_view) = get_view;
935	  break;
936	case LDPT_RELEASE_INPUT_FILE:
937	  TVU(release_input_file) = release_input_file;
938	  break;
939	case LDPT_GET_SYMBOLS:
940	  TVU(get_symbols) = get_symbols_v1;
941	  break;
942	case LDPT_GET_SYMBOLS_V2:
943	  TVU(get_symbols) = get_symbols_v2;
944	  break;
945	case LDPT_ADD_INPUT_FILE:
946	  TVU(add_input_file) = add_input_file;
947	  break;
948	case LDPT_ADD_INPUT_LIBRARY:
949	  TVU(add_input_library) = add_input_library;
950	  break;
951	case LDPT_SET_EXTRA_LIBRARY_PATH:
952	  TVU(set_extra_library_path) = set_extra_library_path;
953	  break;
954	default:
955	  /* Added a new entry to the array without adding
956	     a new case to set up its value is a bug.  */
957	  FAIL ();
958	}
959#undef TVU
960    }
961}
962
963/* Append the per-plugin args list and trailing LDPT_NULL to tv.  */
964static void
965set_tv_plugin_args (plugin_t *plugin, struct ld_plugin_tv *tv)
966{
967  plugin_arg_t *arg = plugin->args;
968  while (arg)
969    {
970      tv->tv_tag = LDPT_OPTION;
971      tv->tv_u.tv_string = arg->arg;
972      arg = arg->next;
973      tv++;
974    }
975  tv->tv_tag = LDPT_NULL;
976  tv->tv_u.tv_val = 0;
977}
978
979/* Load up and initialise all plugins after argument parsing.  */
980void
981plugin_load_plugins (void)
982{
983  struct ld_plugin_tv *my_tv;
984  unsigned int max_args = 0;
985  plugin_t *curplug = plugins_list;
986
987  /* If there are no plugins, we need do nothing this run.  */
988  if (!curplug)
989    return;
990
991  /* First pass over plugins to find max # args needed so that we
992     can size and allocate the tv array.  */
993  while (curplug)
994    {
995      if (curplug->n_args > max_args)
996	max_args = curplug->n_args;
997      curplug = curplug->next;
998    }
999
1000  /* Allocate tv array and initialise constant part.  */
1001  my_tv = xmalloc ((max_args + 1 + tv_header_size) * sizeof *my_tv);
1002  set_tv_header (my_tv);
1003
1004  /* Pass over plugins again, activating them.  */
1005  curplug = plugins_list;
1006  while (curplug)
1007    {
1008      enum ld_plugin_status rv;
1009      ld_plugin_onload onloadfn;
1010
1011      onloadfn = (ld_plugin_onload) dlsym (curplug->dlhandle, "onload");
1012      if (!onloadfn)
1013	onloadfn = (ld_plugin_onload) dlsym (curplug->dlhandle, "_onload");
1014      if (!onloadfn)
1015        einfo (_("%P%F: %s: error loading plugin: %s\n"),
1016	       curplug->name, dlerror ());
1017      set_tv_plugin_args (curplug, &my_tv[tv_header_size]);
1018      called_plugin = curplug;
1019      rv = (*onloadfn) (my_tv);
1020      called_plugin = NULL;
1021      if (rv != LDPS_OK)
1022	einfo (_("%P%F: %s: plugin error: %d\n"), curplug->name, rv);
1023      curplug = curplug->next;
1024    }
1025
1026  /* Since plugin(s) inited ok, assume they're going to want symbol
1027     resolutions, which needs us to track which symbols are referenced
1028     by non-IR files using the linker's notice callback.  */
1029  orig_notice_all = link_info.notice_all;
1030  orig_callbacks = link_info.callbacks;
1031  plugin_callbacks = *orig_callbacks;
1032  plugin_callbacks.notice = &plugin_notice;
1033  link_info.notice_all = TRUE;
1034  link_info.lto_plugin_active = TRUE;
1035  link_info.callbacks = &plugin_callbacks;
1036
1037  register_ld_plugin_object_p (plugin_object_p);
1038
1039#if HAVE_MMAP && HAVE_GETPAGESIZE
1040  plugin_pagesize = getpagesize ();
1041#endif
1042}
1043
1044/* Call 'claim file' hook for all plugins.  */
1045static int
1046plugin_call_claim_file (const struct ld_plugin_input_file *file, int *claimed)
1047{
1048  plugin_t *curplug = plugins_list;
1049  *claimed = FALSE;
1050  while (curplug && !*claimed)
1051    {
1052      if (curplug->claim_file_handler)
1053	{
1054	  off_t cur_offset;
1055	  enum ld_plugin_status rv;
1056
1057	  called_plugin = curplug;
1058	  cur_offset = lseek (file->fd, 0, SEEK_CUR);
1059	  rv = (*curplug->claim_file_handler) (file, claimed);
1060	  if (!*claimed)
1061	    lseek (file->fd, cur_offset, SEEK_SET);
1062	  called_plugin = NULL;
1063	  if (rv != LDPS_OK)
1064	    set_plugin_error (curplug->name);
1065	}
1066      curplug = curplug->next;
1067    }
1068  return plugin_error_p () ? -1 : 0;
1069}
1070
1071/* Duplicates a character string with memory attached to ABFD.  */
1072
1073static char *
1074plugin_strdup (bfd *abfd, const char *str)
1075{
1076  size_t strlength;
1077  char *copy;
1078  strlength = strlen (str) + 1;
1079  copy = bfd_alloc (abfd, strlength);
1080  if (copy == NULL)
1081    einfo (_("%P%F: plugin_strdup failed to allocate memory: %s\n"),
1082	   bfd_get_error ());
1083  memcpy (copy, str, strlength);
1084  return copy;
1085}
1086
1087static const bfd_target *
1088plugin_object_p (bfd *ibfd)
1089{
1090  int claimed;
1091  plugin_input_file_t *input;
1092  struct ld_plugin_input_file file;
1093  bfd *abfd;
1094
1095  /* Don't try the dummy object file.  */
1096  if ((ibfd->flags & BFD_PLUGIN) != 0)
1097    return NULL;
1098
1099  if (ibfd->plugin_format != bfd_plugin_unknown)
1100    {
1101      if (ibfd->plugin_format == bfd_plugin_yes)
1102	return ibfd->plugin_dummy_bfd->xvec;
1103      else
1104	return NULL;
1105    }
1106
1107  /* We create a dummy BFD, initially empty, to house whatever symbols
1108     the plugin may want to add.  */
1109  abfd = plugin_get_ir_dummy_bfd (ibfd->filename, ibfd);
1110
1111  input = bfd_alloc (abfd, sizeof (*input));
1112  if (input == NULL)
1113    einfo (_("%P%F: plugin failed to allocate memory for input: %s\n"),
1114	   bfd_get_error ());
1115
1116  if (!bfd_plugin_open_input (ibfd, &file))
1117    return NULL;
1118
1119  if (file.name == ibfd->filename)
1120    {
1121      /* We must copy filename attached to ibfd if it is not an archive
1122	 member since it may be freed by bfd_close below.  */
1123      file.name = plugin_strdup (abfd, file.name);
1124    }
1125
1126  file.handle = input;
1127  /* The plugin API expects that the file descriptor won't be closed
1128     and reused as done by the bfd file cache.  So dup one.  */
1129  file.fd = dup (file.fd);
1130  if (file.fd < 0)
1131    return NULL;
1132
1133  input->abfd = abfd;
1134  input->view_buffer.addr = NULL;
1135  input->view_buffer.filesize = 0;
1136  input->view_buffer.offset = 0;
1137  input->fd = file.fd;
1138  input->use_mmap = FALSE;
1139  input->offset = file.offset;
1140  input->filesize = file.filesize;
1141  input->name = plugin_strdup (abfd, ibfd->filename);
1142
1143  claimed = 0;
1144
1145  if (plugin_call_claim_file (&file, &claimed))
1146    einfo (_("%P%F: %s: plugin reported error claiming file\n"),
1147	   plugin_error_plugin ());
1148
1149  if (input->fd != -1 && !bfd_plugin_target_p (ibfd->xvec))
1150    {
1151      /* FIXME: fd belongs to us, not the plugin.  GCC plugin, which
1152	 doesn't need fd after plugin_call_claim_file, doesn't use
1153	 BFD plugin target vector.  Since GCC plugin doesn't call
1154	 release_input_file, we close it here.  LLVM plugin, which
1155	 needs fd after plugin_call_claim_file and calls
1156	 release_input_file after it is done, uses BFD plugin target
1157	 vector.  This scheme doesn't work when a plugin needs fd and
1158	 doesn't use BFD plugin target vector neither.  */
1159      close (input->fd);
1160      input->fd = -1;
1161    }
1162
1163  if (claimed)
1164    {
1165      ibfd->plugin_format = bfd_plugin_yes;
1166      ibfd->plugin_dummy_bfd = abfd;
1167      bfd_make_readable (abfd);
1168      return abfd->xvec;
1169    }
1170  else
1171    {
1172#if HAVE_MMAP
1173      if (input->use_mmap)
1174	{
1175	  /* If plugin didn't claim the file, unmap the buffer.  */
1176	  char *addr = input->view_buffer.addr;
1177	  off_t size = input->view_buffer.filesize;
1178# if HAVE_GETPAGESIZE
1179	  off_t bias = input->view_buffer.offset % plugin_pagesize;
1180	  size += bias;
1181	  addr -= bias;
1182# endif
1183	  munmap (addr, size);
1184	}
1185#endif
1186
1187      /* If plugin didn't claim the file, we don't need the dummy bfd.
1188	 Can't avoid speculatively creating it, alas.  */
1189      ibfd->plugin_format = bfd_plugin_no;
1190      bfd_close_all_done (abfd);
1191      return NULL;
1192    }
1193}
1194
1195void
1196plugin_maybe_claim (lang_input_statement_type *entry)
1197{
1198  ASSERT (entry->header.type == lang_input_statement_enum);
1199  if (plugin_object_p (entry->the_bfd))
1200    {
1201      bfd *abfd = entry->the_bfd->plugin_dummy_bfd;
1202
1203      /* Discard the real file's BFD and substitute the dummy one.  */
1204
1205      /* We can't call bfd_close on archives.  BFD archive handling
1206	 caches elements, and add_archive_element keeps pointers to
1207	 the_bfd and the_bfd->filename in a lang_input_statement_type
1208	 linker script statement.  */
1209      if (entry->the_bfd->my_archive == NULL)
1210	bfd_close (entry->the_bfd);
1211      entry->the_bfd = abfd;
1212      entry->flags.claimed = 1;
1213    }
1214}
1215
1216/* Call 'all symbols read' hook for all plugins.  */
1217int
1218plugin_call_all_symbols_read (void)
1219{
1220  plugin_t *curplug = plugins_list;
1221
1222  /* Disable any further file-claiming.  */
1223  no_more_claiming = TRUE;
1224
1225  while (curplug)
1226    {
1227      if (curplug->all_symbols_read_handler)
1228	{
1229	  enum ld_plugin_status rv;
1230	  called_plugin = curplug;
1231	  rv = (*curplug->all_symbols_read_handler) ();
1232	  called_plugin = NULL;
1233	  if (rv != LDPS_OK)
1234	    set_plugin_error (curplug->name);
1235	}
1236      curplug = curplug->next;
1237    }
1238  return plugin_error_p () ? -1 : 0;
1239}
1240
1241/* Call 'cleanup' hook for all plugins at exit.  */
1242void
1243plugin_call_cleanup (void)
1244{
1245  plugin_t *curplug = plugins_list;
1246  while (curplug)
1247    {
1248      if (curplug->cleanup_handler && !curplug->cleanup_done)
1249	{
1250	  enum ld_plugin_status rv;
1251	  curplug->cleanup_done = TRUE;
1252	  called_plugin = curplug;
1253	  rv = (*curplug->cleanup_handler) ();
1254	  called_plugin = NULL;
1255	  if (rv != LDPS_OK)
1256	    info_msg (_("%P: %s: error in plugin cleanup: %d (ignored)\n"),
1257		      curplug->name, rv);
1258	  dlclose (curplug->dlhandle);
1259	}
1260      curplug = curplug->next;
1261    }
1262}
1263
1264/* To determine which symbols should be resolved LDPR_PREVAILING_DEF
1265   and which LDPR_PREVAILING_DEF_IRONLY, we notice all the symbols as
1266   the linker adds them to the linker hash table.  Mark those
1267   referenced from a non-IR file with non_ir_ref.  We have to
1268   notice_all symbols, because we won't necessarily know until later
1269   which ones will be contributed by IR files.  */
1270static bfd_boolean
1271plugin_notice (struct bfd_link_info *info,
1272	       struct bfd_link_hash_entry *h,
1273	       struct bfd_link_hash_entry *inh,
1274	       bfd *abfd,
1275	       asection *section,
1276	       bfd_vma value,
1277	       flagword flags)
1278{
1279  struct bfd_link_hash_entry *orig_h = h;
1280
1281  if (h != NULL)
1282    {
1283      bfd *sym_bfd;
1284
1285      if (h->type == bfd_link_hash_warning)
1286	h = h->u.i.link;
1287
1288      /* Nothing to do here if this def/ref is from an IR dummy BFD.  */
1289      if (is_ir_dummy_bfd (abfd))
1290	;
1291
1292      /* Making an indirect symbol counts as a reference unless this
1293	 is a brand new symbol.  */
1294      else if (bfd_is_ind_section (section)
1295	       || (flags & BSF_INDIRECT) != 0)
1296	{
1297	  /* ??? Some of this is questionable.  See comments in
1298	     _bfd_generic_link_add_one_symbol for case IND.  */
1299	  if (h->type != bfd_link_hash_new)
1300	    {
1301	      h->non_ir_ref = TRUE;
1302	      inh->non_ir_ref = TRUE;
1303	    }
1304	  else if (inh->type == bfd_link_hash_new)
1305	    inh->non_ir_ref = TRUE;
1306	}
1307
1308      /* Nothing to do here for warning symbols.  */
1309      else if ((flags & BSF_WARNING) != 0)
1310	;
1311
1312      /* Nothing to do here for constructor symbols.  */
1313      else if ((flags & BSF_CONSTRUCTOR) != 0)
1314	;
1315
1316      /* If this is a ref, set non_ir_ref.  */
1317      else if (bfd_is_und_section (section))
1318	{
1319	  /* Replace the undefined dummy bfd with the real one.  */
1320	  if ((h->type == bfd_link_hash_undefined
1321	       || h->type == bfd_link_hash_undefweak)
1322	      && (h->u.undef.abfd == NULL
1323		  || (h->u.undef.abfd->flags & BFD_PLUGIN) != 0))
1324	    h->u.undef.abfd = abfd;
1325	  h->non_ir_ref = TRUE;
1326	}
1327
1328      /* Otherwise, it must be a new def.  */
1329      else
1330	{
1331	  /* A common symbol should be merged with other commons or
1332	     defs with the same name.  In particular, a common ought
1333	     to be overridden by a def in a -flto object.  In that
1334	     sense a common is also a ref.  */
1335	  if (bfd_is_com_section (section))
1336	    h->non_ir_ref = TRUE;
1337
1338	  /* Ensure any symbol defined in an IR dummy BFD takes on a
1339	     new value from a real BFD.  Weak symbols are not normally
1340	     overridden by a new weak definition, and strong symbols
1341	     will normally cause multiple definition errors.  Avoid
1342	     this by making the symbol appear to be undefined.  */
1343	  if (((h->type == bfd_link_hash_defweak
1344		|| h->type == bfd_link_hash_defined)
1345	       && is_ir_dummy_bfd (sym_bfd = h->u.def.section->owner))
1346	      || (h->type == bfd_link_hash_common
1347		  && is_ir_dummy_bfd (sym_bfd = h->u.c.p->section->owner)))
1348	    {
1349	      h->type = bfd_link_hash_undefweak;
1350	      h->u.undef.abfd = sym_bfd;
1351	    }
1352	}
1353    }
1354
1355  /* Continue with cref/nocrossref/trace-sym processing.  */
1356  if (orig_h == NULL
1357      || orig_notice_all
1358      || (info->notice_hash != NULL
1359	  && bfd_hash_lookup (info->notice_hash, orig_h->root.string,
1360			      FALSE, FALSE) != NULL))
1361    return (*orig_callbacks->notice) (info, orig_h, inh,
1362				      abfd, section, value, flags);
1363  return TRUE;
1364}
1365