e882dea4e98b062c7cde4a45aa3cf19ad5aec627
[external/binutils.git] / gold / symtab.cc
1 // symtab.cc -- the gold symbol table
2
3 // Copyright 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4 // Written by Ian Lance Taylor <iant@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 <cstring>
26 #include <stdint.h>
27 #include <algorithm>
28 #include <set>
29 #include <string>
30 #include <utility>
31 #include "demangle.h"
32
33 #include "gc.h"
34 #include "object.h"
35 #include "dwarf_reader.h"
36 #include "dynobj.h"
37 #include "output.h"
38 #include "target.h"
39 #include "workqueue.h"
40 #include "symtab.h"
41 #include "script.h"
42 #include "plugin.h"
43
44 namespace gold
45 {
46
47 // Class Symbol.
48
49 // Initialize fields in Symbol.  This initializes everything except u_
50 // and source_.
51
52 void
53 Symbol::init_fields(const char* name, const char* version,
54                     elfcpp::STT type, elfcpp::STB binding,
55                     elfcpp::STV visibility, unsigned char nonvis)
56 {
57   this->name_ = name;
58   this->version_ = version;
59   this->symtab_index_ = 0;
60   this->dynsym_index_ = 0;
61   this->got_offsets_.init();
62   this->plt_offset_ = -1U;
63   this->type_ = type;
64   this->binding_ = binding;
65   this->visibility_ = visibility;
66   this->nonvis_ = nonvis;
67   this->is_def_ = false;
68   this->is_forwarder_ = false;
69   this->has_alias_ = false;
70   this->needs_dynsym_entry_ = false;
71   this->in_reg_ = false;
72   this->in_dyn_ = false;
73   this->has_warning_ = false;
74   this->is_copied_from_dynobj_ = false;
75   this->is_forced_local_ = false;
76   this->is_ordinary_shndx_ = false;
77   this->in_real_elf_ = false;
78   this->is_defined_in_discarded_section_ = false;
79   this->undef_binding_set_ = false;
80   this->undef_binding_weak_ = false;
81 }
82
83 // Return the demangled version of the symbol's name, but only
84 // if the --demangle flag was set.
85
86 static std::string
87 demangle(const char* name)
88 {
89   if (!parameters->options().do_demangle())
90     return name;
91
92   // cplus_demangle allocates memory for the result it returns,
93   // and returns NULL if the name is already demangled.
94   char* demangled_name = cplus_demangle(name, DMGL_ANSI | DMGL_PARAMS);
95   if (demangled_name == NULL)
96     return name;
97
98   std::string retval(demangled_name);
99   free(demangled_name);
100   return retval;
101 }
102
103 std::string
104 Symbol::demangled_name() const
105 {
106   return demangle(this->name());
107 }
108
109 // Initialize the fields in the base class Symbol for SYM in OBJECT.
110
111 template<int size, bool big_endian>
112 void
113 Symbol::init_base_object(const char* name, const char* version, Object* object,
114                          const elfcpp::Sym<size, big_endian>& sym,
115                          unsigned int st_shndx, bool is_ordinary)
116 {
117   this->init_fields(name, version, sym.get_st_type(), sym.get_st_bind(),
118                     sym.get_st_visibility(), sym.get_st_nonvis());
119   this->u_.from_object.object = object;
120   this->u_.from_object.shndx = st_shndx;
121   this->is_ordinary_shndx_ = is_ordinary;
122   this->source_ = FROM_OBJECT;
123   this->in_reg_ = !object->is_dynamic();
124   this->in_dyn_ = object->is_dynamic();
125   this->in_real_elf_ = object->pluginobj() == NULL;
126 }
127
128 // Initialize the fields in the base class Symbol for a symbol defined
129 // in an Output_data.
130
131 void
132 Symbol::init_base_output_data(const char* name, const char* version,
133                               Output_data* od, elfcpp::STT type,
134                               elfcpp::STB binding, elfcpp::STV visibility,
135                               unsigned char nonvis, bool offset_is_from_end)
136 {
137   this->init_fields(name, version, type, binding, visibility, nonvis);
138   this->u_.in_output_data.output_data = od;
139   this->u_.in_output_data.offset_is_from_end = offset_is_from_end;
140   this->source_ = IN_OUTPUT_DATA;
141   this->in_reg_ = true;
142   this->in_real_elf_ = true;
143 }
144
145 // Initialize the fields in the base class Symbol for a symbol defined
146 // in an Output_segment.
147
148 void
149 Symbol::init_base_output_segment(const char* name, const char* version,
150                                  Output_segment* os, elfcpp::STT type,
151                                  elfcpp::STB binding, elfcpp::STV visibility,
152                                  unsigned char nonvis,
153                                  Segment_offset_base offset_base)
154 {
155   this->init_fields(name, version, type, binding, visibility, nonvis);
156   this->u_.in_output_segment.output_segment = os;
157   this->u_.in_output_segment.offset_base = offset_base;
158   this->source_ = IN_OUTPUT_SEGMENT;
159   this->in_reg_ = true;
160   this->in_real_elf_ = true;
161 }
162
163 // Initialize the fields in the base class Symbol for a symbol defined
164 // as a constant.
165
166 void
167 Symbol::init_base_constant(const char* name, const char* version,
168                            elfcpp::STT type, elfcpp::STB binding,
169                            elfcpp::STV visibility, unsigned char nonvis)
170 {
171   this->init_fields(name, version, type, binding, visibility, nonvis);
172   this->source_ = IS_CONSTANT;
173   this->in_reg_ = true;
174   this->in_real_elf_ = true;
175 }
176
177 // Initialize the fields in the base class Symbol for an undefined
178 // symbol.
179
180 void
181 Symbol::init_base_undefined(const char* name, const char* version,
182                             elfcpp::STT type, elfcpp::STB binding,
183                             elfcpp::STV visibility, unsigned char nonvis)
184 {
185   this->init_fields(name, version, type, binding, visibility, nonvis);
186   this->dynsym_index_ = -1U;
187   this->source_ = IS_UNDEFINED;
188   this->in_reg_ = true;
189   this->in_real_elf_ = true;
190 }
191
192 // Allocate a common symbol in the base.
193
194 void
195 Symbol::allocate_base_common(Output_data* od)
196 {
197   gold_assert(this->is_common());
198   this->source_ = IN_OUTPUT_DATA;
199   this->u_.in_output_data.output_data = od;
200   this->u_.in_output_data.offset_is_from_end = false;
201 }
202
203 // Initialize the fields in Sized_symbol for SYM in OBJECT.
204
205 template<int size>
206 template<bool big_endian>
207 void
208 Sized_symbol<size>::init_object(const char* name, const char* version,
209                                 Object* object,
210                                 const elfcpp::Sym<size, big_endian>& sym,
211                                 unsigned int st_shndx, bool is_ordinary)
212 {
213   this->init_base_object(name, version, object, sym, st_shndx, is_ordinary);
214   this->value_ = sym.get_st_value();
215   this->symsize_ = sym.get_st_size();
216 }
217
218 // Initialize the fields in Sized_symbol for a symbol defined in an
219 // Output_data.
220
221 template<int size>
222 void
223 Sized_symbol<size>::init_output_data(const char* name, const char* version,
224                                      Output_data* od, Value_type value,
225                                      Size_type symsize, elfcpp::STT type,
226                                      elfcpp::STB binding,
227                                      elfcpp::STV visibility,
228                                      unsigned char nonvis,
229                                      bool offset_is_from_end)
230 {
231   this->init_base_output_data(name, version, od, type, binding, visibility,
232                               nonvis, offset_is_from_end);
233   this->value_ = value;
234   this->symsize_ = symsize;
235 }
236
237 // Initialize the fields in Sized_symbol for a symbol defined in an
238 // Output_segment.
239
240 template<int size>
241 void
242 Sized_symbol<size>::init_output_segment(const char* name, const char* version,
243                                         Output_segment* os, Value_type value,
244                                         Size_type symsize, elfcpp::STT type,
245                                         elfcpp::STB binding,
246                                         elfcpp::STV visibility,
247                                         unsigned char nonvis,
248                                         Segment_offset_base offset_base)
249 {
250   this->init_base_output_segment(name, version, os, type, binding, visibility,
251                                  nonvis, offset_base);
252   this->value_ = value;
253   this->symsize_ = symsize;
254 }
255
256 // Initialize the fields in Sized_symbol for a symbol defined as a
257 // constant.
258
259 template<int size>
260 void
261 Sized_symbol<size>::init_constant(const char* name, const char* version,
262                                   Value_type value, Size_type symsize,
263                                   elfcpp::STT type, elfcpp::STB binding,
264                                   elfcpp::STV visibility, unsigned char nonvis)
265 {
266   this->init_base_constant(name, version, type, binding, visibility, nonvis);
267   this->value_ = value;
268   this->symsize_ = symsize;
269 }
270
271 // Initialize the fields in Sized_symbol for an undefined symbol.
272
273 template<int size>
274 void
275 Sized_symbol<size>::init_undefined(const char* name, const char* version,
276                                    elfcpp::STT type, elfcpp::STB binding,
277                                    elfcpp::STV visibility, unsigned char nonvis)
278 {
279   this->init_base_undefined(name, version, type, binding, visibility, nonvis);
280   this->value_ = 0;
281   this->symsize_ = 0;
282 }
283
284 // Return true if SHNDX represents a common symbol.
285
286 bool
287 Symbol::is_common_shndx(unsigned int shndx)
288 {
289   return (shndx == elfcpp::SHN_COMMON
290           || shndx == parameters->target().small_common_shndx()
291           || shndx == parameters->target().large_common_shndx());
292 }
293
294 // Allocate a common symbol.
295
296 template<int size>
297 void
298 Sized_symbol<size>::allocate_common(Output_data* od, Value_type value)
299 {
300   this->allocate_base_common(od);
301   this->value_ = value;
302 }
303
304 // The ""'s around str ensure str is a string literal, so sizeof works.
305 #define strprefix(var, str)   (strncmp(var, str, sizeof("" str "") - 1) == 0)
306
307 // Return true if this symbol should be added to the dynamic symbol
308 // table.
309
310 inline bool
311 Symbol::should_add_dynsym_entry(Symbol_table* symtab) const
312 {
313   // If the symbol is only present on plugin files, the plugin decided we
314   // don't need it.
315   if (!this->in_real_elf())
316     return false;
317
318   // If the symbol is used by a dynamic relocation, we need to add it.
319   if (this->needs_dynsym_entry())
320     return true;
321
322   // If this symbol's section is not added, the symbol need not be added. 
323   // The section may have been GCed.  Note that export_dynamic is being 
324   // overridden here.  This should not be done for shared objects.
325   if (parameters->options().gc_sections() 
326       && !parameters->options().shared()
327       && this->source() == Symbol::FROM_OBJECT
328       && !this->object()->is_dynamic())
329     {
330       Relobj* relobj = static_cast<Relobj*>(this->object());
331       bool is_ordinary;
332       unsigned int shndx = this->shndx(&is_ordinary);
333       if (is_ordinary && shndx != elfcpp::SHN_UNDEF
334           && !relobj->is_section_included(shndx)
335           && !symtab->is_section_folded(relobj, shndx))
336         return false;
337     }
338
339   // If the symbol was forced local in a version script, do not add it.
340   if (this->is_forced_local())
341     return false;
342
343   // If the symbol was forced dynamic in a --dynamic-list file, add it.
344   if (parameters->options().in_dynamic_list(this->name()))
345     return true;
346
347   // If dynamic-list-data was specified, add any STT_OBJECT.
348   if (parameters->options().dynamic_list_data()
349       && !this->is_from_dynobj()
350       && this->type() == elfcpp::STT_OBJECT)
351     return true;
352
353   // If --dynamic-list-cpp-new was specified, add any new/delete symbol.
354   // If --dynamic-list-cpp-typeinfo was specified, add any typeinfo symbols.
355   if ((parameters->options().dynamic_list_cpp_new()
356        || parameters->options().dynamic_list_cpp_typeinfo())
357       && !this->is_from_dynobj())
358     {
359       // TODO(csilvers): We could probably figure out if we're an operator
360       //                 new/delete or typeinfo without the need to demangle.
361       char* demangled_name = cplus_demangle(this->name(),
362                                             DMGL_ANSI | DMGL_PARAMS);
363       if (demangled_name == NULL)
364         {
365           // Not a C++ symbol, so it can't satisfy these flags
366         }
367       else if (parameters->options().dynamic_list_cpp_new()
368                && (strprefix(demangled_name, "operator new")
369                    || strprefix(demangled_name, "operator delete")))
370         {
371           free(demangled_name);
372           return true;
373         }
374       else if (parameters->options().dynamic_list_cpp_typeinfo()
375                && (strprefix(demangled_name, "typeinfo name for")
376                    || strprefix(demangled_name, "typeinfo for")))
377         {
378           free(demangled_name);
379           return true;
380         }
381       else
382         free(demangled_name);
383     }
384
385   // If exporting all symbols or building a shared library,
386   // and the symbol is defined in a regular object and is
387   // externally visible, we need to add it.
388   if ((parameters->options().export_dynamic() || parameters->options().shared())
389       && !this->is_from_dynobj()
390       && this->is_externally_visible())
391     return true;
392
393   return false;
394 }
395
396 // Return true if the final value of this symbol is known at link
397 // time.
398
399 bool
400 Symbol::final_value_is_known() const
401 {
402   // If we are not generating an executable, then no final values are
403   // known, since they will change at runtime.
404   if (parameters->options().output_is_position_independent()
405       || parameters->options().relocatable())
406     return false;
407
408   // If the symbol is not from an object file, and is not undefined,
409   // then it is defined, and known.
410   if (this->source_ != FROM_OBJECT)
411     {
412       if (this->source_ != IS_UNDEFINED)
413         return true;
414     }
415   else
416     {
417       // If the symbol is from a dynamic object, then the final value
418       // is not known.
419       if (this->object()->is_dynamic())
420         return false;
421
422       // If the symbol is not undefined (it is defined or common),
423       // then the final value is known.
424       if (!this->is_undefined())
425         return true;
426     }
427
428   // If the symbol is undefined, then whether the final value is known
429   // depends on whether we are doing a static link.  If we are doing a
430   // dynamic link, then the final value could be filled in at runtime.
431   // This could reasonably be the case for a weak undefined symbol.
432   return parameters->doing_static_link();
433 }
434
435 // Return the output section where this symbol is defined.
436
437 Output_section*
438 Symbol::output_section() const
439 {
440   switch (this->source_)
441     {
442     case FROM_OBJECT:
443       {
444         unsigned int shndx = this->u_.from_object.shndx;
445         if (shndx != elfcpp::SHN_UNDEF && this->is_ordinary_shndx_)
446           {
447             gold_assert(!this->u_.from_object.object->is_dynamic());
448             gold_assert(this->u_.from_object.object->pluginobj() == NULL);
449             Relobj* relobj = static_cast<Relobj*>(this->u_.from_object.object);
450             return relobj->output_section(shndx);
451           }
452         return NULL;
453       }
454
455     case IN_OUTPUT_DATA:
456       return this->u_.in_output_data.output_data->output_section();
457
458     case IN_OUTPUT_SEGMENT:
459     case IS_CONSTANT:
460     case IS_UNDEFINED:
461       return NULL;
462
463     default:
464       gold_unreachable();
465     }
466 }
467
468 // Set the symbol's output section.  This is used for symbols defined
469 // in scripts.  This should only be called after the symbol table has
470 // been finalized.
471
472 void
473 Symbol::set_output_section(Output_section* os)
474 {
475   switch (this->source_)
476     {
477     case FROM_OBJECT:
478     case IN_OUTPUT_DATA:
479       gold_assert(this->output_section() == os);
480       break;
481     case IS_CONSTANT:
482       this->source_ = IN_OUTPUT_DATA;
483       this->u_.in_output_data.output_data = os;
484       this->u_.in_output_data.offset_is_from_end = false;
485       break;
486     case IN_OUTPUT_SEGMENT:
487     case IS_UNDEFINED:
488     default:
489       gold_unreachable();
490     }
491 }
492
493 // Class Symbol_table.
494
495 Symbol_table::Symbol_table(unsigned int count,
496                            const Version_script_info& version_script)
497   : saw_undefined_(0), offset_(0), table_(count), namepool_(),
498     forwarders_(), commons_(), tls_commons_(), small_commons_(),
499     large_commons_(), forced_locals_(), warnings_(),
500     version_script_(version_script), gc_(NULL), icf_(NULL)
501 {
502   namepool_.reserve(count);
503 }
504
505 Symbol_table::~Symbol_table()
506 {
507 }
508
509 // The symbol table key equality function.  This is called with
510 // Stringpool keys.
511
512 inline bool
513 Symbol_table::Symbol_table_eq::operator()(const Symbol_table_key& k1,
514                                           const Symbol_table_key& k2) const
515 {
516   return k1.first == k2.first && k1.second == k2.second;
517 }
518
519 bool
520 Symbol_table::is_section_folded(Object* obj, unsigned int shndx) const
521 {
522   return (parameters->options().icf_enabled()
523           && this->icf_->is_section_folded(obj, shndx));
524 }
525
526 // For symbols that have been listed with -u option, add them to the
527 // work list to avoid gc'ing them.
528
529 void 
530 Symbol_table::gc_mark_undef_symbols(Layout* layout)
531 {
532   for (options::String_set::const_iterator p =
533          parameters->options().undefined_begin();
534        p != parameters->options().undefined_end();
535        ++p)
536     {
537       const char* name = p->c_str();
538       Symbol* sym = this->lookup(name);
539       gold_assert(sym != NULL);
540       if (sym->source() == Symbol::FROM_OBJECT 
541           && !sym->object()->is_dynamic())
542         {
543           Relobj* obj = static_cast<Relobj*>(sym->object());
544           bool is_ordinary;
545           unsigned int shndx = sym->shndx(&is_ordinary);
546           if (is_ordinary)
547             {
548               gold_assert(this->gc_ != NULL);
549               this->gc_->worklist().push(Section_id(obj, shndx));
550             }
551         }
552     }
553
554   for (Script_options::referenced_const_iterator p =
555          layout->script_options()->referenced_begin();
556        p != layout->script_options()->referenced_end();
557        ++p)
558     {
559       Symbol* sym = this->lookup(p->c_str());
560       gold_assert(sym != NULL);
561       if (sym->source() == Symbol::FROM_OBJECT
562           && !sym->object()->is_dynamic())
563         {
564           Relobj* obj = static_cast<Relobj*>(sym->object());
565           bool is_ordinary;
566           unsigned int shndx = sym->shndx(&is_ordinary);
567           if (is_ordinary)
568             {
569               gold_assert(this->gc_ != NULL);
570               this->gc_->worklist().push(Section_id(obj, shndx));
571             }
572         }
573     }
574 }
575
576 void
577 Symbol_table::gc_mark_symbol_for_shlib(Symbol* sym)
578 {
579   if (!sym->is_from_dynobj() 
580       && sym->is_externally_visible())
581     {
582       //Add the object and section to the work list.
583       Relobj* obj = static_cast<Relobj*>(sym->object());
584       bool is_ordinary;
585       unsigned int shndx = sym->shndx(&is_ordinary);
586       if (is_ordinary && shndx != elfcpp::SHN_UNDEF)
587         {
588           gold_assert(this->gc_!= NULL);
589           this->gc_->worklist().push(Section_id(obj, shndx));
590         }
591     }
592 }
593
594 // When doing garbage collection, keep symbols that have been seen in
595 // dynamic objects.
596 inline void 
597 Symbol_table::gc_mark_dyn_syms(Symbol* sym)
598 {
599   if (sym->in_dyn() && sym->source() == Symbol::FROM_OBJECT
600       && !sym->object()->is_dynamic())
601     {
602       Relobj* obj = static_cast<Relobj*>(sym->object()); 
603       bool is_ordinary;
604       unsigned int shndx = sym->shndx(&is_ordinary);
605       if (is_ordinary && shndx != elfcpp::SHN_UNDEF)
606         {
607           gold_assert(this->gc_ != NULL);
608           this->gc_->worklist().push(Section_id(obj, shndx));
609         }
610     }
611 }
612
613 // Make TO a symbol which forwards to FROM.
614
615 void
616 Symbol_table::make_forwarder(Symbol* from, Symbol* to)
617 {
618   gold_assert(from != to);
619   gold_assert(!from->is_forwarder() && !to->is_forwarder());
620   this->forwarders_[from] = to;
621   from->set_forwarder();
622 }
623
624 // Resolve the forwards from FROM, returning the real symbol.
625
626 Symbol*
627 Symbol_table::resolve_forwards(const Symbol* from) const
628 {
629   gold_assert(from->is_forwarder());
630   Unordered_map<const Symbol*, Symbol*>::const_iterator p =
631     this->forwarders_.find(from);
632   gold_assert(p != this->forwarders_.end());
633   return p->second;
634 }
635
636 // Look up a symbol by name.
637
638 Symbol*
639 Symbol_table::lookup(const char* name, const char* version) const
640 {
641   Stringpool::Key name_key;
642   name = this->namepool_.find(name, &name_key);
643   if (name == NULL)
644     return NULL;
645
646   Stringpool::Key version_key = 0;
647   if (version != NULL)
648     {
649       version = this->namepool_.find(version, &version_key);
650       if (version == NULL)
651         return NULL;
652     }
653
654   Symbol_table_key key(name_key, version_key);
655   Symbol_table::Symbol_table_type::const_iterator p = this->table_.find(key);
656   if (p == this->table_.end())
657     return NULL;
658   return p->second;
659 }
660
661 // Resolve a Symbol with another Symbol.  This is only used in the
662 // unusual case where there are references to both an unversioned
663 // symbol and a symbol with a version, and we then discover that that
664 // version is the default version.  Because this is unusual, we do
665 // this the slow way, by converting back to an ELF symbol.
666
667 template<int size, bool big_endian>
668 void
669 Symbol_table::resolve(Sized_symbol<size>* to, const Sized_symbol<size>* from)
670 {
671   unsigned char buf[elfcpp::Elf_sizes<size>::sym_size];
672   elfcpp::Sym_write<size, big_endian> esym(buf);
673   // We don't bother to set the st_name or the st_shndx field.
674   esym.put_st_value(from->value());
675   esym.put_st_size(from->symsize());
676   esym.put_st_info(from->binding(), from->type());
677   esym.put_st_other(from->visibility(), from->nonvis());
678   bool is_ordinary;
679   unsigned int shndx = from->shndx(&is_ordinary);
680   this->resolve(to, esym.sym(), shndx, is_ordinary, shndx, from->object(),
681                 from->version());
682   if (from->in_reg())
683     to->set_in_reg();
684   if (from->in_dyn())
685     to->set_in_dyn();
686   if (parameters->options().gc_sections())
687     this->gc_mark_dyn_syms(to);
688 }
689
690 // Record that a symbol is forced to be local by a version script or
691 // by visibility.
692
693 void
694 Symbol_table::force_local(Symbol* sym)
695 {
696   if (!sym->is_defined() && !sym->is_common())
697     return;
698   if (sym->is_forced_local())
699     {
700       // We already got this one.
701       return;
702     }
703   sym->set_is_forced_local();
704   this->forced_locals_.push_back(sym);
705 }
706
707 // Adjust NAME for wrapping, and update *NAME_KEY if necessary.  This
708 // is only called for undefined symbols, when at least one --wrap
709 // option was used.
710
711 const char*
712 Symbol_table::wrap_symbol(const char* name, Stringpool::Key* name_key)
713 {
714   // For some targets, we need to ignore a specific character when
715   // wrapping, and add it back later.
716   char prefix = '\0';
717   if (name[0] == parameters->target().wrap_char())
718     {
719       prefix = name[0];
720       ++name;
721     }
722
723   if (parameters->options().is_wrap(name))
724     {
725       // Turn NAME into __wrap_NAME.
726       std::string s;
727       if (prefix != '\0')
728         s += prefix;
729       s += "__wrap_";
730       s += name;
731
732       // This will give us both the old and new name in NAMEPOOL_, but
733       // that is OK.  Only the versions we need will wind up in the
734       // real string table in the output file.
735       return this->namepool_.add(s.c_str(), true, name_key);
736     }
737
738   const char* const real_prefix = "__real_";
739   const size_t real_prefix_length = strlen(real_prefix);
740   if (strncmp(name, real_prefix, real_prefix_length) == 0
741       && parameters->options().is_wrap(name + real_prefix_length))
742     {
743       // Turn __real_NAME into NAME.
744       std::string s;
745       if (prefix != '\0')
746         s += prefix;
747       s += name + real_prefix_length;
748       return this->namepool_.add(s.c_str(), true, name_key);
749     }
750
751   return name;
752 }
753
754 // This is called when we see a symbol NAME/VERSION, and the symbol
755 // already exists in the symbol table, and VERSION is marked as being
756 // the default version.  SYM is the NAME/VERSION symbol we just added.
757 // DEFAULT_IS_NEW is true if this is the first time we have seen the
758 // symbol NAME/NULL.  PDEF points to the entry for NAME/NULL.
759
760 template<int size, bool big_endian>
761 void
762 Symbol_table::define_default_version(Sized_symbol<size>* sym,
763                                      bool default_is_new,
764                                      Symbol_table_type::iterator pdef)
765 {
766   if (default_is_new)
767     {
768       // This is the first time we have seen NAME/NULL.  Make
769       // NAME/NULL point to NAME/VERSION, and mark SYM as the default
770       // version.
771       pdef->second = sym;
772       sym->set_is_default();
773     }
774   else if (pdef->second == sym)
775     {
776       // NAME/NULL already points to NAME/VERSION.  Don't mark the
777       // symbol as the default if it is not already the default.
778     }
779   else
780     {
781       // This is the unfortunate case where we already have entries
782       // for both NAME/VERSION and NAME/NULL.  We now see a symbol
783       // NAME/VERSION where VERSION is the default version.  We have
784       // already resolved this new symbol with the existing
785       // NAME/VERSION symbol.
786
787       // It's possible that NAME/NULL and NAME/VERSION are both
788       // defined in regular objects.  This can only happen if one
789       // object file defines foo and another defines foo@@ver.  This
790       // is somewhat obscure, but we call it a multiple definition
791       // error.
792
793       // It's possible that NAME/NULL actually has a version, in which
794       // case it won't be the same as VERSION.  This happens with
795       // ver_test_7.so in the testsuite for the symbol t2_2.  We see
796       // t2_2@@VER2, so we define both t2_2/VER2 and t2_2/NULL.  We
797       // then see an unadorned t2_2 in an object file and give it
798       // version VER1 from the version script.  This looks like a
799       // default definition for VER1, so it looks like we should merge
800       // t2_2/NULL with t2_2/VER1.  That doesn't make sense, but it's
801       // not obvious that this is an error, either.  So we just punt.
802
803       // If one of the symbols has non-default visibility, and the
804       // other is defined in a shared object, then they are different
805       // symbols.
806
807       // Otherwise, we just resolve the symbols as though they were
808       // the same.
809
810       if (pdef->second->version() != NULL)
811         gold_assert(pdef->second->version() != sym->version());
812       else if (sym->visibility() != elfcpp::STV_DEFAULT
813                && pdef->second->is_from_dynobj())
814         ;
815       else if (pdef->second->visibility() != elfcpp::STV_DEFAULT
816                && sym->is_from_dynobj())
817         ;
818       else
819         {
820           const Sized_symbol<size>* symdef;
821           symdef = this->get_sized_symbol<size>(pdef->second);
822           Symbol_table::resolve<size, big_endian>(sym, symdef);
823           this->make_forwarder(pdef->second, sym);
824           pdef->second = sym;
825           sym->set_is_default();
826         }
827     }
828 }
829
830 // Add one symbol from OBJECT to the symbol table.  NAME is symbol
831 // name and VERSION is the version; both are canonicalized.  DEF is
832 // whether this is the default version.  ST_SHNDX is the symbol's
833 // section index; IS_ORDINARY is whether this is a normal section
834 // rather than a special code.
835
836 // If IS_DEFAULT_VERSION is true, then this is the definition of a
837 // default version of a symbol.  That means that any lookup of
838 // NAME/NULL and any lookup of NAME/VERSION should always return the
839 // same symbol.  This is obvious for references, but in particular we
840 // want to do this for definitions: overriding NAME/NULL should also
841 // override NAME/VERSION.  If we don't do that, it would be very hard
842 // to override functions in a shared library which uses versioning.
843
844 // We implement this by simply making both entries in the hash table
845 // point to the same Symbol structure.  That is easy enough if this is
846 // the first time we see NAME/NULL or NAME/VERSION, but it is possible
847 // that we have seen both already, in which case they will both have
848 // independent entries in the symbol table.  We can't simply change
849 // the symbol table entry, because we have pointers to the entries
850 // attached to the object files.  So we mark the entry attached to the
851 // object file as a forwarder, and record it in the forwarders_ map.
852 // Note that entries in the hash table will never be marked as
853 // forwarders.
854 //
855 // ORIG_ST_SHNDX and ST_SHNDX are almost always the same.
856 // ORIG_ST_SHNDX is the section index in the input file, or SHN_UNDEF
857 // for a special section code.  ST_SHNDX may be modified if the symbol
858 // is defined in a section being discarded.
859
860 template<int size, bool big_endian>
861 Sized_symbol<size>*
862 Symbol_table::add_from_object(Object* object,
863                               const char* name,
864                               Stringpool::Key name_key,
865                               const char* version,
866                               Stringpool::Key version_key,
867                               bool is_default_version,
868                               const elfcpp::Sym<size, big_endian>& sym,
869                               unsigned int st_shndx,
870                               bool is_ordinary,
871                               unsigned int orig_st_shndx)
872 {
873   // Print a message if this symbol is being traced.
874   if (parameters->options().is_trace_symbol(name))
875     {
876       if (orig_st_shndx == elfcpp::SHN_UNDEF)
877         gold_info(_("%s: reference to %s"), object->name().c_str(), name);
878       else
879         gold_info(_("%s: definition of %s"), object->name().c_str(), name);
880     }
881
882   // For an undefined symbol, we may need to adjust the name using
883   // --wrap.
884   if (orig_st_shndx == elfcpp::SHN_UNDEF
885       && parameters->options().any_wrap())
886     {
887       const char* wrap_name = this->wrap_symbol(name, &name_key);
888       if (wrap_name != name)
889         {
890           // If we see a reference to malloc with version GLIBC_2.0,
891           // and we turn it into a reference to __wrap_malloc, then we
892           // discard the version number.  Otherwise the user would be
893           // required to specify the correct version for
894           // __wrap_malloc.
895           version = NULL;
896           version_key = 0;
897           name = wrap_name;
898         }
899     }
900
901   Symbol* const snull = NULL;
902   std::pair<typename Symbol_table_type::iterator, bool> ins =
903     this->table_.insert(std::make_pair(std::make_pair(name_key, version_key),
904                                        snull));
905
906   std::pair<typename Symbol_table_type::iterator, bool> insdefault =
907     std::make_pair(this->table_.end(), false);
908   if (is_default_version)
909     {
910       const Stringpool::Key vnull_key = 0;
911       insdefault = this->table_.insert(std::make_pair(std::make_pair(name_key,
912                                                                      vnull_key),
913                                                       snull));
914     }
915
916   // ins.first: an iterator, which is a pointer to a pair.
917   // ins.first->first: the key (a pair of name and version).
918   // ins.first->second: the value (Symbol*).
919   // ins.second: true if new entry was inserted, false if not.
920
921   Sized_symbol<size>* ret;
922   bool was_undefined;
923   bool was_common;
924   if (!ins.second)
925     {
926       // We already have an entry for NAME/VERSION.
927       ret = this->get_sized_symbol<size>(ins.first->second);
928       gold_assert(ret != NULL);
929
930       was_undefined = ret->is_undefined();
931       was_common = ret->is_common();
932
933       this->resolve(ret, sym, st_shndx, is_ordinary, orig_st_shndx, object,
934                     version);
935       if (parameters->options().gc_sections())
936         this->gc_mark_dyn_syms(ret);
937
938       if (is_default_version)
939         this->define_default_version<size, big_endian>(ret, insdefault.second,
940                                                        insdefault.first);
941     }
942   else
943     {
944       // This is the first time we have seen NAME/VERSION.
945       gold_assert(ins.first->second == NULL);
946
947       if (is_default_version && !insdefault.second)
948         {
949           // We already have an entry for NAME/NULL.  If we override
950           // it, then change it to NAME/VERSION.
951           ret = this->get_sized_symbol<size>(insdefault.first->second);
952
953           was_undefined = ret->is_undefined();
954           was_common = ret->is_common();
955
956           this->resolve(ret, sym, st_shndx, is_ordinary, orig_st_shndx, object,
957                         version);
958           if (parameters->options().gc_sections())
959             this->gc_mark_dyn_syms(ret);
960           ins.first->second = ret;
961         }
962       else
963         {
964           was_undefined = false;
965           was_common = false;
966
967           Sized_target<size, big_endian>* target =
968             parameters->sized_target<size, big_endian>();
969           if (!target->has_make_symbol())
970             ret = new Sized_symbol<size>();
971           else
972             {
973               ret = target->make_symbol();
974               if (ret == NULL)
975                 {
976                   // This means that we don't want a symbol table
977                   // entry after all.
978                   if (!is_default_version)
979                     this->table_.erase(ins.first);
980                   else
981                     {
982                       this->table_.erase(insdefault.first);
983                       // Inserting INSDEFAULT invalidated INS.
984                       this->table_.erase(std::make_pair(name_key,
985                                                         version_key));
986                     }
987                   return NULL;
988                 }
989             }
990
991           ret->init_object(name, version, object, sym, st_shndx, is_ordinary);
992
993           ins.first->second = ret;
994           if (is_default_version)
995             {
996               // This is the first time we have seen NAME/NULL.  Point
997               // it at the new entry for NAME/VERSION.
998               gold_assert(insdefault.second);
999               insdefault.first->second = ret;
1000             }
1001         }
1002
1003       if (is_default_version)
1004         ret->set_is_default();
1005     }
1006
1007   // Record every time we see a new undefined symbol, to speed up
1008   // archive groups.
1009   if (!was_undefined && ret->is_undefined())
1010     {
1011       ++this->saw_undefined_;
1012       if (parameters->options().has_plugins())
1013         parameters->options().plugins()->new_undefined_symbol(ret);
1014     }
1015
1016   // Keep track of common symbols, to speed up common symbol
1017   // allocation.
1018   if (!was_common && ret->is_common())
1019     {
1020       if (ret->type() == elfcpp::STT_TLS)
1021         this->tls_commons_.push_back(ret);
1022       else if (!is_ordinary
1023                && st_shndx == parameters->target().small_common_shndx())
1024         this->small_commons_.push_back(ret);
1025       else if (!is_ordinary
1026                && st_shndx == parameters->target().large_common_shndx())
1027         this->large_commons_.push_back(ret);
1028       else
1029         this->commons_.push_back(ret);
1030     }
1031
1032   // If we're not doing a relocatable link, then any symbol with
1033   // hidden or internal visibility is local.
1034   if ((ret->visibility() == elfcpp::STV_HIDDEN
1035        || ret->visibility() == elfcpp::STV_INTERNAL)
1036       && (ret->binding() == elfcpp::STB_GLOBAL
1037           || ret->binding() == elfcpp::STB_GNU_UNIQUE
1038           || ret->binding() == elfcpp::STB_WEAK)
1039       && !parameters->options().relocatable())
1040     this->force_local(ret);
1041
1042   return ret;
1043 }
1044
1045 // Add all the symbols in a relocatable object to the hash table.
1046
1047 template<int size, bool big_endian>
1048 void
1049 Symbol_table::add_from_relobj(
1050     Sized_relobj<size, big_endian>* relobj,
1051     const unsigned char* syms,
1052     size_t count,
1053     size_t symndx_offset,
1054     const char* sym_names,
1055     size_t sym_name_size,
1056     typename Sized_relobj<size, big_endian>::Symbols* sympointers,
1057     size_t* defined)
1058 {
1059   *defined = 0;
1060
1061   gold_assert(size == parameters->target().get_size());
1062
1063   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1064
1065   const bool just_symbols = relobj->just_symbols();
1066
1067   const unsigned char* p = syms;
1068   for (size_t i = 0; i < count; ++i, p += sym_size)
1069     {
1070       (*sympointers)[i] = NULL;
1071
1072       elfcpp::Sym<size, big_endian> sym(p);
1073
1074       unsigned int st_name = sym.get_st_name();
1075       if (st_name >= sym_name_size)
1076         {
1077           relobj->error(_("bad global symbol name offset %u at %zu"),
1078                         st_name, i);
1079           continue;
1080         }
1081
1082       const char* name = sym_names + st_name;
1083
1084       bool is_ordinary;
1085       unsigned int st_shndx = relobj->adjust_sym_shndx(i + symndx_offset,
1086                                                        sym.get_st_shndx(),
1087                                                        &is_ordinary);
1088       unsigned int orig_st_shndx = st_shndx;
1089       if (!is_ordinary)
1090         orig_st_shndx = elfcpp::SHN_UNDEF;
1091
1092       if (st_shndx != elfcpp::SHN_UNDEF)
1093         ++*defined;
1094
1095       // A symbol defined in a section which we are not including must
1096       // be treated as an undefined symbol.
1097       bool is_defined_in_discarded_section = false;
1098       if (st_shndx != elfcpp::SHN_UNDEF
1099           && is_ordinary
1100           && !relobj->is_section_included(st_shndx)
1101           && !this->is_section_folded(relobj, st_shndx))
1102         {
1103           st_shndx = elfcpp::SHN_UNDEF;
1104           is_defined_in_discarded_section = true;
1105         }
1106
1107       // In an object file, an '@' in the name separates the symbol
1108       // name from the version name.  If there are two '@' characters,
1109       // this is the default version.
1110       const char* ver = strchr(name, '@');
1111       Stringpool::Key ver_key = 0;
1112       int namelen = 0;
1113       // IS_DEFAULT_VERSION: is the version default?
1114       // IS_FORCED_LOCAL: is the symbol forced local?
1115       bool is_default_version = false;
1116       bool is_forced_local = false;
1117
1118       if (ver != NULL)
1119         {
1120           // The symbol name is of the form foo@VERSION or foo@@VERSION
1121           namelen = ver - name;
1122           ++ver;
1123           if (*ver == '@')
1124             {
1125               is_default_version = true;
1126               ++ver;
1127             }
1128           ver = this->namepool_.add(ver, true, &ver_key);
1129         }
1130       // We don't want to assign a version to an undefined symbol,
1131       // even if it is listed in the version script.  FIXME: What
1132       // about a common symbol?
1133       else
1134         {
1135           namelen = strlen(name);
1136           if (!this->version_script_.empty()
1137               && st_shndx != elfcpp::SHN_UNDEF)
1138             {
1139               // The symbol name did not have a version, but the
1140               // version script may assign a version anyway.
1141               std::string version;
1142               bool is_global;
1143               if (this->version_script_.get_symbol_version(name, &version,
1144                                                            &is_global))
1145                 {
1146                   if (!is_global)
1147                     is_forced_local = true;
1148                   else if (!version.empty())
1149                     {
1150                       ver = this->namepool_.add_with_length(version.c_str(),
1151                                                             version.length(),
1152                                                             true,
1153                                                             &ver_key);
1154                       is_default_version = true;
1155                     }
1156                 }
1157             }
1158         }
1159
1160       elfcpp::Sym<size, big_endian>* psym = &sym;
1161       unsigned char symbuf[sym_size];
1162       elfcpp::Sym<size, big_endian> sym2(symbuf);
1163       if (just_symbols)
1164         {
1165           memcpy(symbuf, p, sym_size);
1166           elfcpp::Sym_write<size, big_endian> sw(symbuf);
1167           if (orig_st_shndx != elfcpp::SHN_UNDEF && is_ordinary)
1168             {
1169               // Symbol values in object files are section relative.
1170               // This is normally what we want, but since here we are
1171               // converting the symbol to absolute we need to add the
1172               // section address.  The section address in an object
1173               // file is normally zero, but people can use a linker
1174               // script to change it.
1175               sw.put_st_value(sym.get_st_value()
1176                               + relobj->section_address(orig_st_shndx));
1177             }
1178           st_shndx = elfcpp::SHN_ABS;
1179           is_ordinary = false;
1180           psym = &sym2;
1181         }
1182
1183       // Fix up visibility if object has no-export set.
1184       if (relobj->no_export()
1185           && (orig_st_shndx != elfcpp::SHN_UNDEF || !is_ordinary))
1186         {
1187           // We may have copied symbol already above.
1188           if (psym != &sym2)
1189             {
1190               memcpy(symbuf, p, sym_size);
1191               psym = &sym2;
1192             }
1193
1194           elfcpp::STV visibility = sym2.get_st_visibility();
1195           if (visibility == elfcpp::STV_DEFAULT
1196               || visibility == elfcpp::STV_PROTECTED)
1197             {
1198               elfcpp::Sym_write<size, big_endian> sw(symbuf);
1199               unsigned char nonvis = sym2.get_st_nonvis();
1200               sw.put_st_other(elfcpp::STV_HIDDEN, nonvis);
1201             }
1202         }
1203
1204       Stringpool::Key name_key;
1205       name = this->namepool_.add_with_length(name, namelen, true,
1206                                              &name_key);
1207
1208       Sized_symbol<size>* res;
1209       res = this->add_from_object(relobj, name, name_key, ver, ver_key,
1210                                   is_default_version, *psym, st_shndx,
1211                                   is_ordinary, orig_st_shndx);
1212       
1213       // If building a shared library using garbage collection, do not 
1214       // treat externally visible symbols as garbage.
1215       if (parameters->options().gc_sections() 
1216           && parameters->options().shared())
1217         this->gc_mark_symbol_for_shlib(res);
1218
1219       if (is_forced_local)
1220         this->force_local(res);
1221
1222       if (is_defined_in_discarded_section)
1223         res->set_is_defined_in_discarded_section();
1224
1225       (*sympointers)[i] = res;
1226     }
1227 }
1228
1229 // Add a symbol from a plugin-claimed file.
1230
1231 template<int size, bool big_endian>
1232 Symbol*
1233 Symbol_table::add_from_pluginobj(
1234     Sized_pluginobj<size, big_endian>* obj,
1235     const char* name,
1236     const char* ver,
1237     elfcpp::Sym<size, big_endian>* sym)
1238 {
1239   unsigned int st_shndx = sym->get_st_shndx();
1240   bool is_ordinary = st_shndx < elfcpp::SHN_LORESERVE;
1241
1242   Stringpool::Key ver_key = 0;
1243   bool is_default_version = false;
1244   bool is_forced_local = false;
1245
1246   if (ver != NULL)
1247     {
1248       ver = this->namepool_.add(ver, true, &ver_key);
1249     }
1250   // We don't want to assign a version to an undefined symbol,
1251   // even if it is listed in the version script.  FIXME: What
1252   // about a common symbol?
1253   else
1254     {
1255       if (!this->version_script_.empty()
1256           && st_shndx != elfcpp::SHN_UNDEF)
1257         {
1258           // The symbol name did not have a version, but the
1259           // version script may assign a version anyway.
1260           std::string version;
1261           bool is_global;
1262           if (this->version_script_.get_symbol_version(name, &version,
1263                                                        &is_global))
1264             {
1265               if (!is_global)
1266                 is_forced_local = true;
1267               else if (!version.empty())
1268                 {
1269                   ver = this->namepool_.add_with_length(version.c_str(),
1270                                                         version.length(),
1271                                                         true,
1272                                                         &ver_key);
1273                   is_default_version = true;
1274                 }
1275             }
1276         }
1277     }
1278
1279   Stringpool::Key name_key;
1280   name = this->namepool_.add(name, true, &name_key);
1281
1282   Sized_symbol<size>* res;
1283   res = this->add_from_object(obj, name, name_key, ver, ver_key,
1284                               is_default_version, *sym, st_shndx,
1285                               is_ordinary, st_shndx);
1286
1287   if (is_forced_local)
1288     this->force_local(res);
1289
1290   return res;
1291 }
1292
1293 // Add all the symbols in a dynamic object to the hash table.
1294
1295 template<int size, bool big_endian>
1296 void
1297 Symbol_table::add_from_dynobj(
1298     Sized_dynobj<size, big_endian>* dynobj,
1299     const unsigned char* syms,
1300     size_t count,
1301     const char* sym_names,
1302     size_t sym_name_size,
1303     const unsigned char* versym,
1304     size_t versym_size,
1305     const std::vector<const char*>* version_map,
1306     typename Sized_relobj<size, big_endian>::Symbols* sympointers,
1307     size_t* defined)
1308 {
1309   *defined = 0;
1310
1311   gold_assert(size == parameters->target().get_size());
1312
1313   if (dynobj->just_symbols())
1314     {
1315       gold_error(_("--just-symbols does not make sense with a shared object"));
1316       return;
1317     }
1318
1319   if (versym != NULL && versym_size / 2 < count)
1320     {
1321       dynobj->error(_("too few symbol versions"));
1322       return;
1323     }
1324
1325   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
1326
1327   // We keep a list of all STT_OBJECT symbols, so that we can resolve
1328   // weak aliases.  This is necessary because if the dynamic object
1329   // provides the same variable under two names, one of which is a
1330   // weak definition, and the regular object refers to the weak
1331   // definition, we have to put both the weak definition and the
1332   // strong definition into the dynamic symbol table.  Given a weak
1333   // definition, the only way that we can find the corresponding
1334   // strong definition, if any, is to search the symbol table.
1335   std::vector<Sized_symbol<size>*> object_symbols;
1336
1337   const unsigned char* p = syms;
1338   const unsigned char* vs = versym;
1339   for (size_t i = 0; i < count; ++i, p += sym_size, vs += 2)
1340     {
1341       elfcpp::Sym<size, big_endian> sym(p);
1342
1343       if (sympointers != NULL)
1344         (*sympointers)[i] = NULL;
1345
1346       // Ignore symbols with local binding or that have
1347       // internal or hidden visibility.
1348       if (sym.get_st_bind() == elfcpp::STB_LOCAL
1349           || sym.get_st_visibility() == elfcpp::STV_INTERNAL
1350           || sym.get_st_visibility() == elfcpp::STV_HIDDEN)
1351         continue;
1352
1353       // A protected symbol in a shared library must be treated as a
1354       // normal symbol when viewed from outside the shared library.
1355       // Implement this by overriding the visibility here.
1356       elfcpp::Sym<size, big_endian>* psym = &sym;
1357       unsigned char symbuf[sym_size];
1358       elfcpp::Sym<size, big_endian> sym2(symbuf);
1359       if (sym.get_st_visibility() == elfcpp::STV_PROTECTED)
1360         {
1361           memcpy(symbuf, p, sym_size);
1362           elfcpp::Sym_write<size, big_endian> sw(symbuf);
1363           sw.put_st_other(elfcpp::STV_DEFAULT, sym.get_st_nonvis());
1364           psym = &sym2;
1365         }
1366
1367       unsigned int st_name = psym->get_st_name();
1368       if (st_name >= sym_name_size)
1369         {
1370           dynobj->error(_("bad symbol name offset %u at %zu"),
1371                         st_name, i);
1372           continue;
1373         }
1374
1375       const char* name = sym_names + st_name;
1376
1377       bool is_ordinary;
1378       unsigned int st_shndx = dynobj->adjust_sym_shndx(i, psym->get_st_shndx(),
1379                                                        &is_ordinary);
1380
1381       if (st_shndx != elfcpp::SHN_UNDEF)
1382         ++*defined;
1383
1384       Sized_symbol<size>* res;
1385
1386       if (versym == NULL)
1387         {
1388           Stringpool::Key name_key;
1389           name = this->namepool_.add(name, true, &name_key);
1390           res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1391                                       false, *psym, st_shndx, is_ordinary,
1392                                       st_shndx);
1393         }
1394       else
1395         {
1396           // Read the version information.
1397
1398           unsigned int v = elfcpp::Swap<16, big_endian>::readval(vs);
1399
1400           bool hidden = (v & elfcpp::VERSYM_HIDDEN) != 0;
1401           v &= elfcpp::VERSYM_VERSION;
1402
1403           // The Sun documentation says that V can be VER_NDX_LOCAL,
1404           // or VER_NDX_GLOBAL, or a version index.  The meaning of
1405           // VER_NDX_LOCAL is defined as "Symbol has local scope."
1406           // The old GNU linker will happily generate VER_NDX_LOCAL
1407           // for an undefined symbol.  I don't know what the Sun
1408           // linker will generate.
1409
1410           if (v == static_cast<unsigned int>(elfcpp::VER_NDX_LOCAL)
1411               && st_shndx != elfcpp::SHN_UNDEF)
1412             {
1413               // This symbol should not be visible outside the object.
1414               continue;
1415             }
1416
1417           // At this point we are definitely going to add this symbol.
1418           Stringpool::Key name_key;
1419           name = this->namepool_.add(name, true, &name_key);
1420
1421           if (v == static_cast<unsigned int>(elfcpp::VER_NDX_LOCAL)
1422               || v == static_cast<unsigned int>(elfcpp::VER_NDX_GLOBAL))
1423             {
1424               // This symbol does not have a version.
1425               res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1426                                           false, *psym, st_shndx, is_ordinary,
1427                                           st_shndx);
1428             }
1429           else
1430             {
1431               if (v >= version_map->size())
1432                 {
1433                   dynobj->error(_("versym for symbol %zu out of range: %u"),
1434                                 i, v);
1435                   continue;
1436                 }
1437
1438               const char* version = (*version_map)[v];
1439               if (version == NULL)
1440                 {
1441                   dynobj->error(_("versym for symbol %zu has no name: %u"),
1442                                 i, v);
1443                   continue;
1444                 }
1445
1446               Stringpool::Key version_key;
1447               version = this->namepool_.add(version, true, &version_key);
1448
1449               // If this is an absolute symbol, and the version name
1450               // and symbol name are the same, then this is the
1451               // version definition symbol.  These symbols exist to
1452               // support using -u to pull in particular versions.  We
1453               // do not want to record a version for them.
1454               if (st_shndx == elfcpp::SHN_ABS
1455                   && !is_ordinary
1456                   && name_key == version_key)
1457                 res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1458                                             false, *psym, st_shndx, is_ordinary,
1459                                             st_shndx);
1460               else
1461                 {
1462                   const bool is_default_version =
1463                     !hidden && st_shndx != elfcpp::SHN_UNDEF;
1464                   res = this->add_from_object(dynobj, name, name_key, version,
1465                                               version_key, is_default_version,
1466                                               *psym, st_shndx,
1467                                               is_ordinary, st_shndx);
1468                 }
1469             }
1470         }
1471
1472       // Note that it is possible that RES was overridden by an
1473       // earlier object, in which case it can't be aliased here.
1474       if (st_shndx != elfcpp::SHN_UNDEF
1475           && is_ordinary
1476           && psym->get_st_type() == elfcpp::STT_OBJECT
1477           && res->source() == Symbol::FROM_OBJECT
1478           && res->object() == dynobj)
1479         object_symbols.push_back(res);
1480
1481       if (sympointers != NULL)
1482         (*sympointers)[i] = res;
1483     }
1484
1485   this->record_weak_aliases(&object_symbols);
1486 }
1487
1488 // This is used to sort weak aliases.  We sort them first by section
1489 // index, then by offset, then by weak ahead of strong.
1490
1491 template<int size>
1492 class Weak_alias_sorter
1493 {
1494  public:
1495   bool operator()(const Sized_symbol<size>*, const Sized_symbol<size>*) const;
1496 };
1497
1498 template<int size>
1499 bool
1500 Weak_alias_sorter<size>::operator()(const Sized_symbol<size>* s1,
1501                                     const Sized_symbol<size>* s2) const
1502 {
1503   bool is_ordinary;
1504   unsigned int s1_shndx = s1->shndx(&is_ordinary);
1505   gold_assert(is_ordinary);
1506   unsigned int s2_shndx = s2->shndx(&is_ordinary);
1507   gold_assert(is_ordinary);
1508   if (s1_shndx != s2_shndx)
1509     return s1_shndx < s2_shndx;
1510
1511   if (s1->value() != s2->value())
1512     return s1->value() < s2->value();
1513   if (s1->binding() != s2->binding())
1514     {
1515       if (s1->binding() == elfcpp::STB_WEAK)
1516         return true;
1517       if (s2->binding() == elfcpp::STB_WEAK)
1518         return false;
1519     }
1520   return std::string(s1->name()) < std::string(s2->name());
1521 }
1522
1523 // SYMBOLS is a list of object symbols from a dynamic object.  Look
1524 // for any weak aliases, and record them so that if we add the weak
1525 // alias to the dynamic symbol table, we also add the corresponding
1526 // strong symbol.
1527
1528 template<int size>
1529 void
1530 Symbol_table::record_weak_aliases(std::vector<Sized_symbol<size>*>* symbols)
1531 {
1532   // Sort the vector by section index, then by offset, then by weak
1533   // ahead of strong.
1534   std::sort(symbols->begin(), symbols->end(), Weak_alias_sorter<size>());
1535
1536   // Walk through the vector.  For each weak definition, record
1537   // aliases.
1538   for (typename std::vector<Sized_symbol<size>*>::const_iterator p =
1539          symbols->begin();
1540        p != symbols->end();
1541        ++p)
1542     {
1543       if ((*p)->binding() != elfcpp::STB_WEAK)
1544         continue;
1545
1546       // Build a circular list of weak aliases.  Each symbol points to
1547       // the next one in the circular list.
1548
1549       Sized_symbol<size>* from_sym = *p;
1550       typename std::vector<Sized_symbol<size>*>::const_iterator q;
1551       for (q = p + 1; q != symbols->end(); ++q)
1552         {
1553           bool dummy;
1554           if ((*q)->shndx(&dummy) != from_sym->shndx(&dummy)
1555               || (*q)->value() != from_sym->value())
1556             break;
1557
1558           this->weak_aliases_[from_sym] = *q;
1559           from_sym->set_has_alias();
1560           from_sym = *q;
1561         }
1562
1563       if (from_sym != *p)
1564         {
1565           this->weak_aliases_[from_sym] = *p;
1566           from_sym->set_has_alias();
1567         }
1568
1569       p = q - 1;
1570     }
1571 }
1572
1573 // Create and return a specially defined symbol.  If ONLY_IF_REF is
1574 // true, then only create the symbol if there is a reference to it.
1575 // If this does not return NULL, it sets *POLDSYM to the existing
1576 // symbol if there is one.  This sets *RESOLVE_OLDSYM if we should
1577 // resolve the newly created symbol to the old one.  This
1578 // canonicalizes *PNAME and *PVERSION.
1579
1580 template<int size, bool big_endian>
1581 Sized_symbol<size>*
1582 Symbol_table::define_special_symbol(const char** pname, const char** pversion,
1583                                     bool only_if_ref,
1584                                     Sized_symbol<size>** poldsym,
1585                                     bool* resolve_oldsym)
1586 {
1587   *resolve_oldsym = false;
1588
1589   // If the caller didn't give us a version, see if we get one from
1590   // the version script.
1591   std::string v;
1592   bool is_default_version = false;
1593   if (*pversion == NULL)
1594     {
1595       bool is_global;
1596       if (this->version_script_.get_symbol_version(*pname, &v, &is_global))
1597         {
1598           if (is_global && !v.empty())
1599             {
1600               *pversion = v.c_str();
1601               // If we get the version from a version script, then we
1602               // are also the default version.
1603               is_default_version = true;
1604             }
1605         }
1606     }
1607
1608   Symbol* oldsym;
1609   Sized_symbol<size>* sym;
1610
1611   bool add_to_table = false;
1612   typename Symbol_table_type::iterator add_loc = this->table_.end();
1613   bool add_def_to_table = false;
1614   typename Symbol_table_type::iterator add_def_loc = this->table_.end();
1615
1616   if (only_if_ref)
1617     {
1618       oldsym = this->lookup(*pname, *pversion);
1619       if (oldsym == NULL && is_default_version)
1620         oldsym = this->lookup(*pname, NULL);
1621       if (oldsym == NULL || !oldsym->is_undefined())
1622         return NULL;
1623
1624       *pname = oldsym->name();
1625       if (!is_default_version)
1626         *pversion = oldsym->version();
1627     }
1628   else
1629     {
1630       // Canonicalize NAME and VERSION.
1631       Stringpool::Key name_key;
1632       *pname = this->namepool_.add(*pname, true, &name_key);
1633
1634       Stringpool::Key version_key = 0;
1635       if (*pversion != NULL)
1636         *pversion = this->namepool_.add(*pversion, true, &version_key);
1637
1638       Symbol* const snull = NULL;
1639       std::pair<typename Symbol_table_type::iterator, bool> ins =
1640         this->table_.insert(std::make_pair(std::make_pair(name_key,
1641                                                           version_key),
1642                                            snull));
1643
1644       std::pair<typename Symbol_table_type::iterator, bool> insdefault =
1645         std::make_pair(this->table_.end(), false);
1646       if (is_default_version)
1647         {
1648           const Stringpool::Key vnull = 0;
1649           insdefault =
1650             this->table_.insert(std::make_pair(std::make_pair(name_key,
1651                                                               vnull),
1652                                                snull));
1653         }
1654
1655       if (!ins.second)
1656         {
1657           // We already have a symbol table entry for NAME/VERSION.
1658           oldsym = ins.first->second;
1659           gold_assert(oldsym != NULL);
1660
1661           if (is_default_version)
1662             {
1663               Sized_symbol<size>* soldsym =
1664                 this->get_sized_symbol<size>(oldsym);
1665               this->define_default_version<size, big_endian>(soldsym,
1666                                                              insdefault.second,
1667                                                              insdefault.first);
1668             }
1669         }
1670       else
1671         {
1672           // We haven't seen this symbol before.
1673           gold_assert(ins.first->second == NULL);
1674
1675           add_to_table = true;
1676           add_loc = ins.first;
1677
1678           if (is_default_version && !insdefault.second)
1679             {
1680               // We are adding NAME/VERSION, and it is the default
1681               // version.  We already have an entry for NAME/NULL.
1682               oldsym = insdefault.first->second;
1683               *resolve_oldsym = true;
1684             }
1685           else
1686             {
1687               oldsym = NULL;
1688
1689               if (is_default_version)
1690                 {
1691                   add_def_to_table = true;
1692                   add_def_loc = insdefault.first;
1693                 }
1694             }
1695         }
1696     }
1697
1698   const Target& target = parameters->target();
1699   if (!target.has_make_symbol())
1700     sym = new Sized_symbol<size>();
1701   else
1702     {
1703       Sized_target<size, big_endian>* sized_target =
1704         parameters->sized_target<size, big_endian>();
1705       sym = sized_target->make_symbol();
1706       if (sym == NULL)
1707         return NULL;
1708     }
1709
1710   if (add_to_table)
1711     add_loc->second = sym;
1712   else
1713     gold_assert(oldsym != NULL);
1714
1715   if (add_def_to_table)
1716     add_def_loc->second = sym;
1717
1718   *poldsym = this->get_sized_symbol<size>(oldsym);
1719
1720   return sym;
1721 }
1722
1723 // Define a symbol based on an Output_data.
1724
1725 Symbol*
1726 Symbol_table::define_in_output_data(const char* name,
1727                                     const char* version,
1728                                     Defined defined,
1729                                     Output_data* od,
1730                                     uint64_t value,
1731                                     uint64_t symsize,
1732                                     elfcpp::STT type,
1733                                     elfcpp::STB binding,
1734                                     elfcpp::STV visibility,
1735                                     unsigned char nonvis,
1736                                     bool offset_is_from_end,
1737                                     bool only_if_ref)
1738 {
1739   if (parameters->target().get_size() == 32)
1740     {
1741 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1742       return this->do_define_in_output_data<32>(name, version, defined, od,
1743                                                 value, symsize, type, binding,
1744                                                 visibility, nonvis,
1745                                                 offset_is_from_end,
1746                                                 only_if_ref);
1747 #else
1748       gold_unreachable();
1749 #endif
1750     }
1751   else if (parameters->target().get_size() == 64)
1752     {
1753 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1754       return this->do_define_in_output_data<64>(name, version, defined, od,
1755                                                 value, symsize, type, binding,
1756                                                 visibility, nonvis,
1757                                                 offset_is_from_end,
1758                                                 only_if_ref);
1759 #else
1760       gold_unreachable();
1761 #endif
1762     }
1763   else
1764     gold_unreachable();
1765 }
1766
1767 // Define a symbol in an Output_data, sized version.
1768
1769 template<int size>
1770 Sized_symbol<size>*
1771 Symbol_table::do_define_in_output_data(
1772     const char* name,
1773     const char* version,
1774     Defined defined,
1775     Output_data* od,
1776     typename elfcpp::Elf_types<size>::Elf_Addr value,
1777     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
1778     elfcpp::STT type,
1779     elfcpp::STB binding,
1780     elfcpp::STV visibility,
1781     unsigned char nonvis,
1782     bool offset_is_from_end,
1783     bool only_if_ref)
1784 {
1785   Sized_symbol<size>* sym;
1786   Sized_symbol<size>* oldsym;
1787   bool resolve_oldsym;
1788
1789   if (parameters->target().is_big_endian())
1790     {
1791 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
1792       sym = this->define_special_symbol<size, true>(&name, &version,
1793                                                     only_if_ref, &oldsym,
1794                                                     &resolve_oldsym);
1795 #else
1796       gold_unreachable();
1797 #endif
1798     }
1799   else
1800     {
1801 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
1802       sym = this->define_special_symbol<size, false>(&name, &version,
1803                                                      only_if_ref, &oldsym,
1804                                                      &resolve_oldsym);
1805 #else
1806       gold_unreachable();
1807 #endif
1808     }
1809
1810   if (sym == NULL)
1811     return NULL;
1812
1813   sym->init_output_data(name, version, od, value, symsize, type, binding,
1814                         visibility, nonvis, offset_is_from_end);
1815
1816   if (oldsym == NULL)
1817     {
1818       if (binding == elfcpp::STB_LOCAL
1819           || this->version_script_.symbol_is_local(name))
1820         this->force_local(sym);
1821       else if (version != NULL)
1822         sym->set_is_default();
1823       return sym;
1824     }
1825
1826   if (Symbol_table::should_override_with_special(oldsym, defined))
1827     this->override_with_special(oldsym, sym);
1828
1829   if (resolve_oldsym)
1830     return sym;
1831   else
1832     {
1833       delete sym;
1834       return oldsym;
1835     }
1836 }
1837
1838 // Define a symbol based on an Output_segment.
1839
1840 Symbol*
1841 Symbol_table::define_in_output_segment(const char* name,
1842                                        const char* version,
1843                                        Defined defined,
1844                                        Output_segment* os,
1845                                        uint64_t value,
1846                                        uint64_t symsize,
1847                                        elfcpp::STT type,
1848                                        elfcpp::STB binding,
1849                                        elfcpp::STV visibility,
1850                                        unsigned char nonvis,
1851                                        Symbol::Segment_offset_base offset_base,
1852                                        bool only_if_ref)
1853 {
1854   if (parameters->target().get_size() == 32)
1855     {
1856 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1857       return this->do_define_in_output_segment<32>(name, version, defined, os,
1858                                                    value, symsize, type,
1859                                                    binding, visibility, nonvis,
1860                                                    offset_base, only_if_ref);
1861 #else
1862       gold_unreachable();
1863 #endif
1864     }
1865   else if (parameters->target().get_size() == 64)
1866     {
1867 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1868       return this->do_define_in_output_segment<64>(name, version, defined, os,
1869                                                    value, symsize, type,
1870                                                    binding, visibility, nonvis,
1871                                                    offset_base, only_if_ref);
1872 #else
1873       gold_unreachable();
1874 #endif
1875     }
1876   else
1877     gold_unreachable();
1878 }
1879
1880 // Define a symbol in an Output_segment, sized version.
1881
1882 template<int size>
1883 Sized_symbol<size>*
1884 Symbol_table::do_define_in_output_segment(
1885     const char* name,
1886     const char* version,
1887     Defined defined,
1888     Output_segment* os,
1889     typename elfcpp::Elf_types<size>::Elf_Addr value,
1890     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
1891     elfcpp::STT type,
1892     elfcpp::STB binding,
1893     elfcpp::STV visibility,
1894     unsigned char nonvis,
1895     Symbol::Segment_offset_base offset_base,
1896     bool only_if_ref)
1897 {
1898   Sized_symbol<size>* sym;
1899   Sized_symbol<size>* oldsym;
1900   bool resolve_oldsym;
1901
1902   if (parameters->target().is_big_endian())
1903     {
1904 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
1905       sym = this->define_special_symbol<size, true>(&name, &version,
1906                                                     only_if_ref, &oldsym,
1907                                                     &resolve_oldsym);
1908 #else
1909       gold_unreachable();
1910 #endif
1911     }
1912   else
1913     {
1914 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
1915       sym = this->define_special_symbol<size, false>(&name, &version,
1916                                                      only_if_ref, &oldsym,
1917                                                      &resolve_oldsym);
1918 #else
1919       gold_unreachable();
1920 #endif
1921     }
1922
1923   if (sym == NULL)
1924     return NULL;
1925
1926   sym->init_output_segment(name, version, os, value, symsize, type, binding,
1927                            visibility, nonvis, offset_base);
1928
1929   if (oldsym == NULL)
1930     {
1931       if (binding == elfcpp::STB_LOCAL
1932           || this->version_script_.symbol_is_local(name))
1933         this->force_local(sym);
1934       else if (version != NULL)
1935         sym->set_is_default();
1936       return sym;
1937     }
1938
1939   if (Symbol_table::should_override_with_special(oldsym, defined))
1940     this->override_with_special(oldsym, sym);
1941
1942   if (resolve_oldsym)
1943     return sym;
1944   else
1945     {
1946       delete sym;
1947       return oldsym;
1948     }
1949 }
1950
1951 // Define a special symbol with a constant value.  It is a multiple
1952 // definition error if this symbol is already defined.
1953
1954 Symbol*
1955 Symbol_table::define_as_constant(const char* name,
1956                                  const char* version,
1957                                  Defined defined,
1958                                  uint64_t value,
1959                                  uint64_t symsize,
1960                                  elfcpp::STT type,
1961                                  elfcpp::STB binding,
1962                                  elfcpp::STV visibility,
1963                                  unsigned char nonvis,
1964                                  bool only_if_ref,
1965                                  bool force_override)
1966 {
1967   if (parameters->target().get_size() == 32)
1968     {
1969 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1970       return this->do_define_as_constant<32>(name, version, defined, value,
1971                                              symsize, type, binding,
1972                                              visibility, nonvis, only_if_ref,
1973                                              force_override);
1974 #else
1975       gold_unreachable();
1976 #endif
1977     }
1978   else if (parameters->target().get_size() == 64)
1979     {
1980 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1981       return this->do_define_as_constant<64>(name, version, defined, value,
1982                                              symsize, type, binding,
1983                                              visibility, nonvis, only_if_ref,
1984                                              force_override);
1985 #else
1986       gold_unreachable();
1987 #endif
1988     }
1989   else
1990     gold_unreachable();
1991 }
1992
1993 // Define a symbol as a constant, sized version.
1994
1995 template<int size>
1996 Sized_symbol<size>*
1997 Symbol_table::do_define_as_constant(
1998     const char* name,
1999     const char* version,
2000     Defined defined,
2001     typename elfcpp::Elf_types<size>::Elf_Addr value,
2002     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
2003     elfcpp::STT type,
2004     elfcpp::STB binding,
2005     elfcpp::STV visibility,
2006     unsigned char nonvis,
2007     bool only_if_ref,
2008     bool force_override)
2009 {
2010   Sized_symbol<size>* sym;
2011   Sized_symbol<size>* oldsym;
2012   bool resolve_oldsym;
2013
2014   if (parameters->target().is_big_endian())
2015     {
2016 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
2017       sym = this->define_special_symbol<size, true>(&name, &version,
2018                                                     only_if_ref, &oldsym,
2019                                                     &resolve_oldsym);
2020 #else
2021       gold_unreachable();
2022 #endif
2023     }
2024   else
2025     {
2026 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
2027       sym = this->define_special_symbol<size, false>(&name, &version,
2028                                                      only_if_ref, &oldsym,
2029                                                      &resolve_oldsym);
2030 #else
2031       gold_unreachable();
2032 #endif
2033     }
2034
2035   if (sym == NULL)
2036     return NULL;
2037
2038   sym->init_constant(name, version, value, symsize, type, binding, visibility,
2039                      nonvis);
2040
2041   if (oldsym == NULL)
2042     {
2043       // Version symbols are absolute symbols with name == version.
2044       // We don't want to force them to be local.
2045       if ((version == NULL
2046            || name != version
2047            || value != 0)
2048           && (binding == elfcpp::STB_LOCAL
2049               || this->version_script_.symbol_is_local(name)))
2050         this->force_local(sym);
2051       else if (version != NULL
2052                && (name != version || value != 0))
2053         sym->set_is_default();
2054       return sym;
2055     }
2056
2057   if (force_override
2058       || Symbol_table::should_override_with_special(oldsym, defined))
2059     this->override_with_special(oldsym, sym);
2060
2061   if (resolve_oldsym)
2062     return sym;
2063   else
2064     {
2065       delete sym;
2066       return oldsym;
2067     }
2068 }
2069
2070 // Define a set of symbols in output sections.
2071
2072 void
2073 Symbol_table::define_symbols(const Layout* layout, int count,
2074                              const Define_symbol_in_section* p,
2075                              bool only_if_ref)
2076 {
2077   for (int i = 0; i < count; ++i, ++p)
2078     {
2079       Output_section* os = layout->find_output_section(p->output_section);
2080       if (os != NULL)
2081         this->define_in_output_data(p->name, NULL, PREDEFINED, os, p->value,
2082                                     p->size, p->type, p->binding,
2083                                     p->visibility, p->nonvis,
2084                                     p->offset_is_from_end,
2085                                     only_if_ref || p->only_if_ref);
2086       else
2087         this->define_as_constant(p->name, NULL, PREDEFINED, 0, p->size,
2088                                  p->type, p->binding, p->visibility, p->nonvis,
2089                                  only_if_ref || p->only_if_ref,
2090                                  false);
2091     }
2092 }
2093
2094 // Define a set of symbols in output segments.
2095
2096 void
2097 Symbol_table::define_symbols(const Layout* layout, int count,
2098                              const Define_symbol_in_segment* p,
2099                              bool only_if_ref)
2100 {
2101   for (int i = 0; i < count; ++i, ++p)
2102     {
2103       Output_segment* os = layout->find_output_segment(p->segment_type,
2104                                                        p->segment_flags_set,
2105                                                        p->segment_flags_clear);
2106       if (os != NULL)
2107         this->define_in_output_segment(p->name, NULL, PREDEFINED, os, p->value,
2108                                        p->size, p->type, p->binding,
2109                                        p->visibility, p->nonvis,
2110                                        p->offset_base,
2111                                        only_if_ref || p->only_if_ref);
2112       else
2113         this->define_as_constant(p->name, NULL, PREDEFINED, 0, p->size,
2114                                  p->type, p->binding, p->visibility, p->nonvis,
2115                                  only_if_ref || p->only_if_ref,
2116                                  false);
2117     }
2118 }
2119
2120 // Define CSYM using a COPY reloc.  POSD is the Output_data where the
2121 // symbol should be defined--typically a .dyn.bss section.  VALUE is
2122 // the offset within POSD.
2123
2124 template<int size>
2125 void
2126 Symbol_table::define_with_copy_reloc(
2127     Sized_symbol<size>* csym,
2128     Output_data* posd,
2129     typename elfcpp::Elf_types<size>::Elf_Addr value)
2130 {
2131   gold_assert(csym->is_from_dynobj());
2132   gold_assert(!csym->is_copied_from_dynobj());
2133   Object* object = csym->object();
2134   gold_assert(object->is_dynamic());
2135   Dynobj* dynobj = static_cast<Dynobj*>(object);
2136
2137   // Our copied variable has to override any variable in a shared
2138   // library.
2139   elfcpp::STB binding = csym->binding();
2140   if (binding == elfcpp::STB_WEAK)
2141     binding = elfcpp::STB_GLOBAL;
2142
2143   this->define_in_output_data(csym->name(), csym->version(), COPY,
2144                               posd, value, csym->symsize(),
2145                               csym->type(), binding,
2146                               csym->visibility(), csym->nonvis(),
2147                               false, false);
2148
2149   csym->set_is_copied_from_dynobj();
2150   csym->set_needs_dynsym_entry();
2151
2152   this->copied_symbol_dynobjs_[csym] = dynobj;
2153
2154   // We have now defined all aliases, but we have not entered them all
2155   // in the copied_symbol_dynobjs_ map.
2156   if (csym->has_alias())
2157     {
2158       Symbol* sym = csym;
2159       while (true)
2160         {
2161           sym = this->weak_aliases_[sym];
2162           if (sym == csym)
2163             break;
2164           gold_assert(sym->output_data() == posd);
2165
2166           sym->set_is_copied_from_dynobj();
2167           this->copied_symbol_dynobjs_[sym] = dynobj;
2168         }
2169     }
2170 }
2171
2172 // SYM is defined using a COPY reloc.  Return the dynamic object where
2173 // the original definition was found.
2174
2175 Dynobj*
2176 Symbol_table::get_copy_source(const Symbol* sym) const
2177 {
2178   gold_assert(sym->is_copied_from_dynobj());
2179   Copied_symbol_dynobjs::const_iterator p =
2180     this->copied_symbol_dynobjs_.find(sym);
2181   gold_assert(p != this->copied_symbol_dynobjs_.end());
2182   return p->second;
2183 }
2184
2185 // Add any undefined symbols named on the command line.
2186
2187 void
2188 Symbol_table::add_undefined_symbols_from_command_line(Layout* layout)
2189 {
2190   if (parameters->options().any_undefined()
2191       || layout->script_options()->any_unreferenced())
2192     {
2193       if (parameters->target().get_size() == 32)
2194         {
2195 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
2196           this->do_add_undefined_symbols_from_command_line<32>(layout);
2197 #else
2198           gold_unreachable();
2199 #endif
2200         }
2201       else if (parameters->target().get_size() == 64)
2202         {
2203 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
2204           this->do_add_undefined_symbols_from_command_line<64>(layout);
2205 #else
2206           gold_unreachable();
2207 #endif
2208         }
2209       else
2210         gold_unreachable();
2211     }
2212 }
2213
2214 template<int size>
2215 void
2216 Symbol_table::do_add_undefined_symbols_from_command_line(Layout* layout)
2217 {
2218   for (options::String_set::const_iterator p =
2219          parameters->options().undefined_begin();
2220        p != parameters->options().undefined_end();
2221        ++p)
2222     this->add_undefined_symbol_from_command_line<size>(p->c_str());
2223
2224   for (Script_options::referenced_const_iterator p =
2225          layout->script_options()->referenced_begin();
2226        p != layout->script_options()->referenced_end();
2227        ++p)
2228     this->add_undefined_symbol_from_command_line<size>(p->c_str());
2229 }
2230
2231 template<int size>
2232 void
2233 Symbol_table::add_undefined_symbol_from_command_line(const char* name)
2234 {
2235   if (this->lookup(name) != NULL)
2236     return;
2237
2238   const char* version = NULL;
2239
2240   Sized_symbol<size>* sym;
2241   Sized_symbol<size>* oldsym;
2242   bool resolve_oldsym;
2243   if (parameters->target().is_big_endian())
2244     {
2245 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
2246       sym = this->define_special_symbol<size, true>(&name, &version,
2247                                                     false, &oldsym,
2248                                                     &resolve_oldsym);
2249 #else
2250       gold_unreachable();
2251 #endif
2252     }
2253   else
2254     {
2255 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
2256       sym = this->define_special_symbol<size, false>(&name, &version,
2257                                                      false, &oldsym,
2258                                                      &resolve_oldsym);
2259 #else
2260       gold_unreachable();
2261 #endif
2262     }
2263
2264   gold_assert(oldsym == NULL);
2265
2266   sym->init_undefined(name, version, elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
2267                       elfcpp::STV_DEFAULT, 0);
2268   ++this->saw_undefined_;
2269 }
2270
2271 // Set the dynamic symbol indexes.  INDEX is the index of the first
2272 // global dynamic symbol.  Pointers to the symbols are stored into the
2273 // vector SYMS.  The names are added to DYNPOOL.  This returns an
2274 // updated dynamic symbol index.
2275
2276 unsigned int
2277 Symbol_table::set_dynsym_indexes(unsigned int index,
2278                                  std::vector<Symbol*>* syms,
2279                                  Stringpool* dynpool,
2280                                  Versions* versions)
2281 {
2282   for (Symbol_table_type::iterator p = this->table_.begin();
2283        p != this->table_.end();
2284        ++p)
2285     {
2286       Symbol* sym = p->second;
2287
2288       // Note that SYM may already have a dynamic symbol index, since
2289       // some symbols appear more than once in the symbol table, with
2290       // and without a version.
2291
2292       if (!sym->should_add_dynsym_entry(this))
2293         sym->set_dynsym_index(-1U);
2294       else if (!sym->has_dynsym_index())
2295         {
2296           sym->set_dynsym_index(index);
2297           ++index;
2298           syms->push_back(sym);
2299           dynpool->add(sym->name(), false, NULL);
2300
2301           // Record any version information.
2302           if (sym->version() != NULL)
2303             versions->record_version(this, dynpool, sym);
2304
2305           // If the symbol is defined in a dynamic object and is
2306           // referenced in a regular object, then mark the dynamic
2307           // object as needed.  This is used to implement --as-needed.
2308           if (sym->is_from_dynobj() && sym->in_reg())
2309             sym->object()->set_is_needed();
2310         }
2311     }
2312
2313   // Finish up the versions.  In some cases this may add new dynamic
2314   // symbols.
2315   index = versions->finalize(this, index, syms);
2316
2317   return index;
2318 }
2319
2320 // Set the final values for all the symbols.  The index of the first
2321 // global symbol in the output file is *PLOCAL_SYMCOUNT.  Record the
2322 // file offset OFF.  Add their names to POOL.  Return the new file
2323 // offset.  Update *PLOCAL_SYMCOUNT if necessary.
2324
2325 off_t
2326 Symbol_table::finalize(off_t off, off_t dynoff, size_t dyn_global_index,
2327                        size_t dyncount, Stringpool* pool,
2328                        unsigned int* plocal_symcount)
2329 {
2330   off_t ret;
2331
2332   gold_assert(*plocal_symcount != 0);
2333   this->first_global_index_ = *plocal_symcount;
2334
2335   this->dynamic_offset_ = dynoff;
2336   this->first_dynamic_global_index_ = dyn_global_index;
2337   this->dynamic_count_ = dyncount;
2338
2339   if (parameters->target().get_size() == 32)
2340     {
2341 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_32_LITTLE)
2342       ret = this->sized_finalize<32>(off, pool, plocal_symcount);
2343 #else
2344       gold_unreachable();
2345 #endif
2346     }
2347   else if (parameters->target().get_size() == 64)
2348     {
2349 #if defined(HAVE_TARGET_64_BIG) || defined(HAVE_TARGET_64_LITTLE)
2350       ret = this->sized_finalize<64>(off, pool, plocal_symcount);
2351 #else
2352       gold_unreachable();
2353 #endif
2354     }
2355   else
2356     gold_unreachable();
2357
2358   // Now that we have the final symbol table, we can reliably note
2359   // which symbols should get warnings.
2360   this->warnings_.note_warnings(this);
2361
2362   return ret;
2363 }
2364
2365 // SYM is going into the symbol table at *PINDEX.  Add the name to
2366 // POOL, update *PINDEX and *POFF.
2367
2368 template<int size>
2369 void
2370 Symbol_table::add_to_final_symtab(Symbol* sym, Stringpool* pool,
2371                                   unsigned int* pindex, off_t* poff)
2372 {
2373   sym->set_symtab_index(*pindex);
2374   pool->add(sym->name(), false, NULL);
2375   ++*pindex;
2376   *poff += elfcpp::Elf_sizes<size>::sym_size;
2377 }
2378
2379 // Set the final value for all the symbols.  This is called after
2380 // Layout::finalize, so all the output sections have their final
2381 // address.
2382
2383 template<int size>
2384 off_t
2385 Symbol_table::sized_finalize(off_t off, Stringpool* pool,
2386                              unsigned int* plocal_symcount)
2387 {
2388   off = align_address(off, size >> 3);
2389   this->offset_ = off;
2390
2391   unsigned int index = *plocal_symcount;
2392   const unsigned int orig_index = index;
2393
2394   // First do all the symbols which have been forced to be local, as
2395   // they must appear before all global symbols.
2396   for (Forced_locals::iterator p = this->forced_locals_.begin();
2397        p != this->forced_locals_.end();
2398        ++p)
2399     {
2400       Symbol* sym = *p;
2401       gold_assert(sym->is_forced_local());
2402       if (this->sized_finalize_symbol<size>(sym))
2403         {
2404           this->add_to_final_symtab<size>(sym, pool, &index, &off);
2405           ++*plocal_symcount;
2406         }
2407     }
2408
2409   // Now do all the remaining symbols.
2410   for (Symbol_table_type::iterator p = this->table_.begin();
2411        p != this->table_.end();
2412        ++p)
2413     {
2414       Symbol* sym = p->second;
2415       if (this->sized_finalize_symbol<size>(sym))
2416         this->add_to_final_symtab<size>(sym, pool, &index, &off);
2417     }
2418
2419   this->output_count_ = index - orig_index;
2420
2421   return off;
2422 }
2423
2424 // Compute the final value of SYM and store status in location PSTATUS.
2425 // During relaxation, this may be called multiple times for a symbol to
2426 // compute its would-be final value in each relaxation pass.
2427
2428 template<int size>
2429 typename Sized_symbol<size>::Value_type
2430 Symbol_table::compute_final_value(
2431     const Sized_symbol<size>* sym,
2432     Compute_final_value_status* pstatus) const
2433 {
2434   typedef typename Sized_symbol<size>::Value_type Value_type;
2435   Value_type value;
2436
2437   switch (sym->source())
2438     {
2439     case Symbol::FROM_OBJECT:
2440       {
2441         bool is_ordinary;
2442         unsigned int shndx = sym->shndx(&is_ordinary);
2443
2444         if (!is_ordinary
2445             && shndx != elfcpp::SHN_ABS
2446             && !Symbol::is_common_shndx(shndx))
2447           {
2448             *pstatus = CFVS_UNSUPPORTED_SYMBOL_SECTION;
2449             return 0;
2450           }
2451
2452         Object* symobj = sym->object();
2453         if (symobj->is_dynamic())
2454           {
2455             value = 0;
2456             shndx = elfcpp::SHN_UNDEF;
2457           }
2458         else if (symobj->pluginobj() != NULL)
2459           {
2460             value = 0;
2461             shndx = elfcpp::SHN_UNDEF;
2462           }
2463         else if (shndx == elfcpp::SHN_UNDEF)
2464           value = 0;
2465         else if (!is_ordinary
2466                  && (shndx == elfcpp::SHN_ABS
2467                      || Symbol::is_common_shndx(shndx)))
2468           value = sym->value();
2469         else
2470           {
2471             Relobj* relobj = static_cast<Relobj*>(symobj);
2472             Output_section* os = relobj->output_section(shndx);
2473
2474             if (this->is_section_folded(relobj, shndx))
2475               {
2476                 gold_assert(os == NULL);
2477                 // Get the os of the section it is folded onto.
2478                 Section_id folded = this->icf_->get_folded_section(relobj,
2479                                                                    shndx);
2480                 gold_assert(folded.first != NULL);
2481                 Relobj* folded_obj = reinterpret_cast<Relobj*>(folded.first);
2482                 unsigned folded_shndx = folded.second;
2483
2484                 os = folded_obj->output_section(folded_shndx);  
2485                 gold_assert(os != NULL);
2486
2487                 // Replace (relobj, shndx) with canonical ICF input section.
2488                 shndx = folded_shndx;
2489                 relobj = folded_obj;
2490               }
2491
2492             uint64_t secoff64 = relobj->output_section_offset(shndx);
2493             if (os == NULL)
2494               {
2495                 bool static_or_reloc = (parameters->doing_static_link() ||
2496                                         parameters->options().relocatable());
2497                 gold_assert(static_or_reloc || sym->dynsym_index() == -1U);
2498
2499                 *pstatus = CFVS_NO_OUTPUT_SECTION;
2500                 return 0;
2501               }
2502
2503             if (secoff64 == -1ULL)
2504               {
2505                 // The section needs special handling (e.g., a merge section).
2506
2507                 value = os->output_address(relobj, shndx, sym->value());
2508               }
2509             else
2510               {
2511                 Value_type secoff =
2512                   convert_types<Value_type, uint64_t>(secoff64);
2513                 if (sym->type() == elfcpp::STT_TLS)
2514                   value = sym->value() + os->tls_offset() + secoff;
2515                 else
2516                   value = sym->value() + os->address() + secoff;
2517               }
2518           }
2519       }
2520       break;
2521
2522     case Symbol::IN_OUTPUT_DATA:
2523       {
2524         Output_data* od = sym->output_data();
2525         value = sym->value();
2526         if (sym->type() != elfcpp::STT_TLS)
2527           value += od->address();
2528         else
2529           {
2530             Output_section* os = od->output_section();
2531             gold_assert(os != NULL);
2532             value += os->tls_offset() + (od->address() - os->address());
2533           }
2534         if (sym->offset_is_from_end())
2535           value += od->data_size();
2536       }
2537       break;
2538
2539     case Symbol::IN_OUTPUT_SEGMENT:
2540       {
2541         Output_segment* os = sym->output_segment();
2542         value = sym->value();
2543         if (sym->type() != elfcpp::STT_TLS)
2544           value += os->vaddr();
2545         switch (sym->offset_base())
2546           {
2547           case Symbol::SEGMENT_START:
2548             break;
2549           case Symbol::SEGMENT_END:
2550             value += os->memsz();
2551             break;
2552           case Symbol::SEGMENT_BSS:
2553             value += os->filesz();
2554             break;
2555           default:
2556             gold_unreachable();
2557           }
2558       }
2559       break;
2560
2561     case Symbol::IS_CONSTANT:
2562       value = sym->value();
2563       break;
2564
2565     case Symbol::IS_UNDEFINED:
2566       value = 0;
2567       break;
2568
2569     default:
2570       gold_unreachable();
2571     }
2572
2573   *pstatus = CFVS_OK;
2574   return value;
2575 }
2576
2577 // Finalize the symbol SYM.  This returns true if the symbol should be
2578 // added to the symbol table, false otherwise.
2579
2580 template<int size>
2581 bool
2582 Symbol_table::sized_finalize_symbol(Symbol* unsized_sym)
2583 {
2584   typedef typename Sized_symbol<size>::Value_type Value_type;
2585
2586   Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(unsized_sym);
2587
2588   // The default version of a symbol may appear twice in the symbol
2589   // table.  We only need to finalize it once.
2590   if (sym->has_symtab_index())
2591     return false;
2592
2593   if (!sym->in_reg())
2594     {
2595       gold_assert(!sym->has_symtab_index());
2596       sym->set_symtab_index(-1U);
2597       gold_assert(sym->dynsym_index() == -1U);
2598       return false;
2599     }
2600
2601   // If the symbol is only present on plugin files, the plugin decided we
2602   // don't need it.
2603   if (!sym->in_real_elf())
2604     {
2605       gold_assert(!sym->has_symtab_index());
2606       sym->set_symtab_index(-1U);
2607       return false;
2608     }
2609
2610   // Compute final symbol value.
2611   Compute_final_value_status status;
2612   Value_type value = this->compute_final_value(sym, &status);
2613
2614   switch (status)
2615     {
2616     case CFVS_OK:
2617       break;
2618     case CFVS_UNSUPPORTED_SYMBOL_SECTION:
2619       {
2620         bool is_ordinary;
2621         unsigned int shndx = sym->shndx(&is_ordinary);
2622         gold_error(_("%s: unsupported symbol section 0x%x"),
2623                    sym->demangled_name().c_str(), shndx);
2624       }
2625       break;
2626     case CFVS_NO_OUTPUT_SECTION:
2627       sym->set_symtab_index(-1U);
2628       return false;
2629     default:
2630       gold_unreachable();
2631     }
2632
2633   sym->set_value(value);
2634
2635   if (parameters->options().strip_all()
2636       || !parameters->options().should_retain_symbol(sym->name()))
2637     {
2638       sym->set_symtab_index(-1U);
2639       return false;
2640     }
2641
2642   return true;
2643 }
2644
2645 // Write out the global symbols.
2646
2647 void
2648 Symbol_table::write_globals(const Stringpool* sympool,
2649                             const Stringpool* dynpool,
2650                             Output_symtab_xindex* symtab_xindex,
2651                             Output_symtab_xindex* dynsym_xindex,
2652                             Output_file* of) const
2653 {
2654   switch (parameters->size_and_endianness())
2655     {
2656 #ifdef HAVE_TARGET_32_LITTLE
2657     case Parameters::TARGET_32_LITTLE:
2658       this->sized_write_globals<32, false>(sympool, dynpool, symtab_xindex,
2659                                            dynsym_xindex, of);
2660       break;
2661 #endif
2662 #ifdef HAVE_TARGET_32_BIG
2663     case Parameters::TARGET_32_BIG:
2664       this->sized_write_globals<32, true>(sympool, dynpool, symtab_xindex,
2665                                           dynsym_xindex, of);
2666       break;
2667 #endif
2668 #ifdef HAVE_TARGET_64_LITTLE
2669     case Parameters::TARGET_64_LITTLE:
2670       this->sized_write_globals<64, false>(sympool, dynpool, symtab_xindex,
2671                                            dynsym_xindex, of);
2672       break;
2673 #endif
2674 #ifdef HAVE_TARGET_64_BIG
2675     case Parameters::TARGET_64_BIG:
2676       this->sized_write_globals<64, true>(sympool, dynpool, symtab_xindex,
2677                                           dynsym_xindex, of);
2678       break;
2679 #endif
2680     default:
2681       gold_unreachable();
2682     }
2683 }
2684
2685 // Write out the global symbols.
2686
2687 template<int size, bool big_endian>
2688 void
2689 Symbol_table::sized_write_globals(const Stringpool* sympool,
2690                                   const Stringpool* dynpool,
2691                                   Output_symtab_xindex* symtab_xindex,
2692                                   Output_symtab_xindex* dynsym_xindex,
2693                                   Output_file* of) const
2694 {
2695   const Target& target = parameters->target();
2696
2697   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2698
2699   const unsigned int output_count = this->output_count_;
2700   const section_size_type oview_size = output_count * sym_size;
2701   const unsigned int first_global_index = this->first_global_index_;
2702   unsigned char* psyms;
2703   if (this->offset_ == 0 || output_count == 0)
2704     psyms = NULL;
2705   else
2706     psyms = of->get_output_view(this->offset_, oview_size);
2707
2708   const unsigned int dynamic_count = this->dynamic_count_;
2709   const section_size_type dynamic_size = dynamic_count * sym_size;
2710   const unsigned int first_dynamic_global_index =
2711     this->first_dynamic_global_index_;
2712   unsigned char* dynamic_view;
2713   if (this->dynamic_offset_ == 0 || dynamic_count == 0)
2714     dynamic_view = NULL;
2715   else
2716     dynamic_view = of->get_output_view(this->dynamic_offset_, dynamic_size);
2717
2718   for (Symbol_table_type::const_iterator p = this->table_.begin();
2719        p != this->table_.end();
2720        ++p)
2721     {
2722       Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(p->second);
2723
2724       // Possibly warn about unresolved symbols in shared libraries.
2725       this->warn_about_undefined_dynobj_symbol(sym);
2726
2727       unsigned int sym_index = sym->symtab_index();
2728       unsigned int dynsym_index;
2729       if (dynamic_view == NULL)
2730         dynsym_index = -1U;
2731       else
2732         dynsym_index = sym->dynsym_index();
2733
2734       if (sym_index == -1U && dynsym_index == -1U)
2735         {
2736           // This symbol is not included in the output file.
2737           continue;
2738         }
2739
2740       unsigned int shndx;
2741       typename elfcpp::Elf_types<size>::Elf_Addr sym_value = sym->value();
2742       typename elfcpp::Elf_types<size>::Elf_Addr dynsym_value = sym_value;
2743       elfcpp::STB binding = sym->binding();
2744       switch (sym->source())
2745         {
2746         case Symbol::FROM_OBJECT:
2747           {
2748             bool is_ordinary;
2749             unsigned int in_shndx = sym->shndx(&is_ordinary);
2750
2751             if (!is_ordinary
2752                 && in_shndx != elfcpp::SHN_ABS
2753                 && !Symbol::is_common_shndx(in_shndx))
2754               {
2755                 gold_error(_("%s: unsupported symbol section 0x%x"),
2756                            sym->demangled_name().c_str(), in_shndx);
2757                 shndx = in_shndx;
2758               }
2759             else
2760               {
2761                 Object* symobj = sym->object();
2762                 if (symobj->is_dynamic())
2763                   {
2764                     if (sym->needs_dynsym_value())
2765                       dynsym_value = target.dynsym_value(sym);
2766                     shndx = elfcpp::SHN_UNDEF;
2767                     if (sym->is_undef_binding_weak())
2768                       binding = elfcpp::STB_WEAK;
2769                     else
2770                       binding = elfcpp::STB_GLOBAL;
2771                   }
2772                 else if (symobj->pluginobj() != NULL)
2773                   shndx = elfcpp::SHN_UNDEF;
2774                 else if (in_shndx == elfcpp::SHN_UNDEF
2775                          || (!is_ordinary
2776                              && (in_shndx == elfcpp::SHN_ABS
2777                                  || Symbol::is_common_shndx(in_shndx))))
2778                   shndx = in_shndx;
2779                 else
2780                   {
2781                     Relobj* relobj = static_cast<Relobj*>(symobj);
2782                     Output_section* os = relobj->output_section(in_shndx);
2783                     if (this->is_section_folded(relobj, in_shndx))
2784                       {
2785                         // This global symbol must be written out even though
2786                         // it is folded.
2787                         // Get the os of the section it is folded onto.
2788                         Section_id folded =
2789                              this->icf_->get_folded_section(relobj, in_shndx);
2790                         gold_assert(folded.first !=NULL);
2791                         Relobj* folded_obj = 
2792                           reinterpret_cast<Relobj*>(folded.first);
2793                         os = folded_obj->output_section(folded.second);  
2794                         gold_assert(os != NULL);
2795                       }
2796                     gold_assert(os != NULL);
2797                     shndx = os->out_shndx();
2798
2799                     if (shndx >= elfcpp::SHN_LORESERVE)
2800                       {
2801                         if (sym_index != -1U)
2802                           symtab_xindex->add(sym_index, shndx);
2803                         if (dynsym_index != -1U)
2804                           dynsym_xindex->add(dynsym_index, shndx);
2805                         shndx = elfcpp::SHN_XINDEX;
2806                       }
2807
2808                     // In object files symbol values are section
2809                     // relative.
2810                     if (parameters->options().relocatable())
2811                       sym_value -= os->address();
2812                   }
2813               }
2814           }
2815           break;
2816
2817         case Symbol::IN_OUTPUT_DATA:
2818           shndx = sym->output_data()->out_shndx();
2819           if (shndx >= elfcpp::SHN_LORESERVE)
2820             {
2821               if (sym_index != -1U)
2822                 symtab_xindex->add(sym_index, shndx);
2823               if (dynsym_index != -1U)
2824                 dynsym_xindex->add(dynsym_index, shndx);
2825               shndx = elfcpp::SHN_XINDEX;
2826             }
2827           break;
2828
2829         case Symbol::IN_OUTPUT_SEGMENT:
2830           shndx = elfcpp::SHN_ABS;
2831           break;
2832
2833         case Symbol::IS_CONSTANT:
2834           shndx = elfcpp::SHN_ABS;
2835           break;
2836
2837         case Symbol::IS_UNDEFINED:
2838           shndx = elfcpp::SHN_UNDEF;
2839           break;
2840
2841         default:
2842           gold_unreachable();
2843         }
2844
2845       if (sym_index != -1U)
2846         {
2847           sym_index -= first_global_index;
2848           gold_assert(sym_index < output_count);
2849           unsigned char* ps = psyms + (sym_index * sym_size);
2850           this->sized_write_symbol<size, big_endian>(sym, sym_value, shndx,
2851                                                      binding, sympool, ps);
2852         }
2853
2854       if (dynsym_index != -1U)
2855         {
2856           dynsym_index -= first_dynamic_global_index;
2857           gold_assert(dynsym_index < dynamic_count);
2858           unsigned char* pd = dynamic_view + (dynsym_index * sym_size);
2859           this->sized_write_symbol<size, big_endian>(sym, dynsym_value, shndx,
2860                                                      binding, dynpool, pd);
2861         }
2862     }
2863
2864   of->write_output_view(this->offset_, oview_size, psyms);
2865   if (dynamic_view != NULL)
2866     of->write_output_view(this->dynamic_offset_, dynamic_size, dynamic_view);
2867 }
2868
2869 // Write out the symbol SYM, in section SHNDX, to P.  POOL is the
2870 // strtab holding the name.
2871
2872 template<int size, bool big_endian>
2873 void
2874 Symbol_table::sized_write_symbol(
2875     Sized_symbol<size>* sym,
2876     typename elfcpp::Elf_types<size>::Elf_Addr value,
2877     unsigned int shndx,
2878     elfcpp::STB binding,
2879     const Stringpool* pool,
2880     unsigned char* p) const
2881 {
2882   elfcpp::Sym_write<size, big_endian> osym(p);
2883   osym.put_st_name(pool->get_offset(sym->name()));
2884   osym.put_st_value(value);
2885   // Use a symbol size of zero for undefined symbols from shared libraries.
2886   if (shndx == elfcpp::SHN_UNDEF && sym->is_from_dynobj())
2887     osym.put_st_size(0);
2888   else
2889     osym.put_st_size(sym->symsize());
2890   elfcpp::STT type = sym->type();
2891   // Turn IFUNC symbols from shared libraries into normal FUNC symbols.
2892   if (type == elfcpp::STT_GNU_IFUNC
2893       && sym->is_from_dynobj())
2894     type = elfcpp::STT_FUNC;
2895   // A version script may have overridden the default binding.
2896   if (sym->is_forced_local())
2897     osym.put_st_info(elfcpp::elf_st_info(elfcpp::STB_LOCAL, type));
2898   else
2899     osym.put_st_info(elfcpp::elf_st_info(binding, type));
2900   osym.put_st_other(elfcpp::elf_st_other(sym->visibility(), sym->nonvis()));
2901   osym.put_st_shndx(shndx);
2902 }
2903
2904 // Check for unresolved symbols in shared libraries.  This is
2905 // controlled by the --allow-shlib-undefined option.
2906
2907 // We only warn about libraries for which we have seen all the
2908 // DT_NEEDED entries.  We don't try to track down DT_NEEDED entries
2909 // which were not seen in this link.  If we didn't see a DT_NEEDED
2910 // entry, we aren't going to be able to reliably report whether the
2911 // symbol is undefined.
2912
2913 // We also don't warn about libraries found in a system library
2914 // directory (e.g., /lib or /usr/lib); we assume that those libraries
2915 // are OK.  This heuristic avoids problems on GNU/Linux, in which -ldl
2916 // can have undefined references satisfied by ld-linux.so.
2917
2918 inline void
2919 Symbol_table::warn_about_undefined_dynobj_symbol(Symbol* sym) const
2920 {
2921   bool dummy;
2922   if (sym->source() == Symbol::FROM_OBJECT
2923       && sym->object()->is_dynamic()
2924       && sym->shndx(&dummy) == elfcpp::SHN_UNDEF
2925       && sym->binding() != elfcpp::STB_WEAK
2926       && !parameters->options().allow_shlib_undefined()
2927       && !parameters->target().is_defined_by_abi(sym)
2928       && !sym->object()->is_in_system_directory())
2929     {
2930       // A very ugly cast.
2931       Dynobj* dynobj = static_cast<Dynobj*>(sym->object());
2932       if (!dynobj->has_unknown_needed_entries())
2933         gold_undefined_symbol(sym);
2934     }
2935 }
2936
2937 // Write out a section symbol.  Return the update offset.
2938
2939 void
2940 Symbol_table::write_section_symbol(const Output_section* os,
2941                                    Output_symtab_xindex* symtab_xindex,
2942                                    Output_file* of,
2943                                    off_t offset) const
2944 {
2945   switch (parameters->size_and_endianness())
2946     {
2947 #ifdef HAVE_TARGET_32_LITTLE
2948     case Parameters::TARGET_32_LITTLE:
2949       this->sized_write_section_symbol<32, false>(os, symtab_xindex, of,
2950                                                   offset);
2951       break;
2952 #endif
2953 #ifdef HAVE_TARGET_32_BIG
2954     case Parameters::TARGET_32_BIG:
2955       this->sized_write_section_symbol<32, true>(os, symtab_xindex, of,
2956                                                  offset);
2957       break;
2958 #endif
2959 #ifdef HAVE_TARGET_64_LITTLE
2960     case Parameters::TARGET_64_LITTLE:
2961       this->sized_write_section_symbol<64, false>(os, symtab_xindex, of,
2962                                                   offset);
2963       break;
2964 #endif
2965 #ifdef HAVE_TARGET_64_BIG
2966     case Parameters::TARGET_64_BIG:
2967       this->sized_write_section_symbol<64, true>(os, symtab_xindex, of,
2968                                                  offset);
2969       break;
2970 #endif
2971     default:
2972       gold_unreachable();
2973     }
2974 }
2975
2976 // Write out a section symbol, specialized for size and endianness.
2977
2978 template<int size, bool big_endian>
2979 void
2980 Symbol_table::sized_write_section_symbol(const Output_section* os,
2981                                          Output_symtab_xindex* symtab_xindex,
2982                                          Output_file* of,
2983                                          off_t offset) const
2984 {
2985   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2986
2987   unsigned char* pov = of->get_output_view(offset, sym_size);
2988
2989   elfcpp::Sym_write<size, big_endian> osym(pov);
2990   osym.put_st_name(0);
2991   if (parameters->options().relocatable())
2992     osym.put_st_value(0);
2993   else
2994     osym.put_st_value(os->address());
2995   osym.put_st_size(0);
2996   osym.put_st_info(elfcpp::elf_st_info(elfcpp::STB_LOCAL,
2997                                        elfcpp::STT_SECTION));
2998   osym.put_st_other(elfcpp::elf_st_other(elfcpp::STV_DEFAULT, 0));
2999
3000   unsigned int shndx = os->out_shndx();
3001   if (shndx >= elfcpp::SHN_LORESERVE)
3002     {
3003       symtab_xindex->add(os->symtab_index(), shndx);
3004       shndx = elfcpp::SHN_XINDEX;
3005     }
3006   osym.put_st_shndx(shndx);
3007
3008   of->write_output_view(offset, sym_size, pov);
3009 }
3010
3011 // Print statistical information to stderr.  This is used for --stats.
3012
3013 void
3014 Symbol_table::print_stats() const
3015 {
3016 #if defined(HAVE_TR1_UNORDERED_MAP) || defined(HAVE_EXT_HASH_MAP)
3017   fprintf(stderr, _("%s: symbol table entries: %zu; buckets: %zu\n"),
3018           program_name, this->table_.size(), this->table_.bucket_count());
3019 #else
3020   fprintf(stderr, _("%s: symbol table entries: %zu\n"),
3021           program_name, this->table_.size());
3022 #endif
3023   this->namepool_.print_stats("symbol table stringpool");
3024 }
3025
3026 // We check for ODR violations by looking for symbols with the same
3027 // name for which the debugging information reports that they were
3028 // defined in disjoint source locations.  When comparing the source
3029 // location, we consider instances with the same base filename to be
3030 // the same.  This is because different object files/shared libraries
3031 // can include the same header file using different paths, and
3032 // different optimization settings can make the line number appear to
3033 // be a couple lines off, and we don't want to report an ODR violation
3034 // in those cases.
3035
3036 // This struct is used to compare line information, as returned by
3037 // Dwarf_line_info::one_addr2line.  It implements a < comparison
3038 // operator used with std::sort.
3039
3040 struct Odr_violation_compare
3041 {
3042   bool
3043   operator()(const std::string& s1, const std::string& s2) const
3044   {
3045     // Inputs should be of the form "dirname/filename:linenum" where
3046     // "dirname/" is optional.  We want to compare just the filename:linenum.
3047
3048     // Find the last '/' in each string.
3049     std::string::size_type s1begin = s1.rfind('/');
3050     std::string::size_type s2begin = s2.rfind('/');
3051     // If there was no '/' in a string, start at the beginning.
3052     if (s1begin == std::string::npos)
3053       s1begin = 0;
3054     if (s2begin == std::string::npos)
3055       s2begin = 0;
3056     return s1.compare(s1begin, std::string::npos,
3057                       s2, s2begin, std::string::npos) < 0;
3058   }
3059 };
3060
3061 // Returns all of the lines attached to LOC, not just the one the
3062 // instruction actually came from.
3063 std::vector<std::string>
3064 Symbol_table::linenos_from_loc(const Task* task,
3065                                const Symbol_location& loc)
3066 {
3067   // We need to lock the object in order to read it.  This
3068   // means that we have to run in a singleton Task.  If we
3069   // want to run this in a general Task for better
3070   // performance, we will need one Task for object, plus
3071   // appropriate locking to ensure that we don't conflict with
3072   // other uses of the object.  Also note, one_addr2line is not
3073   // currently thread-safe.
3074   Task_lock_obj<Object> tl(task, loc.object);
3075
3076   std::vector<std::string> result;
3077   // 16 is the size of the object-cache that one_addr2line should use.
3078   std::string canonical_result = Dwarf_line_info::one_addr2line(
3079       loc.object, loc.shndx, loc.offset, 16, &result);
3080   if (!canonical_result.empty())
3081     result.push_back(canonical_result);
3082   return result;
3083 }
3084
3085 // OutputIterator that records if it was ever assigned to.  This
3086 // allows it to be used with std::set_intersection() to check for
3087 // intersection rather than computing the intersection.
3088 struct Check_intersection
3089 {
3090   Check_intersection()
3091     : value_(false)
3092   {}
3093
3094   bool had_intersection() const
3095   { return this->value_; }
3096
3097   Check_intersection& operator++()
3098   { return *this; }
3099
3100   Check_intersection& operator*()
3101   { return *this; }
3102
3103   template<typename T>
3104   Check_intersection& operator=(const T&)
3105   {
3106     this->value_ = true;
3107     return *this;
3108   }
3109
3110  private:
3111   bool value_;
3112 };
3113
3114 // Check candidate_odr_violations_ to find symbols with the same name
3115 // but apparently different definitions (different source-file/line-no
3116 // for each line assigned to the first instruction).
3117
3118 void
3119 Symbol_table::detect_odr_violations(const Task* task,
3120                                     const char* output_file_name) const
3121 {
3122   for (Odr_map::const_iterator it = candidate_odr_violations_.begin();
3123        it != candidate_odr_violations_.end();
3124        ++it)
3125     {
3126       const char* const symbol_name = it->first;
3127
3128       std::string first_object_name;
3129       std::vector<std::string> first_object_linenos;
3130
3131       Unordered_set<Symbol_location, Symbol_location_hash>::const_iterator
3132           locs = it->second.begin();
3133       const Unordered_set<Symbol_location, Symbol_location_hash>::const_iterator
3134           locs_end = it->second.end();
3135       for (; locs != locs_end && first_object_linenos.empty(); ++locs)
3136         {
3137           // Save the line numbers from the first definition to
3138           // compare to the other definitions.  Ideally, we'd compare
3139           // every definition to every other, but we don't want to
3140           // take O(N^2) time to do this.  This shortcut may cause
3141           // false negatives that appear or disappear depending on the
3142           // link order, but it won't cause false positives.
3143           first_object_name = locs->object->name();
3144           first_object_linenos = this->linenos_from_loc(task, *locs);
3145         }
3146
3147       // Sort by Odr_violation_compare to make std::set_intersection work.
3148       std::sort(first_object_linenos.begin(), first_object_linenos.end(),
3149                 Odr_violation_compare());
3150
3151       for (; locs != locs_end; ++locs)
3152         {
3153           std::vector<std::string> linenos =
3154               this->linenos_from_loc(task, *locs);
3155           // linenos will be empty if we couldn't parse the debug info.
3156           if (linenos.empty())
3157             continue;
3158           // Sort by Odr_violation_compare to make std::set_intersection work.
3159           std::sort(linenos.begin(), linenos.end(), Odr_violation_compare());
3160
3161           Check_intersection intersection_result =
3162               std::set_intersection(first_object_linenos.begin(),
3163                                     first_object_linenos.end(),
3164                                     linenos.begin(),
3165                                     linenos.end(),
3166                                     Check_intersection(),
3167                                     Odr_violation_compare());
3168           if (!intersection_result.had_intersection())
3169             {
3170               gold_warning(_("while linking %s: symbol '%s' defined in "
3171                              "multiple places (possible ODR violation):"),
3172                            output_file_name, demangle(symbol_name).c_str());
3173               // This only prints one location from each definition,
3174               // which may not be the location we expect to intersect
3175               // with another definition.  We could print the whole
3176               // set of locations, but that seems too verbose.
3177               gold_assert(!first_object_linenos.empty());
3178               gold_assert(!linenos.empty());
3179               fprintf(stderr, _("  %s from %s\n"),
3180                       first_object_linenos[0].c_str(),
3181                       first_object_name.c_str());
3182               fprintf(stderr, _("  %s from %s\n"),
3183                       linenos[0].c_str(),
3184                       locs->object->name().c_str());
3185               // Only print one broken pair, to avoid needing to
3186               // compare against a list of the disjoint definition
3187               // locations we've found so far.  (If we kept comparing
3188               // against just the first one, we'd get a lot of
3189               // redundant complaints about the second definition
3190               // location.)
3191               break;
3192             }
3193         }
3194     }
3195   // We only call one_addr2line() in this function, so we can clear its cache.
3196   Dwarf_line_info::clear_addr2line_cache();
3197 }
3198
3199 // Warnings functions.
3200
3201 // Add a new warning.
3202
3203 void
3204 Warnings::add_warning(Symbol_table* symtab, const char* name, Object* obj,
3205                       const std::string& warning)
3206 {
3207   name = symtab->canonicalize_name(name);
3208   this->warnings_[name].set(obj, warning);
3209 }
3210
3211 // Look through the warnings and mark the symbols for which we should
3212 // warn.  This is called during Layout::finalize when we know the
3213 // sources for all the symbols.
3214
3215 void
3216 Warnings::note_warnings(Symbol_table* symtab)
3217 {
3218   for (Warning_table::iterator p = this->warnings_.begin();
3219        p != this->warnings_.end();
3220        ++p)
3221     {
3222       Symbol* sym = symtab->lookup(p->first, NULL);
3223       if (sym != NULL
3224           && sym->source() == Symbol::FROM_OBJECT
3225           && sym->object() == p->second.object)
3226         sym->set_has_warning();
3227     }
3228 }
3229
3230 // Issue a warning.  This is called when we see a relocation against a
3231 // symbol for which has a warning.
3232
3233 template<int size, bool big_endian>
3234 void
3235 Warnings::issue_warning(const Symbol* sym,
3236                         const Relocate_info<size, big_endian>* relinfo,
3237                         size_t relnum, off_t reloffset) const
3238 {
3239   gold_assert(sym->has_warning());
3240   Warning_table::const_iterator p = this->warnings_.find(sym->name());
3241   gold_assert(p != this->warnings_.end());
3242   gold_warning_at_location(relinfo, relnum, reloffset,
3243                            "%s", p->second.text.c_str());
3244 }
3245
3246 // Instantiate the templates we need.  We could use the configure
3247 // script to restrict this to only the ones needed for implemented
3248 // targets.
3249
3250 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
3251 template
3252 void
3253 Sized_symbol<32>::allocate_common(Output_data*, Value_type);
3254 #endif
3255
3256 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
3257 template
3258 void
3259 Sized_symbol<64>::allocate_common(Output_data*, Value_type);
3260 #endif
3261
3262 #ifdef HAVE_TARGET_32_LITTLE
3263 template
3264 void
3265 Symbol_table::add_from_relobj<32, false>(
3266     Sized_relobj<32, false>* relobj,
3267     const unsigned char* syms,
3268     size_t count,
3269     size_t symndx_offset,
3270     const char* sym_names,
3271     size_t sym_name_size,
3272     Sized_relobj<32, false>::Symbols* sympointers,
3273     size_t* defined);
3274 #endif
3275
3276 #ifdef HAVE_TARGET_32_BIG
3277 template
3278 void
3279 Symbol_table::add_from_relobj<32, true>(
3280     Sized_relobj<32, true>* relobj,
3281     const unsigned char* syms,
3282     size_t count,
3283     size_t symndx_offset,
3284     const char* sym_names,
3285     size_t sym_name_size,
3286     Sized_relobj<32, true>::Symbols* sympointers,
3287     size_t* defined);
3288 #endif
3289
3290 #ifdef HAVE_TARGET_64_LITTLE
3291 template
3292 void
3293 Symbol_table::add_from_relobj<64, false>(
3294     Sized_relobj<64, false>* relobj,
3295     const unsigned char* syms,
3296     size_t count,
3297     size_t symndx_offset,
3298     const char* sym_names,
3299     size_t sym_name_size,
3300     Sized_relobj<64, false>::Symbols* sympointers,
3301     size_t* defined);
3302 #endif
3303
3304 #ifdef HAVE_TARGET_64_BIG
3305 template
3306 void
3307 Symbol_table::add_from_relobj<64, true>(
3308     Sized_relobj<64, true>* relobj,
3309     const unsigned char* syms,
3310     size_t count,
3311     size_t symndx_offset,
3312     const char* sym_names,
3313     size_t sym_name_size,
3314     Sized_relobj<64, true>::Symbols* sympointers,
3315     size_t* defined);
3316 #endif
3317
3318 #ifdef HAVE_TARGET_32_LITTLE
3319 template
3320 Symbol*
3321 Symbol_table::add_from_pluginobj<32, false>(
3322     Sized_pluginobj<32, false>* obj,
3323     const char* name,
3324     const char* ver,
3325     elfcpp::Sym<32, false>* sym);
3326 #endif
3327
3328 #ifdef HAVE_TARGET_32_BIG
3329 template
3330 Symbol*
3331 Symbol_table::add_from_pluginobj<32, true>(
3332     Sized_pluginobj<32, true>* obj,
3333     const char* name,
3334     const char* ver,
3335     elfcpp::Sym<32, true>* sym);
3336 #endif
3337
3338 #ifdef HAVE_TARGET_64_LITTLE
3339 template
3340 Symbol*
3341 Symbol_table::add_from_pluginobj<64, false>(
3342     Sized_pluginobj<64, false>* obj,
3343     const char* name,
3344     const char* ver,
3345     elfcpp::Sym<64, false>* sym);
3346 #endif
3347
3348 #ifdef HAVE_TARGET_64_BIG
3349 template
3350 Symbol*
3351 Symbol_table::add_from_pluginobj<64, true>(
3352     Sized_pluginobj<64, true>* obj,
3353     const char* name,
3354     const char* ver,
3355     elfcpp::Sym<64, true>* sym);
3356 #endif
3357
3358 #ifdef HAVE_TARGET_32_LITTLE
3359 template
3360 void
3361 Symbol_table::add_from_dynobj<32, false>(
3362     Sized_dynobj<32, false>* dynobj,
3363     const unsigned char* syms,
3364     size_t count,
3365     const char* sym_names,
3366     size_t sym_name_size,
3367     const unsigned char* versym,
3368     size_t versym_size,
3369     const std::vector<const char*>* version_map,
3370     Sized_relobj<32, false>::Symbols* sympointers,
3371     size_t* defined);
3372 #endif
3373
3374 #ifdef HAVE_TARGET_32_BIG
3375 template
3376 void
3377 Symbol_table::add_from_dynobj<32, true>(
3378     Sized_dynobj<32, true>* dynobj,
3379     const unsigned char* syms,
3380     size_t count,
3381     const char* sym_names,
3382     size_t sym_name_size,
3383     const unsigned char* versym,
3384     size_t versym_size,
3385     const std::vector<const char*>* version_map,
3386     Sized_relobj<32, true>::Symbols* sympointers,
3387     size_t* defined);
3388 #endif
3389
3390 #ifdef HAVE_TARGET_64_LITTLE
3391 template
3392 void
3393 Symbol_table::add_from_dynobj<64, false>(
3394     Sized_dynobj<64, false>* dynobj,
3395     const unsigned char* syms,
3396     size_t count,
3397     const char* sym_names,
3398     size_t sym_name_size,
3399     const unsigned char* versym,
3400     size_t versym_size,
3401     const std::vector<const char*>* version_map,
3402     Sized_relobj<64, false>::Symbols* sympointers,
3403     size_t* defined);
3404 #endif
3405
3406 #ifdef HAVE_TARGET_64_BIG
3407 template
3408 void
3409 Symbol_table::add_from_dynobj<64, true>(
3410     Sized_dynobj<64, true>* dynobj,
3411     const unsigned char* syms,
3412     size_t count,
3413     const char* sym_names,
3414     size_t sym_name_size,
3415     const unsigned char* versym,
3416     size_t versym_size,
3417     const std::vector<const char*>* version_map,
3418     Sized_relobj<64, true>::Symbols* sympointers,
3419     size_t* defined);
3420 #endif
3421
3422 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
3423 template
3424 void
3425 Symbol_table::define_with_copy_reloc<32>(
3426     Sized_symbol<32>* sym,
3427     Output_data* posd,
3428     elfcpp::Elf_types<32>::Elf_Addr value);
3429 #endif
3430
3431 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
3432 template
3433 void
3434 Symbol_table::define_with_copy_reloc<64>(
3435     Sized_symbol<64>* sym,
3436     Output_data* posd,
3437     elfcpp::Elf_types<64>::Elf_Addr value);
3438 #endif
3439
3440 #ifdef HAVE_TARGET_32_LITTLE
3441 template
3442 void
3443 Warnings::issue_warning<32, false>(const Symbol* sym,
3444                                    const Relocate_info<32, false>* relinfo,
3445                                    size_t relnum, off_t reloffset) const;
3446 #endif
3447
3448 #ifdef HAVE_TARGET_32_BIG
3449 template
3450 void
3451 Warnings::issue_warning<32, true>(const Symbol* sym,
3452                                   const Relocate_info<32, true>* relinfo,
3453                                   size_t relnum, off_t reloffset) const;
3454 #endif
3455
3456 #ifdef HAVE_TARGET_64_LITTLE
3457 template
3458 void
3459 Warnings::issue_warning<64, false>(const Symbol* sym,
3460                                    const Relocate_info<64, false>* relinfo,
3461                                    size_t relnum, off_t reloffset) const;
3462 #endif
3463
3464 #ifdef HAVE_TARGET_64_BIG
3465 template
3466 void
3467 Warnings::issue_warning<64, true>(const Symbol* sym,
3468                                   const Relocate_info<64, true>* relinfo,
3469                                   size_t relnum, off_t reloffset) const;
3470 #endif
3471
3472 } // End namespace gold.