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