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");
182 const char *addr = Parent->StringTable->Data.begin()
183 + sizeof(ArchiveMemberHeader)
186 if (Parent->StringTable == Parent->child_end()
187 || addr < (Parent->StringTable->Data.begin()
188 + sizeof(ArchiveMemberHeader))
189 || addr > (Parent->StringTable->Data.begin()
190 + sizeof(ArchiveMemberHeader)
191 + Parent->StringTable->getSize()))
192 return object_error::parse_failed;
194 // GNU long file names end with a "/\n".
195 if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
196 StringRef::size_type End = StringRef(addr).find('\n');
197 return StringRef(addr, End - 1);
199 return StringRef(addr);
200 } else if (name.startswith("#1/")) {
202 if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
203 llvm_unreachable("Long name length is not an ingeter");
204 return Data.substr(sizeof(ArchiveMemberHeader), name_size)
205 .rtrim(StringRef("\0", 1));
207 // It's a simple name.
208 if (name[name.size() - 1] == '/')
209 return name.substr(0, name.size() - 1);
213 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
214 ErrorOr<StringRef> NameOrErr = getName();
215 if (std::error_code EC = NameOrErr.getError())
217 StringRef Name = NameOrErr.get();
218 ErrorOr<StringRef> Buf = getBuffer();
219 if (std::error_code EC = Buf.getError())
221 return MemoryBufferRef(*Buf, Name);
224 ErrorOr<std::unique_ptr<Binary>>
225 Archive::Child::getAsBinary(LLVMContext *Context) const {
226 ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
227 if (std::error_code EC = BuffOrErr.getError())
230 return createBinary(BuffOrErr.get(), Context);
233 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
235 std::unique_ptr<Archive> Ret(new Archive(Source, EC));
238 return std::move(Ret);
241 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
242 : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()),
243 StringTable(child_end()), FirstRegular(child_end()) {
244 StringRef Buffer = Data.getBuffer();
245 // Check for sufficient magic.
246 if (Buffer.startswith(ThinMagic)) {
248 } else if (Buffer.startswith(Magic)) {
251 ec = object_error::invalid_file_type;
255 // Get the special members.
256 child_iterator i = child_begin(false);
257 child_iterator e = child_end();
260 ec = std::error_code();
264 StringRef Name = i->getRawName();
266 // Below is the pattern that is used to figure out the archive format
267 // GNU archive format
268 // First member : / (may exist, if it exists, points to the symbol table )
269 // Second member : // (may exist, if it exists, points to the string table)
270 // Note : The string table is used if the filename exceeds 15 characters
271 // BSD archive format
272 // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
273 // There is no string table, if the filename exceeds 15 characters or has a
274 // embedded space, the filename has #1/<size>, The size represents the size
275 // of the filename that needs to be read after the archive header
276 // COFF archive format
278 // Second member : / (provides a directory of symbols)
279 // Third member : // (may exist, if it exists, contains the string table)
280 // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
281 // even if the string table is empty. However, lib.exe does not in fact
282 // seem to create the third member if there's no member whose filename
283 // exceeds 15 characters. So the third member is optional.
285 if (Name == "__.SYMDEF") {
290 ec = std::error_code();
294 if (Name.startswith("#1/")) {
296 // We know this is BSD, so getName will work since there is no string table.
297 ErrorOr<StringRef> NameOrErr = i->getName();
298 ec = NameOrErr.getError();
301 Name = NameOrErr.get();
302 if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
310 // MIPS 64-bit ELF archives use a special format of a symbol table.
311 // This format is marked by `ar_name` field equals to "/SYM64/".
312 // For detailed description see page 96 in the following document:
313 // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
315 bool has64SymTable = false;
316 if (Name == "/" || Name == "/SYM64/") {
318 if (Name == "/SYM64/")
319 has64SymTable = true;
323 ec = std::error_code();
326 Name = i->getRawName();
330 Format = has64SymTable ? K_MIPS64 : K_GNU;
334 ec = std::error_code();
338 if (Name[0] != '/') {
339 Format = has64SymTable ? K_MIPS64 : K_GNU;
341 ec = std::error_code();
346 ec = object_error::parse_failed;
356 ec = std::error_code();
360 Name = i->getRawName();
368 ec = std::error_code();
371 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
372 if (Data.getBufferSize() == 8) // empty archive.
378 const char *Loc = Data.getBufferStart() + strlen(Magic);
383 Archive::child_iterator Archive::child_end() const {
384 return Child(this, nullptr);
387 StringRef Archive::Symbol::getName() const {
388 return Parent->getSymbolTable().begin() + StringIndex;
391 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
392 const char *Buf = Parent->getSymbolTable().begin();
393 const char *Offsets = Buf;
394 if (Parent->kind() == K_MIPS64)
395 Offsets += sizeof(uint64_t);
397 Offsets += sizeof(uint32_t);
399 if (Parent->kind() == K_GNU) {
400 Offset = read32be(Offsets + SymbolIndex * 4);
401 } else if (Parent->kind() == K_MIPS64) {
402 Offset = read64be(Offsets + SymbolIndex * 8);
403 } else if (Parent->kind() == K_BSD) {
404 // The SymbolIndex is an index into the ranlib structs that start at
405 // Offsets (the first uint32_t is the number of bytes of the ranlib
406 // structs). The ranlib structs are a pair of uint32_t's the first
407 // being a string table offset and the second being the offset into
408 // the archive of the member that defines the symbol. Which is what
410 Offset = read32le(Offsets + SymbolIndex * 8 + 4);
413 uint32_t MemberCount = read32le(Buf);
414 Buf += MemberCount * 4 + 4;
416 uint32_t SymbolCount = read32le(Buf);
417 if (SymbolIndex >= SymbolCount)
418 return object_error::parse_failed;
420 // Skip SymbolCount to get to the indices table.
421 const char *Indices = Buf + 4;
423 // Get the index of the offset in the file member offset table for this
425 uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
426 // Subtract 1 since OffsetIndex is 1 based.
429 if (OffsetIndex >= MemberCount)
430 return object_error::parse_failed;
432 Offset = read32le(Offsets + OffsetIndex * 4);
435 const char *Loc = Parent->getData().begin() + Offset;
436 child_iterator Iter(Child(Parent, Loc));
440 Archive::Symbol Archive::Symbol::getNext() const {
442 if (Parent->kind() == K_BSD) {
443 // t.StringIndex is an offset from the start of the __.SYMDEF or
444 // "__.SYMDEF SORTED" member into the string table for the ranlib
445 // struct indexed by t.SymbolIndex . To change t.StringIndex to the
446 // offset in the string table for t.SymbolIndex+1 we subtract the
447 // its offset from the start of the string table for t.SymbolIndex
448 // and add the offset of the string table for t.SymbolIndex+1.
450 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
451 // which is the number of bytes of ranlib structs that follow. The ranlib
452 // structs are a pair of uint32_t's the first being a string table offset
453 // and the second being the offset into the archive of the member that
454 // define the symbol. After that the next uint32_t is the byte count of
455 // the string table followed by the string table.
456 const char *Buf = Parent->getSymbolTable().begin();
457 uint32_t RanlibCount = 0;
458 RanlibCount = read32le(Buf) / 8;
459 // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
460 // don't change the t.StringIndex as we don't want to reference a ranlib
462 if (t.SymbolIndex + 1 < RanlibCount) {
463 const char *Ranlibs = Buf + 4;
464 uint32_t CurRanStrx = 0;
465 uint32_t NextRanStrx = 0;
466 CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
467 NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
468 t.StringIndex -= CurRanStrx;
469 t.StringIndex += NextRanStrx;
472 // Go to one past next null.
473 t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
479 Archive::symbol_iterator Archive::symbol_begin() const {
480 if (!hasSymbolTable())
481 return symbol_iterator(Symbol(this, 0, 0));
483 const char *buf = getSymbolTable().begin();
484 if (kind() == K_GNU) {
485 uint32_t symbol_count = 0;
486 symbol_count = read32be(buf);
487 buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
488 } else if (kind() == K_MIPS64) {
489 uint64_t symbol_count = read64be(buf);
490 buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
491 } else if (kind() == K_BSD) {
492 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
493 // which is the number of bytes of ranlib structs that follow. The ranlib
494 // structs are a pair of uint32_t's the first being a string table offset
495 // and the second being the offset into the archive of the member that
496 // define the symbol. After that the next uint32_t is the byte count of
497 // the string table followed by the string table.
498 uint32_t ranlib_count = 0;
499 ranlib_count = read32le(buf) / 8;
500 const char *ranlibs = buf + 4;
501 uint32_t ran_strx = 0;
502 ran_strx = read32le(ranlibs);
503 buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
504 // Skip the byte count of the string table.
505 buf += sizeof(uint32_t);
508 uint32_t member_count = 0;
509 uint32_t symbol_count = 0;
510 member_count = read32le(buf);
511 buf += 4 + (member_count * 4); // Skip offsets.
512 symbol_count = read32le(buf);
513 buf += 4 + (symbol_count * 2); // Skip indices.
515 uint32_t string_start_offset = buf - getSymbolTable().begin();
516 return symbol_iterator(Symbol(this, 0, string_start_offset));
519 Archive::symbol_iterator Archive::symbol_end() const {
520 return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
523 uint32_t Archive::getNumberOfSymbols() const {
524 if (!hasSymbolTable())
526 const char *buf = getSymbolTable().begin();
528 return read32be(buf);
529 if (kind() == K_MIPS64)
530 return read64be(buf);
532 return read32le(buf) / 8;
533 uint32_t member_count = 0;
534 member_count = read32le(buf);
535 buf += 4 + (member_count * 4); // Skip offsets.
536 return read32le(buf);
539 Archive::child_iterator Archive::findSym(StringRef name) const {
540 Archive::symbol_iterator bs = symbol_begin();
541 Archive::symbol_iterator es = symbol_end();
543 for (; bs != es; ++bs) {
544 StringRef SymName = bs->getName();
545 if (SymName == name) {
546 ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
547 // FIXME: Should we really eat the error?
548 if (ResultOrErr.getError())
550 return ResultOrErr.get();
556 bool Archive::hasSymbolTable() const {
557 return SymbolTable != child_end();