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