gas/
[external/binutils.git] / gold / archive.cc
1 // archive.cc -- archive support for gold
2
3 // Copyright 2006, 2007 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 <cerrno>
26 #include <cstring>
27 #include <climits>
28 #include <vector>
29
30 #include "elfcpp.h"
31 #include "options.h"
32 #include "fileread.h"
33 #include "readsyms.h"
34 #include "symtab.h"
35 #include "object.h"
36 #include "archive.h"
37
38 namespace gold
39 {
40
41 // The header of an entry in the archive.  This is all readable text,
42 // padded with spaces where necesary.  If the contents of an archive
43 // are all text file, the entire archive is readable.
44
45 struct Archive::Archive_header
46 {
47   // The entry name.
48   char ar_name[16];
49   // The file modification time.
50   char ar_date[12];
51   // The user's UID in decimal.
52   char ar_uid[6];
53   // The user's GID in decimal.
54   char ar_gid[6];
55   // The file mode in octal.
56   char ar_mode[8];
57   // The file size in decimal.
58   char ar_size[10];
59   // The final magic code.
60   char ar_fmag[2];
61 };
62
63 // Archive methods.
64
65 const char Archive::armag[sarmag] =
66 {
67   '!', '<', 'a', 'r', 'c', 'h', '>', '\n'
68 };
69
70 const char Archive::arfmag[2] = { '`', '\n' };
71
72 // Set up the archive: read the symbol map and the extended name
73 // table.
74
75 void
76 Archive::setup()
77 {
78   // The first member of the archive should be the symbol table.
79   std::string armap_name;
80   off_t armap_size = this->read_header(sarmag, &armap_name);
81   off_t off;
82   if (armap_name.empty())
83     {
84       this->read_armap(sarmag + sizeof(Archive_header), armap_size);
85       off = sarmag + sizeof(Archive_header) + armap_size;
86     }
87   else if (!this->input_file_->options().include_whole_archive())
88     {
89       fprintf(stderr, _("%s: %s: no archive symbol table (run ranlib)\n"),
90               program_name, this->name().c_str());
91       gold_exit(false);
92     }
93   else
94     off = sarmag;
95
96   // See if there is an extended name table.
97   if ((off & 1) != 0)
98     ++off;
99   std::string xname;
100   off_t extended_size = this->read_header(off, &xname);
101   if (xname == "/")
102     {
103       const unsigned char* p = this->get_view(off + sizeof(Archive_header),
104                                               extended_size, false);
105       const char* px = reinterpret_cast<const char*>(p);
106       this->extended_names_.assign(px, extended_size);
107     }
108
109   // Opening the file locked it.  Unlock it now.
110   this->input_file_->file().unlock();
111 }
112
113 // Read the archive symbol map.
114
115 void
116 Archive::read_armap(off_t start, off_t size)
117 {
118   // Read in the entire armap.
119   const unsigned char* p = this->get_view(start, size, false);
120
121   // Numbers in the armap are always big-endian.
122   const elfcpp::Elf_Word* pword = reinterpret_cast<const elfcpp::Elf_Word*>(p);
123   unsigned int nsyms = elfcpp::Swap<32, true>::readval(pword);
124   ++pword;
125
126   // Note that the addition is in units of sizeof(elfcpp::Elf_Word).
127   const char* pnames = reinterpret_cast<const char*>(pword + nsyms);
128   off_t names_size = reinterpret_cast<const char*>(p) + size - pnames;
129   this->armap_names_.assign(pnames, names_size);
130
131   this->armap_.resize(nsyms);
132
133   off_t name_offset = 0;
134   for (unsigned int i = 0; i < nsyms; ++i)
135     {
136       this->armap_[i].name_offset = name_offset;
137       this->armap_[i].file_offset = elfcpp::Swap<32, true>::readval(pword);
138       name_offset += strlen(pnames + name_offset) + 1;
139       ++pword;
140     }
141
142   if (reinterpret_cast<const unsigned char*>(pnames) - p > size)
143     {
144       fprintf(stderr, _("%s: %s: bad archive symbol table names\n"),
145               program_name, this->name().c_str());
146       gold_exit(false);
147     }
148
149   // This array keeps track of which symbols are for archive elements
150   // which we have already included in the link.
151   this->armap_checked_.resize(nsyms);
152 }
153
154 // Read the header of an archive member at OFF.  Fail if something
155 // goes wrong.  Return the size of the member.  Set *PNAME to the name
156 // of the member.
157
158 off_t
159 Archive::read_header(off_t off, std::string* pname)
160 {
161   const unsigned char* p = this->get_view(off, sizeof(Archive_header), false);
162   const Archive_header* hdr = reinterpret_cast<const Archive_header*>(p);
163   return this->interpret_header(hdr, off,  pname);
164 }
165
166 // Interpret the header of HDR, the header of the archive member at
167 // file offset OFF.  Fail if something goes wrong.  Return the size of
168 // the member.  Set *PNAME to the name of the member.
169
170 off_t
171 Archive::interpret_header(const Archive_header* hdr, off_t off,
172                           std::string* pname)
173 {
174   if (memcmp(hdr->ar_fmag, arfmag, sizeof arfmag) != 0)
175     {
176       fprintf(stderr, _("%s; %s: malformed archive header at %ld\n"),
177               program_name, this->name().c_str(),
178               static_cast<long>(off));
179       gold_exit(false);
180     }
181
182   const int size_string_size = sizeof hdr->ar_size;
183   char size_string[size_string_size + 1];
184   memcpy(size_string, hdr->ar_size, size_string_size);
185   char* ps = size_string + size_string_size;
186   while (ps[-1] == ' ')
187     --ps;
188   *ps = '\0';
189
190   errno = 0;
191   char* end;
192   off_t member_size = strtol(size_string, &end, 10);
193   if (*end != '\0'
194       || member_size < 0
195       || (member_size == LONG_MAX && errno == ERANGE))
196     {
197       fprintf(stderr, _("%s: %s: malformed archive header size at %ld\n"),
198               program_name, this->name().c_str(),
199               static_cast<long>(off));
200       gold_exit(false);
201     }
202
203   if (hdr->ar_name[0] != '/')
204     {
205       const char* name_end = strchr(hdr->ar_name, '/');
206       if (name_end == NULL
207           || name_end - hdr->ar_name >= static_cast<int>(sizeof hdr->ar_name))
208         {
209           fprintf(stderr, _("%s: %s: malformed archive header name at %ld\n"),
210                   program_name, this->name().c_str(),
211                   static_cast<long>(off));
212           gold_exit(false);
213         }
214       pname->assign(hdr->ar_name, name_end - hdr->ar_name);
215     }
216   else if (hdr->ar_name[1] == ' ')
217     {
218       // This is the symbol table.
219       pname->clear();
220     }
221   else if (hdr->ar_name[1] == '/')
222     {
223       // This is the extended name table.
224       pname->assign(1, '/');
225     }
226   else
227     {
228       errno = 0;
229       long x = strtol(hdr->ar_name + 1, &end, 10);
230       if (*end != ' '
231           || x < 0
232           || (x == LONG_MAX && errno == ERANGE)
233           || static_cast<size_t>(x) >= this->extended_names_.size())
234         {
235           fprintf(stderr, _("%s: %s: bad extended name index at %ld\n"),
236                   program_name, this->name().c_str(),
237                   static_cast<long>(off));
238           gold_exit(false);
239         }
240
241       const char* name = this->extended_names_.data() + x;
242       const char* name_end = strchr(name, '/');
243       if (static_cast<size_t>(name_end - name) > this->extended_names_.size()
244           || name_end[1] != '\n')
245         {
246           fprintf(stderr, _("%s: %s: bad extended name entry at header %ld\n"),
247                   program_name, this->name().c_str(),
248                   static_cast<long>(off));
249           gold_exit(false);
250         }
251       pname->assign(name, name_end - name);
252     }
253
254   return member_size;
255 }
256
257 // Select members from the archive and add them to the link.  We walk
258 // through the elements in the archive map, and look each one up in
259 // the symbol table.  If it exists as a strong undefined symbol, we
260 // pull in the corresponding element.  We have to do this in a loop,
261 // since pulling in one element may create new undefined symbols which
262 // may be satisfied by other objects in the archive.
263
264 void
265 Archive::add_symbols(Symbol_table* symtab, Layout* layout,
266                      Input_objects* input_objects)
267 {
268   if (this->input_file_->options().include_whole_archive())
269     return this->include_all_members(symtab, layout, input_objects);
270
271   const size_t armap_size = this->armap_.size();
272
273   // This is a quick optimization, since we usually see many symbols
274   // in a row with the same offset.  last_seen_offset holds the last
275   // offset we saw that was present in the seen_offsets_ set.
276   off_t last_seen_offset = -1;
277
278   // Track which symbols in the symbol table we've already found to be
279   // defined.
280
281   bool added_new_object;
282   do
283     {
284       added_new_object = false;
285       for (size_t i = 0; i < armap_size; ++i)
286         {
287           if (this->armap_checked_[i])
288             continue;
289           if (this->armap_[i].file_offset == last_seen_offset)
290             {
291               this->armap_checked_[i] = true;
292               continue;
293             }
294           if (this->seen_offsets_.find(this->armap_[i].file_offset)
295               != this->seen_offsets_.end())
296             {
297               this->armap_checked_[i] = true;
298               last_seen_offset = this->armap_[i].file_offset;
299               continue;
300             }
301
302           const char* sym_name = (this->armap_names_.data()
303                                   + this->armap_[i].name_offset);
304           Symbol* sym = symtab->lookup(sym_name);
305           if (sym == NULL)
306             continue;
307           else if (!sym->is_undefined())
308             {
309               this->armap_checked_[i] = true;
310               continue;
311             }
312           else if (sym->binding() == elfcpp::STB_WEAK)
313             continue;
314
315           // We want to include this object in the link.
316           last_seen_offset = this->armap_[i].file_offset;
317           this->seen_offsets_.insert(last_seen_offset);
318           this->armap_checked_[i] = true;
319           this->include_member(symtab, layout, input_objects,
320                                last_seen_offset);
321           added_new_object = true;
322         }
323     }
324   while (added_new_object);
325 }
326
327 // Include all the archive members in the link.  This is for --whole-archive.
328
329 void
330 Archive::include_all_members(Symbol_table* symtab, Layout* layout,
331                              Input_objects* input_objects)
332 {
333   off_t off = sarmag;
334   off_t filesize = this->input_file_->file().filesize();
335   while (true)
336     {
337       if (filesize - off < sizeof(Archive_header))
338         {
339           if (filesize != off)
340             {
341               fprintf(stderr, _("%s: %s: short archive header at %ld\n"),
342                       program_name, this->name().c_str(),
343                       static_cast<long>(off));
344               gold_exit(false);
345             }
346
347           break;
348         }
349
350       unsigned char hdr_buf[sizeof(Archive_header)];
351       this->input_file_->file().read(off, sizeof(Archive_header), hdr_buf);
352
353       const Archive_header* hdr =
354         reinterpret_cast<const Archive_header*>(hdr_buf);
355       std::string name;
356       off_t size = this->interpret_header(hdr, off, &name);
357       if (name.empty())
358         {
359           // Symbol table.
360         }
361       else if (name == "/")
362         {
363           // Extended name table.
364         }
365       else
366         this->include_member(symtab, layout, input_objects, off);
367
368       off += sizeof(Archive_header) + size;
369       if ((off & 1) != 0)
370         ++off;
371     }
372 }
373
374 // Include an archive member in the link.  OFF is the file offset of
375 // the member header.
376
377 void
378 Archive::include_member(Symbol_table* symtab, Layout* layout,
379                         Input_objects* input_objects, off_t off)
380 {
381   std::string n;
382   this->read_header(off, &n);
383
384   size_t memoff = off + sizeof(Archive_header);
385
386   // Read enough of the file to pick up the entire ELF header.
387   unsigned char ehdr_buf[elfcpp::Elf_sizes<64>::ehdr_size];
388
389   off_t filesize = this->input_file_->file().filesize();
390   int read_size = elfcpp::Elf_sizes<64>::ehdr_size;
391   if (filesize - memoff < read_size)
392     read_size = filesize - memoff;
393
394   if (read_size < 4)
395     {
396       fprintf(stderr, _("%s: %s: member at %ld is not an ELF object"),
397               program_name, this->name().c_str(),
398               static_cast<long>(off));
399       gold_exit(false);
400     }
401
402   this->input_file_->file().read(memoff, read_size, ehdr_buf);
403
404   static unsigned char elfmagic[4] =
405     {
406       elfcpp::ELFMAG0, elfcpp::ELFMAG1,
407       elfcpp::ELFMAG2, elfcpp::ELFMAG3
408     };
409   if (memcmp(ehdr_buf, elfmagic, 4) != 0)
410     {
411       fprintf(stderr, _("%s: %s: member at %ld is not an ELF object"),
412               program_name, this->name().c_str(),
413               static_cast<long>(off));
414       gold_exit(false);
415     }
416
417   Object* obj = make_elf_object((std::string(this->input_file_->filename())
418                                  + "(" + n + ")"),
419                                 this->input_file_, memoff, ehdr_buf,
420                                 read_size);
421
422   input_objects->add_object(obj);
423
424   Read_symbols_data sd;
425   obj->read_symbols(&sd);
426   obj->layout(symtab, layout, &sd);
427   obj->add_symbols(symtab, &sd);
428 }
429
430 // Add_archive_symbols methods.
431
432 Add_archive_symbols::~Add_archive_symbols()
433 {
434   if (this->this_blocker_ != NULL)
435     delete this->this_blocker_;
436   // next_blocker_ is deleted by the task associated with the next
437   // input file.
438 }
439
440 // Return whether we can add the archive symbols.  We are blocked by
441 // this_blocker_.  We block next_blocker_.  We also lock the file.
442
443 Task::Is_runnable_type
444 Add_archive_symbols::is_runnable(Workqueue*)
445 {
446   if (this->this_blocker_ != NULL && this->this_blocker_->is_blocked())
447     return IS_BLOCKED;
448   return IS_RUNNABLE;
449 }
450
451 class Add_archive_symbols::Add_archive_symbols_locker : public Task_locker
452 {
453  public:
454   Add_archive_symbols_locker(Task_token& token, Workqueue* workqueue,
455                              File_read& file)
456     : blocker_(token, workqueue), filelock_(file)
457   { }
458
459  private:
460   Task_locker_block blocker_;
461   Task_locker_obj<File_read> filelock_;
462 };
463
464 Task_locker*
465 Add_archive_symbols::locks(Workqueue* workqueue)
466 {
467   return new Add_archive_symbols_locker(*this->next_blocker_,
468                                         workqueue,
469                                         this->archive_->file());
470 }
471
472 void
473 Add_archive_symbols::run(Workqueue*)
474 {
475   this->archive_->add_symbols(this->symtab_, this->layout_,
476                               this->input_objects_);
477
478   if (this->input_group_ != NULL)
479     this->input_group_->add_archive(this->archive_);
480   else
481     {
482       // We no longer need to know about this archive.
483       delete this->archive_;
484     }
485 }
486
487 } // End namespace gold.