2009-10-21 Doug Kwan <dougkwan@google.com>
[platform/upstream/binutils.git] / gold / stringpool.cc
1 // stringpool.cc -- a string pool 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 <cstring>
26 #include <algorithm>
27 #include <vector>
28
29 #include "output.h"
30 #include "parameters.h"
31 #include "stringpool.h"
32
33 namespace gold
34 {
35
36 template<typename Stringpool_char>
37 Stringpool_template<Stringpool_char>::Stringpool_template()
38   : string_set_(), key_to_offset_(), strings_(), strtab_size_(0),
39     zero_null_(true), optimize_(false)
40 {
41   if (parameters->options_valid() && parameters->options().optimize() >= 2)
42     this->optimize_ = true;
43 }
44
45 template<typename Stringpool_char>
46 void
47 Stringpool_template<Stringpool_char>::clear()
48 {
49   for (typename std::list<Stringdata*>::iterator p = this->strings_.begin();
50        p != this->strings_.end();
51        ++p)
52     delete[] reinterpret_cast<char*>(*p);
53   this->strings_.clear();
54   this->key_to_offset_.clear();
55   this->string_set_.clear();
56 }
57
58 template<typename Stringpool_char>
59 Stringpool_template<Stringpool_char>::~Stringpool_template()
60 {
61   this->clear();
62 }
63
64 // Resize the internal hashtable with the expectation we'll get n new
65 // elements.  Note that the hashtable constructor takes a "number of
66 // buckets you'd like," rather than "number of elements you'd like,"
67 // but that's the best we can do.
68
69 template<typename Stringpool_char>
70 void
71 Stringpool_template<Stringpool_char>::reserve(unsigned int n)
72 {
73   this->key_to_offset_.reserve(n);
74
75 #if defined(HAVE_TR1_UNORDERED_MAP)
76   // rehash() implementation is broken in gcc 4.0.3's stl
77   //this->string_set_.rehash(this->string_set_.size() + n);
78   //return;
79 #elif defined(HAVE_EXT_HASH_MAP)
80   this->string_set_.resize(this->string_set_.size() + n);
81   return;
82 #endif
83
84   // This is the generic "reserve" code, if no #ifdef above triggers.
85   String_set_type new_string_set(this->string_set_.size() + n);
86   new_string_set.insert(this->string_set_.begin(), this->string_set_.end());
87   this->string_set_.swap(new_string_set);
88 }
89
90 // Return the length of a string of arbitrary character type.
91
92 template<typename Stringpool_char>
93 size_t
94 Stringpool_template<Stringpool_char>::string_length(const Stringpool_char* p)
95 {
96   size_t len = 0;
97   for (; *p != 0; ++p)
98     ++len;
99   return len;
100 }
101
102 // Specialize string_length for char.  Maybe we could just use
103 // std::char_traits<>::length?
104
105 template<>
106 inline size_t
107 Stringpool_template<char>::string_length(const char* p)
108 {
109   return strlen(p);
110 }
111
112 // Compare two strings of arbitrary character type for equality.
113
114 template<typename Stringpool_char>
115 bool
116 Stringpool_template<Stringpool_char>::string_equal(const Stringpool_char* s1,
117                                                    const Stringpool_char* s2)
118 {
119   while (*s1 != 0)
120     if (*s1++ != *s2++)
121       return false;
122   return *s2 == 0;
123 }
124
125 // Specialize string_equal for char.
126
127 template<>
128 inline bool
129 Stringpool_template<char>::string_equal(const char* s1, const char* s2)
130 {
131   return strcmp(s1, s2) == 0;
132 }
133
134 // Equality comparison function for the hash table.
135
136 template<typename Stringpool_char>
137 inline bool
138 Stringpool_template<Stringpool_char>::Stringpool_eq::operator()(
139     const Hashkey& h1,
140     const Hashkey& h2) const
141 {
142   return (h1.hash_code == h2.hash_code
143           && h1.length == h2.length
144           && (h1.string == h2.string
145               || memcmp(h1.string, h2.string,
146                         h1.length * sizeof(Stringpool_char)) == 0));
147 }
148
149 // Hash function.  The length is in characters, not bytes.
150
151 template<typename Stringpool_char>
152 size_t
153 Stringpool_template<Stringpool_char>::string_hash(const Stringpool_char* s,
154                                                   size_t length)
155 {
156   return gold::string_hash<Stringpool_char>(s, length);
157 }
158
159 // Add the string S to the list of canonical strings.  Return a
160 // pointer to the canonical string.  If PKEY is not NULL, set *PKEY to
161 // the key.  LENGTH is the length of S in characters.  Note that S may
162 // not be NUL terminated.
163
164 template<typename Stringpool_char>
165 const Stringpool_char*
166 Stringpool_template<Stringpool_char>::add_string(const Stringpool_char* s,
167                                                  size_t len)
168 {
169   // We are in trouble if we've already computed the string offsets.
170   gold_assert(this->strtab_size_ == 0);
171
172   // The size we allocate for a new Stringdata.
173   const size_t buffer_size = 1000;
174   // The amount we multiply the Stringdata index when calculating the
175   // key.
176   const size_t key_mult = 1024;
177   gold_assert(key_mult >= buffer_size);
178
179   // Convert len to the number of bytes we need to allocate, including
180   // the null character.
181   len = (len + 1) * sizeof(Stringpool_char);
182
183   size_t alc;
184   bool front = true;
185   if (len > buffer_size)
186     {
187       alc = sizeof(Stringdata) + len;
188       front = false;
189     }
190   else if (this->strings_.empty())
191     alc = sizeof(Stringdata) + buffer_size;
192   else
193     {
194       Stringdata *psd = this->strings_.front();
195       if (len > psd->alc - psd->len)
196         alc = sizeof(Stringdata) + buffer_size;
197       else
198         {
199           char* ret = psd->data + psd->len;
200           memcpy(ret, s, len - sizeof(Stringpool_char));
201           memset(ret + len - sizeof(Stringpool_char), 0,
202                  sizeof(Stringpool_char));
203
204           psd->len += len;
205
206           return reinterpret_cast<const Stringpool_char*>(ret);
207         }
208     }
209
210   Stringdata *psd = reinterpret_cast<Stringdata*>(new char[alc]);
211   psd->alc = alc - sizeof(Stringdata);
212   memcpy(psd->data, s, len - sizeof(Stringpool_char));
213   memset(psd->data + len - sizeof(Stringpool_char), 0,
214          sizeof(Stringpool_char));
215   psd->len = len;
216
217   if (front)
218     this->strings_.push_front(psd);
219   else
220     this->strings_.push_back(psd);
221
222   return reinterpret_cast<const Stringpool_char*>(psd->data);
223 }
224
225 // Add a string to a string pool.
226
227 template<typename Stringpool_char>
228 const Stringpool_char*
229 Stringpool_template<Stringpool_char>::add(const Stringpool_char* s, bool copy,
230                                           Key* pkey)
231 {
232   return this->add_with_length(s, string_length(s), copy, pkey);
233 }
234
235 template<typename Stringpool_char>
236 const Stringpool_char*
237 Stringpool_template<Stringpool_char>::add_with_length(const Stringpool_char* s,
238                                                       size_t length,
239                                                       bool copy,
240                                                       Key* pkey)
241 {
242   typedef std::pair<typename String_set_type::iterator, bool> Insert_type;
243
244   // We add 1 so that 0 is always invalid.
245   const Key k = this->key_to_offset_.size() + 1;
246
247   if (!copy)
248     {
249       // When we don't need to copy the string, we can call insert
250       // directly.
251
252       std::pair<Hashkey, Hashval> element(Hashkey(s, length), k);
253
254       Insert_type ins = this->string_set_.insert(element);
255
256       typename String_set_type::const_iterator p = ins.first;
257
258       if (ins.second)
259         {
260           // We just added the string.  The key value has now been
261           // used.
262           this->key_to_offset_.push_back(0);
263         }
264       else
265         {
266           gold_assert(k != p->second);
267         }
268
269       if (pkey != NULL)
270         *pkey = p->second;
271       return p->first.string;
272     }
273
274   // When we have to copy the string, we look it up twice in the hash
275   // table.  The problem is that we can't insert S before we
276   // canonicalize it by copying it into the canonical list. The hash
277   // code will only be computed once.
278
279   Hashkey hk(s, length);
280   typename String_set_type::const_iterator p = this->string_set_.find(hk);
281   if (p != this->string_set_.end())
282     {
283       if (pkey != NULL)
284         *pkey = p->second;
285       return p->first.string;
286     }
287
288   this->key_to_offset_.push_back(0);
289
290   hk.string = this->add_string(s, length);
291   // The contents of the string stay the same, so we don't need to
292   // adjust hk.hash_code or hk.length.
293
294   std::pair<Hashkey, Hashval> element(hk, k);
295
296   Insert_type ins = this->string_set_.insert(element);
297   gold_assert(ins.second);
298
299   if (pkey != NULL)
300     *pkey = k;
301   return hk.string;
302 }
303
304 template<typename Stringpool_char>
305 const Stringpool_char*
306 Stringpool_template<Stringpool_char>::find(const Stringpool_char* s,
307                                            Key* pkey) const
308 {
309   Hashkey hk(s);
310   typename String_set_type::const_iterator p = this->string_set_.find(hk);
311   if (p == this->string_set_.end())
312     return NULL;
313
314   if (pkey != NULL)
315     *pkey = p->second;
316
317   return p->first.string;
318 }
319
320 // Comparison routine used when sorting into an ELF strtab.  We want
321 // to sort this so that when one string is a suffix of another, we
322 // always see the shorter string immediately after the longer string.
323 // For example, we want to see these strings in this order:
324 //   abcd
325 //   cd
326 //   d
327 // When strings are not suffixes, we don't care what order they are
328 // in, but we need to ensure that suffixes wind up next to each other.
329 // So we do a reversed lexicographic sort on the reversed string.
330
331 template<typename Stringpool_char>
332 bool
333 Stringpool_template<Stringpool_char>::Stringpool_sort_comparison::operator()(
334   const Stringpool_sort_info& sort_info1,
335   const Stringpool_sort_info& sort_info2) const
336 {
337   const Hashkey& h1(sort_info1->first);
338   const Hashkey& h2(sort_info2->first);
339   const Stringpool_char* s1 = h1.string;
340   const Stringpool_char* s2 = h2.string;
341   const size_t len1 = h1.length;
342   const size_t len2 = h2.length;
343   const size_t minlen = len1 < len2 ? len1 : len2;
344   const Stringpool_char* p1 = s1 + len1 - 1;
345   const Stringpool_char* p2 = s2 + len2 - 1;
346   for (size_t i = minlen; i > 0; --i, --p1, --p2)
347     {
348       if (*p1 != *p2)
349         return *p1 > *p2;
350     }
351   return len1 > len2;
352 }
353
354 // Return whether s1 is a suffix of s2.
355
356 template<typename Stringpool_char>
357 bool
358 Stringpool_template<Stringpool_char>::is_suffix(const Stringpool_char* s1,
359                                                 size_t len1,
360                                                 const Stringpool_char* s2,
361                                                 size_t len2)
362 {
363   if (len1 > len2)
364     return false;
365   return memcmp(s1, s2 + len2 - len1, len1 * sizeof(Stringpool_char)) == 0;
366 }
367
368 // Turn the stringpool into an ELF strtab: determine the offsets of
369 // each string in the table.
370
371 template<typename Stringpool_char>
372 void
373 Stringpool_template<Stringpool_char>::set_string_offsets()
374 {
375   if (this->strtab_size_ != 0)
376     {
377       // We've already computed the offsets.
378       return;
379     }
380
381   const size_t charsize = sizeof(Stringpool_char);
382
383   // Offset 0 may be reserved for the empty string.
384   section_offset_type offset = this->zero_null_ ? charsize : 0;
385
386   // Sorting to find suffixes can take over 25% of the total CPU time
387   // used by the linker.  Since it's merely an optimization to reduce
388   // the strtab size, and gives a relatively small benefit (it's
389   // typically rare for a symbol to be a suffix of another), we only
390   // take the time to sort when the user asks for heavy optimization.
391   if (!this->optimize_)
392     {
393       for (typename String_set_type::iterator curr = this->string_set_.begin();
394            curr != this->string_set_.end();
395            curr++)
396         {
397           section_offset_type* poff = &this->key_to_offset_[curr->second - 1];
398           if (this->zero_null_ && curr->first.string[0] == 0)
399             *poff = 0;
400           else
401             {
402               *poff = offset;
403               offset += (curr->first.length + 1) * charsize;
404             }
405         }
406     }
407   else
408     {
409       size_t count = this->string_set_.size();
410
411       std::vector<Stringpool_sort_info> v;
412       v.reserve(count);
413
414       for (typename String_set_type::iterator p = this->string_set_.begin();
415            p != this->string_set_.end();
416            ++p)
417         v.push_back(Stringpool_sort_info(p));
418
419       std::sort(v.begin(), v.end(), Stringpool_sort_comparison());
420
421       section_offset_type last_offset = -1;
422       for (typename std::vector<Stringpool_sort_info>::iterator last = v.end(),
423              curr = v.begin();
424            curr != v.end();
425            last = curr++)
426         {
427           section_offset_type this_offset;
428           if (this->zero_null_ && (*curr)->first.string[0] == 0)
429             this_offset = 0;
430           else if (last != v.end()
431                    && is_suffix((*curr)->first.string,
432                                 (*curr)->first.length,
433                                 (*last)->first.string,
434                                 (*last)->first.length))
435             this_offset = (last_offset
436                            + (((*last)->first.length - (*curr)->first.length)
437                               * charsize));
438           else
439             {
440               this_offset = offset;
441               offset += ((*curr)->first.length + 1) * charsize;
442             }
443           this->key_to_offset_[(*curr)->second - 1] = this_offset;
444           last_offset = this_offset;
445         }
446     }
447
448   this->strtab_size_ = offset;
449 }
450
451 // Get the offset of a string in the ELF strtab.  The string must
452 // exist.
453
454 template<typename Stringpool_char>
455 section_offset_type
456 Stringpool_template<Stringpool_char>::get_offset(const Stringpool_char* s)
457   const
458 {
459   return this->get_offset_with_length(s, string_length(s));
460 }
461
462 template<typename Stringpool_char>
463 section_offset_type
464 Stringpool_template<Stringpool_char>::get_offset_with_length(
465     const Stringpool_char* s,
466     size_t length) const
467 {
468   gold_assert(this->strtab_size_ != 0);
469   Hashkey hk(s, length);
470   typename String_set_type::const_iterator p = this->string_set_.find(hk);
471   if (p != this->string_set_.end())
472     return this->key_to_offset_[p->second - 1];
473   gold_unreachable();
474 }
475
476 // Write the ELF strtab into the buffer.
477
478 template<typename Stringpool_char>
479 void
480 Stringpool_template<Stringpool_char>::write_to_buffer(
481     unsigned char* buffer,
482     section_size_type bufsize)
483 {
484   gold_assert(this->strtab_size_ != 0);
485   gold_assert(bufsize >= this->strtab_size_);
486   if (this->zero_null_)
487     buffer[0] = '\0';
488   for (typename String_set_type::const_iterator p = this->string_set_.begin();
489        p != this->string_set_.end();
490        ++p)
491     {
492       const int len = (p->first.length + 1) * sizeof(Stringpool_char);
493       const section_offset_type offset = this->key_to_offset_[p->second - 1];
494       gold_assert(static_cast<section_size_type>(offset) + len
495                   <= this->strtab_size_);
496       memcpy(buffer + offset, p->first.string, len);
497     }
498 }
499
500 // Write the ELF strtab into the output file at the specified offset.
501
502 template<typename Stringpool_char>
503 void
504 Stringpool_template<Stringpool_char>::write(Output_file* of, off_t offset)
505 {
506   gold_assert(this->strtab_size_ != 0);
507   unsigned char* view = of->get_output_view(offset, this->strtab_size_);
508   this->write_to_buffer(view, this->strtab_size_);
509   of->write_output_view(offset, this->strtab_size_, view);
510 }
511
512 // Print statistical information to stderr.  This is used for --stats.
513
514 template<typename Stringpool_char>
515 void
516 Stringpool_template<Stringpool_char>::print_stats(const char* name) const
517 {
518 #if defined(HAVE_TR1_UNORDERED_MAP) || defined(HAVE_EXT_HASH_MAP)
519   fprintf(stderr, _("%s: %s entries: %zu; buckets: %zu\n"),
520           program_name, name, this->string_set_.size(),
521           this->string_set_.bucket_count());
522 #else
523   fprintf(stderr, _("%s: %s entries: %zu\n"),
524           program_name, name, this->table_.size());
525 #endif
526   fprintf(stderr, _("%s: %s Stringdata structures: %zu\n"),
527           program_name, name, this->strings_.size());
528 }
529
530 // Instantiate the templates we need.
531
532 template
533 class Stringpool_template<char>;
534
535 template
536 class Stringpool_template<uint16_t>;
537
538 template
539 class Stringpool_template<uint32_t>;
540
541 } // End namespace gold.