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