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