• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Plugin control for the GNU linker.
2    Copyright (C) 2010-2014 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.h"
33 #include "plugin-api.h"
34 #include "elf-bfd.h"
35 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
36 #include <windows.h>
37 #endif
38 
39 /* Report plugin symbols.  */
40 bfd_boolean report_plugin_symbols;
41 
42 /* The suffix to append to the name of the real (claimed) object file
43    when generating a dummy BFD to hold the IR symbols sent from the
44    plugin.  For cosmetic use only; appears in maps, crefs etc.  */
45 #define IRONLY_SUFFIX " (symbol from plugin)"
46 
47 /* Stores a single argument passed to a plugin.  */
48 typedef struct plugin_arg
49 {
50   struct plugin_arg *next;
51   const char *arg;
52 } plugin_arg_t;
53 
54 /* Holds all details of a single plugin.  */
55 typedef struct plugin
56 {
57   /* Next on the list of plugins, or NULL at end of chain.  */
58   struct plugin *next;
59   /* The argument string given to --plugin.  */
60   const char *name;
61   /* The shared library handle returned by dlopen.  */
62   void *dlhandle;
63   /* The list of argument string given to --plugin-opt.  */
64   plugin_arg_t *args;
65   /* Number of args in the list, for convenience.  */
66   size_t n_args;
67   /* The plugin's event handlers.  */
68   ld_plugin_claim_file_handler claim_file_handler;
69   ld_plugin_all_symbols_read_handler all_symbols_read_handler;
70   ld_plugin_cleanup_handler cleanup_handler;
71   /* TRUE if the cleanup handlers have been called.  */
72   bfd_boolean cleanup_done;
73 } plugin_t;
74 
75 /* The master list of all plugins.  */
76 static plugin_t *plugins_list = NULL;
77 
78 /* We keep a tail pointer for easy linking on the end.  */
79 static plugin_t **plugins_tail_chain_ptr = &plugins_list;
80 
81 /* The last plugin added to the list, for receiving args.  */
82 static plugin_t *last_plugin = NULL;
83 
84 /* The tail of the arg chain of the last plugin added to the list.  */
85 static plugin_arg_t **last_plugin_args_tail_chain_ptr = NULL;
86 
87 /* The plugin which is currently having a callback executed.  */
88 static plugin_t *called_plugin = NULL;
89 
90 /* Last plugin to cause an error, if any.  */
91 static const char *error_plugin = NULL;
92 
93 /* State of linker "notice" interface before we poked at it.  */
94 static bfd_boolean orig_notice_all;
95 
96 /* Original linker callbacks, and the plugin version.  */
97 static const struct bfd_link_callbacks *orig_callbacks;
98 static struct bfd_link_callbacks plugin_callbacks;
99 
100 /* Set at all symbols read time, to avoid recursively offering the plugin
101    its own newly-added input files and libs to claim.  */
102 bfd_boolean no_more_claiming = FALSE;
103 
104 /* List of tags to set in the constant leading part of the tv array. */
105 static const enum ld_plugin_tag tv_header_tags[] =
106 {
107   LDPT_MESSAGE,
108   LDPT_API_VERSION,
109   LDPT_GNU_LD_VERSION,
110   LDPT_LINKER_OUTPUT,
111   LDPT_OUTPUT_NAME,
112   LDPT_REGISTER_CLAIM_FILE_HOOK,
113   LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK,
114   LDPT_REGISTER_CLEANUP_HOOK,
115   LDPT_ADD_SYMBOLS,
116   LDPT_GET_INPUT_FILE,
117   LDPT_RELEASE_INPUT_FILE,
118   LDPT_GET_SYMBOLS,
119   LDPT_GET_SYMBOLS_V2,
120   LDPT_ADD_INPUT_FILE,
121   LDPT_ADD_INPUT_LIBRARY,
122   LDPT_SET_EXTRA_LIBRARY_PATH
123 };
124 
125 /* How many entries in the constant leading part of the tv array.  */
126 static const size_t tv_header_size = ARRAY_SIZE (tv_header_tags);
127 
128 /* Forward references.  */
129 static bfd_boolean plugin_notice (struct bfd_link_info *,
130 				  struct bfd_link_hash_entry *,
131 				  struct bfd_link_hash_entry *,
132 				  bfd *, asection *, bfd_vma, flagword);
133 
134 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
135 
136 #define RTLD_NOW 0	/* Dummy value.  */
137 
138 static void *
dlopen(const char * file,int mode ATTRIBUTE_UNUSED)139 dlopen (const char *file, int mode ATTRIBUTE_UNUSED)
140 {
141   return LoadLibrary (file);
142 }
143 
144 static void *
dlsym(void * handle,const char * name)145 dlsym (void *handle, const char *name)
146 {
147   return GetProcAddress (handle, name);
148 }
149 
150 static int
dlclose(void * handle)151 dlclose (void *handle)
152 {
153   FreeLibrary (handle);
154   return 0;
155 }
156 
157 #endif /* !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)  */
158 
159 #ifndef HAVE_DLFCN_H
160 static const char *
dlerror(void)161 dlerror (void)
162 {
163   return "";
164 }
165 #endif
166 
167 /* Helper function for exiting with error status.  */
168 static int
set_plugin_error(const char * plugin)169 set_plugin_error (const char *plugin)
170 {
171   error_plugin = plugin;
172   return -1;
173 }
174 
175 /* Test if an error occurred.  */
176 static bfd_boolean
plugin_error_p(void)177 plugin_error_p (void)
178 {
179   return error_plugin != NULL;
180 }
181 
182 /* Return name of plugin which caused an error if any.  */
183 const char *
plugin_error_plugin(void)184 plugin_error_plugin (void)
185 {
186   return error_plugin ? error_plugin : _("<no plugin>");
187 }
188 
189 /* Handle -plugin arg: find and load plugin, or return error.  */
190 void
plugin_opt_plugin(const char * plugin)191 plugin_opt_plugin (const char *plugin)
192 {
193   plugin_t *newplug;
194 
195   newplug = xmalloc (sizeof *newplug);
196   memset (newplug, 0, sizeof *newplug);
197   newplug->name = plugin;
198   newplug->dlhandle = dlopen (plugin, RTLD_NOW);
199   if (!newplug->dlhandle)
200     einfo (_("%P%F: %s: error loading plugin: %s\n"), plugin, dlerror ());
201 
202   /* Chain on end, so when we run list it is in command-line order.  */
203   *plugins_tail_chain_ptr = newplug;
204   plugins_tail_chain_ptr = &newplug->next;
205 
206   /* Record it as current plugin for receiving args.  */
207   last_plugin = newplug;
208   last_plugin_args_tail_chain_ptr = &newplug->args;
209 }
210 
211 /* Accumulate option arguments for last-loaded plugin, or return
212    error if none.  */
213 int
plugin_opt_plugin_arg(const char * arg)214 plugin_opt_plugin_arg (const char *arg)
215 {
216   plugin_arg_t *newarg;
217 
218   if (!last_plugin)
219     return set_plugin_error (_("<no plugin>"));
220 
221   /* Ignore -pass-through= from GCC driver.  */
222   if (*arg == '-')
223     {
224       const char *p = arg + 1;
225 
226       if (*p == '-')
227 	++p;
228       if (strncmp (p, "pass-through=", 13) == 0)
229 	return 0;
230     }
231 
232   newarg = xmalloc (sizeof *newarg);
233   newarg->arg = arg;
234   newarg->next = NULL;
235 
236   /* Chain on end to preserve command-line order.  */
237   *last_plugin_args_tail_chain_ptr = newarg;
238   last_plugin_args_tail_chain_ptr = &newarg->next;
239   last_plugin->n_args++;
240   return 0;
241 }
242 
243 /* Create a dummy BFD.  */
244 bfd *
plugin_get_ir_dummy_bfd(const char * name,bfd * srctemplate)245 plugin_get_ir_dummy_bfd (const char *name, bfd *srctemplate)
246 {
247   bfd *abfd;
248 
249   bfd_use_reserved_id = 1;
250   abfd = bfd_create (concat (name, IRONLY_SUFFIX, (const char *) NULL),
251 		     srctemplate);
252   if (abfd != NULL)
253     {
254       abfd->flags |= BFD_LINKER_CREATED | BFD_PLUGIN;
255       bfd_set_arch_info (abfd, bfd_get_arch_info (srctemplate));
256       bfd_set_gp_size (abfd, bfd_get_gp_size (srctemplate));
257       if (bfd_make_writable (abfd)
258 	  && bfd_copy_private_bfd_data (srctemplate, abfd))
259 	{
260 	  flagword flags;
261 
262 	  /* Create section to own the symbols.  */
263 	  flags = (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
264 		   | SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_EXCLUDE);
265 	  if (bfd_make_section_anyway_with_flags (abfd, ".text", flags))
266 	    return abfd;
267 	}
268     }
269   einfo (_("could not create dummy IR bfd: %F%E\n"));
270   return NULL;
271 }
272 
273 /* Check if the BFD passed in is an IR dummy object file.  */
274 static inline bfd_boolean
is_ir_dummy_bfd(const bfd * abfd)275 is_ir_dummy_bfd (const bfd *abfd)
276 {
277   /* ABFD can sometimes legitimately be NULL, e.g. when called from one
278      of the linker callbacks for a symbol in the *ABS* or *UND* sections.  */
279   return abfd != NULL && (abfd->flags & BFD_PLUGIN) != 0;
280 }
281 
282 /* Helpers to convert between BFD and GOLD symbol formats.  */
283 static enum ld_plugin_status
asymbol_from_plugin_symbol(bfd * abfd,asymbol * asym,const struct ld_plugin_symbol * ldsym)284 asymbol_from_plugin_symbol (bfd *abfd, asymbol *asym,
285 			    const struct ld_plugin_symbol *ldsym)
286 {
287   flagword flags = BSF_NO_FLAGS;
288   struct bfd_section *section;
289 
290   asym->the_bfd = abfd;
291   asym->name = (ldsym->version
292 		? concat (ldsym->name, "@", ldsym->version, (const char *) NULL)
293 		: ldsym->name);
294   asym->value = 0;
295   switch (ldsym->def)
296     {
297     case LDPK_WEAKDEF:
298       flags = BSF_WEAK;
299       /* FALLTHRU */
300     case LDPK_DEF:
301       flags |= BSF_GLOBAL;
302       if (ldsym->comdat_key)
303 	{
304 	  char *name = concat (".gnu.linkonce.t.", ldsym->comdat_key,
305 			       (const char *) NULL);
306 	  section = bfd_get_section_by_name (abfd, name);
307 	  if (section != NULL)
308 	    free (name);
309 	  else
310 	    {
311 	      flagword sflags;
312 
313 	      sflags = (SEC_CODE | SEC_HAS_CONTENTS | SEC_READONLY
314 			| SEC_ALLOC | SEC_LOAD | SEC_KEEP | SEC_EXCLUDE
315 			| SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD);
316 	      section = bfd_make_section_anyway_with_flags (abfd, name, sflags);
317 	      if (section == NULL)
318 		return LDPS_ERR;
319 	    }
320 	}
321       else
322 	section = bfd_get_section_by_name (abfd, ".text");
323       break;
324 
325     case LDPK_WEAKUNDEF:
326       flags = BSF_WEAK;
327       /* FALLTHRU */
328     case LDPK_UNDEF:
329       section = bfd_und_section_ptr;
330       break;
331 
332     case LDPK_COMMON:
333       flags = BSF_GLOBAL;
334       section = bfd_com_section_ptr;
335       asym->value = ldsym->size;
336       /* For ELF targets, set alignment of common symbol to 1.  */
337       if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
338 	{
339 	  ((elf_symbol_type *) asym)->internal_elf_sym.st_shndx = SHN_COMMON;
340 	  ((elf_symbol_type *) asym)->internal_elf_sym.st_value = 1;
341 	}
342       break;
343 
344     default:
345       return LDPS_ERR;
346     }
347   asym->flags = flags;
348   asym->section = section;
349 
350   /* Visibility only applies on ELF targets.  */
351   if (bfd_get_flavour (abfd) == bfd_target_elf_flavour)
352     {
353       elf_symbol_type *elfsym = elf_symbol_from (abfd, asym);
354       unsigned char visibility;
355 
356       if (!elfsym)
357 	einfo (_("%P%F: %s: non-ELF symbol in ELF BFD!\n"), asym->name);
358       switch (ldsym->visibility)
359 	{
360 	default:
361 	  einfo (_("%P%F: unknown ELF symbol visibility: %d!\n"),
362 		 ldsym->visibility);
363 	case LDPV_DEFAULT:
364 	  visibility = STV_DEFAULT;
365 	  break;
366 	case LDPV_PROTECTED:
367 	  visibility = STV_PROTECTED;
368 	  break;
369 	case LDPV_INTERNAL:
370 	  visibility = STV_INTERNAL;
371 	  break;
372 	case LDPV_HIDDEN:
373 	  visibility = STV_HIDDEN;
374 	  break;
375 	}
376       elfsym->internal_elf_sym.st_other
377 	= (visibility | (elfsym->internal_elf_sym.st_other
378 			 & ~ELF_ST_VISIBILITY (-1)));
379     }
380 
381   return LDPS_OK;
382 }
383 
384 /* Register a claim-file handler.  */
385 static enum ld_plugin_status
register_claim_file(ld_plugin_claim_file_handler handler)386 register_claim_file (ld_plugin_claim_file_handler handler)
387 {
388   ASSERT (called_plugin);
389   called_plugin->claim_file_handler = handler;
390   return LDPS_OK;
391 }
392 
393 /* Register an all-symbols-read handler.  */
394 static enum ld_plugin_status
register_all_symbols_read(ld_plugin_all_symbols_read_handler handler)395 register_all_symbols_read (ld_plugin_all_symbols_read_handler handler)
396 {
397   ASSERT (called_plugin);
398   called_plugin->all_symbols_read_handler = handler;
399   return LDPS_OK;
400 }
401 
402 /* Register a cleanup handler.  */
403 static enum ld_plugin_status
register_cleanup(ld_plugin_cleanup_handler handler)404 register_cleanup (ld_plugin_cleanup_handler handler)
405 {
406   ASSERT (called_plugin);
407   called_plugin->cleanup_handler = handler;
408   return LDPS_OK;
409 }
410 
411 /* Add symbols from a plugin-claimed input file.  */
412 static enum ld_plugin_status
add_symbols(void * handle,int nsyms,const struct ld_plugin_symbol * syms)413 add_symbols (void *handle, int nsyms, const struct ld_plugin_symbol *syms)
414 {
415   asymbol **symptrs;
416   bfd *abfd = handle;
417   int n;
418 
419   ASSERT (called_plugin);
420   symptrs = xmalloc (nsyms * sizeof *symptrs);
421   for (n = 0; n < nsyms; n++)
422     {
423       enum ld_plugin_status rv;
424       asymbol *bfdsym;
425 
426       bfdsym = bfd_make_empty_symbol (abfd);
427       symptrs[n] = bfdsym;
428       rv = asymbol_from_plugin_symbol (abfd, bfdsym, syms + n);
429       if (rv != LDPS_OK)
430 	return rv;
431     }
432   bfd_set_symtab (abfd, symptrs, nsyms);
433   return LDPS_OK;
434 }
435 
436 /* Get the input file information with an open (possibly re-opened)
437    file descriptor.  */
438 static enum ld_plugin_status
get_input_file(const void * handle ATTRIBUTE_UNUSED,struct ld_plugin_input_file * file ATTRIBUTE_UNUSED)439 get_input_file (const void *handle ATTRIBUTE_UNUSED,
440                 struct ld_plugin_input_file *file ATTRIBUTE_UNUSED)
441 {
442   ASSERT (called_plugin);
443   return LDPS_ERR;
444 }
445 
446 /* Release the input file.  */
447 static enum ld_plugin_status
release_input_file(const void * handle ATTRIBUTE_UNUSED)448 release_input_file (const void *handle ATTRIBUTE_UNUSED)
449 {
450   ASSERT (called_plugin);
451   return LDPS_ERR;
452 }
453 
454 /* Return TRUE if a defined symbol might be reachable from outside the
455    universe of claimed objects.  */
456 static inline bfd_boolean
is_visible_from_outside(struct ld_plugin_symbol * lsym,struct bfd_link_hash_entry * blhe)457 is_visible_from_outside (struct ld_plugin_symbol *lsym,
458 			 struct bfd_link_hash_entry *blhe)
459 {
460   struct bfd_sym_chain *sym;
461 
462   if (link_info.relocatable)
463     return TRUE;
464   if (link_info.export_dynamic || !link_info.executable)
465     {
466       /* Check if symbol is hidden by version script.  */
467       if (bfd_hide_sym_by_version (link_info.version_info,
468 				   blhe->root.string))
469 	return FALSE;
470       /* Only ELF symbols really have visibility.  */
471       if (bfd_get_flavour (link_info.output_bfd) == bfd_target_elf_flavour)
472 	{
473 	  struct elf_link_hash_entry *el = (struct elf_link_hash_entry *)blhe;
474 	  int vis = ELF_ST_VISIBILITY (el->other);
475 	  return vis == STV_DEFAULT || vis == STV_PROTECTED;
476 	}
477       /* On non-ELF targets, we can safely make inferences by considering
478 	 what visibility the plugin would have liked to apply when it first
479 	 sent us the symbol.  During ELF symbol processing, visibility only
480 	 ever becomes more restrictive, not less, when symbols are merged,
481 	 so this is a conservative estimate; it may give false positives,
482 	 declaring something visible from outside when it in fact would
483 	 not have been, but this will only lead to missed optimisation
484 	 opportunities during LTRANS at worst; it will not give false
485 	 negatives, which can lead to the disastrous conclusion that the
486 	 related symbol is IRONLY.  (See GCC PR46319 for an example.)  */
487       return (lsym->visibility == LDPV_DEFAULT
488 	      || lsym->visibility == LDPV_PROTECTED);
489     }
490 
491   for (sym = &entry_symbol; sym != NULL; sym = sym->next)
492     if (sym->name
493 	&& strcmp (sym->name, blhe->root.string) == 0)
494       return TRUE;
495 
496   return FALSE;
497 }
498 
499 /* Get the symbol resolution info for a plugin-claimed input file.  */
500 static enum ld_plugin_status
get_symbols(const void * handle,int nsyms,struct ld_plugin_symbol * syms,int def_ironly_exp)501 get_symbols (const void *handle, int nsyms, struct ld_plugin_symbol *syms,
502 	     int def_ironly_exp)
503 {
504   const bfd *abfd = handle;
505   int n;
506 
507   ASSERT (called_plugin);
508   for (n = 0; n < nsyms; n++)
509     {
510       struct bfd_link_hash_entry *blhe;
511       asection *owner_sec;
512       int res;
513 
514       if (syms[n].def != LDPK_UNDEF)
515 	blhe = bfd_link_hash_lookup (link_info.hash, syms[n].name,
516 				     FALSE, FALSE, TRUE);
517       else
518 	blhe = bfd_wrapped_link_hash_lookup (link_info.output_bfd, &link_info,
519 					     syms[n].name, FALSE, FALSE, TRUE);
520       if (!blhe)
521 	{
522 	  res = LDPR_UNKNOWN;
523 	  goto report_symbol;
524 	}
525 
526       /* Determine resolution from blhe type and symbol's original type.  */
527       if (blhe->type == bfd_link_hash_undefined
528 	  || blhe->type == bfd_link_hash_undefweak)
529 	{
530 	  res = LDPR_UNDEF;
531 	  goto report_symbol;
532 	}
533       if (blhe->type != bfd_link_hash_defined
534 	  && blhe->type != bfd_link_hash_defweak
535 	  && blhe->type != bfd_link_hash_common)
536 	{
537 	  /* We should not have a new, indirect or warning symbol here.  */
538 	  einfo ("%P%F: %s: plugin symbol table corrupt (sym type %d)\n",
539 		 called_plugin->name, blhe->type);
540 	}
541 
542       /* Find out which section owns the symbol.  Since it's not undef,
543 	 it must have an owner; if it's not a common symbol, both defs
544 	 and weakdefs keep it in the same place. */
545       owner_sec = (blhe->type == bfd_link_hash_common
546 		   ? blhe->u.c.p->section
547 		   : blhe->u.def.section);
548 
549 
550       /* If it was originally undefined or common, then it has been
551 	 resolved; determine how.  */
552       if (syms[n].def == LDPK_UNDEF
553 	  || syms[n].def == LDPK_WEAKUNDEF
554 	  || syms[n].def == LDPK_COMMON)
555 	{
556 	  if (owner_sec->owner == link_info.output_bfd)
557 	    res = LDPR_RESOLVED_EXEC;
558 	  else if (owner_sec->owner == abfd)
559 	    res = LDPR_PREVAILING_DEF_IRONLY;
560 	  else if (is_ir_dummy_bfd (owner_sec->owner))
561 	    res = LDPR_RESOLVED_IR;
562 	  else if (owner_sec->owner != NULL
563 		   && (owner_sec->owner->flags & DYNAMIC) != 0)
564 	    res = LDPR_RESOLVED_DYN;
565 	  else
566 	    res = LDPR_RESOLVED_EXEC;
567 	}
568 
569       /* Was originally def, or weakdef.  Does it prevail?  If the
570 	 owner is the original dummy bfd that supplied it, then this
571 	 is the definition that has prevailed.  */
572       else if (owner_sec->owner == link_info.output_bfd)
573 	res = LDPR_PREEMPTED_REG;
574       else if (owner_sec->owner == abfd)
575 	res = LDPR_PREVAILING_DEF_IRONLY;
576 
577       /* Was originally def, weakdef, or common, but has been pre-empted.  */
578       else if (is_ir_dummy_bfd (owner_sec->owner))
579 	res = LDPR_PREEMPTED_IR;
580       else
581 	res = LDPR_PREEMPTED_REG;
582 
583       if (res == LDPR_PREVAILING_DEF_IRONLY)
584 	{
585 	  /* We need to know if the sym is referenced from non-IR files.  Or
586 	     even potentially-referenced, perhaps in a future final link if
587 	     this is a partial one, perhaps dynamically at load-time if the
588 	     symbol is externally visible.  */
589 	  if (blhe->non_ir_ref)
590 	    res = LDPR_PREVAILING_DEF;
591 	  else if (is_visible_from_outside (&syms[n], blhe))
592 	    res = def_ironly_exp;
593 	}
594 
595     report_symbol:
596       syms[n].resolution = res;
597       if (report_plugin_symbols)
598 	einfo (_("%P: %B: symbol `%s' "
599 		 "definition: %d, visibility: %d, resolution: %d\n"),
600 	       abfd, syms[n].name,
601 	       syms[n].def, syms[n].visibility, res);
602     }
603   return LDPS_OK;
604 }
605 
606 static enum ld_plugin_status
get_symbols_v1(const void * handle,int nsyms,struct ld_plugin_symbol * syms)607 get_symbols_v1 (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
608 {
609   return get_symbols (handle, nsyms, syms, LDPR_PREVAILING_DEF);
610 }
611 
612 static enum ld_plugin_status
get_symbols_v2(const void * handle,int nsyms,struct ld_plugin_symbol * syms)613 get_symbols_v2 (const void *handle, int nsyms, struct ld_plugin_symbol *syms)
614 {
615   return get_symbols (handle, nsyms, syms, LDPR_PREVAILING_DEF_IRONLY_EXP);
616 }
617 
618 /* Add a new (real) input file generated by a plugin.  */
619 static enum ld_plugin_status
add_input_file(const char * pathname)620 add_input_file (const char *pathname)
621 {
622   ASSERT (called_plugin);
623   if (!lang_add_input_file (xstrdup (pathname), lang_input_file_is_file_enum,
624 			    NULL))
625     return LDPS_ERR;
626   return LDPS_OK;
627 }
628 
629 /* Add a new (real) library required by a plugin.  */
630 static enum ld_plugin_status
add_input_library(const char * pathname)631 add_input_library (const char *pathname)
632 {
633   ASSERT (called_plugin);
634   if (!lang_add_input_file (xstrdup (pathname), lang_input_file_is_l_enum,
635 			    NULL))
636     return LDPS_ERR;
637   return LDPS_OK;
638 }
639 
640 /* Set the extra library path to be used by libraries added via
641    add_input_library.  */
642 static enum ld_plugin_status
set_extra_library_path(const char * path)643 set_extra_library_path (const char *path)
644 {
645   ASSERT (called_plugin);
646   ldfile_add_library_path (xstrdup (path), FALSE);
647   return LDPS_OK;
648 }
649 
650 /* Issue a diagnostic message from a plugin.  */
651 static enum ld_plugin_status
message(int level,const char * format,...)652 message (int level, const char *format, ...)
653 {
654   va_list args;
655   va_start (args, format);
656 
657   switch (level)
658     {
659     case LDPL_INFO:
660       vfinfo (stdout, format, args, FALSE);
661       putchar ('\n');
662       break;
663     case LDPL_WARNING:
664       vfinfo (stdout, format, args, TRUE);
665       putchar ('\n');
666       break;
667     case LDPL_FATAL:
668     case LDPL_ERROR:
669     default:
670       {
671 	char *newfmt = ACONCAT ((level == LDPL_FATAL ? "%P%F: " : "%P%X: ",
672 				 format, "\n", (const char *) NULL));
673 	fflush (stdout);
674 	vfinfo (stderr, newfmt, args, TRUE);
675 	fflush (stderr);
676       }
677       break;
678     }
679 
680   va_end (args);
681   return LDPS_OK;
682 }
683 
684 /* Helper to size leading part of tv array and set it up. */
685 static void
set_tv_header(struct ld_plugin_tv * tv)686 set_tv_header (struct ld_plugin_tv *tv)
687 {
688   size_t i;
689 
690   /* Version info.  */
691   static const unsigned int major = (unsigned)(BFD_VERSION / 100000000UL);
692   static const unsigned int minor = (unsigned)(BFD_VERSION / 1000000UL) % 100;
693 
694   for (i = 0; i < tv_header_size; i++)
695     {
696       tv[i].tv_tag = tv_header_tags[i];
697 #define TVU(x) tv[i].tv_u.tv_ ## x
698       switch (tv[i].tv_tag)
699 	{
700 	case LDPT_MESSAGE:
701 	  TVU(message) = message;
702 	  break;
703 	case LDPT_API_VERSION:
704 	  TVU(val) = LD_PLUGIN_API_VERSION;
705 	  break;
706 	case LDPT_GNU_LD_VERSION:
707 	  TVU(val) = major * 100 + minor;
708 	  break;
709 	case LDPT_LINKER_OUTPUT:
710 	  TVU(val) = (link_info.relocatable
711 		      ? LDPO_REL
712 		      : (link_info.executable
713 			 ? (link_info.pie ? LDPO_PIE : LDPO_EXEC)
714 			 : LDPO_DYN));
715 	  break;
716 	case LDPT_OUTPUT_NAME:
717 	  TVU(string) = output_filename;
718 	  break;
719 	case LDPT_REGISTER_CLAIM_FILE_HOOK:
720 	  TVU(register_claim_file) = register_claim_file;
721 	  break;
722 	case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK:
723 	  TVU(register_all_symbols_read) = register_all_symbols_read;
724 	  break;
725 	case LDPT_REGISTER_CLEANUP_HOOK:
726 	  TVU(register_cleanup) = register_cleanup;
727 	  break;
728 	case LDPT_ADD_SYMBOLS:
729 	  TVU(add_symbols) = add_symbols;
730 	  break;
731 	case LDPT_GET_INPUT_FILE:
732 	  TVU(get_input_file) = get_input_file;
733 	  break;
734 	case LDPT_RELEASE_INPUT_FILE:
735 	  TVU(release_input_file) = release_input_file;
736 	  break;
737 	case LDPT_GET_SYMBOLS:
738 	  TVU(get_symbols) = get_symbols_v1;
739 	  break;
740 	case LDPT_GET_SYMBOLS_V2:
741 	  TVU(get_symbols) = get_symbols_v2;
742 	  break;
743 	case LDPT_ADD_INPUT_FILE:
744 	  TVU(add_input_file) = add_input_file;
745 	  break;
746 	case LDPT_ADD_INPUT_LIBRARY:
747 	  TVU(add_input_library) = add_input_library;
748 	  break;
749 	case LDPT_SET_EXTRA_LIBRARY_PATH:
750 	  TVU(set_extra_library_path) = set_extra_library_path;
751 	  break;
752 	default:
753 	  /* Added a new entry to the array without adding
754 	     a new case to set up its value is a bug.  */
755 	  FAIL ();
756 	}
757 #undef TVU
758     }
759 }
760 
761 /* Append the per-plugin args list and trailing LDPT_NULL to tv.  */
762 static void
set_tv_plugin_args(plugin_t * plugin,struct ld_plugin_tv * tv)763 set_tv_plugin_args (plugin_t *plugin, struct ld_plugin_tv *tv)
764 {
765   plugin_arg_t *arg = plugin->args;
766   while (arg)
767     {
768       tv->tv_tag = LDPT_OPTION;
769       tv->tv_u.tv_string = arg->arg;
770       arg = arg->next;
771       tv++;
772     }
773   tv->tv_tag = LDPT_NULL;
774   tv->tv_u.tv_val = 0;
775 }
776 
777 /* Return true if any plugins are active this run.  Only valid
778    after options have been processed.  */
779 bfd_boolean
plugin_active_plugins_p(void)780 plugin_active_plugins_p (void)
781 {
782   return plugins_list != NULL;
783 }
784 
785 /* Load up and initialise all plugins after argument parsing.  */
786 void
plugin_load_plugins(void)787 plugin_load_plugins (void)
788 {
789   struct ld_plugin_tv *my_tv;
790   unsigned int max_args = 0;
791   plugin_t *curplug = plugins_list;
792 
793   /* If there are no plugins, we need do nothing this run.  */
794   if (!curplug)
795     return;
796 
797   /* First pass over plugins to find max # args needed so that we
798      can size and allocate the tv array.  */
799   while (curplug)
800     {
801       if (curplug->n_args > max_args)
802 	max_args = curplug->n_args;
803       curplug = curplug->next;
804     }
805 
806   /* Allocate tv array and initialise constant part.  */
807   my_tv = xmalloc ((max_args + 1 + tv_header_size) * sizeof *my_tv);
808   set_tv_header (my_tv);
809 
810   /* Pass over plugins again, activating them.  */
811   curplug = plugins_list;
812   while (curplug)
813     {
814       enum ld_plugin_status rv;
815       ld_plugin_onload onloadfn;
816 
817       onloadfn = (ld_plugin_onload) dlsym (curplug->dlhandle, "onload");
818       if (!onloadfn)
819 	onloadfn = (ld_plugin_onload) dlsym (curplug->dlhandle, "_onload");
820       if (!onloadfn)
821         einfo (_("%P%F: %s: error loading plugin: %s\n"),
822 	       curplug->name, dlerror ());
823       set_tv_plugin_args (curplug, &my_tv[tv_header_size]);
824       called_plugin = curplug;
825       rv = (*onloadfn) (my_tv);
826       called_plugin = NULL;
827       if (rv != LDPS_OK)
828 	einfo (_("%P%F: %s: plugin error: %d\n"), curplug->name, rv);
829       curplug = curplug->next;
830     }
831 
832   /* Since plugin(s) inited ok, assume they're going to want symbol
833      resolutions, which needs us to track which symbols are referenced
834      by non-IR files using the linker's notice callback.  */
835   orig_notice_all = link_info.notice_all;
836   orig_callbacks = link_info.callbacks;
837   plugin_callbacks = *orig_callbacks;
838   plugin_callbacks.notice = &plugin_notice;
839   link_info.notice_all = TRUE;
840   link_info.lto_plugin_active = TRUE;
841   link_info.callbacks = &plugin_callbacks;
842 }
843 
844 /* Call 'claim file' hook for all plugins.  */
845 static int
plugin_call_claim_file(const struct ld_plugin_input_file * file,int * claimed)846 plugin_call_claim_file (const struct ld_plugin_input_file *file, int *claimed)
847 {
848   plugin_t *curplug = plugins_list;
849   *claimed = FALSE;
850   if (no_more_claiming)
851     return 0;
852   while (curplug && !*claimed)
853     {
854       if (curplug->claim_file_handler)
855 	{
856 	  enum ld_plugin_status rv;
857 	  called_plugin = curplug;
858 	  rv = (*curplug->claim_file_handler) (file, claimed);
859 	  called_plugin = NULL;
860 	  if (rv != LDPS_OK)
861 	    set_plugin_error (curplug->name);
862 	}
863       curplug = curplug->next;
864     }
865   return plugin_error_p () ? -1 : 0;
866 }
867 
868 void
plugin_maybe_claim(struct ld_plugin_input_file * file,lang_input_statement_type * entry)869 plugin_maybe_claim (struct ld_plugin_input_file *file,
870 		    lang_input_statement_type *entry)
871 {
872   int claimed = 0;
873 
874   /* We create a dummy BFD, initially empty, to house whatever symbols
875      the plugin may want to add.  */
876   file->handle = plugin_get_ir_dummy_bfd (entry->the_bfd->filename,
877 					  entry->the_bfd);
878   if (plugin_call_claim_file (file, &claimed))
879     einfo (_("%P%F: %s: plugin reported error claiming file\n"),
880 	   plugin_error_plugin ());
881   /* fd belongs to us, not the plugin; but we don't need it.  */
882   close (file->fd);
883   if (claimed)
884     {
885       /* Discard the real file's BFD and substitute the dummy one.  */
886 
887       /* BFD archive handling caches elements so we can't call
888 	 bfd_close for archives.  */
889       if (entry->the_bfd->my_archive == NULL)
890 	bfd_close (entry->the_bfd);
891       entry->the_bfd = file->handle;
892       entry->flags.claimed = TRUE;
893       bfd_make_readable (entry->the_bfd);
894     }
895   else
896     {
897       /* If plugin didn't claim the file, we don't need the dummy bfd.
898 	 Can't avoid speculatively creating it, alas.  */
899       bfd_close_all_done (file->handle);
900       entry->flags.claimed = FALSE;
901     }
902 }
903 
904 /* Call 'all symbols read' hook for all plugins.  */
905 int
plugin_call_all_symbols_read(void)906 plugin_call_all_symbols_read (void)
907 {
908   plugin_t *curplug = plugins_list;
909 
910   /* Disable any further file-claiming.  */
911   no_more_claiming = TRUE;
912 
913   while (curplug)
914     {
915       if (curplug->all_symbols_read_handler)
916 	{
917 	  enum ld_plugin_status rv;
918 	  called_plugin = curplug;
919 	  rv = (*curplug->all_symbols_read_handler) ();
920 	  called_plugin = NULL;
921 	  if (rv != LDPS_OK)
922 	    set_plugin_error (curplug->name);
923 	}
924       curplug = curplug->next;
925     }
926   return plugin_error_p () ? -1 : 0;
927 }
928 
929 /* Call 'cleanup' hook for all plugins at exit.  */
930 void
plugin_call_cleanup(void)931 plugin_call_cleanup (void)
932 {
933   plugin_t *curplug = plugins_list;
934   while (curplug)
935     {
936       if (curplug->cleanup_handler && !curplug->cleanup_done)
937 	{
938 	  enum ld_plugin_status rv;
939 	  curplug->cleanup_done = TRUE;
940 	  called_plugin = curplug;
941 	  rv = (*curplug->cleanup_handler) ();
942 	  called_plugin = NULL;
943 	  if (rv != LDPS_OK)
944 	    info_msg (_("%P: %s: error in plugin cleanup: %d (ignored)\n"),
945 		      curplug->name, rv);
946 	  dlclose (curplug->dlhandle);
947 	}
948       curplug = curplug->next;
949     }
950 }
951 
952 /* To determine which symbols should be resolved LDPR_PREVAILING_DEF
953    and which LDPR_PREVAILING_DEF_IRONLY, we notice all the symbols as
954    the linker adds them to the linker hash table.  Mark those
955    referenced from a non-IR file with non_ir_ref.  We have to
956    notice_all symbols, because we won't necessarily know until later
957    which ones will be contributed by IR files.  */
958 static bfd_boolean
plugin_notice(struct bfd_link_info * info,struct bfd_link_hash_entry * h,struct bfd_link_hash_entry * inh,bfd * abfd,asection * section,bfd_vma value,flagword flags)959 plugin_notice (struct bfd_link_info *info,
960 	       struct bfd_link_hash_entry *h,
961 	       struct bfd_link_hash_entry *inh,
962 	       bfd *abfd,
963 	       asection *section,
964 	       bfd_vma value,
965 	       flagword flags)
966 {
967   struct bfd_link_hash_entry *orig_h = h;
968 
969   if (h != NULL)
970     {
971       bfd *sym_bfd;
972 
973       if (h->type == bfd_link_hash_warning)
974 	h = h->u.i.link;
975 
976       /* Nothing to do here if this def/ref is from an IR dummy BFD.  */
977       if (is_ir_dummy_bfd (abfd))
978 	;
979 
980       /* Making an indirect symbol counts as a reference unless this
981 	 is a brand new symbol.  */
982       else if (bfd_is_ind_section (section)
983 	       || (flags & BSF_INDIRECT) != 0)
984 	{
985 	  /* ??? Some of this is questionable.  See comments in
986 	     _bfd_generic_link_add_one_symbol for case IND.  */
987 	  if (h->type != bfd_link_hash_new)
988 	    {
989 	      h->non_ir_ref = TRUE;
990 	      inh->non_ir_ref = TRUE;
991 	    }
992 	  else if (inh->type == bfd_link_hash_new)
993 	    inh->non_ir_ref = TRUE;
994 	}
995 
996       /* Nothing to do here for warning symbols.  */
997       else if ((flags & BSF_WARNING) != 0)
998 	;
999 
1000       /* Nothing to do here for constructor symbols.  */
1001       else if ((flags & BSF_CONSTRUCTOR) != 0)
1002 	;
1003 
1004       /* If this is a ref, set non_ir_ref.  */
1005       else if (bfd_is_und_section (section))
1006 	{
1007 	  /* Replace the undefined dummy bfd with the real one.  */
1008 	  if ((h->type == bfd_link_hash_undefined
1009 	       || h->type == bfd_link_hash_undefweak)
1010 	      && (h->u.undef.abfd == NULL
1011 		  || (h->u.undef.abfd->flags & BFD_PLUGIN) != 0))
1012 	    h->u.undef.abfd = abfd;
1013 	  h->non_ir_ref = TRUE;
1014 	}
1015 
1016       /* Otherwise, it must be a new def.  Ensure any symbol defined
1017 	 in an IR dummy BFD takes on a new value from a real BFD.
1018 	 Weak symbols are not normally overridden by a new weak
1019 	 definition, and strong symbols will normally cause multiple
1020 	 definition errors.  Avoid this by making the symbol appear
1021 	 to be undefined.  */
1022       else if (((h->type == bfd_link_hash_defweak
1023 		 || h->type == bfd_link_hash_defined)
1024 		&& is_ir_dummy_bfd (sym_bfd = h->u.def.section->owner))
1025 	       || (h->type == bfd_link_hash_common
1026 		   && is_ir_dummy_bfd (sym_bfd = h->u.c.p->section->owner)))
1027 	{
1028 	  h->type = bfd_link_hash_undefweak;
1029 	  h->u.undef.abfd = sym_bfd;
1030 	}
1031     }
1032 
1033   /* Continue with cref/nocrossref/trace-sym processing.  */
1034   if (orig_h == NULL
1035       || orig_notice_all
1036       || (info->notice_hash != NULL
1037 	  && bfd_hash_lookup (info->notice_hash, orig_h->root.string,
1038 			      FALSE, FALSE) != NULL))
1039     return (*orig_callbacks->notice) (info, orig_h, inh,
1040 				      abfd, section, value, flags);
1041   return TRUE;
1042 }
1043