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