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