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