Handle output sections with more than 0x7fffffff bytes.
[external/binutils.git] / gold / symtab.cc
1 // symtab.cc -- the gold symbol table
2
3 // Copyright 2006, 2007, 2008 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 "object.h"
34 #include "dwarf_reader.h"
35 #include "dynobj.h"
36 #include "output.h"
37 #include "target.h"
38 #include "workqueue.h"
39 #include "symtab.h"
40
41 namespace gold
42 {
43
44 // Class Symbol.
45
46 // Initialize fields in Symbol.  This initializes everything except u_
47 // and source_.
48
49 void
50 Symbol::init_fields(const char* name, const char* version,
51                     elfcpp::STT type, elfcpp::STB binding,
52                     elfcpp::STV visibility, unsigned char nonvis)
53 {
54   this->name_ = name;
55   this->version_ = version;
56   this->symtab_index_ = 0;
57   this->dynsym_index_ = 0;
58   this->got_offsets_.init();
59   this->plt_offset_ = 0;
60   this->type_ = type;
61   this->binding_ = binding;
62   this->visibility_ = visibility;
63   this->nonvis_ = nonvis;
64   this->is_target_special_ = false;
65   this->is_def_ = false;
66   this->is_forwarder_ = false;
67   this->has_alias_ = false;
68   this->needs_dynsym_entry_ = false;
69   this->in_reg_ = false;
70   this->in_dyn_ = false;
71   this->has_plt_offset_ = false;
72   this->has_warning_ = false;
73   this->is_copied_from_dynobj_ = false;
74   this->is_forced_local_ = false;
75   this->is_ordinary_shndx_ = false;
76 }
77
78 // Return the demangled version of the symbol's name, but only
79 // if the --demangle flag was set.
80
81 static std::string
82 demangle(const char* name)
83 {
84   if (!parameters->options().do_demangle())
85     return name;
86
87   // cplus_demangle allocates memory for the result it returns,
88   // and returns NULL if the name is already demangled.
89   char* demangled_name = cplus_demangle(name, DMGL_ANSI | DMGL_PARAMS);
90   if (demangled_name == NULL)
91     return name;
92
93   std::string retval(demangled_name);
94   free(demangled_name);
95   return retval;
96 }
97
98 std::string
99 Symbol::demangled_name() const
100 {
101   return demangle(this->name());
102 }
103
104 // Initialize the fields in the base class Symbol for SYM in OBJECT.
105
106 template<int size, bool big_endian>
107 void
108 Symbol::init_base_object(const char* name, const char* version, Object* object,
109                          const elfcpp::Sym<size, big_endian>& sym,
110                          unsigned int st_shndx, bool is_ordinary)
111 {
112   this->init_fields(name, version, sym.get_st_type(), sym.get_st_bind(),
113                     sym.get_st_visibility(), sym.get_st_nonvis());
114   this->u_.from_object.object = object;
115   this->u_.from_object.shndx = st_shndx;
116   this->is_ordinary_shndx_ = is_ordinary;
117   this->source_ = FROM_OBJECT;
118   this->in_reg_ = !object->is_dynamic();
119   this->in_dyn_ = object->is_dynamic();
120 }
121
122 // Initialize the fields in the base class Symbol for a symbol defined
123 // in an Output_data.
124
125 void
126 Symbol::init_base_output_data(const char* name, const char* version,
127                               Output_data* od, elfcpp::STT type,
128                               elfcpp::STB binding, elfcpp::STV visibility,
129                               unsigned char nonvis, bool offset_is_from_end)
130 {
131   this->init_fields(name, version, type, binding, visibility, nonvis);
132   this->u_.in_output_data.output_data = od;
133   this->u_.in_output_data.offset_is_from_end = offset_is_from_end;
134   this->source_ = IN_OUTPUT_DATA;
135   this->in_reg_ = true;
136 }
137
138 // Initialize the fields in the base class Symbol for a symbol defined
139 // in an Output_segment.
140
141 void
142 Symbol::init_base_output_segment(const char* name, const char* version,
143                                  Output_segment* os, elfcpp::STT type,
144                                  elfcpp::STB binding, elfcpp::STV visibility,
145                                  unsigned char nonvis,
146                                  Segment_offset_base offset_base)
147 {
148   this->init_fields(name, version, type, binding, visibility, nonvis);
149   this->u_.in_output_segment.output_segment = os;
150   this->u_.in_output_segment.offset_base = offset_base;
151   this->source_ = IN_OUTPUT_SEGMENT;
152   this->in_reg_ = true;
153 }
154
155 // Initialize the fields in the base class Symbol for a symbol defined
156 // as a constant.
157
158 void
159 Symbol::init_base_constant(const char* name, const char* version,
160                            elfcpp::STT type, elfcpp::STB binding,
161                            elfcpp::STV visibility, unsigned char nonvis)
162 {
163   this->init_fields(name, version, type, binding, visibility, nonvis);
164   this->source_ = IS_CONSTANT;
165   this->in_reg_ = true;
166 }
167
168 // Initialize the fields in the base class Symbol for an undefined
169 // symbol.
170
171 void
172 Symbol::init_base_undefined(const char* name, const char* version,
173                             elfcpp::STT type, elfcpp::STB binding,
174                             elfcpp::STV visibility, unsigned char nonvis)
175 {
176   this->init_fields(name, version, type, binding, visibility, nonvis);
177   this->source_ = IS_UNDEFINED;
178   this->in_reg_ = true;
179 }
180
181 // Allocate a common symbol in the base.
182
183 void
184 Symbol::allocate_base_common(Output_data* od)
185 {
186   gold_assert(this->is_common());
187   this->source_ = IN_OUTPUT_DATA;
188   this->u_.in_output_data.output_data = od;
189   this->u_.in_output_data.offset_is_from_end = false;
190 }
191
192 // Initialize the fields in Sized_symbol for SYM in OBJECT.
193
194 template<int size>
195 template<bool big_endian>
196 void
197 Sized_symbol<size>::init_object(const char* name, const char* version,
198                                 Object* object,
199                                 const elfcpp::Sym<size, big_endian>& sym,
200                                 unsigned int st_shndx, bool is_ordinary)
201 {
202   this->init_base_object(name, version, object, sym, st_shndx, is_ordinary);
203   this->value_ = sym.get_st_value();
204   this->symsize_ = sym.get_st_size();
205 }
206
207 // Initialize the fields in Sized_symbol for a symbol defined in an
208 // Output_data.
209
210 template<int size>
211 void
212 Sized_symbol<size>::init_output_data(const char* name, const char* version,
213                                      Output_data* od, Value_type value,
214                                      Size_type symsize, elfcpp::STT type,
215                                      elfcpp::STB binding,
216                                      elfcpp::STV visibility,
217                                      unsigned char nonvis,
218                                      bool offset_is_from_end)
219 {
220   this->init_base_output_data(name, version, od, type, binding, visibility,
221                               nonvis, offset_is_from_end);
222   this->value_ = value;
223   this->symsize_ = symsize;
224 }
225
226 // Initialize the fields in Sized_symbol for a symbol defined in an
227 // Output_segment.
228
229 template<int size>
230 void
231 Sized_symbol<size>::init_output_segment(const char* name, const char* version,
232                                         Output_segment* os, Value_type value,
233                                         Size_type symsize, elfcpp::STT type,
234                                         elfcpp::STB binding,
235                                         elfcpp::STV visibility,
236                                         unsigned char nonvis,
237                                         Segment_offset_base offset_base)
238 {
239   this->init_base_output_segment(name, version, os, type, binding, visibility,
240                                  nonvis, offset_base);
241   this->value_ = value;
242   this->symsize_ = symsize;
243 }
244
245 // Initialize the fields in Sized_symbol for a symbol defined as a
246 // constant.
247
248 template<int size>
249 void
250 Sized_symbol<size>::init_constant(const char* name, const char* version,
251                                   Value_type value, Size_type symsize,
252                                   elfcpp::STT type, elfcpp::STB binding,
253                                   elfcpp::STV visibility, unsigned char nonvis)
254 {
255   this->init_base_constant(name, version, type, binding, visibility, nonvis);
256   this->value_ = value;
257   this->symsize_ = symsize;
258 }
259
260 // Initialize the fields in Sized_symbol for an undefined symbol.
261
262 template<int size>
263 void
264 Sized_symbol<size>::init_undefined(const char* name, const char* version,
265                                    elfcpp::STT type, elfcpp::STB binding,
266                                    elfcpp::STV visibility, unsigned char nonvis)
267 {
268   this->init_base_undefined(name, version, type, binding, visibility, nonvis);
269   this->value_ = 0;
270   this->symsize_ = 0;
271 }
272
273 // Allocate a common symbol.
274
275 template<int size>
276 void
277 Sized_symbol<size>::allocate_common(Output_data* od, Value_type value)
278 {
279   this->allocate_base_common(od);
280   this->value_ = value;
281 }
282
283 // Return true if this symbol should be added to the dynamic symbol
284 // table.
285
286 inline bool
287 Symbol::should_add_dynsym_entry() const
288 {
289   // If the symbol is used by a dynamic relocation, we need to add it.
290   if (this->needs_dynsym_entry())
291     return true;
292
293   // If the symbol was forced local in a version script, do not add it.
294   if (this->is_forced_local())
295     return false;
296
297   // If exporting all symbols or building a shared library,
298   // and the symbol is defined in a regular object and is
299   // externally visible, we need to add it.
300   if ((parameters->options().export_dynamic() || parameters->options().shared())
301       && !this->is_from_dynobj()
302       && this->is_externally_visible())
303     return true;
304
305   return false;
306 }
307
308 // Return true if the final value of this symbol is known at link
309 // time.
310
311 bool
312 Symbol::final_value_is_known() const
313 {
314   // If we are not generating an executable, then no final values are
315   // known, since they will change at runtime.
316   if (parameters->options().shared() || parameters->options().relocatable())
317     return false;
318
319   // If the symbol is not from an object file, and is not undefined,
320   // then it is defined, and known.
321   if (this->source_ != FROM_OBJECT)
322     {
323       if (this->source_ != IS_UNDEFINED)
324         return true;
325     }
326   else
327     {
328       // If the symbol is from a dynamic object, then the final value
329       // is not known.
330       if (this->object()->is_dynamic())
331         return false;
332
333       // If the symbol is not undefined (it is defined or common),
334       // then the final value is known.
335       if (!this->is_undefined())
336         return true;
337     }
338
339   // If the symbol is undefined, then whether the final value is known
340   // depends on whether we are doing a static link.  If we are doing a
341   // dynamic link, then the final value could be filled in at runtime.
342   // This could reasonably be the case for a weak undefined symbol.
343   return parameters->doing_static_link();
344 }
345
346 // Return the output section where this symbol is defined.
347
348 Output_section*
349 Symbol::output_section() const
350 {
351   switch (this->source_)
352     {
353     case FROM_OBJECT:
354       {
355         unsigned int shndx = this->u_.from_object.shndx;
356         if (shndx != elfcpp::SHN_UNDEF && this->is_ordinary_shndx_)
357           {
358             gold_assert(!this->u_.from_object.object->is_dynamic());
359             Relobj* relobj = static_cast<Relobj*>(this->u_.from_object.object);
360             return relobj->output_section(shndx);
361           }
362         return NULL;
363       }
364
365     case IN_OUTPUT_DATA:
366       return this->u_.in_output_data.output_data->output_section();
367
368     case IN_OUTPUT_SEGMENT:
369     case IS_CONSTANT:
370     case IS_UNDEFINED:
371       return NULL;
372
373     default:
374       gold_unreachable();
375     }
376 }
377
378 // Set the symbol's output section.  This is used for symbols defined
379 // in scripts.  This should only be called after the symbol table has
380 // been finalized.
381
382 void
383 Symbol::set_output_section(Output_section* os)
384 {
385   switch (this->source_)
386     {
387     case FROM_OBJECT:
388     case IN_OUTPUT_DATA:
389       gold_assert(this->output_section() == os);
390       break;
391     case IS_CONSTANT:
392       this->source_ = IN_OUTPUT_DATA;
393       this->u_.in_output_data.output_data = os;
394       this->u_.in_output_data.offset_is_from_end = false;
395       break;
396     case IN_OUTPUT_SEGMENT:
397     case IS_UNDEFINED:
398     default:
399       gold_unreachable();
400     }
401 }
402
403 // Class Symbol_table.
404
405 Symbol_table::Symbol_table(unsigned int count,
406                            const Version_script_info& version_script)
407   : saw_undefined_(0), offset_(0), table_(count), namepool_(),
408     forwarders_(), commons_(), tls_commons_(), forced_locals_(), warnings_(),
409     version_script_(version_script)
410 {
411   namepool_.reserve(count);
412 }
413
414 Symbol_table::~Symbol_table()
415 {
416 }
417
418 // The hash function.  The key values are Stringpool keys.
419
420 inline size_t
421 Symbol_table::Symbol_table_hash::operator()(const Symbol_table_key& key) const
422 {
423   return key.first ^ key.second;
424 }
425
426 // The symbol table key equality function.  This is called with
427 // Stringpool keys.
428
429 inline bool
430 Symbol_table::Symbol_table_eq::operator()(const Symbol_table_key& k1,
431                                           const Symbol_table_key& k2) const
432 {
433   return k1.first == k2.first && k1.second == k2.second;
434 }
435
436 // Make TO a symbol which forwards to FROM.
437
438 void
439 Symbol_table::make_forwarder(Symbol* from, Symbol* to)
440 {
441   gold_assert(from != to);
442   gold_assert(!from->is_forwarder() && !to->is_forwarder());
443   this->forwarders_[from] = to;
444   from->set_forwarder();
445 }
446
447 // Resolve the forwards from FROM, returning the real symbol.
448
449 Symbol*
450 Symbol_table::resolve_forwards(const Symbol* from) const
451 {
452   gold_assert(from->is_forwarder());
453   Unordered_map<const Symbol*, Symbol*>::const_iterator p =
454     this->forwarders_.find(from);
455   gold_assert(p != this->forwarders_.end());
456   return p->second;
457 }
458
459 // Look up a symbol by name.
460
461 Symbol*
462 Symbol_table::lookup(const char* name, const char* version) const
463 {
464   Stringpool::Key name_key;
465   name = this->namepool_.find(name, &name_key);
466   if (name == NULL)
467     return NULL;
468
469   Stringpool::Key version_key = 0;
470   if (version != NULL)
471     {
472       version = this->namepool_.find(version, &version_key);
473       if (version == NULL)
474         return NULL;
475     }
476
477   Symbol_table_key key(name_key, version_key);
478   Symbol_table::Symbol_table_type::const_iterator p = this->table_.find(key);
479   if (p == this->table_.end())
480     return NULL;
481   return p->second;
482 }
483
484 // Resolve a Symbol with another Symbol.  This is only used in the
485 // unusual case where there are references to both an unversioned
486 // symbol and a symbol with a version, and we then discover that that
487 // version is the default version.  Because this is unusual, we do
488 // this the slow way, by converting back to an ELF symbol.
489
490 template<int size, bool big_endian>
491 void
492 Symbol_table::resolve(Sized_symbol<size>* to, const Sized_symbol<size>* from,
493                       const char* version)
494 {
495   unsigned char buf[elfcpp::Elf_sizes<size>::sym_size];
496   elfcpp::Sym_write<size, big_endian> esym(buf);
497   // We don't bother to set the st_name or the st_shndx field.
498   esym.put_st_value(from->value());
499   esym.put_st_size(from->symsize());
500   esym.put_st_info(from->binding(), from->type());
501   esym.put_st_other(from->visibility(), from->nonvis());
502   bool is_ordinary;
503   unsigned int shndx = from->shndx(&is_ordinary);
504   this->resolve(to, esym.sym(), shndx, is_ordinary, shndx, from->object(),
505                 version);
506   if (from->in_reg())
507     to->set_in_reg();
508   if (from->in_dyn())
509     to->set_in_dyn();
510 }
511
512 // Record that a symbol is forced to be local by a version script.
513
514 void
515 Symbol_table::force_local(Symbol* sym)
516 {
517   if (!sym->is_defined() && !sym->is_common())
518     return;
519   if (sym->is_forced_local())
520     {
521       // We already got this one.
522       return;
523     }
524   sym->set_is_forced_local();
525   this->forced_locals_.push_back(sym);
526 }
527
528 // Adjust NAME for wrapping, and update *NAME_KEY if necessary.  This
529 // is only called for undefined symbols, when at least one --wrap
530 // option was used.
531
532 const char*
533 Symbol_table::wrap_symbol(Object* object, const char* name,
534                           Stringpool::Key* name_key)
535 {
536   // For some targets, we need to ignore a specific character when
537   // wrapping, and add it back later.
538   char prefix = '\0';
539   if (name[0] == object->target()->wrap_char())
540     {
541       prefix = name[0];
542       ++name;
543     }
544
545   if (parameters->options().is_wrap(name))
546     {
547       // Turn NAME into __wrap_NAME.
548       std::string s;
549       if (prefix != '\0')
550         s += prefix;
551       s += "__wrap_";
552       s += name;
553
554       // This will give us both the old and new name in NAMEPOOL_, but
555       // that is OK.  Only the versions we need will wind up in the
556       // real string table in the output file.
557       return this->namepool_.add(s.c_str(), true, name_key);
558     }
559
560   const char* const real_prefix = "__real_";
561   const size_t real_prefix_length = strlen(real_prefix);
562   if (strncmp(name, real_prefix, real_prefix_length) == 0
563       && parameters->options().is_wrap(name + real_prefix_length))
564     {
565       // Turn __real_NAME into NAME.
566       std::string s;
567       if (prefix != '\0')
568         s += prefix;
569       s += name + real_prefix_length;
570       return this->namepool_.add(s.c_str(), true, name_key);
571     }
572
573   return name;
574 }
575
576 // Add one symbol from OBJECT to the symbol table.  NAME is symbol
577 // name and VERSION is the version; both are canonicalized.  DEF is
578 // whether this is the default version.  ST_SHNDX is the symbol's
579 // section index; IS_ORDINARY is whether this is a normal section
580 // rather than a special code.
581
582 // If DEF is true, then this is the definition of a default version of
583 // a symbol.  That means that any lookup of NAME/NULL and any lookup
584 // of NAME/VERSION should always return the same symbol.  This is
585 // obvious for references, but in particular we want to do this for
586 // definitions: overriding NAME/NULL should also override
587 // NAME/VERSION.  If we don't do that, it would be very hard to
588 // override functions in a shared library which uses versioning.
589
590 // We implement this by simply making both entries in the hash table
591 // point to the same Symbol structure.  That is easy enough if this is
592 // the first time we see NAME/NULL or NAME/VERSION, but it is possible
593 // that we have seen both already, in which case they will both have
594 // independent entries in the symbol table.  We can't simply change
595 // the symbol table entry, because we have pointers to the entries
596 // attached to the object files.  So we mark the entry attached to the
597 // object file as a forwarder, and record it in the forwarders_ map.
598 // Note that entries in the hash table will never be marked as
599 // forwarders.
600 //
601 // ORIG_ST_SHNDX and ST_SHNDX are almost always the same.
602 // ORIG_ST_SHNDX is the section index in the input file, or SHN_UNDEF
603 // for a special section code.  ST_SHNDX may be modified if the symbol
604 // is defined in a section being discarded.
605
606 template<int size, bool big_endian>
607 Sized_symbol<size>*
608 Symbol_table::add_from_object(Object* object,
609                               const char *name,
610                               Stringpool::Key name_key,
611                               const char *version,
612                               Stringpool::Key version_key,
613                               bool def,
614                               const elfcpp::Sym<size, big_endian>& sym,
615                               unsigned int st_shndx,
616                               bool is_ordinary,
617                               unsigned int orig_st_shndx)
618 {
619   // Print a message if this symbol is being traced.
620   if (parameters->options().is_trace_symbol(name))
621     {
622       if (orig_st_shndx == elfcpp::SHN_UNDEF)
623         gold_info(_("%s: reference to %s"), object->name().c_str(), name);
624       else
625         gold_info(_("%s: definition of %s"), object->name().c_str(), name);
626     }
627
628   // For an undefined symbol, we may need to adjust the name using
629   // --wrap.
630   if (orig_st_shndx == elfcpp::SHN_UNDEF
631       && parameters->options().any_wrap())
632     {
633       const char* wrap_name = this->wrap_symbol(object, name, &name_key);
634       if (wrap_name != name)
635         {
636           // If we see a reference to malloc with version GLIBC_2.0,
637           // and we turn it into a reference to __wrap_malloc, then we
638           // discard the version number.  Otherwise the user would be
639           // required to specify the correct version for
640           // __wrap_malloc.
641           version = NULL;
642           version_key = 0;
643           name = wrap_name;
644         }
645     }
646
647   Symbol* const snull = NULL;
648   std::pair<typename Symbol_table_type::iterator, bool> ins =
649     this->table_.insert(std::make_pair(std::make_pair(name_key, version_key),
650                                        snull));
651
652   std::pair<typename Symbol_table_type::iterator, bool> insdef =
653     std::make_pair(this->table_.end(), false);
654   if (def)
655     {
656       const Stringpool::Key vnull_key = 0;
657       insdef = this->table_.insert(std::make_pair(std::make_pair(name_key,
658                                                                  vnull_key),
659                                                   snull));
660     }
661
662   // ins.first: an iterator, which is a pointer to a pair.
663   // ins.first->first: the key (a pair of name and version).
664   // ins.first->second: the value (Symbol*).
665   // ins.second: true if new entry was inserted, false if not.
666
667   Sized_symbol<size>* ret;
668   bool was_undefined;
669   bool was_common;
670   if (!ins.second)
671     {
672       // We already have an entry for NAME/VERSION.
673       ret = this->get_sized_symbol<size>(ins.first->second);
674       gold_assert(ret != NULL);
675
676       was_undefined = ret->is_undefined();
677       was_common = ret->is_common();
678
679       this->resolve(ret, sym, st_shndx, is_ordinary, orig_st_shndx, object,
680                     version);
681
682       if (def)
683         {
684           if (insdef.second)
685             {
686               // This is the first time we have seen NAME/NULL.  Make
687               // NAME/NULL point to NAME/VERSION.
688               insdef.first->second = ret;
689             }
690           else if (insdef.first->second != ret
691                    && insdef.first->second->is_undefined())
692             {
693               // This is the unfortunate case where we already have
694               // entries for both NAME/VERSION and NAME/NULL.  Note
695               // that we don't want to combine them if the existing
696               // symbol is going to override the new one.  FIXME: We
697               // currently just test is_undefined, but this may not do
698               // the right thing if the existing symbol is from a
699               // shared library and the new one is from a regular
700               // object.
701
702               const Sized_symbol<size>* sym2;
703               sym2 = this->get_sized_symbol<size>(insdef.first->second);
704               Symbol_table::resolve<size, big_endian>(ret, sym2, version);
705               this->make_forwarder(insdef.first->second, ret);
706               insdef.first->second = ret;
707             }
708           else
709             def = false;
710         }
711     }
712   else
713     {
714       // This is the first time we have seen NAME/VERSION.
715       gold_assert(ins.first->second == NULL);
716
717       if (def && !insdef.second)
718         {
719           // We already have an entry for NAME/NULL.  If we override
720           // it, then change it to NAME/VERSION.
721           ret = this->get_sized_symbol<size>(insdef.first->second);
722
723           was_undefined = ret->is_undefined();
724           was_common = ret->is_common();
725
726           this->resolve(ret, sym, st_shndx, is_ordinary, orig_st_shndx, object,
727                         version);
728           ins.first->second = ret;
729         }
730       else
731         {
732           was_undefined = false;
733           was_common = false;
734
735           Sized_target<size, big_endian>* target =
736             object->sized_target<size, big_endian>();
737           if (!target->has_make_symbol())
738             ret = new Sized_symbol<size>();
739           else
740             {
741               ret = target->make_symbol();
742               if (ret == NULL)
743                 {
744                   // This means that we don't want a symbol table
745                   // entry after all.
746                   if (!def)
747                     this->table_.erase(ins.first);
748                   else
749                     {
750                       this->table_.erase(insdef.first);
751                       // Inserting insdef invalidated ins.
752                       this->table_.erase(std::make_pair(name_key,
753                                                         version_key));
754                     }
755                   return NULL;
756                 }
757             }
758
759           ret->init_object(name, version, object, sym, st_shndx, is_ordinary);
760
761           ins.first->second = ret;
762           if (def)
763             {
764               // This is the first time we have seen NAME/NULL.  Point
765               // it at the new entry for NAME/VERSION.
766               gold_assert(insdef.second);
767               insdef.first->second = ret;
768             }
769         }
770     }
771
772   // Record every time we see a new undefined symbol, to speed up
773   // archive groups.
774   if (!was_undefined && ret->is_undefined())
775     ++this->saw_undefined_;
776
777   // Keep track of common symbols, to speed up common symbol
778   // allocation.
779   if (!was_common && ret->is_common())
780     {
781       if (ret->type() != elfcpp::STT_TLS)
782         this->commons_.push_back(ret);
783       else
784         this->tls_commons_.push_back(ret);
785     }
786
787   if (def)
788     ret->set_is_default();
789   return ret;
790 }
791
792 // Add all the symbols in a relocatable object to the hash table.
793
794 template<int size, bool big_endian>
795 void
796 Symbol_table::add_from_relobj(
797     Sized_relobj<size, big_endian>* relobj,
798     const unsigned char* syms,
799     size_t count,
800     size_t symndx_offset,
801     const char* sym_names,
802     size_t sym_name_size,
803     typename Sized_relobj<size, big_endian>::Symbols* sympointers)
804 {
805   gold_assert(size == relobj->target()->get_size());
806   gold_assert(size == parameters->target().get_size());
807
808   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
809
810   const bool just_symbols = relobj->just_symbols();
811
812   const unsigned char* p = syms;
813   for (size_t i = 0; i < count; ++i, p += sym_size)
814     {
815       elfcpp::Sym<size, big_endian> sym(p);
816
817       unsigned int st_name = sym.get_st_name();
818       if (st_name >= sym_name_size)
819         {
820           relobj->error(_("bad global symbol name offset %u at %zu"),
821                         st_name, i);
822           continue;
823         }
824
825       const char* name = sym_names + st_name;
826
827       bool is_ordinary;
828       unsigned int st_shndx = relobj->adjust_sym_shndx(i + symndx_offset,
829                                                        sym.get_st_shndx(),
830                                                        &is_ordinary);
831       unsigned int orig_st_shndx = st_shndx;
832       if (!is_ordinary)
833         orig_st_shndx = elfcpp::SHN_UNDEF;
834
835       // A symbol defined in a section which we are not including must
836       // be treated as an undefined symbol.
837       if (st_shndx != elfcpp::SHN_UNDEF
838           && is_ordinary
839           && !relobj->is_section_included(st_shndx))
840         st_shndx = elfcpp::SHN_UNDEF;
841
842       // In an object file, an '@' in the name separates the symbol
843       // name from the version name.  If there are two '@' characters,
844       // this is the default version.
845       const char* ver = strchr(name, '@');
846       int namelen = 0;
847       // DEF: is the version default?  LOCAL: is the symbol forced local?
848       bool def = false;
849       bool local = false;
850
851       if (ver != NULL)
852         {
853           // The symbol name is of the form foo@VERSION or foo@@VERSION
854           namelen = ver - name;
855           ++ver;
856           if (*ver == '@')
857             {
858               def = true;
859               ++ver;
860             }
861         }
862       // We don't want to assign a version to an undefined symbol,
863       // even if it is listed in the version script.  FIXME: What
864       // about a common symbol?
865       else if (!version_script_.empty()
866                && st_shndx != elfcpp::SHN_UNDEF)
867         {
868           // The symbol name did not have a version, but
869           // the version script may assign a version anyway.
870           namelen = strlen(name);
871           def = true;
872           // Check the global: entries from the version script.
873           const std::string& version =
874               version_script_.get_symbol_version(name);
875           if (!version.empty())
876             ver = version.c_str();
877           // Check the local: entries from the version script
878           if (version_script_.symbol_is_local(name))
879             local = true;
880         }
881
882       elfcpp::Sym<size, big_endian>* psym = &sym;
883       unsigned char symbuf[sym_size];
884       elfcpp::Sym<size, big_endian> sym2(symbuf);
885       if (just_symbols)
886         {
887           memcpy(symbuf, p, sym_size);
888           elfcpp::Sym_write<size, big_endian> sw(symbuf);
889           if (orig_st_shndx != elfcpp::SHN_UNDEF && is_ordinary)
890             {
891               // Symbol values in object files are section relative.
892               // This is normally what we want, but since here we are
893               // converting the symbol to absolute we need to add the
894               // section address.  The section address in an object
895               // file is normally zero, but people can use a linker
896               // script to change it.
897               sw.put_st_value(sym.get_st_value()
898                               + relobj->section_address(orig_st_shndx));
899             }
900           st_shndx = elfcpp::SHN_ABS;
901           is_ordinary = false;
902           psym = &sym2;
903         }
904
905       Sized_symbol<size>* res;
906       if (ver == NULL)
907         {
908           Stringpool::Key name_key;
909           name = this->namepool_.add(name, true, &name_key);
910           res = this->add_from_object(relobj, name, name_key, NULL, 0,
911                                       false, *psym, st_shndx, is_ordinary,
912                                       orig_st_shndx);
913           if (local)
914             this->force_local(res);
915         }
916       else
917         {
918           Stringpool::Key name_key;
919           name = this->namepool_.add_with_length(name, namelen, true,
920                                                  &name_key);
921           Stringpool::Key ver_key;
922           ver = this->namepool_.add(ver, true, &ver_key);
923
924           res = this->add_from_object(relobj, name, name_key, ver, ver_key,
925                                       def, *psym, st_shndx, is_ordinary,
926                                       orig_st_shndx);
927         }
928
929       (*sympointers)[i] = res;
930     }
931 }
932
933 // Add all the symbols in a dynamic object to the hash table.
934
935 template<int size, bool big_endian>
936 void
937 Symbol_table::add_from_dynobj(
938     Sized_dynobj<size, big_endian>* dynobj,
939     const unsigned char* syms,
940     size_t count,
941     const char* sym_names,
942     size_t sym_name_size,
943     const unsigned char* versym,
944     size_t versym_size,
945     const std::vector<const char*>* version_map)
946 {
947   gold_assert(size == dynobj->target()->get_size());
948   gold_assert(size == parameters->target().get_size());
949
950   if (dynobj->just_symbols())
951     {
952       gold_error(_("--just-symbols does not make sense with a shared object"));
953       return;
954     }
955
956   if (versym != NULL && versym_size / 2 < count)
957     {
958       dynobj->error(_("too few symbol versions"));
959       return;
960     }
961
962   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
963
964   // We keep a list of all STT_OBJECT symbols, so that we can resolve
965   // weak aliases.  This is necessary because if the dynamic object
966   // provides the same variable under two names, one of which is a
967   // weak definition, and the regular object refers to the weak
968   // definition, we have to put both the weak definition and the
969   // strong definition into the dynamic symbol table.  Given a weak
970   // definition, the only way that we can find the corresponding
971   // strong definition, if any, is to search the symbol table.
972   std::vector<Sized_symbol<size>*> object_symbols;
973
974   const unsigned char* p = syms;
975   const unsigned char* vs = versym;
976   for (size_t i = 0; i < count; ++i, p += sym_size, vs += 2)
977     {
978       elfcpp::Sym<size, big_endian> sym(p);
979
980       // Ignore symbols with local binding or that have
981       // internal or hidden visibility.
982       if (sym.get_st_bind() == elfcpp::STB_LOCAL
983           || sym.get_st_visibility() == elfcpp::STV_INTERNAL
984           || sym.get_st_visibility() == elfcpp::STV_HIDDEN)
985         continue;
986
987       // A protected symbol in a shared library must be treated as a
988       // normal symbol when viewed from outside the shared library.
989       // Implement this by overriding the visibility here.
990       elfcpp::Sym<size, big_endian>* psym = &sym;
991       unsigned char symbuf[sym_size];
992       elfcpp::Sym<size, big_endian> sym2(symbuf);
993       if (sym.get_st_visibility() == elfcpp::STV_PROTECTED)
994         {
995           memcpy(symbuf, p, sym_size);
996           elfcpp::Sym_write<size, big_endian> sw(symbuf);
997           sw.put_st_other(elfcpp::STV_DEFAULT, sym.get_st_nonvis());
998           psym = &sym2;
999         }
1000
1001       unsigned int st_name = psym->get_st_name();
1002       if (st_name >= sym_name_size)
1003         {
1004           dynobj->error(_("bad symbol name offset %u at %zu"),
1005                         st_name, i);
1006           continue;
1007         }
1008
1009       const char* name = sym_names + st_name;
1010
1011       bool is_ordinary;
1012       unsigned int st_shndx = dynobj->adjust_sym_shndx(i, psym->get_st_shndx(),
1013                                                        &is_ordinary);
1014
1015       Sized_symbol<size>* res;
1016
1017       if (versym == NULL)
1018         {
1019           Stringpool::Key name_key;
1020           name = this->namepool_.add(name, true, &name_key);
1021           res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1022                                       false, *psym, st_shndx, is_ordinary,
1023                                       st_shndx);
1024         }
1025       else
1026         {
1027           // Read the version information.
1028
1029           unsigned int v = elfcpp::Swap<16, big_endian>::readval(vs);
1030
1031           bool hidden = (v & elfcpp::VERSYM_HIDDEN) != 0;
1032           v &= elfcpp::VERSYM_VERSION;
1033
1034           // The Sun documentation says that V can be VER_NDX_LOCAL,
1035           // or VER_NDX_GLOBAL, or a version index.  The meaning of
1036           // VER_NDX_LOCAL is defined as "Symbol has local scope."
1037           // The old GNU linker will happily generate VER_NDX_LOCAL
1038           // for an undefined symbol.  I don't know what the Sun
1039           // linker will generate.
1040
1041           if (v == static_cast<unsigned int>(elfcpp::VER_NDX_LOCAL)
1042               && st_shndx != elfcpp::SHN_UNDEF)
1043             {
1044               // This symbol should not be visible outside the object.
1045               continue;
1046             }
1047
1048           // At this point we are definitely going to add this symbol.
1049           Stringpool::Key name_key;
1050           name = this->namepool_.add(name, true, &name_key);
1051
1052           if (v == static_cast<unsigned int>(elfcpp::VER_NDX_LOCAL)
1053               || v == static_cast<unsigned int>(elfcpp::VER_NDX_GLOBAL))
1054             {
1055               // This symbol does not have a version.
1056               res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1057                                           false, *psym, st_shndx, is_ordinary,
1058                                           st_shndx);
1059             }
1060           else
1061             {
1062               if (v >= version_map->size())
1063                 {
1064                   dynobj->error(_("versym for symbol %zu out of range: %u"),
1065                                 i, v);
1066                   continue;
1067                 }
1068
1069               const char* version = (*version_map)[v];
1070               if (version == NULL)
1071                 {
1072                   dynobj->error(_("versym for symbol %zu has no name: %u"),
1073                                 i, v);
1074                   continue;
1075                 }
1076
1077               Stringpool::Key version_key;
1078               version = this->namepool_.add(version, true, &version_key);
1079
1080               // If this is an absolute symbol, and the version name
1081               // and symbol name are the same, then this is the
1082               // version definition symbol.  These symbols exist to
1083               // support using -u to pull in particular versions.  We
1084               // do not want to record a version for them.
1085               if (st_shndx == elfcpp::SHN_ABS
1086                   && !is_ordinary
1087                   && name_key == version_key)
1088                 res = this->add_from_object(dynobj, name, name_key, NULL, 0,
1089                                             false, *psym, st_shndx, is_ordinary,
1090                                             st_shndx);
1091               else
1092                 {
1093                   const bool def = (!hidden
1094                                     && st_shndx != elfcpp::SHN_UNDEF);
1095                   res = this->add_from_object(dynobj, name, name_key, version,
1096                                               version_key, def, *psym, st_shndx,
1097                                               is_ordinary, st_shndx);
1098                 }
1099             }
1100         }
1101
1102       // Note that it is possible that RES was overridden by an
1103       // earlier object, in which case it can't be aliased here.
1104       if (st_shndx != elfcpp::SHN_UNDEF
1105           && is_ordinary
1106           && psym->get_st_type() == elfcpp::STT_OBJECT
1107           && res->source() == Symbol::FROM_OBJECT
1108           && res->object() == dynobj)
1109         object_symbols.push_back(res);
1110     }
1111
1112   this->record_weak_aliases(&object_symbols);
1113 }
1114
1115 // This is used to sort weak aliases.  We sort them first by section
1116 // index, then by offset, then by weak ahead of strong.
1117
1118 template<int size>
1119 class Weak_alias_sorter
1120 {
1121  public:
1122   bool operator()(const Sized_symbol<size>*, const Sized_symbol<size>*) const;
1123 };
1124
1125 template<int size>
1126 bool
1127 Weak_alias_sorter<size>::operator()(const Sized_symbol<size>* s1,
1128                                     const Sized_symbol<size>* s2) const
1129 {
1130   bool is_ordinary;
1131   unsigned int s1_shndx = s1->shndx(&is_ordinary);
1132   gold_assert(is_ordinary);
1133   unsigned int s2_shndx = s2->shndx(&is_ordinary);
1134   gold_assert(is_ordinary);
1135   if (s1_shndx != s2_shndx)
1136     return s1_shndx < s2_shndx;
1137
1138   if (s1->value() != s2->value())
1139     return s1->value() < s2->value();
1140   if (s1->binding() != s2->binding())
1141     {
1142       if (s1->binding() == elfcpp::STB_WEAK)
1143         return true;
1144       if (s2->binding() == elfcpp::STB_WEAK)
1145         return false;
1146     }
1147   return std::string(s1->name()) < std::string(s2->name());
1148 }
1149
1150 // SYMBOLS is a list of object symbols from a dynamic object.  Look
1151 // for any weak aliases, and record them so that if we add the weak
1152 // alias to the dynamic symbol table, we also add the corresponding
1153 // strong symbol.
1154
1155 template<int size>
1156 void
1157 Symbol_table::record_weak_aliases(std::vector<Sized_symbol<size>*>* symbols)
1158 {
1159   // Sort the vector by section index, then by offset, then by weak
1160   // ahead of strong.
1161   std::sort(symbols->begin(), symbols->end(), Weak_alias_sorter<size>());
1162
1163   // Walk through the vector.  For each weak definition, record
1164   // aliases.
1165   for (typename std::vector<Sized_symbol<size>*>::const_iterator p =
1166          symbols->begin();
1167        p != symbols->end();
1168        ++p)
1169     {
1170       if ((*p)->binding() != elfcpp::STB_WEAK)
1171         continue;
1172
1173       // Build a circular list of weak aliases.  Each symbol points to
1174       // the next one in the circular list.
1175
1176       Sized_symbol<size>* from_sym = *p;
1177       typename std::vector<Sized_symbol<size>*>::const_iterator q;
1178       for (q = p + 1; q != symbols->end(); ++q)
1179         {
1180           bool dummy;
1181           if ((*q)->shndx(&dummy) != from_sym->shndx(&dummy)
1182               || (*q)->value() != from_sym->value())
1183             break;
1184
1185           this->weak_aliases_[from_sym] = *q;
1186           from_sym->set_has_alias();
1187           from_sym = *q;
1188         }
1189
1190       if (from_sym != *p)
1191         {
1192           this->weak_aliases_[from_sym] = *p;
1193           from_sym->set_has_alias();
1194         }
1195
1196       p = q - 1;
1197     }
1198 }
1199
1200 // Create and return a specially defined symbol.  If ONLY_IF_REF is
1201 // true, then only create the symbol if there is a reference to it.
1202 // If this does not return NULL, it sets *POLDSYM to the existing
1203 // symbol if there is one.  This canonicalizes *PNAME and *PVERSION.
1204
1205 template<int size, bool big_endian>
1206 Sized_symbol<size>*
1207 Symbol_table::define_special_symbol(const char** pname, const char** pversion,
1208                                     bool only_if_ref,
1209                                     Sized_symbol<size>** poldsym)
1210 {
1211   Symbol* oldsym;
1212   Sized_symbol<size>* sym;
1213   bool add_to_table = false;
1214   typename Symbol_table_type::iterator add_loc = this->table_.end();
1215
1216   // If the caller didn't give us a version, see if we get one from
1217   // the version script.
1218   if (*pversion == NULL)
1219     {
1220       const std::string& v(this->version_script_.get_symbol_version(*pname));
1221       if (!v.empty())
1222         *pversion = v.c_str();
1223     }
1224
1225   if (only_if_ref)
1226     {
1227       oldsym = this->lookup(*pname, *pversion);
1228       if (oldsym == NULL || !oldsym->is_undefined())
1229         return NULL;
1230
1231       *pname = oldsym->name();
1232       *pversion = oldsym->version();
1233     }
1234   else
1235     {
1236       // Canonicalize NAME and VERSION.
1237       Stringpool::Key name_key;
1238       *pname = this->namepool_.add(*pname, true, &name_key);
1239
1240       Stringpool::Key version_key = 0;
1241       if (*pversion != NULL)
1242         *pversion = this->namepool_.add(*pversion, true, &version_key);
1243
1244       Symbol* const snull = NULL;
1245       std::pair<typename Symbol_table_type::iterator, bool> ins =
1246         this->table_.insert(std::make_pair(std::make_pair(name_key,
1247                                                           version_key),
1248                                            snull));
1249
1250       if (!ins.second)
1251         {
1252           // We already have a symbol table entry for NAME/VERSION.
1253           oldsym = ins.first->second;
1254           gold_assert(oldsym != NULL);
1255         }
1256       else
1257         {
1258           // We haven't seen this symbol before.
1259           gold_assert(ins.first->second == NULL);
1260           add_to_table = true;
1261           add_loc = ins.first;
1262           oldsym = NULL;
1263         }
1264     }
1265
1266   const Target& target = parameters->target();
1267   if (!target.has_make_symbol())
1268     sym = new Sized_symbol<size>();
1269   else
1270     {
1271       gold_assert(target.get_size() == size);
1272       gold_assert(target.is_big_endian() ? big_endian : !big_endian);
1273       typedef Sized_target<size, big_endian> My_target;
1274       const My_target* sized_target =
1275           static_cast<const My_target*>(&target);
1276       sym = sized_target->make_symbol();
1277       if (sym == NULL)
1278         return NULL;
1279     }
1280
1281   if (add_to_table)
1282     add_loc->second = sym;
1283   else
1284     gold_assert(oldsym != NULL);
1285
1286   *poldsym = this->get_sized_symbol<size>(oldsym);
1287
1288   return sym;
1289 }
1290
1291 // Define a symbol based on an Output_data.
1292
1293 Symbol*
1294 Symbol_table::define_in_output_data(const char* name,
1295                                     const char* version,
1296                                     Output_data* od,
1297                                     uint64_t value,
1298                                     uint64_t symsize,
1299                                     elfcpp::STT type,
1300                                     elfcpp::STB binding,
1301                                     elfcpp::STV visibility,
1302                                     unsigned char nonvis,
1303                                     bool offset_is_from_end,
1304                                     bool only_if_ref)
1305 {
1306   if (parameters->target().get_size() == 32)
1307     {
1308 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1309       return this->do_define_in_output_data<32>(name, version, od,
1310                                                 value, symsize, type, binding,
1311                                                 visibility, nonvis,
1312                                                 offset_is_from_end,
1313                                                 only_if_ref);
1314 #else
1315       gold_unreachable();
1316 #endif
1317     }
1318   else if (parameters->target().get_size() == 64)
1319     {
1320 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1321       return this->do_define_in_output_data<64>(name, version, od,
1322                                                 value, symsize, type, binding,
1323                                                 visibility, nonvis,
1324                                                 offset_is_from_end,
1325                                                 only_if_ref);
1326 #else
1327       gold_unreachable();
1328 #endif
1329     }
1330   else
1331     gold_unreachable();
1332 }
1333
1334 // Define a symbol in an Output_data, sized version.
1335
1336 template<int size>
1337 Sized_symbol<size>*
1338 Symbol_table::do_define_in_output_data(
1339     const char* name,
1340     const char* version,
1341     Output_data* od,
1342     typename elfcpp::Elf_types<size>::Elf_Addr value,
1343     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
1344     elfcpp::STT type,
1345     elfcpp::STB binding,
1346     elfcpp::STV visibility,
1347     unsigned char nonvis,
1348     bool offset_is_from_end,
1349     bool only_if_ref)
1350 {
1351   Sized_symbol<size>* sym;
1352   Sized_symbol<size>* oldsym;
1353
1354   if (parameters->target().is_big_endian())
1355     {
1356 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
1357       sym = this->define_special_symbol<size, true>(&name, &version,
1358                                                     only_if_ref, &oldsym);
1359 #else
1360       gold_unreachable();
1361 #endif
1362     }
1363   else
1364     {
1365 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
1366       sym = this->define_special_symbol<size, false>(&name, &version,
1367                                                      only_if_ref, &oldsym);
1368 #else
1369       gold_unreachable();
1370 #endif
1371     }
1372
1373   if (sym == NULL)
1374     return NULL;
1375
1376   sym->init_output_data(name, version, od, value, symsize, type, binding,
1377                         visibility, nonvis, offset_is_from_end);
1378
1379   if (oldsym == NULL)
1380     {
1381       if (binding == elfcpp::STB_LOCAL
1382           || this->version_script_.symbol_is_local(name))
1383         this->force_local(sym);
1384       else if (version != NULL)
1385         sym->set_is_default();
1386       return sym;
1387     }
1388
1389   if (Symbol_table::should_override_with_special(oldsym))
1390     this->override_with_special(oldsym, sym);
1391   delete sym;
1392   return oldsym;
1393 }
1394
1395 // Define a symbol based on an Output_segment.
1396
1397 Symbol*
1398 Symbol_table::define_in_output_segment(const char* name,
1399                                        const char* version, Output_segment* os,
1400                                        uint64_t value,
1401                                        uint64_t symsize,
1402                                        elfcpp::STT type,
1403                                        elfcpp::STB binding,
1404                                        elfcpp::STV visibility,
1405                                        unsigned char nonvis,
1406                                        Symbol::Segment_offset_base offset_base,
1407                                        bool only_if_ref)
1408 {
1409   if (parameters->target().get_size() == 32)
1410     {
1411 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1412       return this->do_define_in_output_segment<32>(name, version, os,
1413                                                    value, symsize, type,
1414                                                    binding, visibility, nonvis,
1415                                                    offset_base, only_if_ref);
1416 #else
1417       gold_unreachable();
1418 #endif
1419     }
1420   else if (parameters->target().get_size() == 64)
1421     {
1422 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1423       return this->do_define_in_output_segment<64>(name, version, os,
1424                                                    value, symsize, type,
1425                                                    binding, visibility, nonvis,
1426                                                    offset_base, only_if_ref);
1427 #else
1428       gold_unreachable();
1429 #endif
1430     }
1431   else
1432     gold_unreachable();
1433 }
1434
1435 // Define a symbol in an Output_segment, sized version.
1436
1437 template<int size>
1438 Sized_symbol<size>*
1439 Symbol_table::do_define_in_output_segment(
1440     const char* name,
1441     const char* version,
1442     Output_segment* os,
1443     typename elfcpp::Elf_types<size>::Elf_Addr value,
1444     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
1445     elfcpp::STT type,
1446     elfcpp::STB binding,
1447     elfcpp::STV visibility,
1448     unsigned char nonvis,
1449     Symbol::Segment_offset_base offset_base,
1450     bool only_if_ref)
1451 {
1452   Sized_symbol<size>* sym;
1453   Sized_symbol<size>* oldsym;
1454
1455   if (parameters->target().is_big_endian())
1456     {
1457 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
1458       sym = this->define_special_symbol<size, true>(&name, &version,
1459                                                     only_if_ref, &oldsym);
1460 #else
1461       gold_unreachable();
1462 #endif
1463     }
1464   else
1465     {
1466 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
1467       sym = this->define_special_symbol<size, false>(&name, &version,
1468                                                      only_if_ref, &oldsym);
1469 #else
1470       gold_unreachable();
1471 #endif
1472     }
1473
1474   if (sym == NULL)
1475     return NULL;
1476
1477   sym->init_output_segment(name, version, os, value, symsize, type, binding,
1478                            visibility, nonvis, offset_base);
1479
1480   if (oldsym == NULL)
1481     {
1482       if (binding == elfcpp::STB_LOCAL
1483           || this->version_script_.symbol_is_local(name))
1484         this->force_local(sym);
1485       else if (version != NULL)
1486         sym->set_is_default();
1487       return sym;
1488     }
1489
1490   if (Symbol_table::should_override_with_special(oldsym))
1491     this->override_with_special(oldsym, sym);
1492   delete sym;
1493   return oldsym;
1494 }
1495
1496 // Define a special symbol with a constant value.  It is a multiple
1497 // definition error if this symbol is already defined.
1498
1499 Symbol*
1500 Symbol_table::define_as_constant(const char* name,
1501                                  const char* version,
1502                                  uint64_t value,
1503                                  uint64_t symsize,
1504                                  elfcpp::STT type,
1505                                  elfcpp::STB binding,
1506                                  elfcpp::STV visibility,
1507                                  unsigned char nonvis,
1508                                  bool only_if_ref,
1509                                  bool force_override)
1510 {
1511   if (parameters->target().get_size() == 32)
1512     {
1513 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1514       return this->do_define_as_constant<32>(name, version, value,
1515                                              symsize, type, binding,
1516                                              visibility, nonvis, only_if_ref,
1517                                              force_override);
1518 #else
1519       gold_unreachable();
1520 #endif
1521     }
1522   else if (parameters->target().get_size() == 64)
1523     {
1524 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1525       return this->do_define_as_constant<64>(name, version, value,
1526                                              symsize, type, binding,
1527                                              visibility, nonvis, only_if_ref,
1528                                              force_override);
1529 #else
1530       gold_unreachable();
1531 #endif
1532     }
1533   else
1534     gold_unreachable();
1535 }
1536
1537 // Define a symbol as a constant, sized version.
1538
1539 template<int size>
1540 Sized_symbol<size>*
1541 Symbol_table::do_define_as_constant(
1542     const char* name,
1543     const char* version,
1544     typename elfcpp::Elf_types<size>::Elf_Addr value,
1545     typename elfcpp::Elf_types<size>::Elf_WXword symsize,
1546     elfcpp::STT type,
1547     elfcpp::STB binding,
1548     elfcpp::STV visibility,
1549     unsigned char nonvis,
1550     bool only_if_ref,
1551     bool force_override)
1552 {
1553   Sized_symbol<size>* sym;
1554   Sized_symbol<size>* oldsym;
1555
1556   if (parameters->target().is_big_endian())
1557     {
1558 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
1559       sym = this->define_special_symbol<size, true>(&name, &version,
1560                                                     only_if_ref, &oldsym);
1561 #else
1562       gold_unreachable();
1563 #endif
1564     }
1565   else
1566     {
1567 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
1568       sym = this->define_special_symbol<size, false>(&name, &version,
1569                                                      only_if_ref, &oldsym);
1570 #else
1571       gold_unreachable();
1572 #endif
1573     }
1574
1575   if (sym == NULL)
1576     return NULL;
1577
1578   sym->init_constant(name, version, value, symsize, type, binding, visibility,
1579                      nonvis);
1580
1581   if (oldsym == NULL)
1582     {
1583       // Version symbols are absolute symbols with name == version.
1584       // We don't want to force them to be local.
1585       if ((version == NULL
1586            || name != version
1587            || value != 0)
1588           && (binding == elfcpp::STB_LOCAL
1589               || this->version_script_.symbol_is_local(name)))
1590         this->force_local(sym);
1591       else if (version != NULL
1592                && (name != version || value != 0))
1593         sym->set_is_default();
1594       return sym;
1595     }
1596
1597   if (force_override || Symbol_table::should_override_with_special(oldsym))
1598     this->override_with_special(oldsym, sym);
1599   delete sym;
1600   return oldsym;
1601 }
1602
1603 // Define a set of symbols in output sections.
1604
1605 void
1606 Symbol_table::define_symbols(const Layout* layout, int count,
1607                              const Define_symbol_in_section* p,
1608                              bool only_if_ref)
1609 {
1610   for (int i = 0; i < count; ++i, ++p)
1611     {
1612       Output_section* os = layout->find_output_section(p->output_section);
1613       if (os != NULL)
1614         this->define_in_output_data(p->name, NULL, os, p->value,
1615                                     p->size, p->type, p->binding,
1616                                     p->visibility, p->nonvis,
1617                                     p->offset_is_from_end,
1618                                     only_if_ref || p->only_if_ref);
1619       else
1620         this->define_as_constant(p->name, NULL, 0, p->size, p->type,
1621                                  p->binding, p->visibility, p->nonvis,
1622                                  only_if_ref || p->only_if_ref,
1623                                  false);
1624     }
1625 }
1626
1627 // Define a set of symbols in output segments.
1628
1629 void
1630 Symbol_table::define_symbols(const Layout* layout, int count,
1631                              const Define_symbol_in_segment* p,
1632                              bool only_if_ref)
1633 {
1634   for (int i = 0; i < count; ++i, ++p)
1635     {
1636       Output_segment* os = layout->find_output_segment(p->segment_type,
1637                                                        p->segment_flags_set,
1638                                                        p->segment_flags_clear);
1639       if (os != NULL)
1640         this->define_in_output_segment(p->name, NULL, os, p->value,
1641                                        p->size, p->type, p->binding,
1642                                        p->visibility, p->nonvis,
1643                                        p->offset_base,
1644                                        only_if_ref || p->only_if_ref);
1645       else
1646         this->define_as_constant(p->name, NULL, 0, p->size, p->type,
1647                                  p->binding, p->visibility, p->nonvis,
1648                                  only_if_ref || p->only_if_ref,
1649                                  false);
1650     }
1651 }
1652
1653 // Define CSYM using a COPY reloc.  POSD is the Output_data where the
1654 // symbol should be defined--typically a .dyn.bss section.  VALUE is
1655 // the offset within POSD.
1656
1657 template<int size>
1658 void
1659 Symbol_table::define_with_copy_reloc(
1660     Sized_symbol<size>* csym,
1661     Output_data* posd,
1662     typename elfcpp::Elf_types<size>::Elf_Addr value)
1663 {
1664   gold_assert(csym->is_from_dynobj());
1665   gold_assert(!csym->is_copied_from_dynobj());
1666   Object* object = csym->object();
1667   gold_assert(object->is_dynamic());
1668   Dynobj* dynobj = static_cast<Dynobj*>(object);
1669
1670   // Our copied variable has to override any variable in a shared
1671   // library.
1672   elfcpp::STB binding = csym->binding();
1673   if (binding == elfcpp::STB_WEAK)
1674     binding = elfcpp::STB_GLOBAL;
1675
1676   this->define_in_output_data(csym->name(), csym->version(),
1677                               posd, value, csym->symsize(),
1678                               csym->type(), binding,
1679                               csym->visibility(), csym->nonvis(),
1680                               false, false);
1681
1682   csym->set_is_copied_from_dynobj();
1683   csym->set_needs_dynsym_entry();
1684
1685   this->copied_symbol_dynobjs_[csym] = dynobj;
1686
1687   // We have now defined all aliases, but we have not entered them all
1688   // in the copied_symbol_dynobjs_ map.
1689   if (csym->has_alias())
1690     {
1691       Symbol* sym = csym;
1692       while (true)
1693         {
1694           sym = this->weak_aliases_[sym];
1695           if (sym == csym)
1696             break;
1697           gold_assert(sym->output_data() == posd);
1698
1699           sym->set_is_copied_from_dynobj();
1700           this->copied_symbol_dynobjs_[sym] = dynobj;
1701         }
1702     }
1703 }
1704
1705 // SYM is defined using a COPY reloc.  Return the dynamic object where
1706 // the original definition was found.
1707
1708 Dynobj*
1709 Symbol_table::get_copy_source(const Symbol* sym) const
1710 {
1711   gold_assert(sym->is_copied_from_dynobj());
1712   Copied_symbol_dynobjs::const_iterator p =
1713     this->copied_symbol_dynobjs_.find(sym);
1714   gold_assert(p != this->copied_symbol_dynobjs_.end());
1715   return p->second;
1716 }
1717
1718 // Add any undefined symbols named on the command line.
1719
1720 void
1721 Symbol_table::add_undefined_symbols_from_command_line()
1722 {
1723   if (parameters->options().any_undefined())
1724     {
1725       if (parameters->target().get_size() == 32)
1726         {
1727 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
1728           this->do_add_undefined_symbols_from_command_line<32>();
1729 #else
1730           gold_unreachable();
1731 #endif
1732         }
1733       else if (parameters->target().get_size() == 64)
1734         {
1735 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
1736           this->do_add_undefined_symbols_from_command_line<64>();
1737 #else
1738           gold_unreachable();
1739 #endif
1740         }
1741       else
1742         gold_unreachable();
1743     }
1744 }
1745
1746 template<int size>
1747 void
1748 Symbol_table::do_add_undefined_symbols_from_command_line()
1749 {
1750   for (options::String_set::const_iterator p =
1751          parameters->options().undefined_begin();
1752        p != parameters->options().undefined_end();
1753        ++p)
1754     {
1755       const char* name = p->c_str();
1756
1757       if (this->lookup(name) != NULL)
1758         continue;
1759
1760       const char* version = NULL;
1761
1762       Sized_symbol<size>* sym;
1763       Sized_symbol<size>* oldsym;
1764       if (parameters->target().is_big_endian())
1765         {
1766 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
1767           sym = this->define_special_symbol<size, true>(&name, &version,
1768                                                         false, &oldsym);
1769 #else
1770           gold_unreachable();
1771 #endif
1772         }
1773       else
1774         {
1775 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
1776           sym = this->define_special_symbol<size, false>(&name, &version,
1777                                                          false, &oldsym);
1778 #else
1779           gold_unreachable();
1780 #endif
1781         }
1782
1783       gold_assert(oldsym == NULL);
1784
1785       sym->init_undefined(name, version, elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
1786                           elfcpp::STV_DEFAULT, 0);
1787       ++this->saw_undefined_;
1788     }
1789 }
1790
1791 // Set the dynamic symbol indexes.  INDEX is the index of the first
1792 // global dynamic symbol.  Pointers to the symbols are stored into the
1793 // vector SYMS.  The names are added to DYNPOOL.  This returns an
1794 // updated dynamic symbol index.
1795
1796 unsigned int
1797 Symbol_table::set_dynsym_indexes(unsigned int index,
1798                                  std::vector<Symbol*>* syms,
1799                                  Stringpool* dynpool,
1800                                  Versions* versions)
1801 {
1802   for (Symbol_table_type::iterator p = this->table_.begin();
1803        p != this->table_.end();
1804        ++p)
1805     {
1806       Symbol* sym = p->second;
1807
1808       // Note that SYM may already have a dynamic symbol index, since
1809       // some symbols appear more than once in the symbol table, with
1810       // and without a version.
1811
1812       if (!sym->should_add_dynsym_entry())
1813         sym->set_dynsym_index(-1U);
1814       else if (!sym->has_dynsym_index())
1815         {
1816           sym->set_dynsym_index(index);
1817           ++index;
1818           syms->push_back(sym);
1819           dynpool->add(sym->name(), false, NULL);
1820
1821           // Record any version information.
1822           if (sym->version() != NULL)
1823             versions->record_version(this, dynpool, sym);
1824         }
1825     }
1826
1827   // Finish up the versions.  In some cases this may add new dynamic
1828   // symbols.
1829   index = versions->finalize(this, index, syms);
1830
1831   return index;
1832 }
1833
1834 // Set the final values for all the symbols.  The index of the first
1835 // global symbol in the output file is *PLOCAL_SYMCOUNT.  Record the
1836 // file offset OFF.  Add their names to POOL.  Return the new file
1837 // offset.  Update *PLOCAL_SYMCOUNT if necessary.
1838
1839 off_t
1840 Symbol_table::finalize(off_t off, off_t dynoff, size_t dyn_global_index,
1841                        size_t dyncount, Stringpool* pool,
1842                        unsigned int *plocal_symcount)
1843 {
1844   off_t ret;
1845
1846   gold_assert(*plocal_symcount != 0);
1847   this->first_global_index_ = *plocal_symcount;
1848
1849   this->dynamic_offset_ = dynoff;
1850   this->first_dynamic_global_index_ = dyn_global_index;
1851   this->dynamic_count_ = dyncount;
1852
1853   if (parameters->target().get_size() == 32)
1854     {
1855 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_32_LITTLE)
1856       ret = this->sized_finalize<32>(off, pool, plocal_symcount);
1857 #else
1858       gold_unreachable();
1859 #endif
1860     }
1861   else if (parameters->target().get_size() == 64)
1862     {
1863 #if defined(HAVE_TARGET_64_BIG) || defined(HAVE_TARGET_64_LITTLE)
1864       ret = this->sized_finalize<64>(off, pool, plocal_symcount);
1865 #else
1866       gold_unreachable();
1867 #endif
1868     }
1869   else
1870     gold_unreachable();
1871
1872   // Now that we have the final symbol table, we can reliably note
1873   // which symbols should get warnings.
1874   this->warnings_.note_warnings(this);
1875
1876   return ret;
1877 }
1878
1879 // SYM is going into the symbol table at *PINDEX.  Add the name to
1880 // POOL, update *PINDEX and *POFF.
1881
1882 template<int size>
1883 void
1884 Symbol_table::add_to_final_symtab(Symbol* sym, Stringpool* pool,
1885                                   unsigned int* pindex, off_t* poff)
1886 {
1887   sym->set_symtab_index(*pindex);
1888   pool->add(sym->name(), false, NULL);
1889   ++*pindex;
1890   *poff += elfcpp::Elf_sizes<size>::sym_size;
1891 }
1892
1893 // Set the final value for all the symbols.  This is called after
1894 // Layout::finalize, so all the output sections have their final
1895 // address.
1896
1897 template<int size>
1898 off_t
1899 Symbol_table::sized_finalize(off_t off, Stringpool* pool,
1900                              unsigned int* plocal_symcount)
1901 {
1902   off = align_address(off, size >> 3);
1903   this->offset_ = off;
1904
1905   unsigned int index = *plocal_symcount;
1906   const unsigned int orig_index = index;
1907
1908   // First do all the symbols which have been forced to be local, as
1909   // they must appear before all global symbols.
1910   for (Forced_locals::iterator p = this->forced_locals_.begin();
1911        p != this->forced_locals_.end();
1912        ++p)
1913     {
1914       Symbol* sym = *p;
1915       gold_assert(sym->is_forced_local());
1916       if (this->sized_finalize_symbol<size>(sym))
1917         {
1918           this->add_to_final_symtab<size>(sym, pool, &index, &off);
1919           ++*plocal_symcount;
1920         }
1921     }
1922
1923   // Now do all the remaining symbols.
1924   for (Symbol_table_type::iterator p = this->table_.begin();
1925        p != this->table_.end();
1926        ++p)
1927     {
1928       Symbol* sym = p->second;
1929       if (this->sized_finalize_symbol<size>(sym))
1930         this->add_to_final_symtab<size>(sym, pool, &index, &off);
1931     }
1932
1933   this->output_count_ = index - orig_index;
1934
1935   return off;
1936 }
1937
1938 // Finalize the symbol SYM.  This returns true if the symbol should be
1939 // added to the symbol table, false otherwise.
1940
1941 template<int size>
1942 bool
1943 Symbol_table::sized_finalize_symbol(Symbol* unsized_sym)
1944 {
1945   typedef typename Sized_symbol<size>::Value_type Value_type;
1946
1947   Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(unsized_sym);
1948
1949   // The default version of a symbol may appear twice in the symbol
1950   // table.  We only need to finalize it once.
1951   if (sym->has_symtab_index())
1952     return false;
1953
1954   if (!sym->in_reg())
1955     {
1956       gold_assert(!sym->has_symtab_index());
1957       sym->set_symtab_index(-1U);
1958       gold_assert(sym->dynsym_index() == -1U);
1959       return false;
1960     }
1961
1962   Value_type value;
1963
1964   switch (sym->source())
1965     {
1966     case Symbol::FROM_OBJECT:
1967       {
1968         bool is_ordinary;
1969         unsigned int shndx = sym->shndx(&is_ordinary);
1970
1971         // FIXME: We need some target specific support here.
1972         if (!is_ordinary
1973             && shndx != elfcpp::SHN_ABS
1974             && shndx != elfcpp::SHN_COMMON)
1975           {
1976             gold_error(_("%s: unsupported symbol section 0x%x"),
1977                        sym->demangled_name().c_str(), shndx);
1978             shndx = elfcpp::SHN_UNDEF;
1979           }
1980
1981         Object* symobj = sym->object();
1982         if (symobj->is_dynamic())
1983           {
1984             value = 0;
1985             shndx = elfcpp::SHN_UNDEF;
1986           }
1987         else if (shndx == elfcpp::SHN_UNDEF)
1988           value = 0;
1989         else if (!is_ordinary
1990                  && (shndx == elfcpp::SHN_ABS || shndx == elfcpp::SHN_COMMON))
1991           value = sym->value();
1992         else
1993           {
1994             Relobj* relobj = static_cast<Relobj*>(symobj);
1995             Output_section* os = relobj->output_section(shndx);
1996
1997             if (os == NULL)
1998               {
1999                 sym->set_symtab_index(-1U);
2000                 gold_assert(sym->dynsym_index() == -1U);
2001                 return false;
2002               }
2003
2004             uint64_t secoff64 = relobj->output_section_offset(shndx);
2005             Value_type secoff = convert_types<Value_type, uint64_t>(secoff64);
2006             if (sym->type() == elfcpp::STT_TLS)
2007               value = sym->value() + os->tls_offset() + secoff;
2008             else
2009               value = sym->value() + os->address() + secoff;
2010           }
2011       }
2012       break;
2013
2014     case Symbol::IN_OUTPUT_DATA:
2015       {
2016         Output_data* od = sym->output_data();
2017         value = sym->value();
2018         if (sym->type() != elfcpp::STT_TLS)
2019           value += od->address();
2020         else
2021           {
2022             Output_section* os = od->output_section();
2023             gold_assert(os != NULL);
2024             value += os->tls_offset() + (od->address() - os->address());
2025           }
2026         if (sym->offset_is_from_end())
2027           value += od->data_size();
2028       }
2029       break;
2030
2031     case Symbol::IN_OUTPUT_SEGMENT:
2032       {
2033         Output_segment* os = sym->output_segment();
2034         value = sym->value();
2035         if (sym->type() != elfcpp::STT_TLS)
2036           value += os->vaddr();
2037         switch (sym->offset_base())
2038           {
2039           case Symbol::SEGMENT_START:
2040             break;
2041           case Symbol::SEGMENT_END:
2042             value += os->memsz();
2043             break;
2044           case Symbol::SEGMENT_BSS:
2045             value += os->filesz();
2046             break;
2047           default:
2048             gold_unreachable();
2049           }
2050       }
2051       break;
2052
2053     case Symbol::IS_CONSTANT:
2054       value = sym->value();
2055       break;
2056
2057     case Symbol::IS_UNDEFINED:
2058       value = 0;
2059       break;
2060
2061     default:
2062       gold_unreachable();
2063     }
2064
2065   sym->set_value(value);
2066
2067   if (parameters->options().strip_all())
2068     {
2069       sym->set_symtab_index(-1U);
2070       return false;
2071     }
2072
2073   return true;
2074 }
2075
2076 // Write out the global symbols.
2077
2078 void
2079 Symbol_table::write_globals(const Input_objects* input_objects,
2080                             const Stringpool* sympool,
2081                             const Stringpool* dynpool,
2082                             Output_symtab_xindex* symtab_xindex,
2083                             Output_symtab_xindex* dynsym_xindex,
2084                             Output_file* of) const
2085 {
2086   switch (parameters->size_and_endianness())
2087     {
2088 #ifdef HAVE_TARGET_32_LITTLE
2089     case Parameters::TARGET_32_LITTLE:
2090       this->sized_write_globals<32, false>(input_objects, sympool,
2091                                            dynpool, symtab_xindex,
2092                                            dynsym_xindex, of);
2093       break;
2094 #endif
2095 #ifdef HAVE_TARGET_32_BIG
2096     case Parameters::TARGET_32_BIG:
2097       this->sized_write_globals<32, true>(input_objects, sympool,
2098                                           dynpool, symtab_xindex,
2099                                           dynsym_xindex, of);
2100       break;
2101 #endif
2102 #ifdef HAVE_TARGET_64_LITTLE
2103     case Parameters::TARGET_64_LITTLE:
2104       this->sized_write_globals<64, false>(input_objects, sympool,
2105                                            dynpool, symtab_xindex,
2106                                            dynsym_xindex, of);
2107       break;
2108 #endif
2109 #ifdef HAVE_TARGET_64_BIG
2110     case Parameters::TARGET_64_BIG:
2111       this->sized_write_globals<64, true>(input_objects, sympool,
2112                                           dynpool, symtab_xindex,
2113                                           dynsym_xindex, of);
2114       break;
2115 #endif
2116     default:
2117       gold_unreachable();
2118     }
2119 }
2120
2121 // Write out the global symbols.
2122
2123 template<int size, bool big_endian>
2124 void
2125 Symbol_table::sized_write_globals(const Input_objects* input_objects,
2126                                   const Stringpool* sympool,
2127                                   const Stringpool* dynpool,
2128                                   Output_symtab_xindex* symtab_xindex,
2129                                   Output_symtab_xindex* dynsym_xindex,
2130                                   Output_file* of) const
2131 {
2132   const Target& target = parameters->target();
2133
2134   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2135
2136   const unsigned int output_count = this->output_count_;
2137   const section_size_type oview_size = output_count * sym_size;
2138   const unsigned int first_global_index = this->first_global_index_;
2139   unsigned char* psyms;
2140   if (this->offset_ == 0 || output_count == 0)
2141     psyms = NULL;
2142   else
2143     psyms = of->get_output_view(this->offset_, oview_size);
2144
2145   const unsigned int dynamic_count = this->dynamic_count_;
2146   const section_size_type dynamic_size = dynamic_count * sym_size;
2147   const unsigned int first_dynamic_global_index =
2148     this->first_dynamic_global_index_;
2149   unsigned char* dynamic_view;
2150   if (this->dynamic_offset_ == 0 || dynamic_count == 0)
2151     dynamic_view = NULL;
2152   else
2153     dynamic_view = of->get_output_view(this->dynamic_offset_, dynamic_size);
2154
2155   for (Symbol_table_type::const_iterator p = this->table_.begin();
2156        p != this->table_.end();
2157        ++p)
2158     {
2159       Sized_symbol<size>* sym = static_cast<Sized_symbol<size>*>(p->second);
2160
2161       // Possibly warn about unresolved symbols in shared libraries.
2162       this->warn_about_undefined_dynobj_symbol(input_objects, sym);
2163
2164       unsigned int sym_index = sym->symtab_index();
2165       unsigned int dynsym_index;
2166       if (dynamic_view == NULL)
2167         dynsym_index = -1U;
2168       else
2169         dynsym_index = sym->dynsym_index();
2170
2171       if (sym_index == -1U && dynsym_index == -1U)
2172         {
2173           // This symbol is not included in the output file.
2174           continue;
2175         }
2176
2177       unsigned int shndx;
2178       typename elfcpp::Elf_types<size>::Elf_Addr sym_value = sym->value();
2179       typename elfcpp::Elf_types<size>::Elf_Addr dynsym_value = sym_value;
2180       switch (sym->source())
2181         {
2182         case Symbol::FROM_OBJECT:
2183           {
2184             bool is_ordinary;
2185             unsigned int in_shndx = sym->shndx(&is_ordinary);
2186
2187             // FIXME: We need some target specific support here.
2188             if (!is_ordinary
2189                 && in_shndx != elfcpp::SHN_ABS
2190                 && in_shndx != elfcpp::SHN_COMMON)
2191               {
2192                 gold_error(_("%s: unsupported symbol section 0x%x"),
2193                            sym->demangled_name().c_str(), in_shndx);
2194                 shndx = in_shndx;
2195               }
2196             else
2197               {
2198                 Object* symobj = sym->object();
2199                 if (symobj->is_dynamic())
2200                   {
2201                     if (sym->needs_dynsym_value())
2202                       dynsym_value = target.dynsym_value(sym);
2203                     shndx = elfcpp::SHN_UNDEF;
2204                   }
2205                 else if (in_shndx == elfcpp::SHN_UNDEF
2206                          || (!is_ordinary
2207                              && (in_shndx == elfcpp::SHN_ABS
2208                                  || in_shndx == elfcpp::SHN_COMMON)))
2209                   shndx = in_shndx;
2210                 else
2211                   {
2212                     Relobj* relobj = static_cast<Relobj*>(symobj);
2213                     Output_section* os = relobj->output_section(in_shndx);
2214                     gold_assert(os != NULL);
2215                     shndx = os->out_shndx();
2216
2217                     if (shndx >= elfcpp::SHN_LORESERVE)
2218                       {
2219                         if (sym_index != -1U)
2220                           symtab_xindex->add(sym_index, shndx);
2221                         if (dynsym_index != -1U)
2222                           dynsym_xindex->add(dynsym_index, shndx);
2223                         shndx = elfcpp::SHN_XINDEX;
2224                       }
2225
2226                     // In object files symbol values are section
2227                     // relative.
2228                     if (parameters->options().relocatable())
2229                       sym_value -= os->address();
2230                   }
2231               }
2232           }
2233           break;
2234
2235         case Symbol::IN_OUTPUT_DATA:
2236           shndx = sym->output_data()->out_shndx();
2237           if (shndx >= elfcpp::SHN_LORESERVE)
2238             {
2239               if (sym_index != -1U)
2240                 symtab_xindex->add(sym_index, shndx);
2241               if (dynsym_index != -1U)
2242                 dynsym_xindex->add(dynsym_index, shndx);
2243               shndx = elfcpp::SHN_XINDEX;
2244             }
2245           break;
2246
2247         case Symbol::IN_OUTPUT_SEGMENT:
2248           shndx = elfcpp::SHN_ABS;
2249           break;
2250
2251         case Symbol::IS_CONSTANT:
2252           shndx = elfcpp::SHN_ABS;
2253           break;
2254
2255         case Symbol::IS_UNDEFINED:
2256           shndx = elfcpp::SHN_UNDEF;
2257           break;
2258
2259         default:
2260           gold_unreachable();
2261         }
2262
2263       if (sym_index != -1U)
2264         {
2265           sym_index -= first_global_index;
2266           gold_assert(sym_index < output_count);
2267           unsigned char* ps = psyms + (sym_index * sym_size);
2268           this->sized_write_symbol<size, big_endian>(sym, sym_value, shndx,
2269                                                      sympool, ps);
2270         }
2271
2272       if (dynsym_index != -1U)
2273         {
2274           dynsym_index -= first_dynamic_global_index;
2275           gold_assert(dynsym_index < dynamic_count);
2276           unsigned char* pd = dynamic_view + (dynsym_index * sym_size);
2277           this->sized_write_symbol<size, big_endian>(sym, dynsym_value, shndx,
2278                                                      dynpool, pd);
2279         }
2280     }
2281
2282   of->write_output_view(this->offset_, oview_size, psyms);
2283   if (dynamic_view != NULL)
2284     of->write_output_view(this->dynamic_offset_, dynamic_size, dynamic_view);
2285 }
2286
2287 // Write out the symbol SYM, in section SHNDX, to P.  POOL is the
2288 // strtab holding the name.
2289
2290 template<int size, bool big_endian>
2291 void
2292 Symbol_table::sized_write_symbol(
2293     Sized_symbol<size>* sym,
2294     typename elfcpp::Elf_types<size>::Elf_Addr value,
2295     unsigned int shndx,
2296     const Stringpool* pool,
2297     unsigned char* p) const
2298 {
2299   elfcpp::Sym_write<size, big_endian> osym(p);
2300   osym.put_st_name(pool->get_offset(sym->name()));
2301   osym.put_st_value(value);
2302   osym.put_st_size(sym->symsize());
2303   // A version script may have overridden the default binding.
2304   if (sym->is_forced_local())
2305     osym.put_st_info(elfcpp::elf_st_info(elfcpp::STB_LOCAL, sym->type()));
2306   else
2307     osym.put_st_info(elfcpp::elf_st_info(sym->binding(), sym->type()));
2308   osym.put_st_other(elfcpp::elf_st_other(sym->visibility(), sym->nonvis()));
2309   osym.put_st_shndx(shndx);
2310 }
2311
2312 // Check for unresolved symbols in shared libraries.  This is
2313 // controlled by the --allow-shlib-undefined option.
2314
2315 // We only warn about libraries for which we have seen all the
2316 // DT_NEEDED entries.  We don't try to track down DT_NEEDED entries
2317 // which were not seen in this link.  If we didn't see a DT_NEEDED
2318 // entry, we aren't going to be able to reliably report whether the
2319 // symbol is undefined.
2320
2321 // We also don't warn about libraries found in the system library
2322 // directory (the directory were we find libc.so); we assume that
2323 // those libraries are OK.  This heuristic avoids problems in
2324 // GNU/Linux, in which -ldl can have undefined references satisfied by
2325 // ld-linux.so.
2326
2327 inline void
2328 Symbol_table::warn_about_undefined_dynobj_symbol(
2329     const Input_objects* input_objects,
2330     Symbol* sym) const
2331 {
2332   bool dummy;
2333   if (sym->source() == Symbol::FROM_OBJECT
2334       && sym->object()->is_dynamic()
2335       && sym->shndx(&dummy) == elfcpp::SHN_UNDEF
2336       && sym->binding() != elfcpp::STB_WEAK
2337       && !parameters->options().allow_shlib_undefined()
2338       && !parameters->target().is_defined_by_abi(sym)
2339       && !input_objects->found_in_system_library_directory(sym->object()))
2340     {
2341       // A very ugly cast.
2342       Dynobj* dynobj = static_cast<Dynobj*>(sym->object());
2343       if (!dynobj->has_unknown_needed_entries())
2344         gold_error(_("%s: undefined reference to '%s'"),
2345                    sym->object()->name().c_str(),
2346                    sym->demangled_name().c_str());
2347     }
2348 }
2349
2350 // Write out a section symbol.  Return the update offset.
2351
2352 void
2353 Symbol_table::write_section_symbol(const Output_section *os,
2354                                    Output_symtab_xindex* symtab_xindex,
2355                                    Output_file* of,
2356                                    off_t offset) const
2357 {
2358   switch (parameters->size_and_endianness())
2359     {
2360 #ifdef HAVE_TARGET_32_LITTLE
2361     case Parameters::TARGET_32_LITTLE:
2362       this->sized_write_section_symbol<32, false>(os, symtab_xindex, of,
2363                                                   offset);
2364       break;
2365 #endif
2366 #ifdef HAVE_TARGET_32_BIG
2367     case Parameters::TARGET_32_BIG:
2368       this->sized_write_section_symbol<32, true>(os, symtab_xindex, of,
2369                                                  offset);
2370       break;
2371 #endif
2372 #ifdef HAVE_TARGET_64_LITTLE
2373     case Parameters::TARGET_64_LITTLE:
2374       this->sized_write_section_symbol<64, false>(os, symtab_xindex, of,
2375                                                   offset);
2376       break;
2377 #endif
2378 #ifdef HAVE_TARGET_64_BIG
2379     case Parameters::TARGET_64_BIG:
2380       this->sized_write_section_symbol<64, true>(os, symtab_xindex, of,
2381                                                  offset);
2382       break;
2383 #endif
2384     default:
2385       gold_unreachable();
2386     }
2387 }
2388
2389 // Write out a section symbol, specialized for size and endianness.
2390
2391 template<int size, bool big_endian>
2392 void
2393 Symbol_table::sized_write_section_symbol(const Output_section* os,
2394                                          Output_symtab_xindex* symtab_xindex,
2395                                          Output_file* of,
2396                                          off_t offset) const
2397 {
2398   const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
2399
2400   unsigned char* pov = of->get_output_view(offset, sym_size);
2401
2402   elfcpp::Sym_write<size, big_endian> osym(pov);
2403   osym.put_st_name(0);
2404   osym.put_st_value(os->address());
2405   osym.put_st_size(0);
2406   osym.put_st_info(elfcpp::elf_st_info(elfcpp::STB_LOCAL,
2407                                        elfcpp::STT_SECTION));
2408   osym.put_st_other(elfcpp::elf_st_other(elfcpp::STV_DEFAULT, 0));
2409
2410   unsigned int shndx = os->out_shndx();
2411   if (shndx >= elfcpp::SHN_LORESERVE)
2412     {
2413       symtab_xindex->add(os->symtab_index(), shndx);
2414       shndx = elfcpp::SHN_XINDEX;
2415     }
2416   osym.put_st_shndx(shndx);
2417
2418   of->write_output_view(offset, sym_size, pov);
2419 }
2420
2421 // Print statistical information to stderr.  This is used for --stats.
2422
2423 void
2424 Symbol_table::print_stats() const
2425 {
2426 #if defined(HAVE_TR1_UNORDERED_MAP) || defined(HAVE_EXT_HASH_MAP)
2427   fprintf(stderr, _("%s: symbol table entries: %zu; buckets: %zu\n"),
2428           program_name, this->table_.size(), this->table_.bucket_count());
2429 #else
2430   fprintf(stderr, _("%s: symbol table entries: %zu\n"),
2431           program_name, this->table_.size());
2432 #endif
2433   this->namepool_.print_stats("symbol table stringpool");
2434 }
2435
2436 // We check for ODR violations by looking for symbols with the same
2437 // name for which the debugging information reports that they were
2438 // defined in different source locations.  When comparing the source
2439 // location, we consider instances with the same base filename and
2440 // line number to be the same.  This is because different object
2441 // files/shared libraries can include the same header file using
2442 // different paths, and we don't want to report an ODR violation in
2443 // that case.
2444
2445 // This struct is used to compare line information, as returned by
2446 // Dwarf_line_info::one_addr2line.  It implements a < comparison
2447 // operator used with std::set.
2448
2449 struct Odr_violation_compare
2450 {
2451   bool
2452   operator()(const std::string& s1, const std::string& s2) const
2453   {
2454     std::string::size_type pos1 = s1.rfind('/');
2455     std::string::size_type pos2 = s2.rfind('/');
2456     if (pos1 == std::string::npos
2457         || pos2 == std::string::npos)
2458       return s1 < s2;
2459     return s1.compare(pos1, std::string::npos,
2460                       s2, pos2, std::string::npos) < 0;
2461   }
2462 };
2463
2464 // Check candidate_odr_violations_ to find symbols with the same name
2465 // but apparently different definitions (different source-file/line-no).
2466
2467 void
2468 Symbol_table::detect_odr_violations(const Task* task,
2469                                     const char* output_file_name) const
2470 {
2471   for (Odr_map::const_iterator it = candidate_odr_violations_.begin();
2472        it != candidate_odr_violations_.end();
2473        ++it)
2474     {
2475       const char* symbol_name = it->first;
2476       // We use a sorted set so the output is deterministic.
2477       std::set<std::string, Odr_violation_compare> line_nums;
2478
2479       for (Unordered_set<Symbol_location, Symbol_location_hash>::const_iterator
2480                locs = it->second.begin();
2481            locs != it->second.end();
2482            ++locs)
2483         {
2484           // We need to lock the object in order to read it.  This
2485           // means that we have to run in a singleton Task.  If we
2486           // want to run this in a general Task for better
2487           // performance, we will need one Task for object, plus
2488           // appropriate locking to ensure that we don't conflict with
2489           // other uses of the object.  Also note, one_addr2line is not
2490           // currently thread-safe.
2491           Task_lock_obj<Object> tl(task, locs->object);
2492           // 16 is the size of the object-cache that one_addr2line should use.
2493           std::string lineno = Dwarf_line_info::one_addr2line(
2494               locs->object, locs->shndx, locs->offset, 16);
2495           if (!lineno.empty())
2496             line_nums.insert(lineno);
2497         }
2498
2499       if (line_nums.size() > 1)
2500         {
2501           gold_warning(_("while linking %s: symbol '%s' defined in multiple "
2502                          "places (possible ODR violation):"),
2503                        output_file_name, demangle(symbol_name).c_str());
2504           for (std::set<std::string>::const_iterator it2 = line_nums.begin();
2505                it2 != line_nums.end();
2506                ++it2)
2507             fprintf(stderr, "  %s\n", it2->c_str());
2508         }
2509     }
2510   // We only call one_addr2line() in this function, so we can clear its cache.
2511   Dwarf_line_info::clear_addr2line_cache();
2512 }
2513
2514 // Warnings functions.
2515
2516 // Add a new warning.
2517
2518 void
2519 Warnings::add_warning(Symbol_table* symtab, const char* name, Object* obj,
2520                       const std::string& warning)
2521 {
2522   name = symtab->canonicalize_name(name);
2523   this->warnings_[name].set(obj, warning);
2524 }
2525
2526 // Look through the warnings and mark the symbols for which we should
2527 // warn.  This is called during Layout::finalize when we know the
2528 // sources for all the symbols.
2529
2530 void
2531 Warnings::note_warnings(Symbol_table* symtab)
2532 {
2533   for (Warning_table::iterator p = this->warnings_.begin();
2534        p != this->warnings_.end();
2535        ++p)
2536     {
2537       Symbol* sym = symtab->lookup(p->first, NULL);
2538       if (sym != NULL
2539           && sym->source() == Symbol::FROM_OBJECT
2540           && sym->object() == p->second.object)
2541         sym->set_has_warning();
2542     }
2543 }
2544
2545 // Issue a warning.  This is called when we see a relocation against a
2546 // symbol for which has a warning.
2547
2548 template<int size, bool big_endian>
2549 void
2550 Warnings::issue_warning(const Symbol* sym,
2551                         const Relocate_info<size, big_endian>* relinfo,
2552                         size_t relnum, off_t reloffset) const
2553 {
2554   gold_assert(sym->has_warning());
2555   Warning_table::const_iterator p = this->warnings_.find(sym->name());
2556   gold_assert(p != this->warnings_.end());
2557   gold_warning_at_location(relinfo, relnum, reloffset,
2558                            "%s", p->second.text.c_str());
2559 }
2560
2561 // Instantiate the templates we need.  We could use the configure
2562 // script to restrict this to only the ones needed for implemented
2563 // targets.
2564
2565 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
2566 template
2567 void
2568 Sized_symbol<32>::allocate_common(Output_data*, Value_type);
2569 #endif
2570
2571 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
2572 template
2573 void
2574 Sized_symbol<64>::allocate_common(Output_data*, Value_type);
2575 #endif
2576
2577 #ifdef HAVE_TARGET_32_LITTLE
2578 template
2579 void
2580 Symbol_table::add_from_relobj<32, false>(
2581     Sized_relobj<32, false>* relobj,
2582     const unsigned char* syms,
2583     size_t count,
2584     size_t symndx_offset,
2585     const char* sym_names,
2586     size_t sym_name_size,
2587     Sized_relobj<32, true>::Symbols* sympointers);
2588 #endif
2589
2590 #ifdef HAVE_TARGET_32_BIG
2591 template
2592 void
2593 Symbol_table::add_from_relobj<32, true>(
2594     Sized_relobj<32, true>* relobj,
2595     const unsigned char* syms,
2596     size_t count,
2597     size_t symndx_offset,
2598     const char* sym_names,
2599     size_t sym_name_size,
2600     Sized_relobj<32, false>::Symbols* sympointers);
2601 #endif
2602
2603 #ifdef HAVE_TARGET_64_LITTLE
2604 template
2605 void
2606 Symbol_table::add_from_relobj<64, false>(
2607     Sized_relobj<64, false>* relobj,
2608     const unsigned char* syms,
2609     size_t count,
2610     size_t symndx_offset,
2611     const char* sym_names,
2612     size_t sym_name_size,
2613     Sized_relobj<64, true>::Symbols* sympointers);
2614 #endif
2615
2616 #ifdef HAVE_TARGET_64_BIG
2617 template
2618 void
2619 Symbol_table::add_from_relobj<64, true>(
2620     Sized_relobj<64, true>* relobj,
2621     const unsigned char* syms,
2622     size_t count,
2623     size_t symndx_offset,
2624     const char* sym_names,
2625     size_t sym_name_size,
2626     Sized_relobj<64, false>::Symbols* sympointers);
2627 #endif
2628
2629 #ifdef HAVE_TARGET_32_LITTLE
2630 template
2631 void
2632 Symbol_table::add_from_dynobj<32, false>(
2633     Sized_dynobj<32, false>* dynobj,
2634     const unsigned char* syms,
2635     size_t count,
2636     const char* sym_names,
2637     size_t sym_name_size,
2638     const unsigned char* versym,
2639     size_t versym_size,
2640     const std::vector<const char*>* version_map);
2641 #endif
2642
2643 #ifdef HAVE_TARGET_32_BIG
2644 template
2645 void
2646 Symbol_table::add_from_dynobj<32, true>(
2647     Sized_dynobj<32, true>* dynobj,
2648     const unsigned char* syms,
2649     size_t count,
2650     const char* sym_names,
2651     size_t sym_name_size,
2652     const unsigned char* versym,
2653     size_t versym_size,
2654     const std::vector<const char*>* version_map);
2655 #endif
2656
2657 #ifdef HAVE_TARGET_64_LITTLE
2658 template
2659 void
2660 Symbol_table::add_from_dynobj<64, false>(
2661     Sized_dynobj<64, false>* dynobj,
2662     const unsigned char* syms,
2663     size_t count,
2664     const char* sym_names,
2665     size_t sym_name_size,
2666     const unsigned char* versym,
2667     size_t versym_size,
2668     const std::vector<const char*>* version_map);
2669 #endif
2670
2671 #ifdef HAVE_TARGET_64_BIG
2672 template
2673 void
2674 Symbol_table::add_from_dynobj<64, true>(
2675     Sized_dynobj<64, true>* dynobj,
2676     const unsigned char* syms,
2677     size_t count,
2678     const char* sym_names,
2679     size_t sym_name_size,
2680     const unsigned char* versym,
2681     size_t versym_size,
2682     const std::vector<const char*>* version_map);
2683 #endif
2684
2685 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_32_BIG)
2686 template
2687 void
2688 Symbol_table::define_with_copy_reloc<32>(
2689     Sized_symbol<32>* sym,
2690     Output_data* posd,
2691     elfcpp::Elf_types<32>::Elf_Addr value);
2692 #endif
2693
2694 #if defined(HAVE_TARGET_64_LITTLE) || defined(HAVE_TARGET_64_BIG)
2695 template
2696 void
2697 Symbol_table::define_with_copy_reloc<64>(
2698     Sized_symbol<64>* sym,
2699     Output_data* posd,
2700     elfcpp::Elf_types<64>::Elf_Addr value);
2701 #endif
2702
2703 #ifdef HAVE_TARGET_32_LITTLE
2704 template
2705 void
2706 Warnings::issue_warning<32, false>(const Symbol* sym,
2707                                    const Relocate_info<32, false>* relinfo,
2708                                    size_t relnum, off_t reloffset) const;
2709 #endif
2710
2711 #ifdef HAVE_TARGET_32_BIG
2712 template
2713 void
2714 Warnings::issue_warning<32, true>(const Symbol* sym,
2715                                   const Relocate_info<32, true>* relinfo,
2716                                   size_t relnum, off_t reloffset) const;
2717 #endif
2718
2719 #ifdef HAVE_TARGET_64_LITTLE
2720 template
2721 void
2722 Warnings::issue_warning<64, false>(const Symbol* sym,
2723                                    const Relocate_info<64, false>* relinfo,
2724                                    size_t relnum, off_t reloffset) const;
2725 #endif
2726
2727 #ifdef HAVE_TARGET_64_BIG
2728 template
2729 void
2730 Warnings::issue_warning<64, true>(const Symbol* sym,
2731                                   const Relocate_info<64, true>* relinfo,
2732                                   size_t relnum, off_t reloffset) const;
2733 #endif
2734
2735 } // End namespace gold.