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"
22 using namespace object;
24 static const char *const Magic = "!<arch>\n";
25 static const char *const ThinMagic = "!<thin>\n";
27 void Archive::anchor() { }
29 StringRef ArchiveMemberHeader::getName() const {
31 if (Name[0] == '/' || Name[0] == '#')
35 llvm::StringRef::size_type end =
36 llvm::StringRef(Name, sizeof(Name)).find(EndCond);
37 if (end == llvm::StringRef::npos)
39 assert(end <= sizeof(Name) && end > 0);
40 // Don't include the EndCond if there is one.
41 return llvm::StringRef(Name, end);
44 uint32_t ArchiveMemberHeader::getSize() const {
46 if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
47 llvm_unreachable("Size is not a decimal number.");
51 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
53 if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
54 llvm_unreachable("Access mode is not an octal number.");
55 return static_cast<sys::fs::perms>(Ret);
58 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
60 if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
61 .getAsInteger(10, Seconds))
62 llvm_unreachable("Last modified time not a decimal number.");
65 Ret.fromEpochTime(Seconds);
69 unsigned ArchiveMemberHeader::getUID() const {
71 if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
72 llvm_unreachable("UID time not a decimal number.");
76 unsigned ArchiveMemberHeader::getGID() const {
78 if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
79 llvm_unreachable("GID time not a decimal number.");
83 Archive::Child::Child(const Archive *Parent, const char *Start)
88 const ArchiveMemberHeader *Header =
89 reinterpret_cast<const ArchiveMemberHeader *>(Start);
90 uint64_t Size = sizeof(ArchiveMemberHeader);
91 if (!Parent->IsThin || Header->getName() == "/" || Header->getName() == "//")
92 Size += Header->getSize();
93 Data = StringRef(Start, Size);
95 // Setup StartOfFile and PaddingBytes.
96 StartOfFile = sizeof(ArchiveMemberHeader);
97 // Don't include attached name.
98 StringRef Name = Header->getName();
99 if (Name.startswith("#1/")) {
101 if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
102 llvm_unreachable("Long name length is not an integer");
103 StartOfFile += NameSize;
107 uint64_t Archive::Child::getSize() const {
109 return getHeader()->getSize();
110 return Data.size() - StartOfFile;
113 uint64_t Archive::Child::getRawSize() const {
115 return getHeader()->getSize();
119 Archive::Child Archive::Child::getNext() const {
120 size_t SpaceToSkip = Data.size();
121 // If it's odd, add 1 to make it even.
125 const char *NextLoc = Data.data() + SpaceToSkip;
127 // Check to see if this is past the end of the archive.
128 if (NextLoc >= Parent->Data.getBufferEnd())
129 return Child(Parent, nullptr);
131 return Child(Parent, NextLoc);
134 uint64_t Archive::Child::getChildOffset() const {
135 const char *a = Parent->Data.getBuffer().data();
136 const char *c = Data.data();
137 uint64_t offset = c - a;
141 ErrorOr<StringRef> Archive::Child::getName() const {
142 StringRef name = getRawName();
143 // Check if it's a special name.
144 if (name[0] == '/') {
145 if (name.size() == 1) // Linker member.
147 if (name.size() == 2 && name[1] == '/') // String table.
152 if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
153 llvm_unreachable("Long name offset is not an integer");
154 const char *addr = Parent->StringTable->Data.begin()
155 + sizeof(ArchiveMemberHeader)
158 if (Parent->StringTable == Parent->child_end()
159 || addr < (Parent->StringTable->Data.begin()
160 + sizeof(ArchiveMemberHeader))
161 || addr > (Parent->StringTable->Data.begin()
162 + sizeof(ArchiveMemberHeader)
163 + Parent->StringTable->getSize()))
164 return object_error::parse_failed;
166 // GNU long file names end with a /.
167 if (Parent->kind() == K_GNU) {
168 StringRef::size_type End = StringRef(addr).find('/');
169 return StringRef(addr, End);
171 return StringRef(addr);
172 } else if (name.startswith("#1/")) {
174 if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
175 llvm_unreachable("Long name length is not an ingeter");
176 return Data.substr(sizeof(ArchiveMemberHeader), name_size)
177 .rtrim(StringRef("\0", 1));
179 // It's a simple name.
180 if (name[name.size() - 1] == '/')
181 return name.substr(0, name.size() - 1);
185 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
186 ErrorOr<StringRef> NameOrErr = getName();
187 if (std::error_code EC = NameOrErr.getError())
189 StringRef Name = NameOrErr.get();
190 return MemoryBufferRef(getBuffer(), Name);
193 ErrorOr<std::unique_ptr<Binary>>
194 Archive::Child::getAsBinary(LLVMContext *Context) const {
195 ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
196 if (std::error_code EC = BuffOrErr.getError())
199 return createBinary(BuffOrErr.get(), Context);
202 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
204 std::unique_ptr<Archive> Ret(new Archive(Source, EC));
207 return std::move(Ret);
210 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
211 : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()) {
212 StringRef Buffer = Data.getBuffer();
213 // Check for sufficient magic.
214 if (Buffer.startswith(ThinMagic)) {
216 } else if (Buffer.startswith(Magic)) {
219 ec = object_error::invalid_file_type;
223 // Get the special members.
224 child_iterator i = child_begin(false);
225 child_iterator e = child_end();
228 ec = object_error::success;
232 StringRef Name = i->getRawName();
234 // Below is the pattern that is used to figure out the archive format
235 // GNU archive format
236 // First member : / (may exist, if it exists, points to the symbol table )
237 // Second member : // (may exist, if it exists, points to the string table)
238 // Note : The string table is used if the filename exceeds 15 characters
239 // BSD archive format
240 // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
241 // There is no string table, if the filename exceeds 15 characters or has a
242 // embedded space, the filename has #1/<size>, The size represents the size
243 // of the filename that needs to be read after the archive header
244 // COFF archive format
246 // Second member : / (provides a directory of symbols)
247 // Third member : // (may exist, if it exists, contains the string table)
248 // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
249 // even if the string table is empty. However, lib.exe does not in fact
250 // seem to create the third member if there's no member whose filename
251 // exceeds 15 characters. So the third member is optional.
253 if (Name == "__.SYMDEF") {
258 ec = object_error::success;
262 if (Name.startswith("#1/")) {
264 // We know this is BSD, so getName will work since there is no string table.
265 ErrorOr<StringRef> NameOrErr = i->getName();
266 ec = NameOrErr.getError();
269 Name = NameOrErr.get();
270 if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
283 ec = object_error::parse_failed;
286 Name = i->getRawName();
294 ec = object_error::success;
298 if (Name[0] != '/') {
301 ec = object_error::success;
306 ec = object_error::parse_failed;
316 ec = object_error::success;
320 Name = i->getRawName();
328 ec = object_error::success;
331 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
332 if (Data.getBufferSize() == 8) // empty archive.
338 const char *Loc = Data.getBufferStart() + strlen(Magic);
343 Archive::child_iterator Archive::child_end() const {
344 return Child(this, nullptr);
347 StringRef Archive::Symbol::getName() const {
348 return Parent->SymbolTable->getBuffer().begin() + StringIndex;
351 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
352 const char *Buf = Parent->SymbolTable->getBuffer().begin();
353 const char *Offsets = Buf + 4;
355 if (Parent->kind() == K_GNU) {
356 Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
358 } else if (Parent->kind() == K_BSD) {
359 // The SymbolIndex is an index into the ranlib structs that start at
360 // Offsets (the first uint32_t is the number of bytes of the ranlib
361 // structs). The ranlib structs are a pair of uint32_t's the first
362 // being a string table offset and the second being the offset into
363 // the archive of the member that defines the symbol. Which is what
365 Offset = *(reinterpret_cast<const support::ulittle32_t *>(Offsets) +
366 (SymbolIndex * 2) + 1);
368 uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
371 Buf += sizeof(support::ulittle32_t)
372 + (MemberCount * sizeof(support::ulittle32_t));
374 uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
376 if (SymbolIndex >= SymbolCount)
377 return object_error::parse_failed;
379 // Skip SymbolCount to get to the indices table.
380 const char *Indices = Buf + sizeof(support::ulittle32_t);
382 // Get the index of the offset in the file member offset table for this
384 uint16_t OffsetIndex =
385 *(reinterpret_cast<const support::ulittle16_t*>(Indices)
387 // Subtract 1 since OffsetIndex is 1 based.
390 if (OffsetIndex >= MemberCount)
391 return object_error::parse_failed;
393 Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
397 const char *Loc = Parent->getData().begin() + Offset;
398 child_iterator Iter(Child(Parent, Loc));
402 Archive::Symbol Archive::Symbol::getNext() const {
404 if (Parent->kind() == K_BSD) {
405 // t.StringIndex is an offset from the start of the __.SYMDEF or
406 // "__.SYMDEF SORTED" member into the string table for the ranlib
407 // struct indexed by t.SymbolIndex . To change t.StringIndex to the
408 // offset in the string table for t.SymbolIndex+1 we subtract the
409 // its offset from the start of the string table for t.SymbolIndex
410 // and add the offset of the string table for t.SymbolIndex+1.
412 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
413 // which is the number of bytes of ranlib structs that follow. The ranlib
414 // structs are a pair of uint32_t's the first being a string table offset
415 // and the second being the offset into the archive of the member that
416 // define the symbol. After that the next uint32_t is the byte count of
417 // the string table followed by the string table.
418 const char *Buf = Parent->SymbolTable->getBuffer().begin();
419 uint32_t RanlibCount = 0;
420 RanlibCount = (*reinterpret_cast<const support::ulittle32_t *>(Buf)) /
421 (sizeof(uint32_t) * 2);
422 // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
423 // don't change the t.StringIndex as we don't want to reference a ranlib
425 if (t.SymbolIndex + 1 < RanlibCount) {
426 const char *Ranlibs = Buf + 4;
427 uint32_t CurRanStrx = 0;
428 uint32_t NextRanStrx = 0;
429 CurRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
430 (t.SymbolIndex * 2));
431 NextRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
432 ((t.SymbolIndex + 1) * 2));
433 t.StringIndex -= CurRanStrx;
434 t.StringIndex += NextRanStrx;
437 // Go to one past next null.
439 Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
445 Archive::symbol_iterator Archive::symbol_begin() const {
446 if (!hasSymbolTable())
447 return symbol_iterator(Symbol(this, 0, 0));
449 const char *buf = SymbolTable->getBuffer().begin();
450 if (kind() == K_GNU) {
451 uint32_t symbol_count = 0;
452 symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
453 buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
454 } else if (kind() == K_BSD) {
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 uint32_t ranlib_count = 0;
462 ranlib_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
463 (sizeof(uint32_t) * 2);
464 const char *ranlibs = buf + 4;
465 uint32_t ran_strx = 0;
466 ran_strx = *(reinterpret_cast<const support::ulittle32_t *>(ranlibs));
467 buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
468 // Skip the byte count of the string table.
469 buf += sizeof(uint32_t);
472 uint32_t member_count = 0;
473 uint32_t symbol_count = 0;
474 member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
475 buf += 4 + (member_count * 4); // Skip offsets.
476 symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
477 buf += 4 + (symbol_count * 2); // Skip indices.
479 uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
480 return symbol_iterator(Symbol(this, 0, string_start_offset));
483 Archive::symbol_iterator Archive::symbol_end() const {
484 if (!hasSymbolTable())
485 return symbol_iterator(Symbol(this, 0, 0));
487 const char *buf = SymbolTable->getBuffer().begin();
488 uint32_t symbol_count = 0;
489 if (kind() == K_GNU) {
490 symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
491 } else if (kind() == K_BSD) {
492 symbol_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
493 (sizeof(uint32_t) * 2);
495 uint32_t member_count = 0;
496 member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
497 buf += 4 + (member_count * 4); // Skip offsets.
498 symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
500 return symbol_iterator(
501 Symbol(this, symbol_count, 0));
504 Archive::child_iterator Archive::findSym(StringRef name) const {
505 Archive::symbol_iterator bs = symbol_begin();
506 Archive::symbol_iterator es = symbol_end();
508 for (; bs != es; ++bs) {
509 StringRef SymName = bs->getName();
510 if (SymName == name) {
511 ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
512 // FIXME: Should we really eat the error?
513 if (ResultOrErr.getError())
515 return ResultOrErr.get();
521 bool Archive::hasSymbolTable() const {
522 return SymbolTable != child_end();