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, const char *Start)
90 uint64_t Size = sizeof(ArchiveMemberHeader);
91 Data = StringRef(Start, Size);
92 if (!isThinMember()) {
94 Data = StringRef(Start, Size);
97 // Setup StartOfFile and PaddingBytes.
98 StartOfFile = sizeof(ArchiveMemberHeader);
99 // Don't include attached name.
100 StringRef Name = getRawName();
101 if (Name.startswith("#1/")) {
103 if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
104 llvm_unreachable("Long name length is not an integer");
105 StartOfFile += NameSize;
109 uint64_t Archive::Child::getSize() const {
110 if (Parent->IsThin) {
111 ErrorOr<uint32_t> Size = getHeader()->getSize();
116 return Data.size() - StartOfFile;
119 uint64_t Archive::Child::getRawSize() const {
120 ErrorOr<uint32_t> Size = getHeader()->getSize();
126 bool Archive::Child::isThinMember() const {
127 StringRef Name = getHeader()->getName();
128 return Parent->IsThin && Name != "/" && Name != "//";
131 ErrorOr<StringRef> Archive::Child::getBuffer() const {
133 return StringRef(Data.data() + StartOfFile, getSize());
134 ErrorOr<StringRef> Name = getName();
135 if (std::error_code EC = Name.getError())
137 SmallString<128> FullName = sys::path::parent_path(
138 Parent->getMemoryBufferRef().getBufferIdentifier());
139 sys::path::append(FullName, *Name);
140 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
141 if (std::error_code EC = Buf.getError())
143 Parent->ThinBuffers.push_back(std::move(*Buf));
144 return Parent->ThinBuffers.back()->getBuffer();
147 Archive::Child Archive::Child::getNext() const {
148 size_t SpaceToSkip = Data.size();
149 // If it's odd, add 1 to make it even.
153 const char *NextLoc = Data.data() + SpaceToSkip;
155 // Check to see if this is past the end of the archive.
156 if (NextLoc >= Parent->Data.getBufferEnd())
157 return Child(Parent, nullptr);
159 return Child(Parent, NextLoc);
162 uint64_t Archive::Child::getChildOffset() const {
163 const char *a = Parent->Data.getBuffer().data();
164 const char *c = Data.data();
165 uint64_t offset = c - a;
169 ErrorOr<StringRef> Archive::Child::getName() const {
170 StringRef name = getRawName();
171 // Check if it's a special name.
172 if (name[0] == '/') {
173 if (name.size() == 1) // Linker member.
175 if (name.size() == 2 && name[1] == '/') // String table.
180 if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
181 llvm_unreachable("Long name offset is not an integer");
184 if (offset >= Parent->StringTable.size())
185 return object_error::parse_failed;
186 const char *addr = Parent->StringTable.begin() + offset;
188 // GNU long file names end with a "/\n".
189 if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
190 StringRef::size_type End = StringRef(addr).find('\n');
191 return StringRef(addr, End - 1);
193 return StringRef(addr);
194 } else if (name.startswith("#1/")) {
196 if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
197 llvm_unreachable("Long name length is not an ingeter");
198 return Data.substr(sizeof(ArchiveMemberHeader), name_size)
199 .rtrim(StringRef("\0", 1));
201 // It's a simple name.
202 if (name[name.size() - 1] == '/')
203 return name.substr(0, name.size() - 1);
207 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
208 ErrorOr<StringRef> NameOrErr = getName();
209 if (std::error_code EC = NameOrErr.getError())
211 StringRef Name = NameOrErr.get();
212 ErrorOr<StringRef> Buf = getBuffer();
213 if (std::error_code EC = Buf.getError())
215 return MemoryBufferRef(*Buf, Name);
218 ErrorOr<std::unique_ptr<Binary>>
219 Archive::Child::getAsBinary(LLVMContext *Context) const {
220 ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
221 if (std::error_code EC = BuffOrErr.getError())
224 return createBinary(BuffOrErr.get(), Context);
227 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
229 std::unique_ptr<Archive> Ret(new Archive(Source, EC));
232 return std::move(Ret);
235 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
236 : Binary(Binary::ID_Archive, Source), FirstRegular(child_end()) {
237 StringRef Buffer = Data.getBuffer();
238 // Check for sufficient magic.
239 if (Buffer.startswith(ThinMagic)) {
241 } else if (Buffer.startswith(Magic)) {
244 ec = object_error::invalid_file_type;
248 // Get the special members.
249 child_iterator i = child_begin(false);
250 child_iterator e = child_end();
253 ec = std::error_code();
257 StringRef Name = i->getRawName();
259 // Below is the pattern that is used to figure out the archive format
260 // GNU archive format
261 // First member : / (may exist, if it exists, points to the symbol table )
262 // Second member : // (may exist, if it exists, points to the string table)
263 // Note : The string table is used if the filename exceeds 15 characters
264 // BSD archive format
265 // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
266 // There is no string table, if the filename exceeds 15 characters or has a
267 // embedded space, the filename has #1/<size>, The size represents the size
268 // of the filename that needs to be read after the archive header
269 // COFF archive format
271 // Second member : / (provides a directory of symbols)
272 // Third member : // (may exist, if it exists, contains the string table)
273 // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
274 // even if the string table is empty. However, lib.exe does not in fact
275 // seem to create the third member if there's no member whose filename
276 // exceeds 15 characters. So the third member is optional.
278 if (Name == "__.SYMDEF") {
280 // We know that the symbol table is not an external file, so we just assert
281 // there is no error.
282 SymbolTable = *i->getBuffer();
285 ec = std::error_code();
289 if (Name.startswith("#1/")) {
291 // We know this is BSD, so getName will work since there is no string table.
292 ErrorOr<StringRef> NameOrErr = i->getName();
293 ec = NameOrErr.getError();
296 Name = NameOrErr.get();
297 if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
298 // We know that the symbol table is not an external file, so we just
299 // assert there is no error.
300 SymbolTable = *i->getBuffer();
307 // MIPS 64-bit ELF archives use a special format of a symbol table.
308 // This format is marked by `ar_name` field equals to "/SYM64/".
309 // For detailed description see page 96 in the following document:
310 // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
312 bool has64SymTable = false;
313 if (Name == "/" || Name == "/SYM64/") {
314 // We know that the symbol table is not an external file, so we just assert
315 // there is no error.
316 SymbolTable = *i->getBuffer();
317 if (Name == "/SYM64/")
318 has64SymTable = true;
322 ec = std::error_code();
325 Name = i->getRawName();
329 Format = has64SymTable ? K_MIPS64 : K_GNU;
330 // The string table is never an external member, so we just assert on the
332 StringTable = *i->getBuffer();
335 ec = std::error_code();
339 if (Name[0] != '/') {
340 Format = has64SymTable ? K_MIPS64 : K_GNU;
342 ec = std::error_code();
347 ec = object_error::parse_failed;
352 // We know that the symbol table is not an external file, so we just assert
353 // there is no error.
354 SymbolTable = *i->getBuffer();
359 ec = std::error_code();
363 Name = i->getRawName();
366 // The string table is never an external member, so we just assert on the
368 StringTable = *i->getBuffer();
373 ec = std::error_code();
376 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
377 if (Data.getBufferSize() == 8) // empty archive.
383 const char *Loc = Data.getBufferStart() + strlen(Magic);
388 Archive::child_iterator Archive::child_end() const {
389 return Child(this, nullptr);
392 StringRef Archive::Symbol::getName() const {
393 return Parent->getSymbolTable().begin() + StringIndex;
396 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
397 const char *Buf = Parent->getSymbolTable().begin();
398 const char *Offsets = Buf;
399 if (Parent->kind() == K_MIPS64)
400 Offsets += sizeof(uint64_t);
402 Offsets += sizeof(uint32_t);
404 if (Parent->kind() == K_GNU) {
405 Offset = read32be(Offsets + SymbolIndex * 4);
406 } else if (Parent->kind() == K_MIPS64) {
407 Offset = read64be(Offsets + SymbolIndex * 8);
408 } else if (Parent->kind() == K_BSD) {
409 // The SymbolIndex is an index into the ranlib structs that start at
410 // Offsets (the first uint32_t is the number of bytes of the ranlib
411 // structs). The ranlib structs are a pair of uint32_t's the first
412 // being a string table offset and the second being the offset into
413 // the archive of the member that defines the symbol. Which is what
415 Offset = read32le(Offsets + SymbolIndex * 8 + 4);
418 uint32_t MemberCount = read32le(Buf);
419 Buf += MemberCount * 4 + 4;
421 uint32_t SymbolCount = read32le(Buf);
422 if (SymbolIndex >= SymbolCount)
423 return object_error::parse_failed;
425 // Skip SymbolCount to get to the indices table.
426 const char *Indices = Buf + 4;
428 // Get the index of the offset in the file member offset table for this
430 uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
431 // Subtract 1 since OffsetIndex is 1 based.
434 if (OffsetIndex >= MemberCount)
435 return object_error::parse_failed;
437 Offset = read32le(Offsets + OffsetIndex * 4);
440 const char *Loc = Parent->getData().begin() + Offset;
441 child_iterator Iter(Child(Parent, Loc));
445 Archive::Symbol Archive::Symbol::getNext() const {
447 if (Parent->kind() == K_BSD) {
448 // t.StringIndex is an offset from the start of the __.SYMDEF or
449 // "__.SYMDEF SORTED" member into the string table for the ranlib
450 // struct indexed by t.SymbolIndex . To change t.StringIndex to the
451 // offset in the string table for t.SymbolIndex+1 we subtract the
452 // its offset from the start of the string table for t.SymbolIndex
453 // and add the offset of the string table for t.SymbolIndex+1.
455 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
456 // which is the number of bytes of ranlib structs that follow. The ranlib
457 // structs are a pair of uint32_t's the first being a string table offset
458 // and the second being the offset into the archive of the member that
459 // define the symbol. After that the next uint32_t is the byte count of
460 // the string table followed by the string table.
461 const char *Buf = Parent->getSymbolTable().begin();
462 uint32_t RanlibCount = 0;
463 RanlibCount = read32le(Buf) / 8;
464 // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
465 // don't change the t.StringIndex as we don't want to reference a ranlib
467 if (t.SymbolIndex + 1 < RanlibCount) {
468 const char *Ranlibs = Buf + 4;
469 uint32_t CurRanStrx = 0;
470 uint32_t NextRanStrx = 0;
471 CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
472 NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
473 t.StringIndex -= CurRanStrx;
474 t.StringIndex += NextRanStrx;
477 // Go to one past next null.
478 t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
484 Archive::symbol_iterator Archive::symbol_begin() const {
485 if (!hasSymbolTable())
486 return symbol_iterator(Symbol(this, 0, 0));
488 const char *buf = getSymbolTable().begin();
489 if (kind() == K_GNU) {
490 uint32_t symbol_count = 0;
491 symbol_count = read32be(buf);
492 buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
493 } else if (kind() == K_MIPS64) {
494 uint64_t symbol_count = read64be(buf);
495 buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
496 } else if (kind() == K_BSD) {
497 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
498 // which is the number of bytes of ranlib structs that follow. The ranlib
499 // structs are a pair of uint32_t's the first being a string table offset
500 // and the second being the offset into the archive of the member that
501 // define the symbol. After that the next uint32_t is the byte count of
502 // the string table followed by the string table.
503 uint32_t ranlib_count = 0;
504 ranlib_count = read32le(buf) / 8;
505 const char *ranlibs = buf + 4;
506 uint32_t ran_strx = 0;
507 ran_strx = read32le(ranlibs);
508 buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
509 // Skip the byte count of the string table.
510 buf += sizeof(uint32_t);
513 uint32_t member_count = 0;
514 uint32_t symbol_count = 0;
515 member_count = read32le(buf);
516 buf += 4 + (member_count * 4); // Skip offsets.
517 symbol_count = read32le(buf);
518 buf += 4 + (symbol_count * 2); // Skip indices.
520 uint32_t string_start_offset = buf - getSymbolTable().begin();
521 return symbol_iterator(Symbol(this, 0, string_start_offset));
524 Archive::symbol_iterator Archive::symbol_end() const {
525 return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
528 uint32_t Archive::getNumberOfSymbols() const {
529 if (!hasSymbolTable())
531 const char *buf = getSymbolTable().begin();
533 return read32be(buf);
534 if (kind() == K_MIPS64)
535 return read64be(buf);
537 return read32le(buf) / 8;
538 uint32_t member_count = 0;
539 member_count = read32le(buf);
540 buf += 4 + (member_count * 4); // Skip offsets.
541 return read32le(buf);
544 Archive::child_iterator Archive::findSym(StringRef name) const {
545 Archive::symbol_iterator bs = symbol_begin();
546 Archive::symbol_iterator es = symbol_end();
548 for (; bs != es; ++bs) {
549 StringRef SymName = bs->getName();
550 if (SymName == name) {
551 ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
552 // FIXME: Should we really eat the error?
553 if (ResultOrErr.getError())
555 return ResultOrErr.get();
561 bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }