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