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