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