1 //===- Archive.cpp - ar File Format implementation --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ArchiveObjectFile class.
12 //===----------------------------------------------------------------------===//
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"
23 using namespace object;
24 using namespace llvm::support::endian;
26 static const char *const Magic = "!<arch>\n";
27 static const char *const ThinMagic = "!<thin>\n";
29 void Archive::anchor() { }
31 StringRef ArchiveMemberHeader::getName() const {
33 if (Name[0] == '/' || Name[0] == '#')
37 llvm::StringRef::size_type end =
38 llvm::StringRef(Name, sizeof(Name)).find(EndCond);
39 if (end == llvm::StringRef::npos)
41 assert(end <= sizeof(Name) && end > 0);
42 // Don't include the EndCond if there is one.
43 return llvm::StringRef(Name, end);
46 ErrorOr<uint32_t> ArchiveMemberHeader::getSize() const {
48 if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
49 return object_error::parse_failed;
53 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
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);
60 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
62 if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
63 .getAsInteger(10, Seconds))
64 llvm_unreachable("Last modified time not a decimal number.");
67 Ret.fromEpochTime(Seconds);
71 unsigned ArchiveMemberHeader::getUID() const {
73 if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
74 llvm_unreachable("UID time not a decimal number.");
78 unsigned ArchiveMemberHeader::getGID() const {
80 if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
81 llvm_unreachable("GID time not a decimal number.");
85 Archive::Child::Child(const Archive *Parent, StringRef Data,
87 : Parent(Parent), Data(Data), StartOfFile(StartOfFile) {}
89 Archive::Child::Child(const Archive *Parent, const char *Start)
94 uint64_t Size = sizeof(ArchiveMemberHeader);
95 Data = StringRef(Start, Size);
96 if (!isThinMember()) {
98 Data = StringRef(Start, Size);
101 // Setup StartOfFile and PaddingBytes.
102 StartOfFile = sizeof(ArchiveMemberHeader);
103 // Don't include attached name.
104 StringRef Name = getRawName();
105 if (Name.startswith("#1/")) {
107 if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
108 llvm_unreachable("Long name length is not an integer");
109 StartOfFile += NameSize;
113 uint64_t Archive::Child::getSize() const {
114 if (Parent->IsThin) {
115 ErrorOr<uint32_t> Size = getHeader()->getSize();
120 return Data.size() - StartOfFile;
123 uint64_t Archive::Child::getRawSize() const {
124 ErrorOr<uint32_t> Size = getHeader()->getSize();
130 bool Archive::Child::isThinMember() const {
131 StringRef Name = getHeader()->getName();
132 return Parent->IsThin && Name != "/" && Name != "//";
135 ErrorOr<StringRef> Archive::Child::getBuffer() const {
137 return StringRef(Data.data() + StartOfFile, getSize());
138 ErrorOr<StringRef> Name = getName();
139 if (std::error_code EC = Name.getError())
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())
147 Parent->ThinBuffers.push_back(std::move(*Buf));
148 return Parent->ThinBuffers.back()->getBuffer();
151 Archive::Child Archive::Child::getNext() const {
152 size_t SpaceToSkip = Data.size();
153 // If it's odd, add 1 to make it even.
157 const char *NextLoc = Data.data() + SpaceToSkip;
159 // Check to see if this is past the end of the archive.
160 if (NextLoc >= Parent->Data.getBufferEnd())
161 return Child(Parent, nullptr);
163 return Child(Parent, NextLoc);
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;
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.
179 if (name.size() == 2 && name[1] == '/') // String table.
184 if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
185 llvm_unreachable("Long name offset is not an integer");
188 if (offset >= Parent->StringTable.size())
189 return object_error::parse_failed;
190 const char *addr = Parent->StringTable.begin() + offset;
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);
197 return StringRef(addr);
198 } else if (name.startswith("#1/")) {
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));
205 // It's a simple name.
206 if (name[name.size() - 1] == '/')
207 return name.substr(0, name.size() - 1);
211 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
212 ErrorOr<StringRef> NameOrErr = getName();
213 if (std::error_code EC = NameOrErr.getError())
215 StringRef Name = NameOrErr.get();
216 ErrorOr<StringRef> Buf = getBuffer();
217 if (std::error_code EC = Buf.getError())
219 return MemoryBufferRef(*Buf, Name);
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())
228 return createBinary(BuffOrErr.get(), Context);
231 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
233 std::unique_ptr<Archive> Ret(new Archive(Source, EC));
236 return std::move(Ret);
239 void Archive::setFirstRegular(const Child &C) {
240 FirstRegularData = C.Data;
241 FirstRegularStartOfFile = C.StartOfFile;
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)) {
250 } else if (Buffer.startswith(Magic)) {
253 ec = object_error::invalid_file_type;
257 // Get the special members.
258 child_iterator i = child_begin(false);
259 child_iterator e = child_end();
262 ec = std::error_code();
266 StringRef Name = i->getRawName();
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
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.
287 if (Name == "__.SYMDEF") {
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();
294 ec = std::error_code();
298 if (Name.startswith("#1/")) {
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();
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();
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
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;
331 ec = std::error_code();
334 Name = i->getRawName();
338 Format = has64SymTable ? K_MIPS64 : K_GNU;
339 // The string table is never an external member, so we just assert on the
341 StringTable = *i->getBuffer();
344 ec = std::error_code();
348 if (Name[0] != '/') {
349 Format = has64SymTable ? K_MIPS64 : K_GNU;
351 ec = std::error_code();
356 ec = object_error::parse_failed;
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();
368 ec = std::error_code();
372 Name = i->getRawName();
375 // The string table is never an external member, so we just assert on the
377 StringTable = *i->getBuffer();
382 ec = std::error_code();
385 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
386 if (Data.getBufferSize() == 8) // empty archive.
390 return Child(this, FirstRegularData, FirstRegularStartOfFile);
392 const char *Loc = Data.getBufferStart() + strlen(Magic);
397 Archive::child_iterator Archive::child_end() const {
398 return Child(this, nullptr);
401 StringRef Archive::Symbol::getName() const {
402 return Parent->getSymbolTable().begin() + StringIndex;
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);
411 Offsets += sizeof(uint32_t);
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
424 Offset = read32le(Offsets + SymbolIndex * 8 + 4);
427 uint32_t MemberCount = read32le(Buf);
428 Buf += MemberCount * 4 + 4;
430 uint32_t SymbolCount = read32le(Buf);
431 if (SymbolIndex >= SymbolCount)
432 return object_error::parse_failed;
434 // Skip SymbolCount to get to the indices table.
435 const char *Indices = Buf + 4;
437 // Get the index of the offset in the file member offset table for this
439 uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
440 // Subtract 1 since OffsetIndex is 1 based.
443 if (OffsetIndex >= MemberCount)
444 return object_error::parse_failed;
446 Offset = read32le(Offsets + OffsetIndex * 4);
449 const char *Loc = Parent->getData().begin() + Offset;
450 child_iterator Iter(Child(Parent, Loc));
454 Archive::Symbol Archive::Symbol::getNext() const {
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.
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
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;
486 // Go to one past next null.
487 t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
493 Archive::symbol_iterator Archive::symbol_begin() const {
494 if (!hasSymbolTable())
495 return symbol_iterator(Symbol(this, 0, 0));
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);
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.
529 uint32_t string_start_offset = buf - getSymbolTable().begin();
530 return symbol_iterator(Symbol(this, 0, string_start_offset));
533 Archive::symbol_iterator Archive::symbol_end() const {
534 return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
537 uint32_t Archive::getNumberOfSymbols() const {
538 if (!hasSymbolTable())
540 const char *buf = getSymbolTable().begin();
542 return read32be(buf);
543 if (kind() == K_MIPS64)
544 return read64be(buf);
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);
553 Archive::child_iterator Archive::findSym(StringRef name) const {
554 Archive::symbol_iterator bs = symbol_begin();
555 Archive::symbol_iterator es = symbol_end();
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())
564 return ResultOrErr.get();
570 bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }