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