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