* dynobj.cc (Versions::Versions): If there is an soname, use it as
[platform/upstream/binutils.git] / gold / dynobj.cc
1 // dynobj.cc -- dynamic object support for gold
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 <vector>
26 #include <cstring>
27
28 #include "elfcpp.h"
29 #include "parameters.h"
30 #include "script.h"
31 #include "symtab.h"
32 #include "dynobj.h"
33
34 namespace gold
35 {
36
37 // Class Dynobj.
38
39 // Sets up the default soname_ to use, in the (rare) cases we never
40 // see a DT_SONAME entry.
41
42 Dynobj::Dynobj(const std::string& name, Input_file* input_file, off_t offset)
43   : Object(name, input_file, true, offset),
44     needed_(),
45     unknown_needed_(UNKNOWN_NEEDED_UNSET)
46 {
47   // This will be overridden by a DT_SONAME entry, hopefully.  But if
48   // we never see a DT_SONAME entry, our rule is to use the dynamic
49   // object's filename.  The only exception is when the dynamic object
50   // is part of an archive (so the filename is the archive's
51   // filename).  In that case, we use just the dynobj's name-in-archive.
52   this->soname_ = this->input_file()->found_name();
53   if (this->offset() != 0)
54     {
55       std::string::size_type open_paren = this->name().find('(');
56       std::string::size_type close_paren = this->name().find(')');
57       if (open_paren != std::string::npos && close_paren != std::string::npos)
58         {
59           // It's an archive, and name() is of the form 'foo.a(bar.so)'.
60           this->soname_ = this->name().substr(open_paren + 1,
61                                               close_paren - (open_paren + 1));
62         }
63     }
64 }
65
66 // Class Sized_dynobj.
67
68 template<int size, bool big_endian>
69 Sized_dynobj<size, big_endian>::Sized_dynobj(
70     const std::string& name,
71     Input_file* input_file,
72     off_t offset,
73     const elfcpp::Ehdr<size, big_endian>& ehdr)
74   : Dynobj(name, input_file, offset),
75     elf_file_(this, ehdr),
76     dynsym_shndx_(-1U),
77     symbols_(NULL),
78     defined_count_(0)
79 {
80 }
81
82 // Set up the object.
83
84 template<int size, bool big_endian>
85 void
86 Sized_dynobj<size, big_endian>::setup(
87     const elfcpp::Ehdr<size, big_endian>& ehdr)
88 {
89   this->set_target(ehdr.get_e_machine(), size, big_endian,
90                    ehdr.get_e_ident()[elfcpp::EI_OSABI],
91                    ehdr.get_e_ident()[elfcpp::EI_ABIVERSION]);
92
93   const unsigned int shnum = this->elf_file_.shnum();
94   this->set_shnum(shnum);
95 }
96
97 // Find the SHT_DYNSYM section and the various version sections, and
98 // the dynamic section, given the section headers.
99
100 template<int size, bool big_endian>
101 void
102 Sized_dynobj<size, big_endian>::find_dynsym_sections(
103     const unsigned char* pshdrs,
104     unsigned int* pversym_shndx,
105     unsigned int* pverdef_shndx,
106     unsigned int* pverneed_shndx,
107     unsigned int* pdynamic_shndx)
108 {
109   *pversym_shndx = -1U;
110   *pverdef_shndx = -1U;
111   *pverneed_shndx = -1U;
112   *pdynamic_shndx = -1U;
113
114   unsigned int xindex_shndx = 0;
115   unsigned int xindex_link = 0;
116   const unsigned int shnum = this->shnum();
117   const unsigned char* p = pshdrs;
118   for (unsigned int i = 0; i < shnum; ++i, p += This::shdr_size)
119     {
120       typename This::Shdr shdr(p);
121
122       unsigned int* pi;
123       switch (shdr.get_sh_type())
124         {
125         case elfcpp::SHT_DYNSYM:
126           this->dynsym_shndx_ = i;
127           if (xindex_shndx > 0 && xindex_link == i)
128             {
129               Xindex* xindex = new Xindex(this->elf_file_.large_shndx_offset());
130               xindex->read_symtab_xindex<size, big_endian>(this, xindex_shndx,
131                                                            pshdrs);
132               this->set_xindex(xindex);
133             }
134           pi = NULL;
135           break;
136         case elfcpp::SHT_GNU_versym:
137           pi = pversym_shndx;
138           break;
139         case elfcpp::SHT_GNU_verdef:
140           pi = pverdef_shndx;
141           break;
142         case elfcpp::SHT_GNU_verneed:
143           pi = pverneed_shndx;
144           break;
145         case elfcpp::SHT_DYNAMIC:
146           pi = pdynamic_shndx;
147           break;
148         case elfcpp::SHT_SYMTAB_SHNDX:
149           xindex_shndx = i;
150           xindex_link = this->adjust_shndx(shdr.get_sh_link());
151           if (xindex_link == this->dynsym_shndx_)
152             {
153               Xindex* xindex = new Xindex(this->elf_file_.large_shndx_offset());
154               xindex->read_symtab_xindex<size, big_endian>(this, xindex_shndx,
155                                                            pshdrs);
156               this->set_xindex(xindex);
157             }
158           pi = NULL;
159           break;
160         default:
161           pi = NULL;
162           break;
163         }
164
165       if (pi == NULL)
166         continue;
167
168       if (*pi != -1U)
169         this->error(_("unexpected duplicate type %u section: %u, %u"),
170                     shdr.get_sh_type(), *pi, i);
171
172       *pi = i;
173     }
174 }
175
176 // Read the contents of section SHNDX.  PSHDRS points to the section
177 // headers.  TYPE is the expected section type.  LINK is the expected
178 // section link.  Store the data in *VIEW and *VIEW_SIZE.  The
179 // section's sh_info field is stored in *VIEW_INFO.
180
181 template<int size, bool big_endian>
182 void
183 Sized_dynobj<size, big_endian>::read_dynsym_section(
184     const unsigned char* pshdrs,
185     unsigned int shndx,
186     elfcpp::SHT type,
187     unsigned int link,
188     File_view** view,
189     section_size_type* view_size,
190     unsigned int* view_info)
191 {
192   if (shndx == -1U)
193     {
194       *view = NULL;
195       *view_size = 0;
196       *view_info = 0;
197       return;
198     }
199
200   typename This::Shdr shdr(pshdrs + shndx * This::shdr_size);
201
202   gold_assert(shdr.get_sh_type() == type);
203
204   if (this->adjust_shndx(shdr.get_sh_link()) != link)
205     this->error(_("unexpected link in section %u header: %u != %u"),
206                 shndx, this->adjust_shndx(shdr.get_sh_link()), link);
207
208   *view = this->get_lasting_view(shdr.get_sh_offset(), shdr.get_sh_size(),
209                                  true, false);
210   *view_size = convert_to_section_size_type(shdr.get_sh_size());
211   *view_info = shdr.get_sh_info();
212 }
213
214 // Read the dynamic tags.  Set the soname field if this shared object
215 // has a DT_SONAME tag.  Record the DT_NEEDED tags.  PSHDRS points to
216 // the section headers.  DYNAMIC_SHNDX is the section index of the
217 // SHT_DYNAMIC section.  STRTAB_SHNDX, STRTAB, and STRTAB_SIZE are the
218 // section index and contents of a string table which may be the one
219 // associated with the SHT_DYNAMIC section.
220
221 template<int size, bool big_endian>
222 void
223 Sized_dynobj<size, big_endian>::read_dynamic(const unsigned char* pshdrs,
224                                              unsigned int dynamic_shndx,
225                                              unsigned int strtab_shndx,
226                                              const unsigned char* strtabu,
227                                              off_t strtab_size)
228 {
229   typename This::Shdr dynamicshdr(pshdrs + dynamic_shndx * This::shdr_size);
230   gold_assert(dynamicshdr.get_sh_type() == elfcpp::SHT_DYNAMIC);
231
232   const off_t dynamic_size = dynamicshdr.get_sh_size();
233   const unsigned char* pdynamic = this->get_view(dynamicshdr.get_sh_offset(),
234                                                  dynamic_size, true, false);
235
236   const unsigned int link = this->adjust_shndx(dynamicshdr.get_sh_link());
237   if (link != strtab_shndx)
238     {
239       if (link >= this->shnum())
240         {
241           this->error(_("DYNAMIC section %u link out of range: %u"),
242                       dynamic_shndx, link);
243           return;
244         }
245
246       typename This::Shdr strtabshdr(pshdrs + link * This::shdr_size);
247       if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
248         {
249           this->error(_("DYNAMIC section %u link %u is not a strtab"),
250                       dynamic_shndx, link);
251           return;
252         }
253
254       strtab_size = strtabshdr.get_sh_size();
255       strtabu = this->get_view(strtabshdr.get_sh_offset(), strtab_size, false,
256                                false);
257     }
258
259   const char* const strtab = reinterpret_cast<const char*>(strtabu);
260
261   for (const unsigned char* p = pdynamic;
262        p < pdynamic + dynamic_size;
263        p += This::dyn_size)
264     {
265       typename This::Dyn dyn(p);
266
267       switch (dyn.get_d_tag())
268         {
269         case elfcpp::DT_NULL:
270           // We should always see DT_NULL at the end of the dynamic
271           // tags.
272           return;
273
274         case elfcpp::DT_SONAME:
275           {
276             off_t val = dyn.get_d_val();
277             if (val >= strtab_size)
278               this->error(_("DT_SONAME value out of range: %lld >= %lld"),
279                           static_cast<long long>(val),
280                           static_cast<long long>(strtab_size));
281             else
282               this->set_soname_string(strtab + val);
283           }
284           break;
285
286         case elfcpp::DT_NEEDED:
287           {
288             off_t val = dyn.get_d_val();
289             if (val >= strtab_size)
290               this->error(_("DT_NEEDED value out of range: %lld >= %lld"),
291                           static_cast<long long>(val),
292                           static_cast<long long>(strtab_size));
293             else
294               this->add_needed(strtab + val);
295           }
296           break;
297
298         default:
299           break;
300         }
301     }
302
303   this->error(_("missing DT_NULL in dynamic segment"));
304 }
305
306 // Read the symbols and sections from a dynamic object.  We read the
307 // dynamic symbols, not the normal symbols.
308
309 template<int size, bool big_endian>
310 void
311 Sized_dynobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
312 {
313   this->read_section_data(&this->elf_file_, sd);
314
315   const unsigned char* const pshdrs = sd->section_headers->data();
316
317   unsigned int versym_shndx;
318   unsigned int verdef_shndx;
319   unsigned int verneed_shndx;
320   unsigned int dynamic_shndx;
321   this->find_dynsym_sections(pshdrs, &versym_shndx, &verdef_shndx,
322                              &verneed_shndx, &dynamic_shndx);
323
324   unsigned int strtab_shndx = -1U;
325
326   sd->symbols = NULL;
327   sd->symbols_size = 0;
328   sd->external_symbols_offset = 0;
329   sd->symbol_names = NULL;
330   sd->symbol_names_size = 0;
331
332   if (this->dynsym_shndx_ != -1U)
333     {
334       // Get the dynamic symbols.
335       typename This::Shdr dynsymshdr(pshdrs
336                                      + this->dynsym_shndx_ * This::shdr_size);
337       gold_assert(dynsymshdr.get_sh_type() == elfcpp::SHT_DYNSYM);
338
339       sd->symbols = this->get_lasting_view(dynsymshdr.get_sh_offset(),
340                                            dynsymshdr.get_sh_size(), true,
341                                            false);
342       sd->symbols_size =
343         convert_to_section_size_type(dynsymshdr.get_sh_size());
344
345       // Get the symbol names.
346       strtab_shndx = this->adjust_shndx(dynsymshdr.get_sh_link());
347       if (strtab_shndx >= this->shnum())
348         {
349           this->error(_("invalid dynamic symbol table name index: %u"),
350                       strtab_shndx);
351           return;
352         }
353       typename This::Shdr strtabshdr(pshdrs + strtab_shndx * This::shdr_size);
354       if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
355         {
356           this->error(_("dynamic symbol table name section "
357                         "has wrong type: %u"),
358                       static_cast<unsigned int>(strtabshdr.get_sh_type()));
359           return;
360         }
361
362       sd->symbol_names = this->get_lasting_view(strtabshdr.get_sh_offset(),
363                                                 strtabshdr.get_sh_size(),
364                                                 false, false);
365       sd->symbol_names_size =
366         convert_to_section_size_type(strtabshdr.get_sh_size());
367
368       // Get the version information.
369
370       unsigned int dummy;
371       this->read_dynsym_section(pshdrs, versym_shndx, elfcpp::SHT_GNU_versym,
372                                 this->dynsym_shndx_,
373                                 &sd->versym, &sd->versym_size, &dummy);
374
375       // We require that the version definition and need section link
376       // to the same string table as the dynamic symbol table.  This
377       // is not a technical requirement, but it always happens in
378       // practice.  We could change this if necessary.
379
380       this->read_dynsym_section(pshdrs, verdef_shndx, elfcpp::SHT_GNU_verdef,
381                                 strtab_shndx, &sd->verdef, &sd->verdef_size,
382                                 &sd->verdef_info);
383
384       this->read_dynsym_section(pshdrs, verneed_shndx, elfcpp::SHT_GNU_verneed,
385                                 strtab_shndx, &sd->verneed, &sd->verneed_size,
386                                 &sd->verneed_info);
387     }
388
389   // Read the SHT_DYNAMIC section to find whether this shared object
390   // has a DT_SONAME tag and to record any DT_NEEDED tags.  This
391   // doesn't really have anything to do with reading the symbols, but
392   // this is a convenient place to do it.
393   if (dynamic_shndx != -1U)
394     this->read_dynamic(pshdrs, dynamic_shndx, strtab_shndx,
395                        (sd->symbol_names == NULL
396                         ? NULL
397                         : sd->symbol_names->data()),
398                        sd->symbol_names_size);
399 }
400
401 // Return the Xindex structure to use for object with lots of
402 // sections.
403
404 template<int size, bool big_endian>
405 Xindex*
406 Sized_dynobj<size, big_endian>::do_initialize_xindex()
407 {
408   gold_assert(this->dynsym_shndx_ != -1U);
409   Xindex* xindex = new Xindex(this->elf_file_.large_shndx_offset());
410   xindex->initialize_symtab_xindex<size, big_endian>(this, this->dynsym_shndx_);
411   return xindex;
412 }
413
414 // Lay out the input sections for a dynamic object.  We don't want to
415 // include sections from a dynamic object, so all that we actually do
416 // here is check for .gnu.warning sections.
417
418 template<int size, bool big_endian>
419 void
420 Sized_dynobj<size, big_endian>::do_layout(Symbol_table* symtab,
421                                           Layout*,
422                                           Read_symbols_data* sd)
423 {
424   const unsigned int shnum = this->shnum();
425   if (shnum == 0)
426     return;
427
428   // Get the section headers.
429   const unsigned char* pshdrs = sd->section_headers->data();
430
431   // Get the section names.
432   const unsigned char* pnamesu = sd->section_names->data();
433   const char* pnames = reinterpret_cast<const char*>(pnamesu);
434
435   // Skip the first, dummy, section.
436   pshdrs += This::shdr_size;
437   for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
438     {
439       typename This::Shdr shdr(pshdrs);
440
441       if (shdr.get_sh_name() >= sd->section_names_size)
442         {
443           this->error(_("bad section name offset for section %u: %lu"),
444                       i, static_cast<unsigned long>(shdr.get_sh_name()));
445           return;
446         }
447
448       const char* name = pnames + shdr.get_sh_name();
449
450       this->handle_gnu_warning_section(name, i, symtab);
451     }
452
453   delete sd->section_headers;
454   sd->section_headers = NULL;
455   delete sd->section_names;
456   sd->section_names = NULL;
457 }
458
459 // Add an entry to the vector mapping version numbers to version
460 // strings.
461
462 template<int size, bool big_endian>
463 void
464 Sized_dynobj<size, big_endian>::set_version_map(
465     Version_map* version_map,
466     unsigned int ndx,
467     const char* name) const
468 {
469   if (ndx >= version_map->size())
470     version_map->resize(ndx + 1);
471   if ((*version_map)[ndx] != NULL)
472     this->error(_("duplicate definition for version %u"), ndx);
473   (*version_map)[ndx] = name;
474 }
475
476 // Add mappings for the version definitions to VERSION_MAP.
477
478 template<int size, bool big_endian>
479 void
480 Sized_dynobj<size, big_endian>::make_verdef_map(
481     Read_symbols_data* sd,
482     Version_map* version_map) const
483 {
484   if (sd->verdef == NULL)
485     return;
486
487   const char* names = reinterpret_cast<const char*>(sd->symbol_names->data());
488   section_size_type names_size = sd->symbol_names_size;
489
490   const unsigned char* pverdef = sd->verdef->data();
491   section_size_type verdef_size = sd->verdef_size;
492   const unsigned int count = sd->verdef_info;
493
494   const unsigned char* p = pverdef;
495   for (unsigned int i = 0; i < count; ++i)
496     {
497       elfcpp::Verdef<size, big_endian> verdef(p);
498
499       if (verdef.get_vd_version() != elfcpp::VER_DEF_CURRENT)
500         {
501           this->error(_("unexpected verdef version %u"),
502                       verdef.get_vd_version());
503           return;
504         }
505
506       const section_size_type vd_ndx = verdef.get_vd_ndx();
507
508       // The GNU linker clears the VERSYM_HIDDEN bit.  I'm not
509       // sure why.
510
511       // The first Verdaux holds the name of this version.  Subsequent
512       // ones are versions that this one depends upon, which we don't
513       // care about here.
514       const section_size_type vd_cnt = verdef.get_vd_cnt();
515       if (vd_cnt < 1)
516         {
517           this->error(_("verdef vd_cnt field too small: %u"),
518                       static_cast<unsigned int>(vd_cnt));
519           return;
520         }
521
522       const section_size_type vd_aux = verdef.get_vd_aux();
523       if ((p - pverdef) + vd_aux >= verdef_size)
524         {
525           this->error(_("verdef vd_aux field out of range: %u"),
526                       static_cast<unsigned int>(vd_aux));
527           return;
528         }
529
530       const unsigned char* pvda = p + vd_aux;
531       elfcpp::Verdaux<size, big_endian> verdaux(pvda);
532
533       const section_size_type vda_name = verdaux.get_vda_name();
534       if (vda_name >= names_size)
535         {
536           this->error(_("verdaux vda_name field out of range: %u"),
537                       static_cast<unsigned int>(vda_name));
538           return;
539         }
540
541       this->set_version_map(version_map, vd_ndx, names + vda_name);
542
543       const section_size_type vd_next = verdef.get_vd_next();
544       if ((p - pverdef) + vd_next >= verdef_size)
545         {
546           this->error(_("verdef vd_next field out of range: %u"),
547                       static_cast<unsigned int>(vd_next));
548           return;
549         }
550
551       p += vd_next;
552     }
553 }
554
555 // Add mappings for the required versions to VERSION_MAP.
556
557 template<int size, bool big_endian>
558 void
559 Sized_dynobj<size, big_endian>::make_verneed_map(
560     Read_symbols_data* sd,
561     Version_map* version_map) const
562 {
563   if (sd->verneed == NULL)
564     return;
565
566   const char* names = reinterpret_cast<const char*>(sd->symbol_names->data());
567   section_size_type names_size = sd->symbol_names_size;
568
569   const unsigned char* pverneed = sd->verneed->data();
570   const section_size_type verneed_size = sd->verneed_size;
571   const unsigned int count = sd->verneed_info;
572
573   const unsigned char* p = pverneed;
574   for (unsigned int i = 0; i < count; ++i)
575     {
576       elfcpp::Verneed<size, big_endian> verneed(p);
577
578       if (verneed.get_vn_version() != elfcpp::VER_NEED_CURRENT)
579         {
580           this->error(_("unexpected verneed version %u"),
581                       verneed.get_vn_version());
582           return;
583         }
584
585       const section_size_type vn_aux = verneed.get_vn_aux();
586
587       if ((p - pverneed) + vn_aux >= verneed_size)
588         {
589           this->error(_("verneed vn_aux field out of range: %u"),
590                       static_cast<unsigned int>(vn_aux));
591           return;
592         }
593
594       const unsigned int vn_cnt = verneed.get_vn_cnt();
595       const unsigned char* pvna = p + vn_aux;
596       for (unsigned int j = 0; j < vn_cnt; ++j)
597         {
598           elfcpp::Vernaux<size, big_endian> vernaux(pvna);
599
600           const unsigned int vna_name = vernaux.get_vna_name();
601           if (vna_name >= names_size)
602             {
603               this->error(_("vernaux vna_name field out of range: %u"),
604                           static_cast<unsigned int>(vna_name));
605               return;
606             }
607
608           this->set_version_map(version_map, vernaux.get_vna_other(),
609                                 names + vna_name);
610
611           const section_size_type vna_next = vernaux.get_vna_next();
612           if ((pvna - pverneed) + vna_next >= verneed_size)
613             {
614               this->error(_("verneed vna_next field out of range: %u"),
615                           static_cast<unsigned int>(vna_next));
616               return;
617             }
618
619           pvna += vna_next;
620         }
621
622       const section_size_type vn_next = verneed.get_vn_next();
623       if ((p - pverneed) + vn_next >= verneed_size)
624         {
625           this->error(_("verneed vn_next field out of range: %u"),
626                       static_cast<unsigned int>(vn_next));
627           return;
628         }
629
630       p += vn_next;
631     }
632 }
633
634 // Create a vector mapping version numbers to version strings.
635
636 template<int size, bool big_endian>
637 void
638 Sized_dynobj<size, big_endian>::make_version_map(
639     Read_symbols_data* sd,
640     Version_map* version_map) const
641 {
642   if (sd->verdef == NULL && sd->verneed == NULL)
643     return;
644
645   // A guess at the maximum version number we will see.  If this is
646   // wrong we will be less efficient but still correct.
647   version_map->reserve(sd->verdef_info + sd->verneed_info * 10);
648
649   this->make_verdef_map(sd, version_map);
650   this->make_verneed_map(sd, version_map);
651 }
652
653 // Add the dynamic symbols to the symbol table.
654
655 template<int size, bool big_endian>
656 void
657 Sized_dynobj<size, big_endian>::do_add_symbols(Symbol_table* symtab,
658                                                Read_symbols_data* sd)
659 {
660   if (sd->symbols == NULL)
661     {
662       gold_assert(sd->symbol_names == NULL);
663       gold_assert(sd->versym == NULL && sd->verdef == NULL
664                   && sd->verneed == NULL);
665       return;
666     }
667
668   const int sym_size = This::sym_size;
669   const size_t symcount = sd->symbols_size / sym_size;
670   gold_assert(sd->external_symbols_offset == 0);
671   if (symcount * sym_size != sd->symbols_size)
672     {
673       this->error(_("size of dynamic symbols is not multiple of symbol size"));
674       return;
675     }
676
677   Version_map version_map;
678   this->make_version_map(sd, &version_map);
679
680   // If printing symbol counts, we want to track symbols.
681   
682   if (parameters->options().user_set_print_symbol_counts())
683     {
684       this->symbols_ = new Symbols();
685       this->symbols_->resize(symcount);
686     }
687
688   const char* sym_names =
689     reinterpret_cast<const char*>(sd->symbol_names->data());
690   symtab->add_from_dynobj(this, sd->symbols->data(), symcount,
691                           sym_names, sd->symbol_names_size,
692                           (sd->versym == NULL
693                            ? NULL
694                            : sd->versym->data()),
695                           sd->versym_size,
696                           &version_map,
697                           this->symbols_,
698                           &this->defined_count_);
699
700   delete sd->symbols;
701   sd->symbols = NULL;
702   delete sd->symbol_names;
703   sd->symbol_names = NULL;
704   if (sd->versym != NULL)
705     {
706       delete sd->versym;
707       sd->versym = NULL;
708     }
709   if (sd->verdef != NULL)
710     {
711       delete sd->verdef;
712       sd->verdef = NULL;
713     }
714   if (sd->verneed != NULL)
715     {
716       delete sd->verneed;
717       sd->verneed = NULL;
718     }
719
720   // This is normally the last time we will read any data from this
721   // file.
722   this->clear_view_cache_marks();
723 }
724
725 // Get symbol counts.
726
727 template<int size, bool big_endian>
728 void
729 Sized_dynobj<size, big_endian>::do_get_global_symbol_counts(
730     const Symbol_table*,
731     size_t* defined,
732     size_t* used) const
733 {
734   *defined = this->defined_count_;
735   size_t count = 0;
736   for (typename Symbols::const_iterator p = this->symbols_->begin();
737        p != this->symbols_->end();
738        ++p)
739     if (*p != NULL
740         && (*p)->source() == Symbol::FROM_OBJECT
741         && (*p)->object() == this
742         && (*p)->is_defined()
743         && (*p)->dynsym_index() != -1U)
744       ++count;
745   *used = count;
746 }
747
748 // Given a vector of hash codes, compute the number of hash buckets to
749 // use.
750
751 unsigned int
752 Dynobj::compute_bucket_count(const std::vector<uint32_t>& hashcodes,
753                              bool for_gnu_hash_table)
754 {
755   // FIXME: Implement optional hash table optimization.
756
757   // Array used to determine the number of hash table buckets to use
758   // based on the number of symbols there are.  If there are fewer
759   // than 3 symbols we use 1 bucket, fewer than 17 symbols we use 3
760   // buckets, fewer than 37 we use 17 buckets, and so forth.  We never
761   // use more than 262147 buckets.  This is straight from the old GNU
762   // linker.
763   static const unsigned int buckets[] =
764   {
765     1, 3, 17, 37, 67, 97, 131, 197, 263, 521, 1031, 2053, 4099, 8209,
766     16411, 32771, 65537, 131101, 262147
767   };
768   const int buckets_count = sizeof buckets / sizeof buckets[0];
769
770   unsigned int symcount = hashcodes.size();
771   unsigned int ret = 1;
772   const double full_fraction
773     = 1.0 - parameters->options().hash_bucket_empty_fraction();
774   for (int i = 0; i < buckets_count; ++i)
775     {
776       if (symcount < buckets[i] * full_fraction)
777         break;
778       ret = buckets[i];
779     }
780
781   if (for_gnu_hash_table && ret < 2)
782     ret = 2;
783
784   return ret;
785 }
786
787 // The standard ELF hash function.  This hash function must not
788 // change, as the dynamic linker uses it also.
789
790 uint32_t
791 Dynobj::elf_hash(const char* name)
792 {
793   const unsigned char* nameu = reinterpret_cast<const unsigned char*>(name);
794   uint32_t h = 0;
795   unsigned char c;
796   while ((c = *nameu++) != '\0')
797     {
798       h = (h << 4) + c;
799       uint32_t g = h & 0xf0000000;
800       if (g != 0)
801         {
802           h ^= g >> 24;
803           // The ELF ABI says h &= ~g, but using xor is equivalent in
804           // this case (since g was set from h) and may save one
805           // instruction.
806           h ^= g;
807         }
808     }
809   return h;
810 }
811
812 // Create a standard ELF hash table, setting *PPHASH and *PHASHLEN.
813 // DYNSYMS is a vector with all the global dynamic symbols.
814 // LOCAL_DYNSYM_COUNT is the number of local symbols in the dynamic
815 // symbol table.
816
817 void
818 Dynobj::create_elf_hash_table(const std::vector<Symbol*>& dynsyms,
819                               unsigned int local_dynsym_count,
820                               unsigned char** pphash,
821                               unsigned int* phashlen)
822 {
823   unsigned int dynsym_count = dynsyms.size();
824
825   // Get the hash values for all the symbols.
826   std::vector<uint32_t> dynsym_hashvals(dynsym_count);
827   for (unsigned int i = 0; i < dynsym_count; ++i)
828     dynsym_hashvals[i] = Dynobj::elf_hash(dynsyms[i]->name());
829
830   const unsigned int bucketcount =
831     Dynobj::compute_bucket_count(dynsym_hashvals, false);
832
833   std::vector<uint32_t> bucket(bucketcount);
834   std::vector<uint32_t> chain(local_dynsym_count + dynsym_count);
835
836   for (unsigned int i = 0; i < dynsym_count; ++i)
837     {
838       unsigned int dynsym_index = dynsyms[i]->dynsym_index();
839       unsigned int bucketpos = dynsym_hashvals[i] % bucketcount;
840       chain[dynsym_index] = bucket[bucketpos];
841       bucket[bucketpos] = dynsym_index;
842     }
843
844   unsigned int hashlen = ((2
845                            + bucketcount
846                            + local_dynsym_count
847                            + dynsym_count)
848                           * 4);
849   unsigned char* phash = new unsigned char[hashlen];
850
851   if (parameters->target().is_big_endian())
852     {
853 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
854       Dynobj::sized_create_elf_hash_table<true>(bucket, chain, phash,
855                                                 hashlen);
856 #else
857       gold_unreachable();
858 #endif
859     }
860   else
861     {
862 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
863       Dynobj::sized_create_elf_hash_table<false>(bucket, chain, phash,
864                                                  hashlen);
865 #else
866       gold_unreachable();
867 #endif
868     }
869
870   *pphash = phash;
871   *phashlen = hashlen;
872 }
873
874 // Fill in an ELF hash table.
875
876 template<bool big_endian>
877 void
878 Dynobj::sized_create_elf_hash_table(const std::vector<uint32_t>& bucket,
879                                     const std::vector<uint32_t>& chain,
880                                     unsigned char* phash,
881                                     unsigned int hashlen)
882 {
883   unsigned char* p = phash;
884
885   const unsigned int bucketcount = bucket.size();
886   const unsigned int chaincount = chain.size();
887
888   elfcpp::Swap<32, big_endian>::writeval(p, bucketcount);
889   p += 4;
890   elfcpp::Swap<32, big_endian>::writeval(p, chaincount);
891   p += 4;
892
893   for (unsigned int i = 0; i < bucketcount; ++i)
894     {
895       elfcpp::Swap<32, big_endian>::writeval(p, bucket[i]);
896       p += 4;
897     }
898
899   for (unsigned int i = 0; i < chaincount; ++i)
900     {
901       elfcpp::Swap<32, big_endian>::writeval(p, chain[i]);
902       p += 4;
903     }
904
905   gold_assert(static_cast<unsigned int>(p - phash) == hashlen);
906 }
907
908 // The hash function used for the GNU hash table.  This hash function
909 // must not change, as the dynamic linker uses it also.
910
911 uint32_t
912 Dynobj::gnu_hash(const char* name)
913 {
914   const unsigned char* nameu = reinterpret_cast<const unsigned char*>(name);
915   uint32_t h = 5381;
916   unsigned char c;
917   while ((c = *nameu++) != '\0')
918     h = (h << 5) + h + c;
919   return h;
920 }
921
922 // Create a GNU hash table, setting *PPHASH and *PHASHLEN.  GNU hash
923 // tables are an extension to ELF which are recognized by the GNU
924 // dynamic linker.  They are referenced using dynamic tag DT_GNU_HASH.
925 // TARGET is the target.  DYNSYMS is a vector with all the global
926 // symbols which will be going into the dynamic symbol table.
927 // LOCAL_DYNSYM_COUNT is the number of local symbols in the dynamic
928 // symbol table.
929
930 void
931 Dynobj::create_gnu_hash_table(const std::vector<Symbol*>& dynsyms,
932                               unsigned int local_dynsym_count,
933                               unsigned char** pphash,
934                               unsigned int* phashlen)
935 {
936   const unsigned int count = dynsyms.size();
937
938   // Sort the dynamic symbols into two vectors.  Symbols which we do
939   // not want to put into the hash table we store into
940   // UNHASHED_DYNSYMS.  Symbols which we do want to store we put into
941   // HASHED_DYNSYMS.  DYNSYM_HASHVALS is parallel to HASHED_DYNSYMS,
942   // and records the hash codes.
943
944   std::vector<Symbol*> unhashed_dynsyms;
945   unhashed_dynsyms.reserve(count);
946
947   std::vector<Symbol*> hashed_dynsyms;
948   hashed_dynsyms.reserve(count);
949
950   std::vector<uint32_t> dynsym_hashvals;
951   dynsym_hashvals.reserve(count);
952   
953   for (unsigned int i = 0; i < count; ++i)
954     {
955       Symbol* sym = dynsyms[i];
956
957       // FIXME: Should put on unhashed_dynsyms if the symbol is
958       // hidden.
959       if (sym->is_undefined())
960         unhashed_dynsyms.push_back(sym);
961       else
962         {
963           hashed_dynsyms.push_back(sym);
964           dynsym_hashvals.push_back(Dynobj::gnu_hash(sym->name()));
965         }
966     }
967
968   // Put the unhashed symbols at the start of the global portion of
969   // the dynamic symbol table.
970   const unsigned int unhashed_count = unhashed_dynsyms.size();
971   unsigned int unhashed_dynsym_index = local_dynsym_count;
972   for (unsigned int i = 0; i < unhashed_count; ++i)
973     {
974       unhashed_dynsyms[i]->set_dynsym_index(unhashed_dynsym_index);
975       ++unhashed_dynsym_index;
976     }
977
978   // For the actual data generation we call out to a templatized
979   // function.
980   int size = parameters->target().get_size();
981   bool big_endian = parameters->target().is_big_endian();
982   if (size == 32)
983     {
984       if (big_endian)
985         {
986 #ifdef HAVE_TARGET_32_BIG
987           Dynobj::sized_create_gnu_hash_table<32, true>(hashed_dynsyms,
988                                                         dynsym_hashvals,
989                                                         unhashed_dynsym_index,
990                                                         pphash,
991                                                         phashlen);
992 #else
993           gold_unreachable();
994 #endif
995         }
996       else
997         {
998 #ifdef HAVE_TARGET_32_LITTLE
999           Dynobj::sized_create_gnu_hash_table<32, false>(hashed_dynsyms,
1000                                                          dynsym_hashvals,
1001                                                          unhashed_dynsym_index,
1002                                                          pphash,
1003                                                          phashlen);
1004 #else
1005           gold_unreachable();
1006 #endif
1007         }
1008     }
1009   else if (size == 64)
1010     {
1011       if (big_endian)
1012         {
1013 #ifdef HAVE_TARGET_64_BIG
1014           Dynobj::sized_create_gnu_hash_table<64, true>(hashed_dynsyms,
1015                                                         dynsym_hashvals,
1016                                                         unhashed_dynsym_index,
1017                                                         pphash,
1018                                                         phashlen);
1019 #else
1020           gold_unreachable();
1021 #endif
1022         }
1023       else
1024         {
1025 #ifdef HAVE_TARGET_64_LITTLE
1026           Dynobj::sized_create_gnu_hash_table<64, false>(hashed_dynsyms,
1027                                                          dynsym_hashvals,
1028                                                          unhashed_dynsym_index,
1029                                                          pphash,
1030                                                          phashlen);
1031 #else
1032           gold_unreachable();
1033 #endif
1034         }
1035     }
1036   else
1037     gold_unreachable();
1038 }
1039
1040 // Create the actual data for a GNU hash table.  This is just a copy
1041 // of the code from the old GNU linker.
1042
1043 template<int size, bool big_endian>
1044 void
1045 Dynobj::sized_create_gnu_hash_table(
1046     const std::vector<Symbol*>& hashed_dynsyms,
1047     const std::vector<uint32_t>& dynsym_hashvals,
1048     unsigned int unhashed_dynsym_count,
1049     unsigned char** pphash,
1050     unsigned int* phashlen)
1051 {
1052   if (hashed_dynsyms.empty())
1053     {
1054       // Special case for the empty hash table.
1055       unsigned int hashlen = 5 * 4 + size / 8;
1056       unsigned char* phash = new unsigned char[hashlen];
1057       // One empty bucket.
1058       elfcpp::Swap<32, big_endian>::writeval(phash, 1);
1059       // Symbol index above unhashed symbols.
1060       elfcpp::Swap<32, big_endian>::writeval(phash + 4, unhashed_dynsym_count);
1061       // One word for bitmask.
1062       elfcpp::Swap<32, big_endian>::writeval(phash + 8, 1);
1063       // Only bloom filter.
1064       elfcpp::Swap<32, big_endian>::writeval(phash + 12, 0);
1065       // No valid hashes.
1066       elfcpp::Swap<size, big_endian>::writeval(phash + 16, 0);
1067       // No hashes in only bucket.
1068       elfcpp::Swap<32, big_endian>::writeval(phash + 16 + size / 8, 0);
1069
1070       *phashlen = hashlen;
1071       *pphash = phash;
1072
1073       return;
1074     }
1075
1076   const unsigned int bucketcount =
1077     Dynobj::compute_bucket_count(dynsym_hashvals, true);
1078
1079   const unsigned int nsyms = hashed_dynsyms.size();
1080
1081   uint32_t maskbitslog2 = 1;
1082   uint32_t x = nsyms >> 1;
1083   while (x != 0)
1084     {
1085       ++maskbitslog2;
1086       x >>= 1;
1087     }
1088   if (maskbitslog2 < 3)
1089     maskbitslog2 = 5;
1090   else if (((1U << (maskbitslog2 - 2)) & nsyms) != 0)
1091     maskbitslog2 += 3;
1092   else
1093     maskbitslog2 += 2;
1094
1095   uint32_t shift1;
1096   if (size == 32)
1097     shift1 = 5;
1098   else
1099     {
1100       if (maskbitslog2 == 5)
1101         maskbitslog2 = 6;
1102       shift1 = 6;
1103     }
1104   uint32_t mask = (1U << shift1) - 1U;
1105   uint32_t shift2 = maskbitslog2;
1106   uint32_t maskbits = 1U << maskbitslog2;
1107   uint32_t maskwords = 1U << (maskbitslog2 - shift1);
1108
1109   typedef typename elfcpp::Elf_types<size>::Elf_WXword Word;
1110   std::vector<Word> bitmask(maskwords);
1111   std::vector<uint32_t> counts(bucketcount);
1112   std::vector<uint32_t> indx(bucketcount);
1113   uint32_t symindx = unhashed_dynsym_count;
1114
1115   // Count the number of times each hash bucket is used.
1116   for (unsigned int i = 0; i < nsyms; ++i)
1117     ++counts[dynsym_hashvals[i] % bucketcount];
1118
1119   unsigned int cnt = symindx;
1120   for (unsigned int i = 0; i < bucketcount; ++i)
1121     {
1122       indx[i] = cnt;
1123       cnt += counts[i];
1124     }
1125
1126   unsigned int hashlen = (4 + bucketcount + nsyms) * 4;
1127   hashlen += maskbits / 8;
1128   unsigned char* phash = new unsigned char[hashlen];
1129
1130   elfcpp::Swap<32, big_endian>::writeval(phash, bucketcount);
1131   elfcpp::Swap<32, big_endian>::writeval(phash + 4, symindx);
1132   elfcpp::Swap<32, big_endian>::writeval(phash + 8, maskwords);
1133   elfcpp::Swap<32, big_endian>::writeval(phash + 12, shift2);
1134
1135   unsigned char* p = phash + 16 + maskbits / 8;
1136   for (unsigned int i = 0; i < bucketcount; ++i)
1137     {
1138       if (counts[i] == 0)
1139         elfcpp::Swap<32, big_endian>::writeval(p, 0);
1140       else
1141         elfcpp::Swap<32, big_endian>::writeval(p, indx[i]);
1142       p += 4;
1143     }
1144
1145   for (unsigned int i = 0; i < nsyms; ++i)
1146     {
1147       Symbol* sym = hashed_dynsyms[i];
1148       uint32_t hashval = dynsym_hashvals[i];
1149
1150       unsigned int bucket = hashval % bucketcount;
1151       unsigned int val = ((hashval >> shift1)
1152                           & ((maskbits >> shift1) - 1));
1153       bitmask[val] |= (static_cast<Word>(1U)) << (hashval & mask);
1154       bitmask[val] |= (static_cast<Word>(1U)) << ((hashval >> shift2) & mask);
1155       val = hashval & ~ 1U;
1156       if (counts[bucket] == 1)
1157         {
1158           // Last element terminates the chain.
1159           val |= 1;
1160         }
1161       elfcpp::Swap<32, big_endian>::writeval(p + (indx[bucket] - symindx) * 4,
1162                                              val);
1163       --counts[bucket];
1164
1165       sym->set_dynsym_index(indx[bucket]);
1166       ++indx[bucket];
1167     }
1168
1169   p = phash + 16;
1170   for (unsigned int i = 0; i < maskwords; ++i)
1171     {
1172       elfcpp::Swap<size, big_endian>::writeval(p, bitmask[i]);
1173       p += size / 8;
1174     }
1175
1176   *phashlen = hashlen;
1177   *pphash = phash;
1178 }
1179
1180 // Verdef methods.
1181
1182 // Write this definition to a buffer for the output section.
1183
1184 template<int size, bool big_endian>
1185 unsigned char*
1186 Verdef::write(const Stringpool* dynpool, bool is_last, unsigned char* pb) const
1187 {
1188   const int verdef_size = elfcpp::Elf_sizes<size>::verdef_size;
1189   const int verdaux_size = elfcpp::Elf_sizes<size>::verdaux_size;
1190
1191   elfcpp::Verdef_write<size, big_endian> vd(pb);
1192   vd.set_vd_version(elfcpp::VER_DEF_CURRENT);
1193   vd.set_vd_flags((this->is_base_ ? elfcpp::VER_FLG_BASE : 0)
1194                   | (this->is_weak_ ? elfcpp::VER_FLG_WEAK : 0));
1195   vd.set_vd_ndx(this->index());
1196   vd.set_vd_cnt(1 + this->deps_.size());
1197   vd.set_vd_hash(Dynobj::elf_hash(this->name()));
1198   vd.set_vd_aux(verdef_size);
1199   vd.set_vd_next(is_last
1200                  ? 0
1201                  : verdef_size + (1 + this->deps_.size()) * verdaux_size);
1202   pb += verdef_size;
1203
1204   elfcpp::Verdaux_write<size, big_endian> vda(pb);
1205   vda.set_vda_name(dynpool->get_offset(this->name()));
1206   vda.set_vda_next(this->deps_.empty() ? 0 : verdaux_size);
1207   pb += verdaux_size;
1208
1209   Deps::const_iterator p;
1210   unsigned int i;
1211   for (p = this->deps_.begin(), i = 0;
1212        p != this->deps_.end();
1213        ++p, ++i)
1214     {
1215       elfcpp::Verdaux_write<size, big_endian> vda(pb);
1216       vda.set_vda_name(dynpool->get_offset(*p));
1217       vda.set_vda_next(i + 1 >= this->deps_.size() ? 0 : verdaux_size);
1218       pb += verdaux_size;
1219     }
1220
1221   return pb;
1222 }
1223
1224 // Verneed methods.
1225
1226 Verneed::~Verneed()
1227 {
1228   for (Need_versions::iterator p = this->need_versions_.begin();
1229        p != this->need_versions_.end();
1230        ++p)
1231     delete *p;
1232 }
1233
1234 // Add a new version to this file reference.
1235
1236 Verneed_version*
1237 Verneed::add_name(const char* name)
1238 {
1239   Verneed_version* vv = new Verneed_version(name);
1240   this->need_versions_.push_back(vv);
1241   return vv;
1242 }
1243
1244 // Set the version indexes starting at INDEX.
1245
1246 unsigned int
1247 Verneed::finalize(unsigned int index)
1248 {
1249   for (Need_versions::iterator p = this->need_versions_.begin();
1250        p != this->need_versions_.end();
1251        ++p)
1252     {
1253       (*p)->set_index(index);
1254       ++index;
1255     }
1256   return index;
1257 }
1258
1259 // Write this list of referenced versions to a buffer for the output
1260 // section.
1261
1262 template<int size, bool big_endian>
1263 unsigned char*
1264 Verneed::write(const Stringpool* dynpool, bool is_last,
1265                unsigned char* pb) const
1266 {
1267   const int verneed_size = elfcpp::Elf_sizes<size>::verneed_size;
1268   const int vernaux_size = elfcpp::Elf_sizes<size>::vernaux_size;
1269
1270   elfcpp::Verneed_write<size, big_endian> vn(pb);
1271   vn.set_vn_version(elfcpp::VER_NEED_CURRENT);
1272   vn.set_vn_cnt(this->need_versions_.size());
1273   vn.set_vn_file(dynpool->get_offset(this->filename()));
1274   vn.set_vn_aux(verneed_size);
1275   vn.set_vn_next(is_last
1276                  ? 0
1277                  : verneed_size + this->need_versions_.size() * vernaux_size);
1278   pb += verneed_size;
1279
1280   Need_versions::const_iterator p;
1281   unsigned int i;
1282   for (p = this->need_versions_.begin(), i = 0;
1283        p != this->need_versions_.end();
1284        ++p, ++i)
1285     {
1286       elfcpp::Vernaux_write<size, big_endian> vna(pb);
1287       vna.set_vna_hash(Dynobj::elf_hash((*p)->version()));
1288       // FIXME: We need to sometimes set VER_FLG_WEAK here.
1289       vna.set_vna_flags(0);
1290       vna.set_vna_other((*p)->index());
1291       vna.set_vna_name(dynpool->get_offset((*p)->version()));
1292       vna.set_vna_next(i + 1 >= this->need_versions_.size()
1293                        ? 0
1294                        : vernaux_size);
1295       pb += vernaux_size;
1296     }
1297
1298   return pb;
1299 }
1300
1301 // Versions methods.
1302
1303 Versions::Versions(const Version_script_info& version_script,
1304                    Stringpool* dynpool)
1305   : defs_(), needs_(), version_table_(),
1306     is_finalized_(false), version_script_(version_script)
1307 {
1308   // We always need a base version, so define that first. Nothing
1309   // explicitly declares itself as part of base, so it doesn't need to
1310   // be in version_table_.
1311   // FIXME: Should use soname here when creating a shared object. Is
1312   // this fixme still valid? It looks like it's doing the right thing
1313   // to me.
1314   if (parameters->options().shared())
1315     {
1316       const char* name = parameters->options().soname();
1317       if (name == NULL)
1318         name = parameters->options().output_file_name();
1319       name = dynpool->add(name, false, NULL);
1320       Verdef* vdbase = new Verdef(name, std::vector<std::string>(),
1321                                   true, false, true);
1322       this->defs_.push_back(vdbase);
1323     }
1324
1325   if (!this->version_script_.empty())
1326     {
1327       // Parse the version script, and insert each declared version into
1328       // defs_ and version_table_.
1329       std::vector<std::string> versions = this->version_script_.get_versions();
1330       for (size_t k = 0; k < versions.size(); ++k)
1331         {
1332           Stringpool::Key version_key;
1333           const char* version = dynpool->add(versions[k].c_str(),
1334                                              true, &version_key);
1335           Verdef* const vd = new Verdef(
1336               version,
1337               this->version_script_.get_dependencies(version),
1338               false, false, false);
1339           this->defs_.push_back(vd);
1340           Key key(version_key, 0);
1341           this->version_table_.insert(std::make_pair(key, vd));
1342         }
1343     }
1344 }
1345
1346 Versions::~Versions()
1347 {
1348   for (Defs::iterator p = this->defs_.begin();
1349        p != this->defs_.end();
1350        ++p)
1351     delete *p;
1352
1353   for (Needs::iterator p = this->needs_.begin();
1354        p != this->needs_.end();
1355        ++p)
1356     delete *p;
1357 }
1358
1359 // Return the dynamic object which a symbol refers to.
1360
1361 Dynobj*
1362 Versions::get_dynobj_for_sym(const Symbol_table* symtab,
1363                              const Symbol* sym) const
1364 {
1365   if (sym->is_copied_from_dynobj())
1366     return symtab->get_copy_source(sym);
1367   else
1368     {
1369       Object* object = sym->object();
1370       gold_assert(object->is_dynamic());
1371       return static_cast<Dynobj*>(object);
1372     }
1373 }
1374
1375 // Record version information for a symbol going into the dynamic
1376 // symbol table.
1377
1378 void
1379 Versions::record_version(const Symbol_table* symtab,
1380                          Stringpool* dynpool, const Symbol* sym)
1381 {
1382   gold_assert(!this->is_finalized_);
1383   gold_assert(sym->version() != NULL);
1384
1385   Stringpool::Key version_key;
1386   const char* version = dynpool->add(sym->version(), false, &version_key);
1387
1388   if (!sym->is_from_dynobj() && !sym->is_copied_from_dynobj())
1389     {
1390       if (parameters->options().shared())
1391         this->add_def(sym, version, version_key);
1392     }
1393   else
1394     {
1395       // This is a version reference.
1396       Dynobj* dynobj = this->get_dynobj_for_sym(symtab, sym);
1397       this->add_need(dynpool, dynobj->soname(), version, version_key);
1398     }
1399 }
1400
1401 // We've found a symbol SYM defined in version VERSION.
1402
1403 void
1404 Versions::add_def(const Symbol* sym, const char* version,
1405                   Stringpool::Key version_key)
1406 {
1407   Key k(version_key, 0);
1408   Version_base* const vbnull = NULL;
1409   std::pair<Version_table::iterator, bool> ins =
1410     this->version_table_.insert(std::make_pair(k, vbnull));
1411
1412   if (!ins.second)
1413     {
1414       // We already have an entry for this version.
1415       Version_base* vb = ins.first->second;
1416
1417       // We have now seen a symbol in this version, so it is not
1418       // weak.
1419       gold_assert(vb != NULL);
1420       vb->clear_weak();
1421     }
1422   else
1423     {
1424       // If we are creating a shared object, it is an error to
1425       // find a definition of a symbol with a version which is not
1426       // in the version script.
1427       if (parameters->options().shared())
1428         gold_error(_("symbol %s has undefined version %s"),
1429                    sym->demangled_name().c_str(), version);
1430
1431       // When creating a regular executable, automatically define
1432       // a new version.
1433       Verdef* vd = new Verdef(version, std::vector<std::string>(),
1434                               false, false, false);
1435       this->defs_.push_back(vd);
1436       ins.first->second = vd;
1437     }
1438 }
1439
1440 // Add a reference to version NAME in file FILENAME.
1441
1442 void
1443 Versions::add_need(Stringpool* dynpool, const char* filename, const char* name,
1444                    Stringpool::Key name_key)
1445 {
1446   Stringpool::Key filename_key;
1447   filename = dynpool->add(filename, true, &filename_key);
1448
1449   Key k(name_key, filename_key);
1450   Version_base* const vbnull = NULL;
1451   std::pair<Version_table::iterator, bool> ins =
1452     this->version_table_.insert(std::make_pair(k, vbnull));
1453
1454   if (!ins.second)
1455     {
1456       // We already have an entry for this filename/version.
1457       return;
1458     }
1459
1460   // See whether we already have this filename.  We don't expect many
1461   // version references, so we just do a linear search.  This could be
1462   // replaced by a hash table.
1463   Verneed* vn = NULL;
1464   for (Needs::iterator p = this->needs_.begin();
1465        p != this->needs_.end();
1466        ++p)
1467     {
1468       if ((*p)->filename() == filename)
1469         {
1470           vn = *p;
1471           break;
1472         }
1473     }
1474
1475   if (vn == NULL)
1476     {
1477       // We have a new filename.
1478       vn = new Verneed(filename);
1479       this->needs_.push_back(vn);
1480     }
1481
1482   ins.first->second = vn->add_name(name);
1483 }
1484
1485 // Set the version indexes.  Create a new dynamic version symbol for
1486 // each new version definition.
1487
1488 unsigned int
1489 Versions::finalize(Symbol_table* symtab, unsigned int dynsym_index,
1490                    std::vector<Symbol*>* syms)
1491 {
1492   gold_assert(!this->is_finalized_);
1493
1494   unsigned int vi = 1;
1495
1496   for (Defs::iterator p = this->defs_.begin();
1497        p != this->defs_.end();
1498        ++p)
1499     {
1500       (*p)->set_index(vi);
1501       ++vi;
1502
1503       // Create a version symbol if necessary.
1504       if (!(*p)->is_symbol_created())
1505         {
1506           Symbol* vsym = symtab->define_as_constant((*p)->name(),
1507                                                     (*p)->name(), 0, 0,
1508                                                     elfcpp::STT_OBJECT,
1509                                                     elfcpp::STB_GLOBAL,
1510                                                     elfcpp::STV_DEFAULT, 0,
1511                                                     false, false);
1512           vsym->set_needs_dynsym_entry();
1513           vsym->set_dynsym_index(dynsym_index);
1514           ++dynsym_index;
1515           syms->push_back(vsym);
1516           // The name is already in the dynamic pool.
1517         }
1518     }
1519
1520   // Index 1 is used for global symbols.
1521   if (vi == 1)
1522     {
1523       gold_assert(this->defs_.empty());
1524       vi = 2;
1525     }
1526
1527   for (Needs::iterator p = this->needs_.begin();
1528        p != this->needs_.end();
1529        ++p)
1530     vi = (*p)->finalize(vi);
1531
1532   this->is_finalized_ = true;
1533
1534   return dynsym_index;
1535 }
1536
1537 // Return the version index to use for a symbol.  This does two hash
1538 // table lookups: one in DYNPOOL and one in this->version_table_.
1539 // Another approach alternative would be store a pointer in SYM, which
1540 // would increase the size of the symbol table.  Or perhaps we could
1541 // use a hash table from dynamic symbol pointer values to Version_base
1542 // pointers.
1543
1544 unsigned int
1545 Versions::version_index(const Symbol_table* symtab, const Stringpool* dynpool,
1546                         const Symbol* sym) const
1547 {
1548   Stringpool::Key version_key;
1549   const char* version = dynpool->find(sym->version(), &version_key);
1550   gold_assert(version != NULL);
1551
1552   Key k;
1553   if (!sym->is_from_dynobj() && !sym->is_copied_from_dynobj())
1554     {
1555       if (!parameters->options().shared())
1556         return elfcpp::VER_NDX_GLOBAL;
1557       k = Key(version_key, 0);
1558     }
1559   else
1560     {
1561       Dynobj* dynobj = this->get_dynobj_for_sym(symtab, sym);
1562
1563       Stringpool::Key filename_key;
1564       const char* filename = dynpool->find(dynobj->soname(), &filename_key);
1565       gold_assert(filename != NULL);
1566
1567       k = Key(version_key, filename_key);
1568     }
1569
1570   Version_table::const_iterator p = this->version_table_.find(k);
1571   gold_assert(p != this->version_table_.end());
1572
1573   return p->second->index();
1574 }
1575
1576 // Return an allocated buffer holding the contents of the symbol
1577 // version section.
1578
1579 template<int size, bool big_endian>
1580 void
1581 Versions::symbol_section_contents(const Symbol_table* symtab,
1582                                   const Stringpool* dynpool,
1583                                   unsigned int local_symcount,
1584                                   const std::vector<Symbol*>& syms,
1585                                   unsigned char** pp,
1586                                   unsigned int* psize) const
1587 {
1588   gold_assert(this->is_finalized_);
1589
1590   unsigned int sz = (local_symcount + syms.size()) * 2;
1591   unsigned char* pbuf = new unsigned char[sz];
1592
1593   for (unsigned int i = 0; i < local_symcount; ++i)
1594     elfcpp::Swap<16, big_endian>::writeval(pbuf + i * 2,
1595                                            elfcpp::VER_NDX_LOCAL);
1596
1597   for (std::vector<Symbol*>::const_iterator p = syms.begin();
1598        p != syms.end();
1599        ++p)
1600     {
1601       unsigned int version_index;
1602       const char* version = (*p)->version();
1603       if (version == NULL)
1604         version_index = elfcpp::VER_NDX_GLOBAL;
1605       else        
1606         version_index = this->version_index(symtab, dynpool, *p);
1607       // If the symbol was defined as foo@V1 instead of foo@@V1, add
1608       // the hidden bit.
1609       if ((*p)->version() != NULL && !(*p)->is_default())
1610         version_index |= elfcpp::VERSYM_HIDDEN;
1611       elfcpp::Swap<16, big_endian>::writeval(pbuf + (*p)->dynsym_index() * 2,
1612                                              version_index);
1613     }
1614
1615   *pp = pbuf;
1616   *psize = sz;
1617 }
1618
1619 // Return an allocated buffer holding the contents of the version
1620 // definition section.
1621
1622 template<int size, bool big_endian>
1623 void
1624 Versions::def_section_contents(const Stringpool* dynpool,
1625                                unsigned char** pp, unsigned int* psize,
1626                                unsigned int* pentries) const
1627 {
1628   gold_assert(this->is_finalized_);
1629   gold_assert(!this->defs_.empty());
1630
1631   const int verdef_size = elfcpp::Elf_sizes<size>::verdef_size;
1632   const int verdaux_size = elfcpp::Elf_sizes<size>::verdaux_size;
1633
1634   unsigned int sz = 0;
1635   for (Defs::const_iterator p = this->defs_.begin();
1636        p != this->defs_.end();
1637        ++p)
1638     {
1639       sz += verdef_size + verdaux_size;
1640       sz += (*p)->count_dependencies() * verdaux_size;
1641     }
1642
1643   unsigned char* pbuf = new unsigned char[sz];
1644
1645   unsigned char* pb = pbuf;
1646   Defs::const_iterator p;
1647   unsigned int i;
1648   for (p = this->defs_.begin(), i = 0;
1649        p != this->defs_.end();
1650        ++p, ++i)
1651     pb = (*p)->write<size, big_endian>(dynpool,
1652                                        i + 1 >= this->defs_.size(),
1653                                        pb);
1654
1655   gold_assert(static_cast<unsigned int>(pb - pbuf) == sz);
1656
1657   *pp = pbuf;
1658   *psize = sz;
1659   *pentries = this->defs_.size();
1660 }
1661
1662 // Return an allocated buffer holding the contents of the version
1663 // reference section.
1664
1665 template<int size, bool big_endian>
1666 void
1667 Versions::need_section_contents(const Stringpool* dynpool,
1668                                 unsigned char** pp, unsigned int *psize,
1669                                 unsigned int *pentries) const
1670 {
1671   gold_assert(this->is_finalized_);
1672   gold_assert(!this->needs_.empty());
1673
1674   const int verneed_size = elfcpp::Elf_sizes<size>::verneed_size;
1675   const int vernaux_size = elfcpp::Elf_sizes<size>::vernaux_size;
1676
1677   unsigned int sz = 0;
1678   for (Needs::const_iterator p = this->needs_.begin();
1679        p != this->needs_.end();
1680        ++p)
1681     {
1682       sz += verneed_size;
1683       sz += (*p)->count_versions() * vernaux_size;
1684     }
1685
1686   unsigned char* pbuf = new unsigned char[sz];
1687
1688   unsigned char* pb = pbuf;
1689   Needs::const_iterator p;
1690   unsigned int i;
1691   for (p = this->needs_.begin(), i = 0;
1692        p != this->needs_.end();
1693        ++p, ++i)
1694     pb = (*p)->write<size, big_endian>(dynpool,
1695                                        i + 1 >= this->needs_.size(),
1696                                        pb);
1697
1698   gold_assert(static_cast<unsigned int>(pb - pbuf) == sz);
1699
1700   *pp = pbuf;
1701   *psize = sz;
1702   *pentries = this->needs_.size();
1703 }
1704
1705 // Instantiate the templates we need.  We could use the configure
1706 // script to restrict this to only the ones for implemented targets.
1707
1708 #ifdef HAVE_TARGET_32_LITTLE
1709 template
1710 class Sized_dynobj<32, false>;
1711 #endif
1712
1713 #ifdef HAVE_TARGET_32_BIG
1714 template
1715 class Sized_dynobj<32, true>;
1716 #endif
1717
1718 #ifdef HAVE_TARGET_64_LITTLE
1719 template
1720 class Sized_dynobj<64, false>;
1721 #endif
1722
1723 #ifdef HAVE_TARGET_64_BIG
1724 template
1725 class Sized_dynobj<64, true>;
1726 #endif
1727
1728 #ifdef HAVE_TARGET_32_LITTLE
1729 template
1730 void
1731 Versions::symbol_section_contents<32, false>(
1732     const Symbol_table*,
1733     const Stringpool*,
1734     unsigned int,
1735     const std::vector<Symbol*>&,
1736     unsigned char**,
1737     unsigned int*) const;
1738 #endif
1739
1740 #ifdef HAVE_TARGET_32_BIG
1741 template
1742 void
1743 Versions::symbol_section_contents<32, true>(
1744     const Symbol_table*,
1745     const Stringpool*,
1746     unsigned int,
1747     const std::vector<Symbol*>&,
1748     unsigned char**,
1749     unsigned int*) const;
1750 #endif
1751
1752 #ifdef HAVE_TARGET_64_LITTLE
1753 template
1754 void
1755 Versions::symbol_section_contents<64, false>(
1756     const Symbol_table*,
1757     const Stringpool*,
1758     unsigned int,
1759     const std::vector<Symbol*>&,
1760     unsigned char**,
1761     unsigned int*) const;
1762 #endif
1763
1764 #ifdef HAVE_TARGET_64_BIG
1765 template
1766 void
1767 Versions::symbol_section_contents<64, true>(
1768     const Symbol_table*,
1769     const Stringpool*,
1770     unsigned int,
1771     const std::vector<Symbol*>&,
1772     unsigned char**,
1773     unsigned int*) const;
1774 #endif
1775
1776 #ifdef HAVE_TARGET_32_LITTLE
1777 template
1778 void
1779 Versions::def_section_contents<32, false>(
1780     const Stringpool*,
1781     unsigned char**,
1782     unsigned int*,
1783     unsigned int*) const;
1784 #endif
1785
1786 #ifdef HAVE_TARGET_32_BIG
1787 template
1788 void
1789 Versions::def_section_contents<32, true>(
1790     const Stringpool*,
1791     unsigned char**,
1792     unsigned int*,
1793     unsigned int*) const;
1794 #endif
1795
1796 #ifdef HAVE_TARGET_64_LITTLE
1797 template
1798 void
1799 Versions::def_section_contents<64, false>(
1800     const Stringpool*,
1801     unsigned char**,
1802     unsigned int*,
1803     unsigned int*) const;
1804 #endif
1805
1806 #ifdef HAVE_TARGET_64_BIG
1807 template
1808 void
1809 Versions::def_section_contents<64, true>(
1810     const Stringpool*,
1811     unsigned char**,
1812     unsigned int*,
1813     unsigned int*) const;
1814 #endif
1815
1816 #ifdef HAVE_TARGET_32_LITTLE
1817 template
1818 void
1819 Versions::need_section_contents<32, false>(
1820     const Stringpool*,
1821     unsigned char**,
1822     unsigned int*,
1823     unsigned int*) const;
1824 #endif
1825
1826 #ifdef HAVE_TARGET_32_BIG
1827 template
1828 void
1829 Versions::need_section_contents<32, true>(
1830     const Stringpool*,
1831     unsigned char**,
1832     unsigned int*,
1833     unsigned int*) const;
1834 #endif
1835
1836 #ifdef HAVE_TARGET_64_LITTLE
1837 template
1838 void
1839 Versions::need_section_contents<64, false>(
1840     const Stringpool*,
1841     unsigned char**,
1842     unsigned int*,
1843     unsigned int*) const;
1844 #endif
1845
1846 #ifdef HAVE_TARGET_64_BIG
1847 template
1848 void
1849 Versions::need_section_contents<64, true>(
1850     const Stringpool*,
1851     unsigned char**,
1852     unsigned int*,
1853     unsigned int*) const;
1854 #endif
1855
1856 } // End namespace gold.