Backing out commit r250906 as it broke lld.
[oota-llvm.git] / lib / Object / Archive.cpp
1 //===- Archive.cpp - ar File Format implementation --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ArchiveObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Object/Archive.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Support/Endian.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/Path.h"
21
22 using namespace llvm;
23 using namespace object;
24 using namespace llvm::support::endian;
25
26 static const char *const Magic = "!<arch>\n";
27 static const char *const ThinMagic = "!<thin>\n";
28
29 void Archive::anchor() { }
30
31 StringRef ArchiveMemberHeader::getName() const {
32   char EndCond;
33   if (Name[0] == '/' || Name[0] == '#')
34     EndCond = ' ';
35   else
36     EndCond = '/';
37   llvm::StringRef::size_type end =
38       llvm::StringRef(Name, sizeof(Name)).find(EndCond);
39   if (end == llvm::StringRef::npos)
40     end = sizeof(Name);
41   assert(end <= sizeof(Name) && end > 0);
42   // Don't include the EndCond if there is one.
43   return llvm::StringRef(Name, end);
44 }
45
46 ErrorOr<uint32_t> ArchiveMemberHeader::getSize() const {
47   uint32_t Ret;
48   if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
49     return object_error::parse_failed;
50   return Ret;
51 }
52
53 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
54   unsigned Ret;
55   if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
56     llvm_unreachable("Access mode is not an octal number.");
57   return static_cast<sys::fs::perms>(Ret);
58 }
59
60 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
61   unsigned Seconds;
62   if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
63           .getAsInteger(10, Seconds))
64     llvm_unreachable("Last modified time not a decimal number.");
65
66   sys::TimeValue Ret;
67   Ret.fromEpochTime(Seconds);
68   return Ret;
69 }
70
71 unsigned ArchiveMemberHeader::getUID() const {
72   unsigned Ret;
73   if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
74     llvm_unreachable("UID time not a decimal number.");
75   return Ret;
76 }
77
78 unsigned ArchiveMemberHeader::getGID() const {
79   unsigned Ret;
80   if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
81     llvm_unreachable("GID time not a decimal number.");
82   return Ret;
83 }
84
85 Archive::Child::Child(const Archive *Parent, const char *Start)
86     : Parent(Parent) {
87   if (!Start)
88     return;
89
90   uint64_t Size = sizeof(ArchiveMemberHeader);
91   Data = StringRef(Start, Size);
92   if (!isThinMember()) {
93     Size += getRawSize();
94     Data = StringRef(Start, Size);
95   }
96
97   // Setup StartOfFile and PaddingBytes.
98   StartOfFile = sizeof(ArchiveMemberHeader);
99   // Don't include attached name.
100   StringRef Name = getRawName();
101   if (Name.startswith("#1/")) {
102     uint64_t NameSize;
103     if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
104       llvm_unreachable("Long name length is not an integer");
105     StartOfFile += NameSize;
106   }
107 }
108
109 uint64_t Archive::Child::getSize() const {
110   if (Parent->IsThin) {
111     ErrorOr<uint32_t> Size = getHeader()->getSize();
112     if (Size.getError())
113       return 0;
114     return Size.get();
115   }
116   return Data.size() - StartOfFile;
117 }
118
119 uint64_t Archive::Child::getRawSize() const {
120   ErrorOr<uint32_t> Size = getHeader()->getSize();
121   if (Size.getError())
122     return 0;
123   return Size.get();
124 }
125
126 bool Archive::Child::isThinMember() const {
127   StringRef Name = getHeader()->getName();
128   return Parent->IsThin && Name != "/" && Name != "//";
129 }
130
131 ErrorOr<StringRef> Archive::Child::getBuffer() const {
132   if (!isThinMember())
133     return StringRef(Data.data() + StartOfFile, getSize());
134   ErrorOr<StringRef> Name = getName();
135   if (std::error_code EC = Name.getError())
136     return EC;
137   SmallString<128> FullName = sys::path::parent_path(
138       Parent->getMemoryBufferRef().getBufferIdentifier());
139   sys::path::append(FullName, *Name);
140   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
141   if (std::error_code EC = Buf.getError())
142     return EC;
143   Parent->ThinBuffers.push_back(std::move(*Buf));
144   return Parent->ThinBuffers.back()->getBuffer();
145 }
146
147 Archive::Child Archive::Child::getNext() const {
148   size_t SpaceToSkip = Data.size();
149   // If it's odd, add 1 to make it even.
150   if (SpaceToSkip & 1)
151     ++SpaceToSkip;
152
153   const char *NextLoc = Data.data() + SpaceToSkip;
154
155   // Check to see if this is past the end of the archive.
156   if (NextLoc >= Parent->Data.getBufferEnd())
157     return Child(Parent, nullptr);
158
159   return Child(Parent, NextLoc);
160 }
161
162 uint64_t Archive::Child::getChildOffset() const {
163   const char *a = Parent->Data.getBuffer().data();
164   const char *c = Data.data();
165   uint64_t offset = c - a;
166   return offset;
167 }
168
169 ErrorOr<StringRef> Archive::Child::getName() const {
170   StringRef name = getRawName();
171   // Check if it's a special name.
172   if (name[0] == '/') {
173     if (name.size() == 1) // Linker member.
174       return name;
175     if (name.size() == 2 && name[1] == '/') // String table.
176       return name;
177     // It's a long name.
178     // Get the offset.
179     std::size_t offset;
180     if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
181       llvm_unreachable("Long name offset is not an integer");
182     const char *addr = Parent->StringTable->Data.begin()
183                        + sizeof(ArchiveMemberHeader)
184                        + offset;
185     // Verify it.
186     if (Parent->StringTable == Parent->child_end()
187         || addr < (Parent->StringTable->Data.begin()
188                    + sizeof(ArchiveMemberHeader))
189         || addr > (Parent->StringTable->Data.begin()
190                    + sizeof(ArchiveMemberHeader)
191                    + Parent->StringTable->getSize()))
192       return object_error::parse_failed;
193
194     // GNU long file names end with a "/\n".
195     if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
196       StringRef::size_type End = StringRef(addr).find('\n');
197       return StringRef(addr, End - 1);
198     }
199     return StringRef(addr);
200   } else if (name.startswith("#1/")) {
201     uint64_t name_size;
202     if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
203       llvm_unreachable("Long name length is not an ingeter");
204     return Data.substr(sizeof(ArchiveMemberHeader), name_size)
205         .rtrim(StringRef("\0", 1));
206   }
207   // It's a simple name.
208   if (name[name.size() - 1] == '/')
209     return name.substr(0, name.size() - 1);
210   return name;
211 }
212
213 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
214   ErrorOr<StringRef> NameOrErr = getName();
215   if (std::error_code EC = NameOrErr.getError())
216     return EC;
217   StringRef Name = NameOrErr.get();
218   ErrorOr<StringRef> Buf = getBuffer();
219   if (std::error_code EC = Buf.getError())
220     return EC;
221   return MemoryBufferRef(*Buf, Name);
222 }
223
224 ErrorOr<std::unique_ptr<Binary>>
225 Archive::Child::getAsBinary(LLVMContext *Context) const {
226   ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
227   if (std::error_code EC = BuffOrErr.getError())
228     return EC;
229
230   return createBinary(BuffOrErr.get(), Context);
231 }
232
233 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
234   std::error_code EC;
235   std::unique_ptr<Archive> Ret(new Archive(Source, EC));
236   if (EC)
237     return EC;
238   return std::move(Ret);
239 }
240
241 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
242     : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()),
243       StringTable(child_end()), FirstRegular(child_end()) {
244   StringRef Buffer = Data.getBuffer();
245   // Check for sufficient magic.
246   if (Buffer.startswith(ThinMagic)) {
247     IsThin = true;
248   } else if (Buffer.startswith(Magic)) {
249     IsThin = false;
250   } else {
251     ec = object_error::invalid_file_type;
252     return;
253   }
254
255   // Get the special members.
256   child_iterator i = child_begin(false);
257   child_iterator e = child_end();
258
259   if (i == e) {
260     ec = std::error_code();
261     return;
262   }
263
264   StringRef Name = i->getRawName();
265
266   // Below is the pattern that is used to figure out the archive format
267   // GNU archive format
268   //  First member : / (may exist, if it exists, points to the symbol table )
269   //  Second member : // (may exist, if it exists, points to the string table)
270   //  Note : The string table is used if the filename exceeds 15 characters
271   // BSD archive format
272   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
273   //  There is no string table, if the filename exceeds 15 characters or has a
274   //  embedded space, the filename has #1/<size>, The size represents the size
275   //  of the filename that needs to be read after the archive header
276   // COFF archive format
277   //  First member : /
278   //  Second member : / (provides a directory of symbols)
279   //  Third member : // (may exist, if it exists, contains the string table)
280   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
281   //  even if the string table is empty. However, lib.exe does not in fact
282   //  seem to create the third member if there's no member whose filename
283   //  exceeds 15 characters. So the third member is optional.
284
285   if (Name == "__.SYMDEF") {
286     Format = K_BSD;
287     SymbolTable = i;
288     ++i;
289     FirstRegular = i;
290     ec = std::error_code();
291     return;
292   }
293
294   if (Name.startswith("#1/")) {
295     Format = K_BSD;
296     // We know this is BSD, so getName will work since there is no string table.
297     ErrorOr<StringRef> NameOrErr = i->getName();
298     ec = NameOrErr.getError();
299     if (ec)
300       return;
301     Name = NameOrErr.get();
302     if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
303       SymbolTable = i;
304       ++i;
305     }
306     FirstRegular = i;
307     return;
308   }
309
310   // MIPS 64-bit ELF archives use a special format of a symbol table.
311   // This format is marked by `ar_name` field equals to "/SYM64/".
312   // For detailed description see page 96 in the following document:
313   // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
314
315   bool has64SymTable = false;
316   if (Name == "/" || Name == "/SYM64/") {
317     SymbolTable = i;
318     if (Name == "/SYM64/")
319       has64SymTable = true;
320
321     ++i;
322     if (i == e) {
323       ec = std::error_code();
324       return;
325     }
326     Name = i->getRawName();
327   }
328
329   if (Name == "//") {
330     Format = has64SymTable ? K_MIPS64 : K_GNU;
331     StringTable = i;
332     ++i;
333     FirstRegular = i;
334     ec = std::error_code();
335     return;
336   }
337
338   if (Name[0] != '/') {
339     Format = has64SymTable ? K_MIPS64 : K_GNU;
340     FirstRegular = i;
341     ec = std::error_code();
342     return;
343   }
344
345   if (Name != "/") {
346     ec = object_error::parse_failed;
347     return;
348   }
349
350   Format = K_COFF;
351   SymbolTable = i;
352
353   ++i;
354   if (i == e) {
355     FirstRegular = i;
356     ec = std::error_code();
357     return;
358   }
359
360   Name = i->getRawName();
361
362   if (Name == "//") {
363     StringTable = i;
364     ++i;
365   }
366
367   FirstRegular = i;
368   ec = std::error_code();
369 }
370
371 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
372   if (Data.getBufferSize() == 8) // empty archive.
373     return child_end();
374
375   if (SkipInternal)
376     return FirstRegular;
377
378   const char *Loc = Data.getBufferStart() + strlen(Magic);
379   Child c(this, Loc);
380   return c;
381 }
382
383 Archive::child_iterator Archive::child_end() const {
384   return Child(this, nullptr);
385 }
386
387 StringRef Archive::Symbol::getName() const {
388   return Parent->getSymbolTable().begin() + StringIndex;
389 }
390
391 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
392   const char *Buf = Parent->getSymbolTable().begin();
393   const char *Offsets = Buf;
394   if (Parent->kind() == K_MIPS64)
395     Offsets += sizeof(uint64_t);
396   else
397     Offsets += sizeof(uint32_t);
398   uint32_t Offset = 0;
399   if (Parent->kind() == K_GNU) {
400     Offset = read32be(Offsets + SymbolIndex * 4);
401   } else if (Parent->kind() == K_MIPS64) {
402     Offset = read64be(Offsets + SymbolIndex * 8);
403   } else if (Parent->kind() == K_BSD) {
404     // The SymbolIndex is an index into the ranlib structs that start at
405     // Offsets (the first uint32_t is the number of bytes of the ranlib
406     // structs).  The ranlib structs are a pair of uint32_t's the first
407     // being a string table offset and the second being the offset into
408     // the archive of the member that defines the symbol.  Which is what
409     // is needed here.
410     Offset = read32le(Offsets + SymbolIndex * 8 + 4);
411   } else {
412     // Skip offsets.
413     uint32_t MemberCount = read32le(Buf);
414     Buf += MemberCount * 4 + 4;
415
416     uint32_t SymbolCount = read32le(Buf);
417     if (SymbolIndex >= SymbolCount)
418       return object_error::parse_failed;
419
420     // Skip SymbolCount to get to the indices table.
421     const char *Indices = Buf + 4;
422
423     // Get the index of the offset in the file member offset table for this
424     // symbol.
425     uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
426     // Subtract 1 since OffsetIndex is 1 based.
427     --OffsetIndex;
428
429     if (OffsetIndex >= MemberCount)
430       return object_error::parse_failed;
431
432     Offset = read32le(Offsets + OffsetIndex * 4);
433   }
434
435   const char *Loc = Parent->getData().begin() + Offset;
436   child_iterator Iter(Child(Parent, Loc));
437   return Iter;
438 }
439
440 Archive::Symbol Archive::Symbol::getNext() const {
441   Symbol t(*this);
442   if (Parent->kind() == K_BSD) {
443     // t.StringIndex is an offset from the start of the __.SYMDEF or
444     // "__.SYMDEF SORTED" member into the string table for the ranlib
445     // struct indexed by t.SymbolIndex .  To change t.StringIndex to the
446     // offset in the string table for t.SymbolIndex+1 we subtract the
447     // its offset from the start of the string table for t.SymbolIndex
448     // and add the offset of the string table for t.SymbolIndex+1.
449
450     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
451     // which is the number of bytes of ranlib structs that follow.  The ranlib
452     // structs are a pair of uint32_t's the first being a string table offset
453     // and the second being the offset into the archive of the member that
454     // define the symbol. After that the next uint32_t is the byte count of
455     // the string table followed by the string table.
456     const char *Buf = Parent->getSymbolTable().begin();
457     uint32_t RanlibCount = 0;
458     RanlibCount = read32le(Buf) / 8;
459     // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
460     // don't change the t.StringIndex as we don't want to reference a ranlib
461     // past RanlibCount.
462     if (t.SymbolIndex + 1 < RanlibCount) {
463       const char *Ranlibs = Buf + 4;
464       uint32_t CurRanStrx = 0;
465       uint32_t NextRanStrx = 0;
466       CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
467       NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
468       t.StringIndex -= CurRanStrx;
469       t.StringIndex += NextRanStrx;
470     }
471   } else {
472     // Go to one past next null.
473     t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
474   }
475   ++t.SymbolIndex;
476   return t;
477 }
478
479 Archive::symbol_iterator Archive::symbol_begin() const {
480   if (!hasSymbolTable())
481     return symbol_iterator(Symbol(this, 0, 0));
482
483   const char *buf = getSymbolTable().begin();
484   if (kind() == K_GNU) {
485     uint32_t symbol_count = 0;
486     symbol_count = read32be(buf);
487     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
488   } else if (kind() == K_MIPS64) {
489     uint64_t symbol_count = read64be(buf);
490     buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
491   } else if (kind() == K_BSD) {
492     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
493     // which is the number of bytes of ranlib structs that follow.  The ranlib
494     // structs are a pair of uint32_t's the first being a string table offset
495     // and the second being the offset into the archive of the member that
496     // define the symbol. After that the next uint32_t is the byte count of
497     // the string table followed by the string table.
498     uint32_t ranlib_count = 0;
499     ranlib_count = read32le(buf) / 8;
500     const char *ranlibs = buf + 4;
501     uint32_t ran_strx = 0;
502     ran_strx = read32le(ranlibs);
503     buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
504     // Skip the byte count of the string table.
505     buf += sizeof(uint32_t);
506     buf += ran_strx;
507   } else {
508     uint32_t member_count = 0;
509     uint32_t symbol_count = 0;
510     member_count = read32le(buf);
511     buf += 4 + (member_count * 4); // Skip offsets.
512     symbol_count = read32le(buf);
513     buf += 4 + (symbol_count * 2); // Skip indices.
514   }
515   uint32_t string_start_offset = buf - getSymbolTable().begin();
516   return symbol_iterator(Symbol(this, 0, string_start_offset));
517 }
518
519 Archive::symbol_iterator Archive::symbol_end() const {
520   return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
521 }
522
523 uint32_t Archive::getNumberOfSymbols() const {
524   if (!hasSymbolTable())
525     return 0;
526   const char *buf = getSymbolTable().begin();
527   if (kind() == K_GNU)
528     return read32be(buf);
529   if (kind() == K_MIPS64)
530     return read64be(buf);
531   if (kind() == K_BSD)
532     return read32le(buf) / 8;
533   uint32_t member_count = 0;
534   member_count = read32le(buf);
535   buf += 4 + (member_count * 4); // Skip offsets.
536   return read32le(buf);
537 }
538
539 Archive::child_iterator Archive::findSym(StringRef name) const {
540   Archive::symbol_iterator bs = symbol_begin();
541   Archive::symbol_iterator es = symbol_end();
542
543   for (; bs != es; ++bs) {
544     StringRef SymName = bs->getName();
545     if (SymName == name) {
546       ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
547       // FIXME: Should we really eat the error?
548       if (ResultOrErr.getError())
549         return child_end();
550       return ResultOrErr.get();
551     }
552   }
553   return child_end();
554 }
555
556 bool Archive::hasSymbolTable() const {
557   return SymbolTable != child_end();
558 }