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