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