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