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";
26 void Archive::anchor() { }
28 StringRef ArchiveMemberHeader::getName() const {
30 if (Name[0] == '/' || Name[0] == '#')
34 llvm::StringRef::size_type end =
35 llvm::StringRef(Name, sizeof(Name)).find(EndCond);
36 if (end == llvm::StringRef::npos)
38 assert(end <= sizeof(Name) && end > 0);
39 // Don't include the EndCond if there is one.
40 return llvm::StringRef(Name, end);
43 uint32_t ArchiveMemberHeader::getSize() const {
45 if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
46 llvm_unreachable("Size is not a decimal number.");
50 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
52 if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
53 llvm_unreachable("Access mode is not an octal number.");
54 return static_cast<sys::fs::perms>(Ret);
57 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
59 if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
60 .getAsInteger(10, Seconds))
61 llvm_unreachable("Last modified time not a decimal number.");
64 Ret.fromEpochTime(Seconds);
68 unsigned ArchiveMemberHeader::getUID() const {
70 if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
71 llvm_unreachable("UID time not a decimal number.");
75 unsigned ArchiveMemberHeader::getGID() const {
77 if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
78 llvm_unreachable("GID time not a decimal number.");
82 Archive::Child::Child(const Archive *Parent, const char *Start)
87 const ArchiveMemberHeader *Header =
88 reinterpret_cast<const ArchiveMemberHeader *>(Start);
89 Data = StringRef(Start, sizeof(ArchiveMemberHeader) + Header->getSize());
91 // Setup StartOfFile and PaddingBytes.
92 StartOfFile = sizeof(ArchiveMemberHeader);
93 // Don't include attached name.
94 StringRef Name = Header->getName();
95 if (Name.startswith("#1/")) {
97 if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
98 llvm_unreachable("Long name length is not an integer");
99 StartOfFile += NameSize;
103 Archive::Child Archive::Child::getNext() const {
104 size_t SpaceToSkip = Data.size();
105 // If it's odd, add 1 to make it even.
109 const char *NextLoc = Data.data() + SpaceToSkip;
111 // Check to see if this is past the end of the archive.
112 if (NextLoc >= Parent->Data->getBufferEnd())
113 return Child(Parent, nullptr);
115 return Child(Parent, NextLoc);
118 ErrorOr<StringRef> Archive::Child::getName() const {
119 StringRef name = getRawName();
120 // Check if it's a special name.
121 if (name[0] == '/') {
122 if (name.size() == 1) // Linker member.
124 if (name.size() == 2 && name[1] == '/') // String table.
129 if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
130 llvm_unreachable("Long name offset is not an integer");
131 const char *addr = Parent->StringTable->Data.begin()
132 + sizeof(ArchiveMemberHeader)
135 if (Parent->StringTable == Parent->child_end()
136 || addr < (Parent->StringTable->Data.begin()
137 + sizeof(ArchiveMemberHeader))
138 || addr > (Parent->StringTable->Data.begin()
139 + sizeof(ArchiveMemberHeader)
140 + Parent->StringTable->getSize()))
141 return object_error::parse_failed;
143 // GNU long file names end with a /.
144 if (Parent->kind() == K_GNU) {
145 StringRef::size_type End = StringRef(addr).find('/');
146 return StringRef(addr, End);
148 return StringRef(addr);
149 } else if (name.startswith("#1/")) {
151 if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
152 llvm_unreachable("Long name length is not an ingeter");
153 return Data.substr(sizeof(ArchiveMemberHeader), name_size)
154 .rtrim(StringRef("\0", 1));
156 // It's a simple name.
157 if (name[name.size() - 1] == '/')
158 return name.substr(0, name.size() - 1);
162 ErrorOr<std::unique_ptr<MemoryBuffer>>
163 Archive::Child::getMemoryBuffer(bool FullPath) const {
164 ErrorOr<StringRef> NameOrErr = getName();
165 if (std::error_code EC = NameOrErr.getError())
167 StringRef Name = NameOrErr.get();
168 SmallString<128> Path;
169 std::unique_ptr<MemoryBuffer> Ret(MemoryBuffer::getMemBuffer(
172 ? (Twine(Parent->getFileName()) + "(" + Name + ")").toStringRef(Path)
175 return std::move(Ret);
178 ErrorOr<std::unique_ptr<Binary>>
179 Archive::Child::getAsBinary(LLVMContext *Context) const {
180 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr = getMemoryBuffer();
181 if (std::error_code EC = BuffOrErr.getError())
184 return createBinary(std::move(*BuffOrErr), Context);
187 ErrorOr<std::unique_ptr<Archive>>
188 Archive::create(std::unique_ptr<MemoryBuffer> Source) {
190 std::unique_ptr<Archive> Ret(new Archive(std::move(Source), EC));
193 return std::move(Ret);
196 Archive::Archive(std::unique_ptr<MemoryBuffer> Source, std::error_code &ec)
197 : Binary(Binary::ID_Archive, std::move(Source)), SymbolTable(child_end()) {
198 // Check for sufficient magic.
199 if (Data->getBufferSize() < 8 ||
200 StringRef(Data->getBufferStart(), 8) != Magic) {
201 ec = object_error::invalid_file_type;
205 // Get the special members.
206 child_iterator i = child_begin(false);
207 child_iterator e = child_end();
210 ec = object_error::success;
214 StringRef Name = i->getRawName();
216 // Below is the pattern that is used to figure out the archive format
217 // GNU archive format
218 // First member : / (may exist, if it exists, points to the symbol table )
219 // Second member : // (may exist, if it exists, points to the string table)
220 // Note : The string table is used if the filename exceeds 15 characters
221 // BSD archive format
222 // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
223 // There is no string table, if the filename exceeds 15 characters or has a
224 // embedded space, the filename has #1/<size>, The size represents the size
225 // of the filename that needs to be read after the archive header
226 // COFF archive format
228 // Second member : / (provides a directory of symbols)
229 // Third member : // (may exist, if it exists, contains the string table)
230 // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
231 // even if the string table is empty. However, lib.exe does not in fact
232 // seem to create the third member if there's no member whose filename
233 // exceeds 15 characters. So the third member is optional.
235 if (Name == "__.SYMDEF") {
240 ec = object_error::success;
244 if (Name.startswith("#1/")) {
246 // We know this is BSD, so getName will work since there is no string table.
247 ErrorOr<StringRef> NameOrErr = i->getName();
248 ec = NameOrErr.getError();
251 Name = NameOrErr.get();
252 if (Name == "__.SYMDEF SORTED") {
265 ec = object_error::parse_failed;
268 Name = i->getRawName();
276 ec = object_error::success;
280 if (Name[0] != '/') {
283 ec = object_error::success;
288 ec = object_error::parse_failed;
298 ec = object_error::success;
302 Name = i->getRawName();
310 ec = object_error::success;
313 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
314 if (Data->getBufferSize() == 8) // empty archive.
320 const char *Loc = Data->getBufferStart() + strlen(Magic);
325 Archive::child_iterator Archive::child_end() const {
326 return Child(this, nullptr);
329 StringRef Archive::Symbol::getName() const {
330 return Parent->SymbolTable->getBuffer().begin() + StringIndex;
333 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
334 const char *Buf = Parent->SymbolTable->getBuffer().begin();
335 const char *Offsets = Buf + 4;
337 if (Parent->kind() == K_GNU) {
338 Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
340 } else if (Parent->kind() == K_BSD) {
341 // The SymbolIndex is an index into the ranlib structs that start at
342 // Offsets (the first uint32_t is the number of bytes of the ranlib
343 // structs). The ranlib structs are a pair of uint32_t's the first
344 // being a string table offset and the second being the offset into
345 // the archive of the member that defines the symbol. Which is what
347 Offset = *(reinterpret_cast<const support::ulittle32_t *>(Offsets) +
348 (SymbolIndex * 2) + 1);
350 uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
353 Buf += sizeof(support::ulittle32_t)
354 + (MemberCount * sizeof(support::ulittle32_t));
356 uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
358 if (SymbolIndex >= SymbolCount)
359 return object_error::parse_failed;
361 // Skip SymbolCount to get to the indices table.
362 const char *Indices = Buf + sizeof(support::ulittle32_t);
364 // Get the index of the offset in the file member offset table for this
366 uint16_t OffsetIndex =
367 *(reinterpret_cast<const support::ulittle16_t*>(Indices)
369 // Subtract 1 since OffsetIndex is 1 based.
372 if (OffsetIndex >= MemberCount)
373 return object_error::parse_failed;
375 Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
379 const char *Loc = Parent->getData().begin() + Offset;
380 child_iterator Iter(Child(Parent, Loc));
384 Archive::Symbol Archive::Symbol::getNext() const {
386 if (Parent->kind() == K_BSD) {
387 // t.StringIndex is an offset from the start of the __.SYMDEF or
388 // "__.SYMDEF SORTED" member into the string table for the ranlib
389 // struct indexed by t.SymbolIndex . To change t.StringIndex to the
390 // offset in the string table for t.SymbolIndex+1 we subtract the
391 // its offset from the start of the string table for t.SymbolIndex
392 // and add the offset of the string table for t.SymbolIndex+1.
394 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
395 // which is the number of bytes of ranlib structs that follow. The ranlib
396 // structs are a pair of uint32_t's the first being a string table offset
397 // and the second being the offset into the archive of the member that
398 // define the symbol. After that the next uint32_t is the byte count of
399 // the string table followed by the string table.
400 const char *Buf = Parent->SymbolTable->getBuffer().begin();
401 uint32_t RanlibCount = 0;
402 RanlibCount = (*reinterpret_cast<const support::ulittle32_t *>(Buf)) /
403 (sizeof(uint32_t) * 2);
404 // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
405 // don't change the t.StringIndex as we don't want to reference a ranlib
407 if (t.SymbolIndex + 1 < RanlibCount) {
408 const char *Ranlibs = Buf + 4;
409 uint32_t CurRanStrx = 0;
410 uint32_t NextRanStrx = 0;
411 CurRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
412 (t.SymbolIndex * 2));
413 NextRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
414 ((t.SymbolIndex + 1) * 2));
415 t.StringIndex -= CurRanStrx;
416 t.StringIndex += NextRanStrx;
419 // Go to one past next null.
421 Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
427 Archive::symbol_iterator Archive::symbol_begin() const {
428 if (!hasSymbolTable())
429 return symbol_iterator(Symbol(this, 0, 0));
431 const char *buf = SymbolTable->getBuffer().begin();
432 if (kind() == K_GNU) {
433 uint32_t symbol_count = 0;
434 symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
435 buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
436 } else if (kind() == K_BSD) {
437 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
438 // which is the number of bytes of ranlib structs that follow. The ranlib
439 // structs are a pair of uint32_t's the first being a string table offset
440 // and the second being the offset into the archive of the member that
441 // define the symbol. After that the next uint32_t is the byte count of
442 // the string table followed by the string table.
443 uint32_t ranlib_count = 0;
444 ranlib_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
445 (sizeof(uint32_t) * 2);
446 const char *ranlibs = buf + 4;
447 uint32_t ran_strx = 0;
448 ran_strx = *(reinterpret_cast<const support::ulittle32_t *>(ranlibs));
449 buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
450 // Skip the byte count of the string table.
451 buf += sizeof(uint32_t);
454 uint32_t member_count = 0;
455 uint32_t symbol_count = 0;
456 member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
457 buf += 4 + (member_count * 4); // Skip offsets.
458 symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
459 buf += 4 + (symbol_count * 2); // Skip indices.
461 uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
462 return symbol_iterator(Symbol(this, 0, string_start_offset));
465 Archive::symbol_iterator Archive::symbol_end() const {
466 if (!hasSymbolTable())
467 return symbol_iterator(Symbol(this, 0, 0));
469 const char *buf = SymbolTable->getBuffer().begin();
470 uint32_t symbol_count = 0;
471 if (kind() == K_GNU) {
472 symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
473 } else if (kind() == K_BSD) {
474 symbol_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
475 (sizeof(uint32_t) * 2);
477 uint32_t member_count = 0;
478 member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
479 buf += 4 + (member_count * 4); // Skip offsets.
480 symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
482 return symbol_iterator(
483 Symbol(this, symbol_count, 0));
486 Archive::child_iterator Archive::findSym(StringRef name) const {
487 Archive::symbol_iterator bs = symbol_begin();
488 Archive::symbol_iterator es = symbol_end();
490 for (; bs != es; ++bs) {
491 StringRef SymName = bs->getName();
492 if (SymName == name) {
493 ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
494 // FIXME: Should we really eat the error?
495 if (ResultOrErr.getError())
497 return ResultOrErr.get();
503 bool Archive::hasSymbolTable() const {
504 return SymbolTable != child_end();