New plugin interface to get list of symbols wrapped with --wrap option.
[external/binutils.git] / gold / plugin.cc
1 // plugin.cc -- plugin manager for gold      -*- C++ -*-
2
3 // Copyright (C) 2008-2018 Free Software Foundation, Inc.
4 // Written by Cary Coutant <ccoutant@google.com>.
5
6 // This file is part of gold.
7
8 // This program is free software; you can redistribute it and/or modify
9 // it under the terms of the GNU General Public License as published by
10 // the Free Software Foundation; either version 3 of the License, or
11 // (at your option) any later version.
12
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 // GNU General Public License for more details.
17
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21 // MA 02110-1301, USA.
22
23 #include "gold.h"
24
25 #include <cstdio>
26 #include <cstdarg>
27 #include <cstring>
28 #include <string>
29 #include <vector>
30
31 #ifdef ENABLE_PLUGINS
32 #ifdef HAVE_DLFCN_H
33 #include <dlfcn.h>
34 #elif defined (HAVE_WINDOWS_H)
35 #include <windows.h>
36 #else
37 #error Unknown how to handle dynamic-load-libraries.
38 #endif
39
40 #if !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)
41
42 #define RTLD_NOW 0      /* Dummy value.  */
43 static void *
44 dlopen(const char *file, int mode ATTRIBUTE_UNUSED)
45 {
46   return LoadLibrary(file);
47 }
48
49 static void *
50 dlsym(void *handle, const char *name)
51 {
52   return reinterpret_cast<void *>(
53      GetProcAddress(static_cast<HMODULE>(handle),name));
54 }
55
56 static const char *
57 dlerror(void)
58 {
59   return "unable to load dll";
60 }
61
62 #endif /* !defined (HAVE_DLFCN_H) && defined (HAVE_WINDOWS_H)  */
63 #endif /* ENABLE_PLUGINS */
64
65 #include "parameters.h"
66 #include "errors.h"
67 #include "fileread.h"
68 #include "layout.h"
69 #include "options.h"
70 #include "plugin.h"
71 #include "target.h"
72 #include "readsyms.h"
73 #include "symtab.h"
74 #include "descriptors.h"
75 #include "elfcpp.h"
76
77 namespace gold
78 {
79
80 #ifdef ENABLE_PLUGINS
81
82 // The linker's exported interfaces.
83
84 extern "C"
85 {
86
87 static enum ld_plugin_status
88 register_claim_file(ld_plugin_claim_file_handler handler);
89
90 static enum ld_plugin_status
91 register_all_symbols_read(ld_plugin_all_symbols_read_handler handler);
92
93 static enum ld_plugin_status
94 register_cleanup(ld_plugin_cleanup_handler handler);
95
96 static enum ld_plugin_status
97 add_symbols(void *handle, int nsyms, const struct ld_plugin_symbol *syms);
98
99 static enum ld_plugin_status
100 get_input_file(const void *handle, struct ld_plugin_input_file *file);
101
102 static enum ld_plugin_status
103 get_view(const void *handle, const void **viewp);
104
105 static enum ld_plugin_status
106 release_input_file(const void *handle);
107
108 static enum ld_plugin_status
109 get_symbols(const void *handle, int nsyms, struct ld_plugin_symbol *syms);
110
111 static enum ld_plugin_status
112 get_symbols_v2(const void *handle, int nsyms, struct ld_plugin_symbol *syms);
113
114 static enum ld_plugin_status
115 get_symbols_v3(const void *handle, int nsyms, struct ld_plugin_symbol *syms);
116
117 static enum ld_plugin_status
118 add_input_file(const char *pathname);
119
120 static enum ld_plugin_status
121 add_input_library(const char *pathname);
122
123 static enum ld_plugin_status
124 set_extra_library_path(const char *path);
125
126 static enum ld_plugin_status
127 message(int level, const char *format, ...);
128
129 static enum ld_plugin_status
130 get_input_section_count(const void* handle, unsigned int* count);
131
132 static enum ld_plugin_status
133 get_input_section_type(const struct ld_plugin_section section,
134                        unsigned int* type);
135
136 static enum ld_plugin_status
137 get_input_section_name(const struct ld_plugin_section section,
138                        char** section_name_ptr);
139
140 static enum ld_plugin_status
141 get_input_section_contents(const struct ld_plugin_section section,
142                            const unsigned char** section_contents,
143                            size_t* len);
144
145 static enum ld_plugin_status
146 update_section_order(const struct ld_plugin_section *section_list,
147                      unsigned int num_sections);
148
149 static enum ld_plugin_status
150 allow_section_ordering();
151
152 static enum ld_plugin_status
153 allow_unique_segment_for_sections();
154
155 static enum ld_plugin_status
156 unique_segment_for_sections(const char* segment_name,
157                             uint64_t flags,
158                             uint64_t align,
159                             const struct ld_plugin_section *section_list,
160                             unsigned int num_sections);
161
162 static enum ld_plugin_status
163 get_input_section_alignment(const struct ld_plugin_section section,
164                             unsigned int* addralign);
165
166 static enum ld_plugin_status
167 get_input_section_size(const struct ld_plugin_section section,
168                        uint64_t* secsize);
169
170 static enum ld_plugin_status
171 register_new_input(ld_plugin_new_input_handler handler);
172
173 static enum ld_plugin_status
174 get_wrap_symbols(uint64_t *num_symbols, const char ***wrap_symbol_list);
175
176 };
177
178 #endif // ENABLE_PLUGINS
179
180 static Pluginobj* make_sized_plugin_object(Input_file* input_file,
181                                            off_t offset, off_t filesize);
182
183 // Plugin methods.
184
185 // Load one plugin library.
186
187 void
188 Plugin::load()
189 {
190 #ifdef ENABLE_PLUGINS
191   // Load the plugin library.
192   // FIXME: Look for the library in standard locations.
193   this->handle_ = dlopen(this->filename_.c_str(), RTLD_NOW);
194   if (this->handle_ == NULL)
195     {
196       gold_error(_("%s: could not load plugin library: %s"),
197                  this->filename_.c_str(), dlerror());
198       return;
199     }
200
201   // Find the plugin's onload entry point.
202   void* ptr = dlsym(this->handle_, "onload");
203   if (ptr == NULL)
204     {
205       gold_error(_("%s: could not find onload entry point"),
206                  this->filename_.c_str());
207       return;
208     }
209   ld_plugin_onload onload;
210   gold_assert(sizeof(onload) == sizeof(ptr));
211   memcpy(&onload, &ptr, sizeof(ptr));
212
213   // Get the linker's version number.
214   const char* ver = get_version_string();
215   int major = 0;
216   int minor = 0;
217   sscanf(ver, "%d.%d", &major, &minor);
218
219   // Allocate and populate a transfer vector.
220   const int tv_fixed_size = 31;
221
222   int tv_size = this->args_.size() + tv_fixed_size;
223   ld_plugin_tv* tv = new ld_plugin_tv[tv_size];
224
225   // Put LDPT_MESSAGE at the front of the list so the plugin can use it
226   // while processing subsequent entries.
227   int i = 0;
228   tv[i].tv_tag = LDPT_MESSAGE;
229   tv[i].tv_u.tv_message = message;
230
231   ++i;
232   tv[i].tv_tag = LDPT_API_VERSION;
233   tv[i].tv_u.tv_val = LD_PLUGIN_API_VERSION;
234
235   ++i;
236   tv[i].tv_tag = LDPT_GOLD_VERSION;
237   tv[i].tv_u.tv_val = major * 100 + minor;
238
239   ++i;
240   tv[i].tv_tag = LDPT_LINKER_OUTPUT;
241   if (parameters->options().relocatable())
242     tv[i].tv_u.tv_val = LDPO_REL;
243   else if (parameters->options().shared())
244     tv[i].tv_u.tv_val = LDPO_DYN;
245   else if (parameters->options().pie())
246     tv[i].tv_u.tv_val = LDPO_PIE;
247   else
248     tv[i].tv_u.tv_val = LDPO_EXEC;
249
250   ++i;
251   tv[i].tv_tag = LDPT_OUTPUT_NAME;
252   tv[i].tv_u.tv_string = parameters->options().output();
253
254   for (unsigned int j = 0; j < this->args_.size(); ++j)
255     {
256       ++i;
257       tv[i].tv_tag = LDPT_OPTION;
258       tv[i].tv_u.tv_string = this->args_[j].c_str();
259     }
260
261   ++i;
262   tv[i].tv_tag = LDPT_REGISTER_CLAIM_FILE_HOOK;
263   tv[i].tv_u.tv_register_claim_file = register_claim_file;
264
265   ++i;
266   tv[i].tv_tag = LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK;
267   tv[i].tv_u.tv_register_all_symbols_read = register_all_symbols_read;
268
269   ++i;
270   tv[i].tv_tag = LDPT_REGISTER_CLEANUP_HOOK;
271   tv[i].tv_u.tv_register_cleanup = register_cleanup;
272
273   ++i;
274   tv[i].tv_tag = LDPT_ADD_SYMBOLS;
275   tv[i].tv_u.tv_add_symbols = add_symbols;
276
277   ++i;
278   tv[i].tv_tag = LDPT_GET_INPUT_FILE;
279   tv[i].tv_u.tv_get_input_file = get_input_file;
280
281   ++i;
282   tv[i].tv_tag = LDPT_GET_VIEW;
283   tv[i].tv_u.tv_get_view = get_view;
284
285   ++i;
286   tv[i].tv_tag = LDPT_RELEASE_INPUT_FILE;
287   tv[i].tv_u.tv_release_input_file = release_input_file;
288
289   ++i;
290   tv[i].tv_tag = LDPT_GET_SYMBOLS;
291   tv[i].tv_u.tv_get_symbols = get_symbols;
292
293   ++i;
294   tv[i].tv_tag = LDPT_GET_SYMBOLS_V2;
295   tv[i].tv_u.tv_get_symbols = get_symbols_v2;
296
297   ++i;
298   tv[i].tv_tag = LDPT_GET_SYMBOLS_V3;
299   tv[i].tv_u.tv_get_symbols = get_symbols_v3;
300
301   ++i;
302   tv[i].tv_tag = LDPT_ADD_INPUT_FILE;
303   tv[i].tv_u.tv_add_input_file = add_input_file;
304
305   ++i;
306   tv[i].tv_tag = LDPT_ADD_INPUT_LIBRARY;
307   tv[i].tv_u.tv_add_input_library = add_input_library;
308
309   ++i;
310   tv[i].tv_tag = LDPT_SET_EXTRA_LIBRARY_PATH;
311   tv[i].tv_u.tv_set_extra_library_path = set_extra_library_path;
312
313   ++i;
314   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_COUNT;
315   tv[i].tv_u.tv_get_input_section_count = get_input_section_count;
316
317   ++i;
318   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_TYPE;
319   tv[i].tv_u.tv_get_input_section_type = get_input_section_type;
320
321   ++i;
322   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_NAME;
323   tv[i].tv_u.tv_get_input_section_name = get_input_section_name;
324
325   ++i;
326   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_CONTENTS;
327   tv[i].tv_u.tv_get_input_section_contents = get_input_section_contents;
328
329   ++i;
330   tv[i].tv_tag = LDPT_UPDATE_SECTION_ORDER;
331   tv[i].tv_u.tv_update_section_order = update_section_order;
332
333   ++i;
334   tv[i].tv_tag = LDPT_ALLOW_SECTION_ORDERING;
335   tv[i].tv_u.tv_allow_section_ordering = allow_section_ordering;
336
337   ++i;
338   tv[i].tv_tag = LDPT_ALLOW_UNIQUE_SEGMENT_FOR_SECTIONS;
339   tv[i].tv_u.tv_allow_unique_segment_for_sections
340     = allow_unique_segment_for_sections;
341
342   ++i;
343   tv[i].tv_tag = LDPT_UNIQUE_SEGMENT_FOR_SECTIONS;
344   tv[i].tv_u.tv_unique_segment_for_sections = unique_segment_for_sections;
345
346   ++i;
347   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_ALIGNMENT;
348   tv[i].tv_u.tv_get_input_section_alignment = get_input_section_alignment;
349
350   ++i;
351   tv[i].tv_tag = LDPT_GET_INPUT_SECTION_SIZE;
352   tv[i].tv_u.tv_get_input_section_size = get_input_section_size;
353
354   ++i;
355   tv[i].tv_tag = LDPT_REGISTER_NEW_INPUT_HOOK;
356   tv[i].tv_u.tv_register_new_input = register_new_input;
357
358   ++i;
359   tv[i].tv_tag = LDPT_GET_WRAP_SYMBOLS;
360   tv[i].tv_u.tv_get_wrap_symbols = get_wrap_symbols;
361
362   ++i;
363   tv[i].tv_tag = LDPT_NULL;
364   tv[i].tv_u.tv_val = 0;
365
366   gold_assert(i == tv_size - 1);
367
368   // Call the onload entry point.
369   (*onload)(tv);
370
371   delete[] tv;
372 #endif // ENABLE_PLUGINS
373 }
374
375 // Call the plugin claim-file handler.
376
377 inline bool
378 Plugin::claim_file(struct ld_plugin_input_file* plugin_input_file)
379 {
380   int claimed = 0;
381
382   if (this->claim_file_handler_ != NULL)
383     {
384       (*this->claim_file_handler_)(plugin_input_file, &claimed);
385       if (claimed)
386         return true;
387     }
388   return false;
389 }
390
391 // Call the all-symbols-read handler.
392
393 inline void
394 Plugin::all_symbols_read()
395 {
396   if (this->all_symbols_read_handler_ != NULL)
397     (*this->all_symbols_read_handler_)();
398 }
399
400 // Call the new_input handler.
401
402 inline void
403 Plugin::new_input(struct ld_plugin_input_file* plugin_input_file)
404 {
405   if (this->new_input_handler_ != NULL)
406     (*this->new_input_handler_)(plugin_input_file);
407 }
408
409 // Call the cleanup handler.
410
411 inline void
412 Plugin::cleanup()
413 {
414   if (this->cleanup_handler_ != NULL && !this->cleanup_done_)
415     {
416       // Set this flag before calling to prevent a recursive plunge
417       // in the event that a plugin's cleanup handler issues a
418       // fatal error.
419       this->cleanup_done_ = true;
420       (*this->cleanup_handler_)();
421     }
422 }
423
424 // This task is used to rescan archives as needed.
425
426 class Plugin_rescan : public Task
427 {
428  public:
429   Plugin_rescan(Task_token* this_blocker, Task_token* next_blocker)
430     : this_blocker_(this_blocker), next_blocker_(next_blocker)
431   { }
432
433   ~Plugin_rescan()
434   {
435     delete this->this_blocker_;
436   }
437
438   Task_token*
439   is_runnable()
440   {
441     if (this->this_blocker_->is_blocked())
442       return this->this_blocker_;
443     return NULL;
444   }
445
446   void
447   locks(Task_locker* tl)
448   { tl->add(this, this->next_blocker_); }
449
450   void
451   run(Workqueue*)
452   { parameters->options().plugins()->rescan(this); }
453
454   std::string
455   get_name() const
456   { return "Plugin_rescan"; }
457
458  private:
459   Task_token* this_blocker_;
460   Task_token* next_blocker_;
461 };
462
463 // Plugin_manager methods.
464
465 Plugin_manager::~Plugin_manager()
466 {
467   for (Plugin_list::iterator p = this->plugins_.begin();
468        p != this->plugins_.end();
469        ++p)
470     delete *p;
471   this->plugins_.clear();
472   for (Object_list::iterator obj = this->objects_.begin();
473        obj != this->objects_.end();
474        ++obj)
475     delete *obj;
476   this->objects_.clear();
477   delete this->lock_;
478 }
479
480 // Load all plugin libraries.
481
482 void
483 Plugin_manager::load_plugins(Layout* layout)
484 {
485   this->layout_ = layout;
486   for (this->current_ = this->plugins_.begin();
487        this->current_ != this->plugins_.end();
488        ++this->current_)
489     (*this->current_)->load();
490 }
491
492 // Call the plugin claim-file handlers in turn to see if any claim the file.
493
494 Pluginobj*
495 Plugin_manager::claim_file(Input_file* input_file, off_t offset,
496                            off_t filesize, Object* elf_object)
497 {
498   bool lock_initialized = this->initialize_lock_.initialize();
499
500   gold_assert(lock_initialized);
501   Hold_lock hl(*this->lock_);
502
503   unsigned int handle = this->objects_.size();
504   this->input_file_ = input_file;
505   this->plugin_input_file_.name = input_file->filename().c_str();
506   this->plugin_input_file_.fd = input_file->file().descriptor();
507   this->plugin_input_file_.offset = offset;
508   this->plugin_input_file_.filesize = filesize;
509   this->plugin_input_file_.handle = reinterpret_cast<void*>(handle);
510   if (elf_object != NULL)
511     this->objects_.push_back(elf_object);
512   this->in_claim_file_handler_ = true;
513
514   for (this->current_ = this->plugins_.begin();
515        this->current_ != this->plugins_.end();
516        ++this->current_)
517     {
518       // If we aren't yet in replacement phase, allow plugins to claim input
519       // files, otherwise notify the plugin of the new input file, if needed.
520       if (!this->in_replacement_phase_)
521         {
522           if ((*this->current_)->claim_file(&this->plugin_input_file_))
523             {
524               this->any_claimed_ = true;
525               this->in_claim_file_handler_ = false;
526
527               if (this->objects_.size() > handle
528                   && this->objects_[handle]->pluginobj() != NULL)
529                 return this->objects_[handle]->pluginobj();
530
531               // If the plugin claimed the file but did not call the
532               // add_symbols callback, we need to create the Pluginobj now.
533               Pluginobj* obj = this->make_plugin_object(handle);
534               return obj;
535             }
536         }
537       else
538         {
539           (*this->current_)->new_input(&this->plugin_input_file_);
540         }
541     }
542
543   this->in_claim_file_handler_ = false;
544   return NULL;
545 }
546
547 // Save an archive.  This is used so that a plugin can add a file
548 // which refers to a symbol which was not previously referenced.  In
549 // that case we want to pretend that the symbol was referenced before,
550 // and pull in the archive object.
551
552 void
553 Plugin_manager::save_archive(Archive* archive)
554 {
555   if (this->in_replacement_phase_ || !this->any_claimed_)
556     delete archive;
557   else
558     this->rescannable_.push_back(Rescannable(archive));
559 }
560
561 // Save an Input_group.  This is like save_archive.
562
563 void
564 Plugin_manager::save_input_group(Input_group* input_group)
565 {
566   if (this->in_replacement_phase_ || !this->any_claimed_)
567     delete input_group;
568   else
569     this->rescannable_.push_back(Rescannable(input_group));
570 }
571
572 // Call the all-symbols-read handlers.
573
574 void
575 Plugin_manager::all_symbols_read(Workqueue* workqueue, Task* task,
576                                  Input_objects* input_objects,
577                                  Symbol_table* symtab,
578                                  Dirsearch* dirpath, Mapfile* mapfile,
579                                  Task_token** last_blocker)
580 {
581   this->in_replacement_phase_ = true;
582   this->workqueue_ = workqueue;
583   this->task_ = task;
584   this->input_objects_ = input_objects;
585   this->symtab_ = symtab;
586   this->dirpath_ = dirpath;
587   this->mapfile_ = mapfile;
588   this->this_blocker_ = NULL;
589
590   // Set symbols used in defsym expressions as seen in real ELF.
591   Layout *layout = parameters->options().plugins()->layout();
592   layout->script_options()->set_defsym_uses_in_real_elf(symtab);
593   layout->script_options()->find_defsym_defs(this->defsym_defines_set_);
594
595   for (this->current_ = this->plugins_.begin();
596        this->current_ != this->plugins_.end();
597        ++this->current_)
598     (*this->current_)->all_symbols_read();
599
600   if (this->any_added_)
601     {
602       Task_token* next_blocker = new Task_token(true);
603       next_blocker->add_blocker();
604       workqueue->queue(new Plugin_rescan(this->this_blocker_, next_blocker));
605       this->this_blocker_ = next_blocker;
606     }
607
608   *last_blocker = this->this_blocker_;
609 }
610
611 // This is called when we see a new undefined symbol.  If we are in
612 // the replacement phase, this means that we may need to rescan some
613 // archives we have previously seen.
614
615 void
616 Plugin_manager::new_undefined_symbol(Symbol* sym)
617 {
618   if (this->in_replacement_phase_)
619     this->undefined_symbols_.push_back(sym);
620 }
621
622 // Rescan archives as needed.  This handles the case where a new
623 // object file added by a plugin has an undefined reference to some
624 // symbol defined in an archive.
625
626 void
627 Plugin_manager::rescan(Task* task)
628 {
629   size_t rescan_pos = 0;
630   size_t rescan_size = this->rescannable_.size();
631   while (!this->undefined_symbols_.empty())
632     {
633       if (rescan_pos >= rescan_size)
634         {
635           this->undefined_symbols_.clear();
636           return;
637         }
638
639       Undefined_symbol_list undefs;
640       undefs.reserve(this->undefined_symbols_.size());
641       this->undefined_symbols_.swap(undefs);
642
643       size_t min_rescan_pos = rescan_size;
644
645       for (Undefined_symbol_list::const_iterator p = undefs.begin();
646            p != undefs.end();
647            ++p)
648         {
649           if (!(*p)->is_undefined())
650             continue;
651
652           this->undefined_symbols_.push_back(*p);
653
654           // Find the first rescan archive which defines this symbol,
655           // starting at the current rescan position.  The rescan position
656           // exists so that given -la -lb -lc we don't look for undefined
657           // symbols in -lb back in -la, but instead get the definition
658           // from -lc.  Don't bother to look past the current minimum
659           // rescan position.
660           for (size_t i = rescan_pos; i < min_rescan_pos; ++i)
661             {
662               if (this->rescannable_defines(i, *p))
663                 {
664                   min_rescan_pos = i;
665                   break;
666                 }
667             }
668         }
669
670       if (min_rescan_pos >= rescan_size)
671         {
672           // We didn't find any rescannable archives which define any
673           // undefined symbols.
674           return;
675         }
676
677       const Rescannable& r(this->rescannable_[min_rescan_pos]);
678       if (r.is_archive)
679         {
680           Task_lock_obj<Archive> tl(task, r.u.archive);
681           r.u.archive->add_symbols(this->symtab_, this->layout_,
682                                    this->input_objects_, this->mapfile_);
683         }
684       else
685         {
686           size_t next_saw_undefined = this->symtab_->saw_undefined();
687           size_t saw_undefined;
688           do
689             {
690               saw_undefined = next_saw_undefined;
691
692               for (Input_group::const_iterator p = r.u.input_group->begin();
693                    p != r.u.input_group->end();
694                    ++p)
695                 {
696                   Task_lock_obj<Archive> tl(task, *p);
697
698                   (*p)->add_symbols(this->symtab_, this->layout_,
699                                     this->input_objects_, this->mapfile_);
700                 }
701
702               next_saw_undefined = this->symtab_->saw_undefined();
703             }
704           while (saw_undefined != next_saw_undefined);
705         }
706
707       for (size_t i = rescan_pos; i < min_rescan_pos + 1; ++i)
708         {
709           if (this->rescannable_[i].is_archive)
710             delete this->rescannable_[i].u.archive;
711           else
712             delete this->rescannable_[i].u.input_group;
713         }
714
715       rescan_pos = min_rescan_pos + 1;
716     }
717 }
718
719 // Return whether the rescannable at index I defines SYM.
720
721 bool
722 Plugin_manager::rescannable_defines(size_t i, Symbol* sym)
723 {
724   const Rescannable& r(this->rescannable_[i]);
725   if (r.is_archive)
726     return r.u.archive->defines_symbol(sym);
727   else
728     {
729       for (Input_group::const_iterator p = r.u.input_group->begin();
730            p != r.u.input_group->end();
731            ++p)
732         {
733           if ((*p)->defines_symbol(sym))
734             return true;
735         }
736       return false;
737     }
738 }
739
740 // Layout deferred objects.
741
742 void
743 Plugin_manager::layout_deferred_objects()
744 {
745   Deferred_layout_list::iterator obj;
746
747   for (obj = this->deferred_layout_objects_.begin();
748        obj != this->deferred_layout_objects_.end();
749        ++obj)
750     {
751       // Lock the object so we can read from it.  This is only called
752       // single-threaded from queue_middle_tasks, so it is OK to lock.
753       // Unfortunately we have no way to pass in a Task token.
754       const Task* dummy_task = reinterpret_cast<const Task*>(-1);
755       Task_lock_obj<Object> tl(dummy_task, *obj);
756       (*obj)->layout_deferred_sections(this->layout_);
757     }
758 }
759
760 // Call the cleanup handlers.
761
762 void
763 Plugin_manager::cleanup()
764 {
765   if (this->any_added_)
766     {
767       // If any input files were added, close all the input files.
768       // This is because the plugin may want to remove them, and on
769       // Windows you are not allowed to remove an open file.
770       close_all_descriptors();
771     }
772
773   for (this->current_ = this->plugins_.begin();
774        this->current_ != this->plugins_.end();
775        ++this->current_)
776     (*this->current_)->cleanup();
777 }
778
779 // Make a new Pluginobj object.  This is called when the plugin calls
780 // the add_symbols API.
781
782 Pluginobj*
783 Plugin_manager::make_plugin_object(unsigned int handle)
784 {
785   // Make sure we aren't asked to make an object for the same handle twice.
786   if (this->objects_.size() != handle
787       && this->objects_[handle]->pluginobj() != NULL)
788     return NULL;
789
790   Pluginobj* obj = make_sized_plugin_object(this->input_file_,
791                                             this->plugin_input_file_.offset,
792                                             this->plugin_input_file_.filesize);
793
794
795   // If the elf object for this file was pushed into the objects_ vector, delete
796   // it to make room for the Pluginobj as this file is claimed.
797   if (this->objects_.size() != handle)
798     this->objects_.pop_back();
799
800   this->objects_.push_back(obj);
801   return obj;
802 }
803
804 // Get the input file information with an open (possibly re-opened)
805 // file descriptor.
806
807 ld_plugin_status
808 Plugin_manager::get_input_file(unsigned int handle,
809                                struct ld_plugin_input_file* file)
810 {
811   Pluginobj* obj = this->object(handle)->pluginobj();
812   if (obj == NULL)
813     return LDPS_BAD_HANDLE;
814
815   obj->lock(this->task_);
816   file->name = obj->filename().c_str();
817   file->fd = obj->descriptor();
818   file->offset = obj->offset();
819   file->filesize = obj->filesize();
820   file->handle = reinterpret_cast<void*>(handle);
821   return LDPS_OK;
822 }
823
824 // Release the input file.
825
826 ld_plugin_status
827 Plugin_manager::release_input_file(unsigned int handle)
828 {
829   if (this->object(handle) == NULL)
830     return LDPS_BAD_HANDLE;
831
832   Pluginobj* obj = this->object(handle)->pluginobj();
833
834   if (obj == NULL)
835     return LDPS_BAD_HANDLE;
836
837   obj->unlock(this->task_);
838   return LDPS_OK;
839 }
840
841 // Get the elf object corresponding to the handle. Return NULL if we
842 // found a Pluginobj instead.
843
844 Object*
845 Plugin_manager::get_elf_object(const void* handle)
846 {
847   Object* obj = this->object(
848       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
849
850   // The object should not be a Pluginobj.
851   if (obj == NULL
852       || obj->pluginobj() != NULL)
853     return NULL;
854
855   return obj;
856 }
857
858 ld_plugin_status
859 Plugin_manager::get_view(unsigned int handle, const void **viewp)
860 {
861   off_t offset;
862   size_t filesize;
863   Input_file *input_file;
864   if (this->in_claim_file_handler_)
865     {
866       // We are being called from the claim_file hook.
867       const struct ld_plugin_input_file &f = this->plugin_input_file_;
868       offset = f.offset;
869       filesize = f.filesize;
870       input_file = this->input_file_;
871     }
872   else
873     {
874       // An already claimed file.
875       if (this->object(handle) == NULL)
876         return LDPS_BAD_HANDLE;
877       Pluginobj* obj = this->object(handle)->pluginobj();
878       if (obj == NULL)
879         return LDPS_BAD_HANDLE;
880       offset = obj->offset();
881       filesize = obj->filesize();
882       input_file = obj->input_file();
883     }
884   *viewp = (void*) input_file->file().get_view(offset, 0, filesize, false,
885                                                false);
886   return LDPS_OK;
887 }
888
889 // Add a new library path.
890
891 ld_plugin_status
892 Plugin_manager::set_extra_library_path(const char* path)
893 {
894   this->extra_search_path_ = std::string(path);
895   return LDPS_OK;
896 }
897
898 // Add a new input file.
899
900 ld_plugin_status
901 Plugin_manager::add_input_file(const char* pathname, bool is_lib)
902 {
903   Input_file_argument file(pathname,
904                            (is_lib
905                             ? Input_file_argument::INPUT_FILE_TYPE_LIBRARY
906                             : Input_file_argument::INPUT_FILE_TYPE_FILE),
907                            (is_lib
908                             ? this->extra_search_path_.c_str()
909                             : ""),
910                            false,
911                            this->options_);
912   Input_argument* input_argument = new Input_argument(file);
913   Task_token* next_blocker = new Task_token(true);
914   next_blocker->add_blocker();
915   if (parameters->incremental())
916     gold_error(_("input files added by plug-ins in --incremental mode not "
917                  "supported yet"));
918   this->workqueue_->queue_soon(new Read_symbols(this->input_objects_,
919                                                 this->symtab_,
920                                                 this->layout_,
921                                                 this->dirpath_,
922                                                 0,
923                                                 this->mapfile_,
924                                                 input_argument,
925                                                 NULL,
926                                                 NULL,
927                                                 this->this_blocker_,
928                                                 next_blocker));
929   this->this_blocker_ = next_blocker;
930   this->any_added_ = true;
931   return LDPS_OK;
932 }
933
934 // Class Pluginobj.
935
936 Pluginobj::Pluginobj(const std::string& name, Input_file* input_file,
937                      off_t offset, off_t filesize)
938   : Object(name, input_file, false, offset),
939     nsyms_(0), syms_(NULL), symbols_(), filesize_(filesize), comdat_map_()
940 {
941 }
942
943 // Return TRUE if a defined symbol is referenced from outside the
944 // universe of claimed objects.  Only references from relocatable,
945 // non-IR (unclaimed) objects count as a reference.  References from
946 // dynamic objects count only as "visible".
947
948 static inline bool
949 is_referenced_from_outside(Symbol* lsym)
950 {
951   if (lsym->in_real_elf())
952     return true;
953   if (parameters->options().relocatable())
954     return true;
955   if (parameters->options().is_undefined(lsym->name()))
956     return true;
957   return false;
958 }
959
960 // Return TRUE if a defined symbol might be reachable from outside the
961 // load module.
962
963 static inline bool
964 is_visible_from_outside(Symbol* lsym)
965 {
966   if (lsym->in_dyn())
967     return true;
968   if (parameters->options().export_dynamic() || parameters->options().shared()
969       || parameters->options().in_dynamic_list(lsym->name())
970       || parameters->options().is_export_dynamic_symbol(lsym->name()))
971     return lsym->is_externally_visible();
972   return false;
973 }
974
975 // Get symbol resolution info.
976
977 ld_plugin_status
978 Pluginobj::get_symbol_resolution_info(Symbol_table* symtab,
979                                       int nsyms,
980                                       ld_plugin_symbol* syms,
981                                       int version) const
982 {
983   // For version 1 of this interface, we cannot use
984   // LDPR_PREVAILING_DEF_IRONLY_EXP, so we return LDPR_PREVAILING_DEF
985   // instead.
986   const ld_plugin_symbol_resolution ldpr_prevailing_def_ironly_exp
987       = (version > 1
988          ? LDPR_PREVAILING_DEF_IRONLY_EXP
989          : LDPR_PREVAILING_DEF);
990
991   if (nsyms > this->nsyms_)
992     return LDPS_NO_SYMS;
993
994   if (static_cast<size_t>(nsyms) > this->symbols_.size())
995     {
996       // We never decided to include this object. We mark all symbols as
997       // preempted.
998       gold_assert(this->symbols_.size() == 0);
999       for (int i = 0; i < nsyms; i++)
1000         syms[i].resolution = LDPR_PREEMPTED_REG;
1001       return version > 2 ? LDPS_NO_SYMS : LDPS_OK;
1002     }
1003
1004   Plugin_manager* plugins = parameters->options().plugins();
1005   for (int i = 0; i < nsyms; i++)
1006     {
1007       ld_plugin_symbol* isym = &syms[i];
1008       Symbol* lsym = this->symbols_[i];
1009       if (lsym->is_forwarder())
1010         lsym = symtab->resolve_forwards(lsym);
1011       ld_plugin_symbol_resolution res = LDPR_UNKNOWN;
1012
1013       if (plugins->is_defsym_def(lsym->name()))
1014         {
1015           // The symbol is redefined via defsym.
1016           res = LDPR_PREEMPTED_REG;
1017         }
1018       else if (lsym->is_undefined())
1019         {
1020           // The symbol remains undefined.
1021           res = LDPR_UNDEF;
1022         }
1023       else if (isym->def == LDPK_UNDEF
1024                || isym->def == LDPK_WEAKUNDEF
1025                || isym->def == LDPK_COMMON)
1026         {
1027           // The original symbol was undefined or common.
1028           if (lsym->source() != Symbol::FROM_OBJECT)
1029             res = LDPR_RESOLVED_EXEC;
1030           else if (lsym->object()->pluginobj() == this)
1031             {
1032               if (is_referenced_from_outside(lsym))
1033                 res = LDPR_PREVAILING_DEF;
1034               else if (is_visible_from_outside(lsym))
1035                 res = ldpr_prevailing_def_ironly_exp;
1036               else
1037                 res = LDPR_PREVAILING_DEF_IRONLY;
1038             }
1039           else if (lsym->object()->pluginobj() != NULL)
1040             res = LDPR_RESOLVED_IR;
1041           else if (lsym->object()->is_dynamic())
1042             res = LDPR_RESOLVED_DYN;
1043           else
1044             res = LDPR_RESOLVED_EXEC;
1045         }
1046       else
1047         {
1048           // The original symbol was a definition.
1049           if (lsym->source() != Symbol::FROM_OBJECT)
1050             res = LDPR_PREEMPTED_REG;
1051           else if (lsym->object() == static_cast<const Object*>(this))
1052             {
1053               if (is_referenced_from_outside(lsym))
1054                 res = LDPR_PREVAILING_DEF;
1055               else if (is_visible_from_outside(lsym))
1056                 res = ldpr_prevailing_def_ironly_exp;
1057               else
1058                 res = LDPR_PREVAILING_DEF_IRONLY;
1059             }
1060           else
1061             res = (lsym->object()->pluginobj() != NULL
1062                    ? LDPR_PREEMPTED_IR
1063                    : LDPR_PREEMPTED_REG);
1064         }
1065       isym->resolution = res;
1066     }
1067   return LDPS_OK;
1068 }
1069
1070 // Return TRUE if the comdat group with key COMDAT_KEY from this object
1071 // should be kept.
1072
1073 bool
1074 Pluginobj::include_comdat_group(std::string comdat_key, Layout* layout)
1075 {
1076   std::pair<Comdat_map::iterator, bool> ins =
1077     this->comdat_map_.insert(std::make_pair(comdat_key, false));
1078
1079   // If this is the first time we've seen this comdat key, ask the
1080   // layout object whether it should be included.
1081   if (ins.second)
1082     ins.first->second = layout->find_or_add_kept_section(comdat_key,
1083                                                          NULL, 0, true,
1084                                                          true, NULL);
1085
1086   return ins.first->second;
1087 }
1088
1089 // Class Sized_pluginobj.
1090
1091 template<int size, bool big_endian>
1092 Sized_pluginobj<size, big_endian>::Sized_pluginobj(
1093     const std::string& name,
1094     Input_file* input_file,
1095     off_t offset,
1096     off_t filesize)
1097   : Pluginobj(name, input_file, offset, filesize)
1098 {
1099 }
1100
1101 // Read the symbols.  Not used for plugin objects.
1102
1103 template<int size, bool big_endian>
1104 void
1105 Sized_pluginobj<size, big_endian>::do_read_symbols(Read_symbols_data*)
1106 {
1107   gold_unreachable();
1108 }
1109
1110 // Lay out the input sections.  Not used for plugin objects.
1111
1112 template<int size, bool big_endian>
1113 void
1114 Sized_pluginobj<size, big_endian>::do_layout(Symbol_table*, Layout*,
1115                                              Read_symbols_data*)
1116 {
1117   gold_unreachable();
1118 }
1119
1120 // Add the symbols to the symbol table.
1121
1122 template<int size, bool big_endian>
1123 void
1124 Sized_pluginobj<size, big_endian>::do_add_symbols(Symbol_table* symtab,
1125                                                   Read_symbols_data*,
1126                                                   Layout* layout)
1127 {
1128   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1129   unsigned char symbuf[sym_size];
1130   elfcpp::Sym<size, big_endian> sym(symbuf);
1131   elfcpp::Sym_write<size, big_endian> osym(symbuf);
1132
1133   this->symbols_.resize(this->nsyms_);
1134
1135   for (int i = 0; i < this->nsyms_; ++i)
1136     {
1137       const struct ld_plugin_symbol* isym = &this->syms_[i];
1138       const char* name = isym->name;
1139       const char* ver = isym->version;
1140       elfcpp::Elf_Half shndx;
1141       elfcpp::STB bind;
1142       elfcpp::STV vis;
1143
1144       if (name != NULL && name[0] == '\0')
1145         name = NULL;
1146       if (ver != NULL && ver[0] == '\0')
1147         ver = NULL;
1148
1149       switch (isym->def)
1150         {
1151         case LDPK_WEAKDEF:
1152         case LDPK_WEAKUNDEF:
1153           bind = elfcpp::STB_WEAK;
1154           break;
1155         case LDPK_DEF:
1156         case LDPK_UNDEF:
1157         case LDPK_COMMON:
1158         default:
1159           bind = elfcpp::STB_GLOBAL;
1160           break;
1161         }
1162
1163       switch (isym->def)
1164         {
1165         case LDPK_DEF:
1166         case LDPK_WEAKDEF:
1167           shndx = elfcpp::SHN_ABS;
1168           break;
1169         case LDPK_COMMON:
1170           shndx = elfcpp::SHN_COMMON;
1171           break;
1172         case LDPK_UNDEF:
1173         case LDPK_WEAKUNDEF:
1174         default:
1175           shndx = elfcpp::SHN_UNDEF;
1176           break;
1177         }
1178
1179       switch (isym->visibility)
1180         {
1181         case LDPV_PROTECTED:
1182           vis = elfcpp::STV_PROTECTED;
1183           break;
1184         case LDPV_INTERNAL:
1185           vis = elfcpp::STV_INTERNAL;
1186           break;
1187         case LDPV_HIDDEN:
1188           vis = elfcpp::STV_HIDDEN;
1189           break;
1190         case LDPV_DEFAULT:
1191         default:
1192           vis = elfcpp::STV_DEFAULT;
1193           break;
1194         }
1195
1196       if (isym->comdat_key != NULL
1197           && isym->comdat_key[0] != '\0'
1198           && !this->include_comdat_group(isym->comdat_key, layout))
1199         shndx = elfcpp::SHN_UNDEF;
1200
1201       osym.put_st_name(0);
1202       osym.put_st_value(0);
1203       osym.put_st_size(0);
1204       osym.put_st_info(bind, elfcpp::STT_NOTYPE);
1205       osym.put_st_other(vis, 0);
1206       osym.put_st_shndx(shndx);
1207
1208       this->symbols_[i] =
1209         symtab->add_from_pluginobj<size, big_endian>(this, name, ver, &sym);
1210     }
1211 }
1212
1213 template<int size, bool big_endian>
1214 Archive::Should_include
1215 Sized_pluginobj<size, big_endian>::do_should_include_member(
1216     Symbol_table* symtab,
1217     Layout* layout,
1218     Read_symbols_data*,
1219     std::string* why)
1220 {
1221   char* tmpbuf = NULL;
1222   size_t tmpbuflen = 0;
1223
1224   for (int i = 0; i < this->nsyms_; ++i)
1225     {
1226       const struct ld_plugin_symbol& sym = this->syms_[i];
1227       if (sym.def == LDPK_UNDEF || sym.def == LDPK_WEAKUNDEF)
1228         continue;
1229       const char* name = sym.name;
1230       Symbol* symbol;
1231       Archive::Should_include t = Archive::should_include_member(symtab,
1232                                                                  layout,
1233                                                                  name,
1234                                                                  &symbol, why,
1235                                                                  &tmpbuf,
1236                                                                  &tmpbuflen);
1237       if (t == Archive::SHOULD_INCLUDE_YES)
1238         {
1239           if (tmpbuf != NULL)
1240             free(tmpbuf);
1241           return t;
1242         }
1243     }
1244   if (tmpbuf != NULL)
1245     free(tmpbuf);
1246   return Archive::SHOULD_INCLUDE_UNKNOWN;
1247 }
1248
1249 // Iterate over global symbols, calling a visitor class V for each.
1250
1251 template<int size, bool big_endian>
1252 void
1253 Sized_pluginobj<size, big_endian>::do_for_all_global_symbols(
1254     Read_symbols_data*,
1255     Library_base::Symbol_visitor_base* v)
1256 {
1257   for (int i = 0; i < this->nsyms_; ++i)
1258     {
1259       const struct ld_plugin_symbol& sym = this->syms_[i];
1260       if (sym.def != LDPK_UNDEF)
1261         v->visit(sym.name);
1262     }
1263 }
1264
1265 // Iterate over local symbols, calling a visitor class V for each GOT offset
1266 // associated with a local symbol.
1267 template<int size, bool big_endian>
1268 void
1269 Sized_pluginobj<size, big_endian>::do_for_all_local_got_entries(
1270     Got_offset_list::Visitor*) const
1271 {
1272   gold_unreachable();
1273 }
1274
1275 // Get the size of a section.  Not used for plugin objects.
1276
1277 template<int size, bool big_endian>
1278 uint64_t
1279 Sized_pluginobj<size, big_endian>::do_section_size(unsigned int)
1280 {
1281   gold_unreachable();
1282   return 0;
1283 }
1284
1285 // Get the name of a section.  Not used for plugin objects.
1286
1287 template<int size, bool big_endian>
1288 std::string
1289 Sized_pluginobj<size, big_endian>::do_section_name(unsigned int) const
1290 {
1291   gold_unreachable();
1292   return std::string();
1293 }
1294
1295 // Return a view of the contents of a section.  Not used for plugin objects.
1296
1297 template<int size, bool big_endian>
1298 const unsigned char*
1299 Sized_pluginobj<size, big_endian>::do_section_contents(
1300     unsigned int,
1301     section_size_type*,
1302     bool)
1303 {
1304   gold_unreachable();
1305   return NULL;
1306 }
1307
1308 // Return section flags.  Not used for plugin objects.
1309
1310 template<int size, bool big_endian>
1311 uint64_t
1312 Sized_pluginobj<size, big_endian>::do_section_flags(unsigned int)
1313 {
1314   gold_unreachable();
1315   return 0;
1316 }
1317
1318 // Return section entsize.  Not used for plugin objects.
1319
1320 template<int size, bool big_endian>
1321 uint64_t
1322 Sized_pluginobj<size, big_endian>::do_section_entsize(unsigned int)
1323 {
1324   gold_unreachable();
1325   return 0;
1326 }
1327
1328 // Return section address.  Not used for plugin objects.
1329
1330 template<int size, bool big_endian>
1331 uint64_t
1332 Sized_pluginobj<size, big_endian>::do_section_address(unsigned int)
1333 {
1334   gold_unreachable();
1335   return 0;
1336 }
1337
1338 // Return section type.  Not used for plugin objects.
1339
1340 template<int size, bool big_endian>
1341 unsigned int
1342 Sized_pluginobj<size, big_endian>::do_section_type(unsigned int)
1343 {
1344   gold_unreachable();
1345   return 0;
1346 }
1347
1348 // Return the section link field.  Not used for plugin objects.
1349
1350 template<int size, bool big_endian>
1351 unsigned int
1352 Sized_pluginobj<size, big_endian>::do_section_link(unsigned int)
1353 {
1354   gold_unreachable();
1355   return 0;
1356 }
1357
1358 // Return the section link field.  Not used for plugin objects.
1359
1360 template<int size, bool big_endian>
1361 unsigned int
1362 Sized_pluginobj<size, big_endian>::do_section_info(unsigned int)
1363 {
1364   gold_unreachable();
1365   return 0;
1366 }
1367
1368 // Return the section alignment.  Not used for plugin objects.
1369
1370 template<int size, bool big_endian>
1371 uint64_t
1372 Sized_pluginobj<size, big_endian>::do_section_addralign(unsigned int)
1373 {
1374   gold_unreachable();
1375   return 0;
1376 }
1377
1378 // Return the Xindex structure to use.  Not used for plugin objects.
1379
1380 template<int size, bool big_endian>
1381 Xindex*
1382 Sized_pluginobj<size, big_endian>::do_initialize_xindex()
1383 {
1384   gold_unreachable();
1385   return NULL;
1386 }
1387
1388 // Get symbol counts.  Don't count plugin objects; the replacement
1389 // files will provide the counts.
1390
1391 template<int size, bool big_endian>
1392 void
1393 Sized_pluginobj<size, big_endian>::do_get_global_symbol_counts(
1394     const Symbol_table*,
1395     size_t* defined,
1396     size_t* used) const
1397 {
1398   *defined = 0;
1399   *used = 0;
1400 }
1401
1402 // Get symbols.  Not used for plugin objects.
1403
1404 template<int size, bool big_endian>
1405 const Object::Symbols*
1406 Sized_pluginobj<size, big_endian>::do_get_global_symbols() const
1407 {
1408   gold_unreachable();
1409 }
1410
1411 // Class Plugin_finish.  This task runs after all replacement files have
1412 // been added.  For now, it's a placeholder for a possible plugin API
1413 // to allow the plugin to release most of its resources.  The cleanup
1414 // handlers must be called later, because they can remove the temporary
1415 // object files that are needed until the end of the link.
1416
1417 class Plugin_finish : public Task
1418 {
1419  public:
1420   Plugin_finish(Task_token* this_blocker, Task_token* next_blocker)
1421     : this_blocker_(this_blocker), next_blocker_(next_blocker)
1422   { }
1423
1424   ~Plugin_finish()
1425   {
1426     if (this->this_blocker_ != NULL)
1427       delete this->this_blocker_;
1428   }
1429
1430   Task_token*
1431   is_runnable()
1432   {
1433     if (this->this_blocker_ != NULL && this->this_blocker_->is_blocked())
1434       return this->this_blocker_;
1435     return NULL;
1436   }
1437
1438   void
1439   locks(Task_locker* tl)
1440   { tl->add(this, this->next_blocker_); }
1441
1442   void
1443   run(Workqueue*)
1444   {
1445     // We could call early cleanup handlers here.
1446   }
1447
1448   std::string
1449   get_name() const
1450   { return "Plugin_finish"; }
1451
1452  private:
1453   Task_token* this_blocker_;
1454   Task_token* next_blocker_;
1455 };
1456
1457 // Class Plugin_hook.
1458
1459 Plugin_hook::~Plugin_hook()
1460 {
1461 }
1462
1463 // Return whether a Plugin_hook task is runnable.
1464
1465 Task_token*
1466 Plugin_hook::is_runnable()
1467 {
1468   if (this->this_blocker_ != NULL && this->this_blocker_->is_blocked())
1469     return this->this_blocker_;
1470   return NULL;
1471 }
1472
1473 // Return a Task_locker for a Plugin_hook task.  We don't need any
1474 // locks here.
1475
1476 void
1477 Plugin_hook::locks(Task_locker*)
1478 {
1479 }
1480
1481 // Run the "all symbols read" plugin hook.
1482
1483 void
1484 Plugin_hook::run(Workqueue* workqueue)
1485 {
1486   gold_assert(this->options_.has_plugins());
1487   Symbol* start_sym = this->symtab_->lookup(parameters->entry());
1488   if (start_sym != NULL)
1489     start_sym->set_in_real_elf();
1490
1491   this->options_.plugins()->all_symbols_read(workqueue,
1492                                              this,
1493                                              this->input_objects_,
1494                                              this->symtab_,
1495                                              this->dirpath_,
1496                                              this->mapfile_,
1497                                              &this->this_blocker_);
1498   workqueue->queue_soon(new Plugin_finish(this->this_blocker_,
1499                                           this->next_blocker_));
1500 }
1501
1502 // The C interface routines called by the plugins.
1503
1504 #ifdef ENABLE_PLUGINS
1505
1506 // Register a claim-file handler.
1507
1508 static enum ld_plugin_status
1509 register_claim_file(ld_plugin_claim_file_handler handler)
1510 {
1511   gold_assert(parameters->options().has_plugins());
1512   parameters->options().plugins()->set_claim_file_handler(handler);
1513   return LDPS_OK;
1514 }
1515
1516 // Register an all-symbols-read handler.
1517
1518 static enum ld_plugin_status
1519 register_all_symbols_read(ld_plugin_all_symbols_read_handler handler)
1520 {
1521   gold_assert(parameters->options().has_plugins());
1522   parameters->options().plugins()->set_all_symbols_read_handler(handler);
1523   return LDPS_OK;
1524 }
1525
1526 // Register a cleanup handler.
1527
1528 static enum ld_plugin_status
1529 register_cleanup(ld_plugin_cleanup_handler handler)
1530 {
1531   gold_assert(parameters->options().has_plugins());
1532   parameters->options().plugins()->set_cleanup_handler(handler);
1533   return LDPS_OK;
1534 }
1535
1536 // Add symbols from a plugin-claimed input file.
1537
1538 static enum ld_plugin_status
1539 add_symbols(void* handle, int nsyms, const ld_plugin_symbol* syms)
1540 {
1541   gold_assert(parameters->options().has_plugins());
1542   Pluginobj* obj = parameters->options().plugins()->make_plugin_object(
1543       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1544   if (obj == NULL)
1545     return LDPS_ERR;
1546   obj->store_incoming_symbols(nsyms, syms);
1547   return LDPS_OK;
1548 }
1549
1550 // Get the input file information with an open (possibly re-opened)
1551 // file descriptor.
1552
1553 static enum ld_plugin_status
1554 get_input_file(const void* handle, struct ld_plugin_input_file* file)
1555 {
1556   gold_assert(parameters->options().has_plugins());
1557   unsigned int obj_index =
1558       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle));
1559   return parameters->options().plugins()->get_input_file(obj_index, file);
1560 }
1561
1562 // Release the input file.
1563
1564 static enum ld_plugin_status
1565 release_input_file(const void* handle)
1566 {
1567   gold_assert(parameters->options().has_plugins());
1568   unsigned int obj_index =
1569       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle));
1570   return parameters->options().plugins()->release_input_file(obj_index);
1571 }
1572
1573 static enum ld_plugin_status
1574 get_view(const void *handle, const void **viewp)
1575 {
1576   gold_assert(parameters->options().has_plugins());
1577   unsigned int obj_index =
1578       static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle));
1579   return parameters->options().plugins()->get_view(obj_index, viewp);
1580 }
1581
1582 // Get the symbol resolution info for a plugin-claimed input file.
1583
1584 static enum ld_plugin_status
1585 get_symbols(const void* handle, int nsyms, ld_plugin_symbol* syms)
1586 {
1587   gold_assert(parameters->options().has_plugins());
1588   Plugin_manager* plugins = parameters->options().plugins();
1589   Object* obj = plugins->object(
1590     static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1591   if (obj == NULL)
1592     return LDPS_ERR;
1593   Pluginobj* plugin_obj = obj->pluginobj();
1594   if (plugin_obj == NULL)
1595     return LDPS_ERR;
1596   Symbol_table* symtab = plugins->symtab();
1597   return plugin_obj->get_symbol_resolution_info(symtab, nsyms, syms, 1);
1598 }
1599
1600 // Version 2 of the above.  The only difference is that this version
1601 // is allowed to return the resolution code LDPR_PREVAILING_DEF_IRONLY_EXP.
1602
1603 static enum ld_plugin_status
1604 get_symbols_v2(const void* handle, int nsyms, ld_plugin_symbol* syms)
1605 {
1606   gold_assert(parameters->options().has_plugins());
1607   Plugin_manager* plugins = parameters->options().plugins();
1608   Object* obj = plugins->object(
1609     static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1610   if (obj == NULL)
1611     return LDPS_ERR;
1612   Pluginobj* plugin_obj = obj->pluginobj();
1613   if (plugin_obj == NULL)
1614     return LDPS_ERR;
1615   Symbol_table* symtab = plugins->symtab();
1616   return plugin_obj->get_symbol_resolution_info(symtab, nsyms, syms, 2);
1617 }
1618
1619 // Version 3 of the above.  The only difference from v2 is that it
1620 // returns LDPS_NO_SYMS instead of LDPS_OK for the objects we never
1621 // decided to include.
1622
1623 static enum ld_plugin_status
1624 get_symbols_v3(const void* handle, int nsyms, ld_plugin_symbol* syms)
1625 {
1626   gold_assert(parameters->options().has_plugins());
1627   Plugin_manager* plugins = parameters->options().plugins();
1628   Object* obj = plugins->object(
1629     static_cast<unsigned int>(reinterpret_cast<intptr_t>(handle)));
1630   if (obj == NULL)
1631     return LDPS_ERR;
1632   Pluginobj* plugin_obj = obj->pluginobj();
1633   if (plugin_obj == NULL)
1634     return LDPS_ERR;
1635   Symbol_table* symtab = plugins->symtab();
1636   return plugin_obj->get_symbol_resolution_info(symtab, nsyms, syms, 3);
1637 }
1638
1639 // Add a new (real) input file generated by a plugin.
1640
1641 static enum ld_plugin_status
1642 add_input_file(const char* pathname)
1643 {
1644   gold_assert(parameters->options().has_plugins());
1645   return parameters->options().plugins()->add_input_file(pathname, false);
1646 }
1647
1648 // Add a new (real) library required by a plugin.
1649
1650 static enum ld_plugin_status
1651 add_input_library(const char* pathname)
1652 {
1653   gold_assert(parameters->options().has_plugins());
1654   return parameters->options().plugins()->add_input_file(pathname, true);
1655 }
1656
1657 // Set the extra library path to be used by libraries added via
1658 // add_input_library
1659
1660 static enum ld_plugin_status
1661 set_extra_library_path(const char* path)
1662 {
1663   gold_assert(parameters->options().has_plugins());
1664   return parameters->options().plugins()->set_extra_library_path(path);
1665 }
1666
1667 // Issue a diagnostic message from a plugin.
1668
1669 static enum ld_plugin_status
1670 message(int level, const char* format, ...)
1671 {
1672   va_list args;
1673   va_start(args, format);
1674
1675   switch (level)
1676     {
1677     case LDPL_INFO:
1678       parameters->errors()->info(format, args);
1679       break;
1680     case LDPL_WARNING:
1681       parameters->errors()->warning(format, args);
1682       break;
1683     case LDPL_ERROR:
1684     default:
1685       parameters->errors()->error(format, args);
1686       break;
1687     case LDPL_FATAL:
1688       parameters->errors()->fatal(format, args);
1689       break;
1690     }
1691
1692   va_end(args);
1693   return LDPS_OK;
1694 }
1695
1696 // Get the section count of the object corresponding to the handle.  This
1697 // plugin interface can only be called in the claim_file handler of the plugin.
1698
1699 static enum ld_plugin_status
1700 get_input_section_count(const void* handle, unsigned int* count)
1701 {
1702   gold_assert(parameters->options().has_plugins());
1703
1704   if (!parameters->options().plugins()->in_claim_file_handler())
1705     return LDPS_ERR;
1706
1707   Object* obj = parameters->options().plugins()->get_elf_object(handle);
1708
1709   if (obj == NULL)
1710     return LDPS_ERR;
1711
1712   *count = obj->shnum();
1713   return LDPS_OK;
1714 }
1715
1716 // Get the type of the specified section in the object corresponding
1717 // to the handle.  This plugin interface can only be called in the
1718 // claim_file handler of the plugin.
1719
1720 static enum ld_plugin_status
1721 get_input_section_type(const struct ld_plugin_section section,
1722                        unsigned int* type)
1723 {
1724   gold_assert(parameters->options().has_plugins());
1725
1726   if (!parameters->options().plugins()->in_claim_file_handler())
1727     return LDPS_ERR;
1728
1729   Object* obj
1730     = parameters->options().plugins()->get_elf_object(section.handle); 
1731
1732   if (obj == NULL)
1733     return LDPS_BAD_HANDLE;
1734
1735   *type = obj->section_type(section.shndx);
1736   return LDPS_OK;
1737 }
1738
1739 // Get the name of the specified section in the object corresponding
1740 // to the handle.  This plugin interface can only be called in the
1741 // claim_file handler of the plugin.
1742
1743 static enum ld_plugin_status
1744 get_input_section_name(const struct ld_plugin_section section,
1745                        char** section_name_ptr)
1746 {
1747   gold_assert(parameters->options().has_plugins());
1748
1749   if (!parameters->options().plugins()->in_claim_file_handler())
1750     return LDPS_ERR;
1751
1752   Object* obj
1753     = parameters->options().plugins()->get_elf_object(section.handle); 
1754
1755   if (obj == NULL)
1756     return LDPS_BAD_HANDLE;
1757
1758   // Check if the object is locked before getting the section name.
1759   gold_assert(obj->is_locked());
1760
1761   const std::string section_name = obj->section_name(section.shndx);
1762   *section_name_ptr = static_cast<char*>(malloc(section_name.length() + 1));
1763   memcpy(*section_name_ptr, section_name.c_str(), section_name.length() + 1);
1764   return LDPS_OK;
1765 }
1766
1767 // Get the contents of the specified section in the object corresponding
1768 // to the handle.  This plugin interface can only be called in the
1769 // claim_file handler of the plugin.
1770
1771 static enum ld_plugin_status
1772 get_input_section_contents(const struct ld_plugin_section section,
1773                            const unsigned char** section_contents_ptr,
1774                            size_t* len)
1775 {
1776   gold_assert(parameters->options().has_plugins());
1777
1778   if (!parameters->options().plugins()->in_claim_file_handler())
1779     return LDPS_ERR;
1780
1781   Object* obj
1782     = parameters->options().plugins()->get_elf_object(section.handle); 
1783
1784   if (obj == NULL)
1785     return LDPS_BAD_HANDLE;
1786
1787   // Check if the object is locked before getting the section contents.
1788   gold_assert(obj->is_locked());
1789
1790   section_size_type plen;
1791   *section_contents_ptr
1792       = obj->section_contents(section.shndx, &plen, false);
1793   *len = plen;
1794   return LDPS_OK;
1795 }
1796
1797 // Get the alignment of the specified section in the object corresponding
1798 // to the handle.  This plugin interface can only be called in the
1799 // claim_file handler of the plugin.
1800
1801 static enum ld_plugin_status
1802 get_input_section_alignment(const struct ld_plugin_section section,
1803                             unsigned int* addralign)
1804 {
1805   gold_assert(parameters->options().has_plugins());
1806
1807   if (!parameters->options().plugins()->in_claim_file_handler())
1808     return LDPS_ERR;
1809
1810   Object* obj
1811     = parameters->options().plugins()->get_elf_object(section.handle);
1812
1813   if (obj == NULL)
1814     return LDPS_BAD_HANDLE;
1815
1816   *addralign = obj->section_addralign(section.shndx);
1817   return LDPS_OK;
1818 }
1819
1820 // Get the size of the specified section in the object corresponding
1821 // to the handle.  This plugin interface can only be called in the
1822 // claim_file handler of the plugin.
1823
1824 static enum ld_plugin_status
1825 get_input_section_size(const struct ld_plugin_section section,
1826                        uint64_t* secsize)
1827 {
1828   gold_assert(parameters->options().has_plugins());
1829
1830   if (!parameters->options().plugins()->in_claim_file_handler())
1831     return LDPS_ERR;
1832
1833   Object* obj
1834     = parameters->options().plugins()->get_elf_object(section.handle);
1835
1836   if (obj == NULL)
1837     return LDPS_BAD_HANDLE;
1838
1839   *secsize = obj->section_size(section.shndx);
1840   return LDPS_OK;
1841 }
1842
1843 static enum ld_plugin_status
1844 get_wrap_symbols(uint64_t *count, const char ***wrap_symbols)
1845 {
1846   gold_assert(parameters->options().has_plugins());
1847   *count = parameters->options().wrap_size();
1848
1849   if (*count == 0)
1850     return LDPS_OK;
1851
1852   *wrap_symbols = new const char *[*count];
1853   int i = 0;
1854   for (options::String_set::const_iterator
1855        it = parameters->options().wrap_begin();
1856        it != parameters->options().wrap_end(); ++it, ++i) {
1857     (*wrap_symbols)[i] = it->c_str();
1858   }
1859   return LDPS_OK;
1860 }
1861
1862
1863 // Specify the ordering of sections in the final layout. The sections are
1864 // specified as (handle,shndx) pairs in the two arrays in the order in
1865 // which they should appear in the final layout.
1866
1867 static enum ld_plugin_status
1868 update_section_order(const struct ld_plugin_section* section_list,
1869                      unsigned int num_sections)
1870 {
1871   gold_assert(parameters->options().has_plugins());
1872
1873   if (num_sections == 0)
1874     return LDPS_OK;
1875
1876   if (section_list == NULL)
1877     return LDPS_ERR;
1878
1879   Layout* layout = parameters->options().plugins()->layout();
1880   gold_assert (layout != NULL);
1881
1882   std::map<Section_id, unsigned int>* order_map
1883     = layout->get_section_order_map();
1884
1885   /* Store the mapping from Section_id to section position in layout's
1886      order_map to consult after output sections are added.  */
1887   for (unsigned int i = 0; i < num_sections; ++i)
1888     {
1889       Object* obj = parameters->options().plugins()->get_elf_object(
1890           section_list[i].handle);
1891       if (obj == NULL || obj->is_dynamic())
1892         return LDPS_BAD_HANDLE;
1893       unsigned int shndx = section_list[i].shndx;
1894       Section_id secn_id(static_cast<Relobj*>(obj), shndx);
1895       (*order_map)[secn_id] = i + 1;
1896     }
1897
1898   return LDPS_OK;
1899 }
1900
1901 // Let the linker know that the sections could be reordered.
1902
1903 static enum ld_plugin_status
1904 allow_section_ordering()
1905 {
1906   gold_assert(parameters->options().has_plugins());
1907   Layout* layout = parameters->options().plugins()->layout();
1908   layout->set_section_ordering_specified();
1909   return LDPS_OK;
1910 }
1911
1912 // Let the linker know that a subset of sections could be mapped
1913 // to a unique segment.
1914
1915 static enum ld_plugin_status
1916 allow_unique_segment_for_sections()
1917 {
1918   gold_assert(parameters->options().has_plugins());
1919   Layout* layout = parameters->options().plugins()->layout();
1920   layout->set_unique_segment_for_sections_specified();
1921   return LDPS_OK;
1922 }
1923
1924 // This function should map the list of sections specified in the
1925 // SECTION_LIST to a unique segment.  ELF segments do not have names
1926 // and the NAME is used to identify Output Section which should contain
1927 // the list of sections.  This Output Section will then be mapped to
1928 // a unique segment.  FLAGS is used to specify if any additional segment
1929 // flags need to be set.  For instance, a specific segment flag can be
1930 // set to identify this segment.  Unsetting segment flags is not possible.
1931 // ALIGN specifies the alignment of the segment.
1932
1933 static enum ld_plugin_status
1934 unique_segment_for_sections(const char* segment_name,
1935                             uint64_t flags,
1936                             uint64_t align,
1937                             const struct ld_plugin_section* section_list,
1938                             unsigned int num_sections)
1939 {
1940   gold_assert(parameters->options().has_plugins());
1941
1942   if (num_sections == 0)
1943     return LDPS_OK;
1944
1945   if (section_list == NULL)
1946     return LDPS_ERR;
1947
1948   Layout* layout = parameters->options().plugins()->layout();
1949   gold_assert (layout != NULL);
1950
1951   Layout::Unique_segment_info* s = new Layout::Unique_segment_info;
1952   s->name = segment_name;
1953   s->flags = flags;
1954   s->align = align;
1955
1956   for (unsigned int i = 0; i < num_sections; ++i)
1957     {
1958       Object* obj = parameters->options().plugins()->get_elf_object(
1959           section_list[i].handle);
1960       if (obj == NULL || obj->is_dynamic())
1961         return LDPS_BAD_HANDLE;
1962       unsigned int shndx = section_list[i].shndx;
1963       Const_section_id secn_id(static_cast<Relobj*>(obj), shndx);
1964       layout->insert_section_segment_map(secn_id, s);
1965     }
1966
1967   return LDPS_OK;
1968 }
1969
1970 // Register a new_input handler.
1971
1972 static enum ld_plugin_status
1973 register_new_input(ld_plugin_new_input_handler handler)
1974 {
1975   gold_assert(parameters->options().has_plugins());
1976   parameters->options().plugins()->set_new_input_handler(handler);
1977   return LDPS_OK;
1978 }
1979
1980 #endif // ENABLE_PLUGINS
1981
1982 // Allocate a Pluginobj object of the appropriate size and endianness.
1983
1984 static Pluginobj*
1985 make_sized_plugin_object(Input_file* input_file, off_t offset, off_t filesize)
1986 {
1987   Pluginobj* obj = NULL;
1988
1989   parameters_force_valid_target();
1990   const Target& target(parameters->target());
1991
1992   if (target.get_size() == 32)
1993     {
1994       if (target.is_big_endian())
1995 #ifdef HAVE_TARGET_32_BIG
1996         obj = new Sized_pluginobj<32, true>(input_file->filename(),
1997                                             input_file, offset, filesize);
1998 #else
1999         gold_error(_("%s: not configured to support "
2000                      "32-bit big-endian object"),
2001                    input_file->filename().c_str());
2002 #endif
2003       else
2004 #ifdef HAVE_TARGET_32_LITTLE
2005         obj = new Sized_pluginobj<32, false>(input_file->filename(),
2006                                              input_file, offset, filesize);
2007 #else
2008         gold_error(_("%s: not configured to support "
2009                      "32-bit little-endian object"),
2010                    input_file->filename().c_str());
2011 #endif
2012     }
2013   else if (target.get_size() == 64)
2014     {
2015       if (target.is_big_endian())
2016 #ifdef HAVE_TARGET_64_BIG
2017         obj = new Sized_pluginobj<64, true>(input_file->filename(),
2018                                             input_file, offset, filesize);
2019 #else
2020         gold_error(_("%s: not configured to support "
2021                      "64-bit big-endian object"),
2022                    input_file->filename().c_str());
2023 #endif
2024       else
2025 #ifdef HAVE_TARGET_64_LITTLE
2026         obj = new Sized_pluginobj<64, false>(input_file->filename(),
2027                                              input_file, offset, filesize);
2028 #else
2029         gold_error(_("%s: not configured to support "
2030                      "64-bit little-endian object"),
2031                    input_file->filename().c_str());
2032 #endif
2033     }
2034
2035   gold_assert(obj != NULL);
2036   return obj;
2037 }
2038
2039 } // End namespace gold.