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