Support compressed debug sections in dynamic object files.
[external/binutils.git] / gold / dynobj.cc
1 // dynobj.cc -- dynamic object support for gold
2
3 // Copyright (C) 2006-2015 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   unsigned int hashlen = ((2
950                            + bucketcount
951                            + local_dynsym_count
952                            + dynsym_count)
953                           * 4);
954   unsigned char* phash = new unsigned char[hashlen];
955
956   if (parameters->target().is_big_endian())
957     {
958 #if defined(HAVE_TARGET_32_BIG) || defined(HAVE_TARGET_64_BIG)
959       Dynobj::sized_create_elf_hash_table<true>(bucket, chain, phash,
960                                                 hashlen);
961 #else
962       gold_unreachable();
963 #endif
964     }
965   else
966     {
967 #if defined(HAVE_TARGET_32_LITTLE) || defined(HAVE_TARGET_64_LITTLE)
968       Dynobj::sized_create_elf_hash_table<false>(bucket, chain, phash,
969                                                  hashlen);
970 #else
971       gold_unreachable();
972 #endif
973     }
974
975   *pphash = phash;
976   *phashlen = hashlen;
977 }
978
979 // Fill in an ELF hash table.
980
981 template<bool big_endian>
982 void
983 Dynobj::sized_create_elf_hash_table(const std::vector<uint32_t>& bucket,
984                                     const std::vector<uint32_t>& chain,
985                                     unsigned char* phash,
986                                     unsigned int hashlen)
987 {
988   unsigned char* p = phash;
989
990   const unsigned int bucketcount = bucket.size();
991   const unsigned int chaincount = chain.size();
992
993   elfcpp::Swap<32, big_endian>::writeval(p, bucketcount);
994   p += 4;
995   elfcpp::Swap<32, big_endian>::writeval(p, chaincount);
996   p += 4;
997
998   for (unsigned int i = 0; i < bucketcount; ++i)
999     {
1000       elfcpp::Swap<32, big_endian>::writeval(p, bucket[i]);
1001       p += 4;
1002     }
1003
1004   for (unsigned int i = 0; i < chaincount; ++i)
1005     {
1006       elfcpp::Swap<32, big_endian>::writeval(p, chain[i]);
1007       p += 4;
1008     }
1009
1010   gold_assert(static_cast<unsigned int>(p - phash) == hashlen);
1011 }
1012
1013 // The hash function used for the GNU hash table.  This hash function
1014 // must not change, as the dynamic linker uses it also.
1015
1016 uint32_t
1017 Dynobj::gnu_hash(const char* name)
1018 {
1019   const unsigned char* nameu = reinterpret_cast<const unsigned char*>(name);
1020   uint32_t h = 5381;
1021   unsigned char c;
1022   while ((c = *nameu++) != '\0')
1023     h = (h << 5) + h + c;
1024   return h;
1025 }
1026
1027 // Create a GNU hash table, setting *PPHASH and *PHASHLEN.  GNU hash
1028 // tables are an extension to ELF which are recognized by the GNU
1029 // dynamic linker.  They are referenced using dynamic tag DT_GNU_HASH.
1030 // TARGET is the target.  DYNSYMS is a vector with all the global
1031 // symbols which will be going into the dynamic symbol table.
1032 // LOCAL_DYNSYM_COUNT is the number of local symbols in the dynamic
1033 // symbol table.
1034
1035 void
1036 Dynobj::create_gnu_hash_table(const std::vector<Symbol*>& dynsyms,
1037                               unsigned int local_dynsym_count,
1038                               unsigned char** pphash,
1039                               unsigned int* phashlen)
1040 {
1041   const unsigned int count = dynsyms.size();
1042
1043   // Sort the dynamic symbols into two vectors.  Symbols which we do
1044   // not want to put into the hash table we store into
1045   // UNHASHED_DYNSYMS.  Symbols which we do want to store we put into
1046   // HASHED_DYNSYMS.  DYNSYM_HASHVALS is parallel to HASHED_DYNSYMS,
1047   // and records the hash codes.
1048
1049   std::vector<Symbol*> unhashed_dynsyms;
1050   unhashed_dynsyms.reserve(count);
1051
1052   std::vector<Symbol*> hashed_dynsyms;
1053   hashed_dynsyms.reserve(count);
1054
1055   std::vector<uint32_t> dynsym_hashvals;
1056   dynsym_hashvals.reserve(count);
1057   
1058   for (unsigned int i = 0; i < count; ++i)
1059     {
1060       Symbol* sym = dynsyms[i];
1061
1062       if (!sym->needs_dynsym_value()
1063           && (sym->is_undefined()
1064               || sym->is_from_dynobj()
1065               || sym->is_forced_local()))
1066         unhashed_dynsyms.push_back(sym);
1067       else
1068         {
1069           hashed_dynsyms.push_back(sym);
1070           dynsym_hashvals.push_back(Dynobj::gnu_hash(sym->name()));
1071         }
1072     }
1073
1074   // Put the unhashed symbols at the start of the global portion of
1075   // the dynamic symbol table.
1076   const unsigned int unhashed_count = unhashed_dynsyms.size();
1077   unsigned int unhashed_dynsym_index = local_dynsym_count;
1078   for (unsigned int i = 0; i < unhashed_count; ++i)
1079     {
1080       unhashed_dynsyms[i]->set_dynsym_index(unhashed_dynsym_index);
1081       ++unhashed_dynsym_index;
1082     }
1083
1084   // For the actual data generation we call out to a templatized
1085   // function.
1086   int size = parameters->target().get_size();
1087   bool big_endian = parameters->target().is_big_endian();
1088   if (size == 32)
1089     {
1090       if (big_endian)
1091         {
1092 #ifdef HAVE_TARGET_32_BIG
1093           Dynobj::sized_create_gnu_hash_table<32, true>(hashed_dynsyms,
1094                                                         dynsym_hashvals,
1095                                                         unhashed_dynsym_index,
1096                                                         pphash,
1097                                                         phashlen);
1098 #else
1099           gold_unreachable();
1100 #endif
1101         }
1102       else
1103         {
1104 #ifdef HAVE_TARGET_32_LITTLE
1105           Dynobj::sized_create_gnu_hash_table<32, false>(hashed_dynsyms,
1106                                                          dynsym_hashvals,
1107                                                          unhashed_dynsym_index,
1108                                                          pphash,
1109                                                          phashlen);
1110 #else
1111           gold_unreachable();
1112 #endif
1113         }
1114     }
1115   else if (size == 64)
1116     {
1117       if (big_endian)
1118         {
1119 #ifdef HAVE_TARGET_64_BIG
1120           Dynobj::sized_create_gnu_hash_table<64, true>(hashed_dynsyms,
1121                                                         dynsym_hashvals,
1122                                                         unhashed_dynsym_index,
1123                                                         pphash,
1124                                                         phashlen);
1125 #else
1126           gold_unreachable();
1127 #endif
1128         }
1129       else
1130         {
1131 #ifdef HAVE_TARGET_64_LITTLE
1132           Dynobj::sized_create_gnu_hash_table<64, false>(hashed_dynsyms,
1133                                                          dynsym_hashvals,
1134                                                          unhashed_dynsym_index,
1135                                                          pphash,
1136                                                          phashlen);
1137 #else
1138           gold_unreachable();
1139 #endif
1140         }
1141     }
1142   else
1143     gold_unreachable();
1144 }
1145
1146 // Create the actual data for a GNU hash table.  This is just a copy
1147 // of the code from the old GNU linker.
1148
1149 template<int size, bool big_endian>
1150 void
1151 Dynobj::sized_create_gnu_hash_table(
1152     const std::vector<Symbol*>& hashed_dynsyms,
1153     const std::vector<uint32_t>& dynsym_hashvals,
1154     unsigned int unhashed_dynsym_count,
1155     unsigned char** pphash,
1156     unsigned int* phashlen)
1157 {
1158   if (hashed_dynsyms.empty())
1159     {
1160       // Special case for the empty hash table.
1161       unsigned int hashlen = 5 * 4 + size / 8;
1162       unsigned char* phash = new unsigned char[hashlen];
1163       // One empty bucket.
1164       elfcpp::Swap<32, big_endian>::writeval(phash, 1);
1165       // Symbol index above unhashed symbols.
1166       elfcpp::Swap<32, big_endian>::writeval(phash + 4, unhashed_dynsym_count);
1167       // One word for bitmask.
1168       elfcpp::Swap<32, big_endian>::writeval(phash + 8, 1);
1169       // Only bloom filter.
1170       elfcpp::Swap<32, big_endian>::writeval(phash + 12, 0);
1171       // No valid hashes.
1172       elfcpp::Swap<size, big_endian>::writeval(phash + 16, 0);
1173       // No hashes in only bucket.
1174       elfcpp::Swap<32, big_endian>::writeval(phash + 16 + size / 8, 0);
1175
1176       *phashlen = hashlen;
1177       *pphash = phash;
1178
1179       return;
1180     }
1181
1182   const unsigned int bucketcount =
1183     Dynobj::compute_bucket_count(dynsym_hashvals, true);
1184
1185   const unsigned int nsyms = hashed_dynsyms.size();
1186
1187   uint32_t maskbitslog2 = 1;
1188   uint32_t x = nsyms >> 1;
1189   while (x != 0)
1190     {
1191       ++maskbitslog2;
1192       x >>= 1;
1193     }
1194   if (maskbitslog2 < 3)
1195     maskbitslog2 = 5;
1196   else if (((1U << (maskbitslog2 - 2)) & nsyms) != 0)
1197     maskbitslog2 += 3;
1198   else
1199     maskbitslog2 += 2;
1200
1201   uint32_t shift1;
1202   if (size == 32)
1203     shift1 = 5;
1204   else
1205     {
1206       if (maskbitslog2 == 5)
1207         maskbitslog2 = 6;
1208       shift1 = 6;
1209     }
1210   uint32_t mask = (1U << shift1) - 1U;
1211   uint32_t shift2 = maskbitslog2;
1212   uint32_t maskbits = 1U << maskbitslog2;
1213   uint32_t maskwords = 1U << (maskbitslog2 - shift1);
1214
1215   typedef typename elfcpp::Elf_types<size>::Elf_WXword Word;
1216   std::vector<Word> bitmask(maskwords);
1217   std::vector<uint32_t> counts(bucketcount);
1218   std::vector<uint32_t> indx(bucketcount);
1219   uint32_t symindx = unhashed_dynsym_count;
1220
1221   // Count the number of times each hash bucket is used.
1222   for (unsigned int i = 0; i < nsyms; ++i)
1223     ++counts[dynsym_hashvals[i] % bucketcount];
1224
1225   unsigned int cnt = symindx;
1226   for (unsigned int i = 0; i < bucketcount; ++i)
1227     {
1228       indx[i] = cnt;
1229       cnt += counts[i];
1230     }
1231
1232   unsigned int hashlen = (4 + bucketcount + nsyms) * 4;
1233   hashlen += maskbits / 8;
1234   unsigned char* phash = new unsigned char[hashlen];
1235
1236   elfcpp::Swap<32, big_endian>::writeval(phash, bucketcount);
1237   elfcpp::Swap<32, big_endian>::writeval(phash + 4, symindx);
1238   elfcpp::Swap<32, big_endian>::writeval(phash + 8, maskwords);
1239   elfcpp::Swap<32, big_endian>::writeval(phash + 12, shift2);
1240
1241   unsigned char* p = phash + 16 + maskbits / 8;
1242   for (unsigned int i = 0; i < bucketcount; ++i)
1243     {
1244       if (counts[i] == 0)
1245         elfcpp::Swap<32, big_endian>::writeval(p, 0);
1246       else
1247         elfcpp::Swap<32, big_endian>::writeval(p, indx[i]);
1248       p += 4;
1249     }
1250
1251   for (unsigned int i = 0; i < nsyms; ++i)
1252     {
1253       Symbol* sym = hashed_dynsyms[i];
1254       uint32_t hashval = dynsym_hashvals[i];
1255
1256       unsigned int bucket = hashval % bucketcount;
1257       unsigned int val = ((hashval >> shift1)
1258                           & ((maskbits >> shift1) - 1));
1259       bitmask[val] |= (static_cast<Word>(1U)) << (hashval & mask);
1260       bitmask[val] |= (static_cast<Word>(1U)) << ((hashval >> shift2) & mask);
1261       val = hashval & ~ 1U;
1262       if (counts[bucket] == 1)
1263         {
1264           // Last element terminates the chain.
1265           val |= 1;
1266         }
1267       elfcpp::Swap<32, big_endian>::writeval(p + (indx[bucket] - symindx) * 4,
1268                                              val);
1269       --counts[bucket];
1270
1271       sym->set_dynsym_index(indx[bucket]);
1272       ++indx[bucket];
1273     }
1274
1275   p = phash + 16;
1276   for (unsigned int i = 0; i < maskwords; ++i)
1277     {
1278       elfcpp::Swap<size, big_endian>::writeval(p, bitmask[i]);
1279       p += size / 8;
1280     }
1281
1282   *phashlen = hashlen;
1283   *pphash = phash;
1284 }
1285
1286 // Verdef methods.
1287
1288 // Write this definition to a buffer for the output section.
1289
1290 template<int size, bool big_endian>
1291 unsigned char*
1292 Verdef::write(const Stringpool* dynpool, bool is_last, unsigned char* pb) const
1293 {
1294   const int verdef_size = elfcpp::Elf_sizes<size>::verdef_size;
1295   const int verdaux_size = elfcpp::Elf_sizes<size>::verdaux_size;
1296
1297   elfcpp::Verdef_write<size, big_endian> vd(pb);
1298   vd.set_vd_version(elfcpp::VER_DEF_CURRENT);
1299   vd.set_vd_flags((this->is_base_ ? elfcpp::VER_FLG_BASE : 0)
1300                   | (this->is_weak_ ? elfcpp::VER_FLG_WEAK : 0)
1301                   | (this->is_info_ ? elfcpp::VER_FLG_INFO : 0));
1302   vd.set_vd_ndx(this->index());
1303   vd.set_vd_cnt(1 + this->deps_.size());
1304   vd.set_vd_hash(Dynobj::elf_hash(this->name()));
1305   vd.set_vd_aux(verdef_size);
1306   vd.set_vd_next(is_last
1307                  ? 0
1308                  : verdef_size + (1 + this->deps_.size()) * verdaux_size);
1309   pb += verdef_size;
1310
1311   elfcpp::Verdaux_write<size, big_endian> vda(pb);
1312   vda.set_vda_name(dynpool->get_offset(this->name()));
1313   vda.set_vda_next(this->deps_.empty() ? 0 : verdaux_size);
1314   pb += verdaux_size;
1315
1316   Deps::const_iterator p;
1317   unsigned int i;
1318   for (p = this->deps_.begin(), i = 0;
1319        p != this->deps_.end();
1320        ++p, ++i)
1321     {
1322       elfcpp::Verdaux_write<size, big_endian> vda(pb);
1323       vda.set_vda_name(dynpool->get_offset(*p));
1324       vda.set_vda_next(i + 1 >= this->deps_.size() ? 0 : verdaux_size);
1325       pb += verdaux_size;
1326     }
1327
1328   return pb;
1329 }
1330
1331 // Verneed methods.
1332
1333 Verneed::~Verneed()
1334 {
1335   for (Need_versions::iterator p = this->need_versions_.begin();
1336        p != this->need_versions_.end();
1337        ++p)
1338     delete *p;
1339 }
1340
1341 // Add a new version to this file reference.
1342
1343 Verneed_version*
1344 Verneed::add_name(const char* name)
1345 {
1346   Verneed_version* vv = new Verneed_version(name);
1347   this->need_versions_.push_back(vv);
1348   return vv;
1349 }
1350
1351 // Set the version indexes starting at INDEX.
1352
1353 unsigned int
1354 Verneed::finalize(unsigned int index)
1355 {
1356   for (Need_versions::iterator p = this->need_versions_.begin();
1357        p != this->need_versions_.end();
1358        ++p)
1359     {
1360       (*p)->set_index(index);
1361       ++index;
1362     }
1363   return index;
1364 }
1365
1366 // Write this list of referenced versions to a buffer for the output
1367 // section.
1368
1369 template<int size, bool big_endian>
1370 unsigned char*
1371 Verneed::write(const Stringpool* dynpool, bool is_last,
1372                unsigned char* pb) const
1373 {
1374   const int verneed_size = elfcpp::Elf_sizes<size>::verneed_size;
1375   const int vernaux_size = elfcpp::Elf_sizes<size>::vernaux_size;
1376
1377   elfcpp::Verneed_write<size, big_endian> vn(pb);
1378   vn.set_vn_version(elfcpp::VER_NEED_CURRENT);
1379   vn.set_vn_cnt(this->need_versions_.size());
1380   vn.set_vn_file(dynpool->get_offset(this->filename()));
1381   vn.set_vn_aux(verneed_size);
1382   vn.set_vn_next(is_last
1383                  ? 0
1384                  : verneed_size + this->need_versions_.size() * vernaux_size);
1385   pb += verneed_size;
1386
1387   Need_versions::const_iterator p;
1388   unsigned int i;
1389   for (p = this->need_versions_.begin(), i = 0;
1390        p != this->need_versions_.end();
1391        ++p, ++i)
1392     {
1393       elfcpp::Vernaux_write<size, big_endian> vna(pb);
1394       vna.set_vna_hash(Dynobj::elf_hash((*p)->version()));
1395       // FIXME: We need to sometimes set VER_FLG_WEAK here.
1396       vna.set_vna_flags(0);
1397       vna.set_vna_other((*p)->index());
1398       vna.set_vna_name(dynpool->get_offset((*p)->version()));
1399       vna.set_vna_next(i + 1 >= this->need_versions_.size()
1400                        ? 0
1401                        : vernaux_size);
1402       pb += vernaux_size;
1403     }
1404
1405   return pb;
1406 }
1407
1408 // Versions methods.
1409
1410 Versions::Versions(const Version_script_info& version_script,
1411                    Stringpool* dynpool)
1412   : defs_(), needs_(), version_table_(),
1413     is_finalized_(false), version_script_(version_script),
1414     needs_base_version_(parameters->options().shared())
1415 {
1416   if (!this->version_script_.empty())
1417     {
1418       // Parse the version script, and insert each declared version into
1419       // defs_ and version_table_.
1420       std::vector<std::string> versions = this->version_script_.get_versions();
1421
1422       if (this->needs_base_version_ && !versions.empty())
1423         this->define_base_version(dynpool);
1424
1425       for (size_t k = 0; k < versions.size(); ++k)
1426         {
1427           Stringpool::Key version_key;
1428           const char* version = dynpool->add(versions[k].c_str(),
1429                                              true, &version_key);
1430           Verdef* const vd = new Verdef(
1431               version,
1432               this->version_script_.get_dependencies(version),
1433               false, false, false, false);
1434           this->defs_.push_back(vd);
1435           Key key(version_key, 0);
1436           this->version_table_.insert(std::make_pair(key, vd));
1437         }
1438     }
1439 }
1440
1441 Versions::~Versions()
1442 {
1443   for (Defs::iterator p = this->defs_.begin();
1444        p != this->defs_.end();
1445        ++p)
1446     delete *p;
1447
1448   for (Needs::iterator p = this->needs_.begin();
1449        p != this->needs_.end();
1450        ++p)
1451     delete *p;
1452 }
1453
1454 // Define the base version of a shared library.  The base version definition
1455 // must be the first entry in defs_.  We insert it lazily so that defs_ is
1456 // empty if no symbol versioning is used.  Then layout can just drop the
1457 // version sections.
1458
1459 void
1460 Versions::define_base_version(Stringpool* dynpool)
1461 {
1462   // If we do any versioning at all,  we always need a base version, so
1463   // define that first.  Nothing explicitly declares itself as part of base,
1464   // so it doesn't need to be in version_table_.
1465   gold_assert(this->defs_.empty());
1466   const char* name = parameters->options().soname();
1467   if (name == NULL)
1468     name = parameters->options().output_file_name();
1469   name = dynpool->add(name, false, NULL);
1470   Verdef* vdbase = new Verdef(name, std::vector<std::string>(),
1471                               true, false, false, true);
1472   this->defs_.push_back(vdbase);
1473   this->needs_base_version_ = false;
1474 }
1475
1476 // Return the dynamic object which a symbol refers to.
1477
1478 Dynobj*
1479 Versions::get_dynobj_for_sym(const Symbol_table* symtab,
1480                              const Symbol* sym) const
1481 {
1482   if (sym->is_copied_from_dynobj())
1483     return symtab->get_copy_source(sym);
1484   else
1485     {
1486       Object* object = sym->object();
1487       gold_assert(object->is_dynamic());
1488       return static_cast<Dynobj*>(object);
1489     }
1490 }
1491
1492 // Record version information for a symbol going into the dynamic
1493 // symbol table.
1494
1495 void
1496 Versions::record_version(const Symbol_table* symtab,
1497                          Stringpool* dynpool, const Symbol* sym)
1498 {
1499   gold_assert(!this->is_finalized_);
1500   gold_assert(sym->version() != NULL);
1501
1502   Stringpool::Key version_key;
1503   const char* version = dynpool->add(sym->version(), false, &version_key);
1504
1505   if (!sym->is_from_dynobj() && !sym->is_copied_from_dynobj())
1506     {
1507       if (parameters->options().shared())
1508         this->add_def(dynpool, sym, version, version_key);
1509     }
1510   else
1511     {
1512       // This is a version reference.
1513       Dynobj* dynobj = this->get_dynobj_for_sym(symtab, sym);
1514       this->add_need(dynpool, dynobj->soname(), version, version_key);
1515     }
1516 }
1517
1518 // We've found a symbol SYM defined in version VERSION.
1519
1520 void
1521 Versions::add_def(Stringpool* dynpool, const Symbol* sym, const char* version,
1522                   Stringpool::Key version_key)
1523 {
1524   Key k(version_key, 0);
1525   Version_base* const vbnull = NULL;
1526   std::pair<Version_table::iterator, bool> ins =
1527     this->version_table_.insert(std::make_pair(k, vbnull));
1528
1529   if (!ins.second)
1530     {
1531       // We already have an entry for this version.
1532       Version_base* vb = ins.first->second;
1533
1534       // We have now seen a symbol in this version, so it is not
1535       // weak.
1536       gold_assert(vb != NULL);
1537       vb->clear_weak();
1538     }
1539   else
1540     {
1541       // If we are creating a shared object, it is an error to
1542       // find a definition of a symbol with a version which is not
1543       // in the version script.
1544       if (parameters->options().shared())
1545         {
1546           gold_error(_("symbol %s has undefined version %s"),
1547                      sym->demangled_name().c_str(), version);
1548           if (this->needs_base_version_)
1549             this->define_base_version(dynpool);
1550         }
1551       else
1552         // We only insert a base version for shared library.
1553         gold_assert(!this->needs_base_version_);
1554         
1555       // When creating a regular executable, automatically define
1556       // a new version.
1557       Verdef* vd = new Verdef(version, std::vector<std::string>(),
1558                               false, false, false, false);
1559       this->defs_.push_back(vd);
1560       ins.first->second = vd;
1561     }
1562 }
1563
1564 // Add a reference to version NAME in file FILENAME.
1565
1566 void
1567 Versions::add_need(Stringpool* dynpool, const char* filename, const char* name,
1568                    Stringpool::Key name_key)
1569 {
1570   Stringpool::Key filename_key;
1571   filename = dynpool->add(filename, true, &filename_key);
1572
1573   Key k(name_key, filename_key);
1574   Version_base* const vbnull = NULL;
1575   std::pair<Version_table::iterator, bool> ins =
1576     this->version_table_.insert(std::make_pair(k, vbnull));
1577
1578   if (!ins.second)
1579     {
1580       // We already have an entry for this filename/version.
1581       return;
1582     }
1583
1584   // See whether we already have this filename.  We don't expect many
1585   // version references, so we just do a linear search.  This could be
1586   // replaced by a hash table.
1587   Verneed* vn = NULL;
1588   for (Needs::iterator p = this->needs_.begin();
1589        p != this->needs_.end();
1590        ++p)
1591     {
1592       if ((*p)->filename() == filename)
1593         {
1594           vn = *p;
1595           break;
1596         }
1597     }
1598
1599   if (vn == NULL)
1600     {
1601       // Create base version definition lazily for shared library.
1602       if (this->needs_base_version_)
1603         this->define_base_version(dynpool);
1604
1605       // We have a new filename.
1606       vn = new Verneed(filename);
1607       this->needs_.push_back(vn);
1608     }
1609
1610   ins.first->second = vn->add_name(name);
1611 }
1612
1613 // Set the version indexes.  Create a new dynamic version symbol for
1614 // each new version definition.
1615
1616 unsigned int
1617 Versions::finalize(Symbol_table* symtab, unsigned int dynsym_index,
1618                    std::vector<Symbol*>* syms)
1619 {
1620   gold_assert(!this->is_finalized_);
1621
1622   unsigned int vi = 1;
1623
1624   for (Defs::iterator p = this->defs_.begin();
1625        p != this->defs_.end();
1626        ++p)
1627     {
1628       (*p)->set_index(vi);
1629       ++vi;
1630
1631       // Create a version symbol if necessary.
1632       if (!(*p)->is_symbol_created())
1633         {
1634           Symbol* vsym = symtab->define_as_constant((*p)->name(),
1635                                                     (*p)->name(),
1636                                                     Symbol_table::PREDEFINED,
1637                                                     0, 0,
1638                                                     elfcpp::STT_OBJECT,
1639                                                     elfcpp::STB_GLOBAL,
1640                                                     elfcpp::STV_DEFAULT, 0,
1641                                                     false, false);
1642           vsym->set_needs_dynsym_entry();
1643           vsym->set_dynsym_index(dynsym_index);
1644           vsym->set_is_default();
1645           ++dynsym_index;
1646           syms->push_back(vsym);
1647           // The name is already in the dynamic pool.
1648         }
1649     }
1650
1651   // Index 1 is used for global symbols.
1652   if (vi == 1)
1653     {
1654       gold_assert(this->defs_.empty());
1655       vi = 2;
1656     }
1657
1658   for (Needs::iterator p = this->needs_.begin();
1659        p != this->needs_.end();
1660        ++p)
1661     vi = (*p)->finalize(vi);
1662
1663   this->is_finalized_ = true;
1664
1665   return dynsym_index;
1666 }
1667
1668 // Return the version index to use for a symbol.  This does two hash
1669 // table lookups: one in DYNPOOL and one in this->version_table_.
1670 // Another approach alternative would be store a pointer in SYM, which
1671 // would increase the size of the symbol table.  Or perhaps we could
1672 // use a hash table from dynamic symbol pointer values to Version_base
1673 // pointers.
1674
1675 unsigned int
1676 Versions::version_index(const Symbol_table* symtab, const Stringpool* dynpool,
1677                         const Symbol* sym) const
1678 {
1679   Stringpool::Key version_key;
1680   const char* version = dynpool->find(sym->version(), &version_key);
1681   gold_assert(version != NULL);
1682
1683   Key k;
1684   if (!sym->is_from_dynobj() && !sym->is_copied_from_dynobj())
1685     {
1686       if (!parameters->options().shared())
1687         return elfcpp::VER_NDX_GLOBAL;
1688       k = Key(version_key, 0);
1689     }
1690   else
1691     {
1692       Dynobj* dynobj = this->get_dynobj_for_sym(symtab, sym);
1693
1694       Stringpool::Key filename_key;
1695       const char* filename = dynpool->find(dynobj->soname(), &filename_key);
1696       gold_assert(filename != NULL);
1697
1698       k = Key(version_key, filename_key);
1699     }
1700
1701   Version_table::const_iterator p = this->version_table_.find(k);
1702   gold_assert(p != this->version_table_.end());
1703
1704   return p->second->index();
1705 }
1706
1707 // Return an allocated buffer holding the contents of the symbol
1708 // version section.
1709
1710 template<int size, bool big_endian>
1711 void
1712 Versions::symbol_section_contents(const Symbol_table* symtab,
1713                                   const Stringpool* dynpool,
1714                                   unsigned int local_symcount,
1715                                   const std::vector<Symbol*>& syms,
1716                                   unsigned char** pp,
1717                                   unsigned int* psize) const
1718 {
1719   gold_assert(this->is_finalized_);
1720
1721   unsigned int sz = (local_symcount + syms.size()) * 2;
1722   unsigned char* pbuf = new unsigned char[sz];
1723
1724   for (unsigned int i = 0; i < local_symcount; ++i)
1725     elfcpp::Swap<16, big_endian>::writeval(pbuf + i * 2,
1726                                            elfcpp::VER_NDX_LOCAL);
1727
1728   for (std::vector<Symbol*>::const_iterator p = syms.begin();
1729        p != syms.end();
1730        ++p)
1731     {
1732       unsigned int version_index;
1733       const char* version = (*p)->version();
1734       if (version != NULL)
1735         version_index = this->version_index(symtab, dynpool, *p);
1736       else
1737         {
1738           if ((*p)->is_defined() && !(*p)->is_from_dynobj())
1739             version_index = elfcpp::VER_NDX_GLOBAL;
1740           else
1741             version_index = elfcpp::VER_NDX_LOCAL;
1742         }
1743       // If the symbol was defined as foo@V1 instead of foo@@V1, add
1744       // the hidden bit.
1745       if ((*p)->version() != NULL && !(*p)->is_default())
1746         version_index |= elfcpp::VERSYM_HIDDEN;
1747       elfcpp::Swap<16, big_endian>::writeval(pbuf + (*p)->dynsym_index() * 2,
1748                                              version_index);
1749     }
1750
1751   *pp = pbuf;
1752   *psize = sz;
1753 }
1754
1755 // Return an allocated buffer holding the contents of the version
1756 // definition section.
1757
1758 template<int size, bool big_endian>
1759 void
1760 Versions::def_section_contents(const Stringpool* dynpool,
1761                                unsigned char** pp, unsigned int* psize,
1762                                unsigned int* pentries) const
1763 {
1764   gold_assert(this->is_finalized_);
1765   gold_assert(!this->defs_.empty());
1766
1767   const int verdef_size = elfcpp::Elf_sizes<size>::verdef_size;
1768   const int verdaux_size = elfcpp::Elf_sizes<size>::verdaux_size;
1769
1770   unsigned int sz = 0;
1771   for (Defs::const_iterator p = this->defs_.begin();
1772        p != this->defs_.end();
1773        ++p)
1774     {
1775       sz += verdef_size + verdaux_size;
1776       sz += (*p)->count_dependencies() * verdaux_size;
1777     }
1778
1779   unsigned char* pbuf = new unsigned char[sz];
1780
1781   unsigned char* pb = pbuf;
1782   Defs::const_iterator p;
1783   unsigned int i;
1784   for (p = this->defs_.begin(), i = 0;
1785        p != this->defs_.end();
1786        ++p, ++i)
1787     pb = (*p)->write<size, big_endian>(dynpool,
1788                                        i + 1 >= this->defs_.size(),
1789                                        pb);
1790
1791   gold_assert(static_cast<unsigned int>(pb - pbuf) == sz);
1792
1793   *pp = pbuf;
1794   *psize = sz;
1795   *pentries = this->defs_.size();
1796 }
1797
1798 // Return an allocated buffer holding the contents of the version
1799 // reference section.
1800
1801 template<int size, bool big_endian>
1802 void
1803 Versions::need_section_contents(const Stringpool* dynpool,
1804                                 unsigned char** pp, unsigned int* psize,
1805                                 unsigned int* pentries) const
1806 {
1807   gold_assert(this->is_finalized_);
1808   gold_assert(!this->needs_.empty());
1809
1810   const int verneed_size = elfcpp::Elf_sizes<size>::verneed_size;
1811   const int vernaux_size = elfcpp::Elf_sizes<size>::vernaux_size;
1812
1813   unsigned int sz = 0;
1814   for (Needs::const_iterator p = this->needs_.begin();
1815        p != this->needs_.end();
1816        ++p)
1817     {
1818       sz += verneed_size;
1819       sz += (*p)->count_versions() * vernaux_size;
1820     }
1821
1822   unsigned char* pbuf = new unsigned char[sz];
1823
1824   unsigned char* pb = pbuf;
1825   Needs::const_iterator p;
1826   unsigned int i;
1827   for (p = this->needs_.begin(), i = 0;
1828        p != this->needs_.end();
1829        ++p, ++i)
1830     pb = (*p)->write<size, big_endian>(dynpool,
1831                                        i + 1 >= this->needs_.size(),
1832                                        pb);
1833
1834   gold_assert(static_cast<unsigned int>(pb - pbuf) == sz);
1835
1836   *pp = pbuf;
1837   *psize = sz;
1838   *pentries = this->needs_.size();
1839 }
1840
1841 // Instantiate the templates we need.  We could use the configure
1842 // script to restrict this to only the ones for implemented targets.
1843
1844 #ifdef HAVE_TARGET_32_LITTLE
1845 template
1846 class Sized_dynobj<32, false>;
1847 #endif
1848
1849 #ifdef HAVE_TARGET_32_BIG
1850 template
1851 class Sized_dynobj<32, true>;
1852 #endif
1853
1854 #ifdef HAVE_TARGET_64_LITTLE
1855 template
1856 class Sized_dynobj<64, false>;
1857 #endif
1858
1859 #ifdef HAVE_TARGET_64_BIG
1860 template
1861 class Sized_dynobj<64, true>;
1862 #endif
1863
1864 #ifdef HAVE_TARGET_32_LITTLE
1865 template
1866 void
1867 Versions::symbol_section_contents<32, false>(
1868     const Symbol_table*,
1869     const Stringpool*,
1870     unsigned int,
1871     const std::vector<Symbol*>&,
1872     unsigned char**,
1873     unsigned int*) const;
1874 #endif
1875
1876 #ifdef HAVE_TARGET_32_BIG
1877 template
1878 void
1879 Versions::symbol_section_contents<32, true>(
1880     const Symbol_table*,
1881     const Stringpool*,
1882     unsigned int,
1883     const std::vector<Symbol*>&,
1884     unsigned char**,
1885     unsigned int*) const;
1886 #endif
1887
1888 #ifdef HAVE_TARGET_64_LITTLE
1889 template
1890 void
1891 Versions::symbol_section_contents<64, false>(
1892     const Symbol_table*,
1893     const Stringpool*,
1894     unsigned int,
1895     const std::vector<Symbol*>&,
1896     unsigned char**,
1897     unsigned int*) const;
1898 #endif
1899
1900 #ifdef HAVE_TARGET_64_BIG
1901 template
1902 void
1903 Versions::symbol_section_contents<64, true>(
1904     const Symbol_table*,
1905     const Stringpool*,
1906     unsigned int,
1907     const std::vector<Symbol*>&,
1908     unsigned char**,
1909     unsigned int*) const;
1910 #endif
1911
1912 #ifdef HAVE_TARGET_32_LITTLE
1913 template
1914 void
1915 Versions::def_section_contents<32, false>(
1916     const Stringpool*,
1917     unsigned char**,
1918     unsigned int*,
1919     unsigned int*) const;
1920 #endif
1921
1922 #ifdef HAVE_TARGET_32_BIG
1923 template
1924 void
1925 Versions::def_section_contents<32, true>(
1926     const Stringpool*,
1927     unsigned char**,
1928     unsigned int*,
1929     unsigned int*) const;
1930 #endif
1931
1932 #ifdef HAVE_TARGET_64_LITTLE
1933 template
1934 void
1935 Versions::def_section_contents<64, false>(
1936     const Stringpool*,
1937     unsigned char**,
1938     unsigned int*,
1939     unsigned int*) const;
1940 #endif
1941
1942 #ifdef HAVE_TARGET_64_BIG
1943 template
1944 void
1945 Versions::def_section_contents<64, true>(
1946     const Stringpool*,
1947     unsigned char**,
1948     unsigned int*,
1949     unsigned int*) const;
1950 #endif
1951
1952 #ifdef HAVE_TARGET_32_LITTLE
1953 template
1954 void
1955 Versions::need_section_contents<32, false>(
1956     const Stringpool*,
1957     unsigned char**,
1958     unsigned int*,
1959     unsigned int*) const;
1960 #endif
1961
1962 #ifdef HAVE_TARGET_32_BIG
1963 template
1964 void
1965 Versions::need_section_contents<32, true>(
1966     const Stringpool*,
1967     unsigned char**,
1968     unsigned int*,
1969     unsigned int*) const;
1970 #endif
1971
1972 #ifdef HAVE_TARGET_64_LITTLE
1973 template
1974 void
1975 Versions::need_section_contents<64, false>(
1976     const Stringpool*,
1977     unsigned char**,
1978     unsigned int*,
1979     unsigned int*) const;
1980 #endif
1981
1982 #ifdef HAVE_TARGET_64_BIG
1983 template
1984 void
1985 Versions::need_section_contents<64, true>(
1986     const Stringpool*,
1987     unsigned char**,
1988     unsigned int*,
1989     unsigned int*) const;
1990 #endif
1991
1992 } // End namespace gold.