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