1 //===- Archive.cpp - ar File Format implementation ------------------------===//
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/ADT/Optional.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/Binary.h"
20 #include "llvm/Object/Error.h"
21 #include "llvm/Support/Chrono.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/Error.h"
24 #include "llvm/Support/ErrorOr.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/raw_ostream.h"
36 #include <system_error>
39 using namespace object;
40 using namespace llvm::support::endian;
42 static const char *const Magic = "!<arch>\n";
43 static const char *const ThinMagic = "!<thin>\n";
45 void Archive::anchor() {}
48 malformedError(Twine Msg) {
49 std::string StringMsg = "truncated or malformed archive (" + Msg.str() + ")";
50 return make_error<GenericBinaryError>(std::move(StringMsg),
51 object_error::parse_failed);
54 ArchiveMemberHeader::ArchiveMemberHeader(const Archive *Parent,
55 const char *RawHeaderPtr,
56 uint64_t Size, Error *Err)
58 ArMemHdr(reinterpret_cast<const ArMemHdrType *>(RawHeaderPtr)) {
59 if (RawHeaderPtr == nullptr)
61 ErrorAsOutParameter ErrAsOutParam(Err);
63 if (Size < sizeof(ArMemHdrType)) {
65 std::string Msg("remaining size of archive too small for next archive "
67 Expected<StringRef> NameOrErr = getName(Size);
69 consumeError(NameOrErr.takeError());
70 uint64_t Offset = RawHeaderPtr - Parent->getData().data();
71 *Err = malformedError(Msg + "at offset " + Twine(Offset));
73 *Err = malformedError(Msg + "for " + NameOrErr.get());
77 if (ArMemHdr->Terminator[0] != '`' || ArMemHdr->Terminator[1] != '\n') {
80 raw_string_ostream OS(Buf);
81 OS.write_escaped(StringRef(ArMemHdr->Terminator,
82 sizeof(ArMemHdr->Terminator)));
84 std::string Msg("terminator characters in archive member \"" + Buf +
85 "\" not the correct \"`\\n\" values for the archive "
87 Expected<StringRef> NameOrErr = getName(Size);
89 consumeError(NameOrErr.takeError());
90 uint64_t Offset = RawHeaderPtr - Parent->getData().data();
91 *Err = malformedError(Msg + "at offset " + Twine(Offset));
93 *Err = malformedError(Msg + "for " + NameOrErr.get());
99 // This gets the raw name from the ArMemHdr->Name field and checks that it is
100 // valid for the kind of archive. If it is not valid it returns an Error.
101 Expected<StringRef> ArchiveMemberHeader::getRawName() const {
103 auto Kind = Parent->kind();
104 if (Kind == Archive::K_BSD || Kind == Archive::K_DARWIN64) {
105 if (ArMemHdr->Name[0] == ' ') {
106 uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
107 Parent->getData().data();
108 return malformedError("name contains a leading space for archive member "
109 "header at offset " + Twine(Offset));
113 else if (ArMemHdr->Name[0] == '/' || ArMemHdr->Name[0] == '#')
117 StringRef::size_type end =
118 StringRef(ArMemHdr->Name, sizeof(ArMemHdr->Name)).find(EndCond);
119 if (end == StringRef::npos)
120 end = sizeof(ArMemHdr->Name);
121 assert(end <= sizeof(ArMemHdr->Name) && end > 0);
122 // Don't include the EndCond if there is one.
123 return StringRef(ArMemHdr->Name, end);
126 // This gets the name looking up long names. Size is the size of the archive
127 // member including the header, so the size of any name following the header
128 // is checked to make sure it does not overflow.
129 Expected<StringRef> ArchiveMemberHeader::getName(uint64_t Size) const {
131 // This can be called from the ArchiveMemberHeader constructor when the
132 // archive header is truncated to produce an error message with the name.
133 // Make sure the name field is not truncated.
134 if (Size < offsetof(ArMemHdrType, Name) + sizeof(ArMemHdr->Name)) {
135 uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
136 Parent->getData().data();
137 return malformedError("archive header truncated before the name field "
138 "for archive member header at offset " +
139 Twine(ArchiveOffset));
142 // The raw name itself can be invalid.
143 Expected<StringRef> NameOrErr = getRawName();
145 return NameOrErr.takeError();
146 StringRef Name = NameOrErr.get();
148 // Check if it's a special name.
149 if (Name[0] == '/') {
150 if (Name.size() == 1) // Linker member.
152 if (Name.size() == 2 && Name[1] == '/') // String table.
155 // Get the string table offset.
156 std::size_t StringOffset;
157 if (Name.substr(1).rtrim(' ').getAsInteger(10, StringOffset)) {
159 raw_string_ostream OS(Buf);
160 OS.write_escaped(Name.substr(1).rtrim(' '));
162 uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
163 Parent->getData().data();
164 return malformedError("long name offset characters after the '/' are "
165 "not all decimal numbers: '" + Buf + "' for "
166 "archive member header at offset " +
167 Twine(ArchiveOffset));
171 if (StringOffset >= Parent->getStringTable().size()) {
172 uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
173 Parent->getData().data();
174 return malformedError("long name offset " + Twine(StringOffset) + " past "
175 "the end of the string table for archive member "
176 "header at offset " + Twine(ArchiveOffset));
178 const char *addr = Parent->getStringTable().begin() + StringOffset;
180 // GNU long file names end with a "/\n".
181 if (Parent->kind() == Archive::K_GNU ||
182 Parent->kind() == Archive::K_MIPS64) {
183 StringRef::size_type End = StringRef(addr).find('\n');
184 return StringRef(addr, End - 1);
189 if (Name.startswith("#1/")) {
191 if (Name.substr(3).rtrim(' ').getAsInteger(10, NameLength)) {
193 raw_string_ostream OS(Buf);
194 OS.write_escaped(Name.substr(3).rtrim(' '));
196 uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
197 Parent->getData().data();
198 return malformedError("long name length characters after the #1/ are "
199 "not all decimal numbers: '" + Buf + "' for "
200 "archive member header at offset " +
201 Twine(ArchiveOffset));
203 if (getSizeOf() + NameLength > Size) {
204 uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
205 Parent->getData().data();
206 return malformedError("long name length: " + Twine(NameLength) +
207 " extends past the end of the member or archive "
208 "for archive member header at offset " +
209 Twine(ArchiveOffset));
211 return StringRef(reinterpret_cast<const char *>(ArMemHdr) + getSizeOf(),
212 NameLength).rtrim('\0');
215 // It is not a long name so trim the blanks at the end of the name.
216 if (Name[Name.size() - 1] != '/')
217 return Name.rtrim(' ');
219 // It's a simple name.
220 return Name.drop_back(1);
223 Expected<uint32_t> ArchiveMemberHeader::getSize() const {
225 if (StringRef(ArMemHdr->Size,
226 sizeof(ArMemHdr->Size)).rtrim(" ").getAsInteger(10, Ret)) {
228 raw_string_ostream OS(Buf);
229 OS.write_escaped(StringRef(ArMemHdr->Size,
230 sizeof(ArMemHdr->Size)).rtrim(" "));
232 uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
233 Parent->getData().data();
234 return malformedError("characters in size field in archive header are not "
235 "all decimal numbers: '" + Buf + "' for archive "
236 "member header at offset " + Twine(Offset));
241 Expected<sys::fs::perms> ArchiveMemberHeader::getAccessMode() const {
243 if (StringRef(ArMemHdr->AccessMode,
244 sizeof(ArMemHdr->AccessMode)).rtrim(' ').getAsInteger(8, Ret)) {
246 raw_string_ostream OS(Buf);
247 OS.write_escaped(StringRef(ArMemHdr->AccessMode,
248 sizeof(ArMemHdr->AccessMode)).rtrim(" "));
250 uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
251 Parent->getData().data();
252 return malformedError("characters in AccessMode field in archive header "
253 "are not all decimal numbers: '" + Buf + "' for the "
254 "archive member header at offset " + Twine(Offset));
256 return static_cast<sys::fs::perms>(Ret);
259 Expected<sys::TimePoint<std::chrono::seconds>>
260 ArchiveMemberHeader::getLastModified() const {
262 if (StringRef(ArMemHdr->LastModified,
263 sizeof(ArMemHdr->LastModified)).rtrim(' ')
264 .getAsInteger(10, Seconds)) {
266 raw_string_ostream OS(Buf);
267 OS.write_escaped(StringRef(ArMemHdr->LastModified,
268 sizeof(ArMemHdr->LastModified)).rtrim(" "));
270 uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
271 Parent->getData().data();
272 return malformedError("characters in LastModified field in archive header "
273 "are not all decimal numbers: '" + Buf + "' for the "
274 "archive member header at offset " + Twine(Offset));
277 return sys::toTimePoint(Seconds);
280 Expected<unsigned> ArchiveMemberHeader::getUID() const {
282 StringRef User = StringRef(ArMemHdr->UID, sizeof(ArMemHdr->UID)).rtrim(' ');
285 if (User.getAsInteger(10, Ret)) {
287 raw_string_ostream OS(Buf);
288 OS.write_escaped(User);
290 uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
291 Parent->getData().data();
292 return malformedError("characters in UID field in archive header "
293 "are not all decimal numbers: '" + Buf + "' for the "
294 "archive member header at offset " + Twine(Offset));
299 Expected<unsigned> ArchiveMemberHeader::getGID() const {
301 StringRef Group = StringRef(ArMemHdr->GID, sizeof(ArMemHdr->GID)).rtrim(' ');
304 if (Group.getAsInteger(10, Ret)) {
306 raw_string_ostream OS(Buf);
307 OS.write_escaped(Group);
309 uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
310 Parent->getData().data();
311 return malformedError("characters in GID field in archive header "
312 "are not all decimal numbers: '" + Buf + "' for the "
313 "archive member header at offset " + Twine(Offset));
318 Archive::Child::Child(const Archive *Parent, StringRef Data,
319 uint16_t StartOfFile)
320 : Parent(Parent), Header(Parent, Data.data(), Data.size(), nullptr),
321 Data(Data), StartOfFile(StartOfFile) {
324 Archive::Child::Child(const Archive *Parent, const char *Start, Error *Err)
326 Header(Parent, Start,
328 ? Parent->getData().size() - (Start - Parent->getData().data())
333 // If we are pointed to real data, Start is not a nullptr, then there must be
334 // a non-null Err pointer available to report malformed data on. Only in
335 // the case sentinel value is being constructed is Err is permitted to be a
337 assert(Err && "Err can't be nullptr if Start is not a nullptr");
339 ErrorAsOutParameter ErrAsOutParam(Err);
341 // If there was an error in the construction of the Header
342 // then just return with the error now set.
346 uint64_t Size = Header.getSizeOf();
347 Data = StringRef(Start, Size);
348 Expected<bool> isThinOrErr = isThinMember();
350 *Err = isThinOrErr.takeError();
353 bool isThin = isThinOrErr.get();
355 Expected<uint64_t> MemberSize = getRawSize();
357 *Err = MemberSize.takeError();
360 Size += MemberSize.get();
361 Data = StringRef(Start, Size);
364 // Setup StartOfFile and PaddingBytes.
365 StartOfFile = Header.getSizeOf();
366 // Don't include attached name.
367 Expected<StringRef> NameOrErr = getRawName();
369 *Err = NameOrErr.takeError();
372 StringRef Name = NameOrErr.get();
373 if (Name.startswith("#1/")) {
375 if (Name.substr(3).rtrim(' ').getAsInteger(10, NameSize)) {
377 raw_string_ostream OS(Buf);
378 OS.write_escaped(Name.substr(3).rtrim(' '));
380 uint64_t Offset = Start - Parent->getData().data();
381 *Err = malformedError("long name length characters after the #1/ are "
382 "not all decimal numbers: '" + Buf + "' for "
383 "archive member header at offset " +
387 StartOfFile += NameSize;
391 Expected<uint64_t> Archive::Child::getSize() const {
392 if (Parent->IsThin) {
393 Expected<uint32_t> Size = Header.getSize();
395 return Size.takeError();
398 return Data.size() - StartOfFile;
401 Expected<uint64_t> Archive::Child::getRawSize() const {
402 return Header.getSize();
405 Expected<bool> Archive::Child::isThinMember() const {
406 Expected<StringRef> NameOrErr = Header.getRawName();
408 return NameOrErr.takeError();
409 StringRef Name = NameOrErr.get();
410 return Parent->IsThin && Name != "/" && Name != "//";
413 Expected<std::string> Archive::Child::getFullName() const {
414 Expected<bool> isThin = isThinMember();
416 return isThin.takeError();
417 assert(isThin.get());
418 Expected<StringRef> NameOrErr = getName();
420 return NameOrErr.takeError();
421 StringRef Name = *NameOrErr;
422 if (sys::path::is_absolute(Name))
425 SmallString<128> FullName = sys::path::parent_path(
426 Parent->getMemoryBufferRef().getBufferIdentifier());
427 sys::path::append(FullName, Name);
428 return StringRef(FullName);
431 Expected<StringRef> Archive::Child::getBuffer() const {
432 Expected<bool> isThinOrErr = isThinMember();
434 return isThinOrErr.takeError();
435 bool isThin = isThinOrErr.get();
437 Expected<uint32_t> Size = getSize();
439 return Size.takeError();
440 return StringRef(Data.data() + StartOfFile, Size.get());
442 Expected<std::string> FullNameOrErr = getFullName();
444 return FullNameOrErr.takeError();
445 const std::string &FullName = *FullNameOrErr;
446 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
447 if (std::error_code EC = Buf.getError())
448 return errorCodeToError(EC);
449 Parent->ThinBuffers.push_back(std::move(*Buf));
450 return Parent->ThinBuffers.back()->getBuffer();
453 Expected<Archive::Child> Archive::Child::getNext() const {
454 size_t SpaceToSkip = Data.size();
455 // If it's odd, add 1 to make it even.
459 const char *NextLoc = Data.data() + SpaceToSkip;
461 // Check to see if this is at the end of the archive.
462 if (NextLoc == Parent->Data.getBufferEnd())
463 return Child(nullptr, nullptr, nullptr);
465 // Check to see if this is past the end of the archive.
466 if (NextLoc > Parent->Data.getBufferEnd()) {
467 std::string Msg("offset to next archive member past the end of the archive "
469 Expected<StringRef> NameOrErr = getName();
471 consumeError(NameOrErr.takeError());
472 uint64_t Offset = Data.data() - Parent->getData().data();
473 return malformedError(Msg + "at offset " + Twine(Offset));
475 return malformedError(Msg + NameOrErr.get());
478 Error Err = Error::success();
479 Child Ret(Parent, NextLoc, &Err);
481 return std::move(Err);
485 uint64_t Archive::Child::getChildOffset() const {
486 const char *a = Parent->Data.getBuffer().data();
487 const char *c = Data.data();
488 uint64_t offset = c - a;
492 Expected<StringRef> Archive::Child::getName() const {
493 Expected<uint64_t> RawSizeOrErr = getRawSize();
495 return RawSizeOrErr.takeError();
496 uint64_t RawSize = RawSizeOrErr.get();
497 Expected<StringRef> NameOrErr = Header.getName(Header.getSizeOf() + RawSize);
499 return NameOrErr.takeError();
500 StringRef Name = NameOrErr.get();
504 Expected<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
505 Expected<StringRef> NameOrErr = getName();
507 return NameOrErr.takeError();
508 StringRef Name = NameOrErr.get();
509 Expected<StringRef> Buf = getBuffer();
511 return Buf.takeError();
512 return MemoryBufferRef(*Buf, Name);
515 Expected<std::unique_ptr<Binary>>
516 Archive::Child::getAsBinary(LLVMContext *Context) const {
517 Expected<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
519 return BuffOrErr.takeError();
521 auto BinaryOrErr = createBinary(BuffOrErr.get(), Context);
523 return std::move(*BinaryOrErr);
524 return BinaryOrErr.takeError();
527 Expected<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
528 Error Err = Error::success();
529 std::unique_ptr<Archive> Ret(new Archive(Source, Err));
531 return std::move(Err);
532 return std::move(Ret);
535 void Archive::setFirstRegular(const Child &C) {
536 FirstRegularData = C.Data;
537 FirstRegularStartOfFile = C.StartOfFile;
540 Archive::Archive(MemoryBufferRef Source, Error &Err)
541 : Binary(Binary::ID_Archive, Source) {
542 ErrorAsOutParameter ErrAsOutParam(&Err);
543 StringRef Buffer = Data.getBuffer();
544 // Check for sufficient magic.
545 if (Buffer.startswith(ThinMagic)) {
547 } else if (Buffer.startswith(Magic)) {
550 Err = make_error<GenericBinaryError>("File too small to be an archive",
551 object_error::invalid_file_type);
555 // Make sure Format is initialized before any call to
556 // ArchiveMemberHeader::getName() is made. This could be a valid empty
557 // archive which is the same in all formats. So claiming it to be gnu to is
558 // fine if not totally correct before we look for a string table or table of
562 // Get the special members.
563 child_iterator I = child_begin(Err, false);
566 child_iterator E = child_end();
568 // See if this is a valid empty archive and if so return.
570 Err = Error::success();
573 const Child *C = &*I;
575 auto Increment = [&]() {
583 Expected<StringRef> NameOrErr = C->getRawName();
585 Err = NameOrErr.takeError();
588 StringRef Name = NameOrErr.get();
590 // Below is the pattern that is used to figure out the archive format
591 // GNU archive format
592 // First member : / (may exist, if it exists, points to the symbol table )
593 // Second member : // (may exist, if it exists, points to the string table)
594 // Note : The string table is used if the filename exceeds 15 characters
595 // BSD archive format
596 // First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
597 // There is no string table, if the filename exceeds 15 characters or has a
598 // embedded space, the filename has #1/<size>, The size represents the size
599 // of the filename that needs to be read after the archive header
600 // COFF archive format
602 // Second member : / (provides a directory of symbols)
603 // Third member : // (may exist, if it exists, contains the string table)
604 // Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
605 // even if the string table is empty. However, lib.exe does not in fact
606 // seem to create the third member if there's no member whose filename
607 // exceeds 15 characters. So the third member is optional.
609 if (Name == "__.SYMDEF" || Name == "__.SYMDEF_64") {
610 if (Name == "__.SYMDEF")
612 else // Name == "__.SYMDEF_64"
614 // We know that the symbol table is not an external file, but we still must
615 // check any Expected<> return value.
616 Expected<StringRef> BufOrErr = C->getBuffer();
618 Err = BufOrErr.takeError();
621 SymbolTable = BufOrErr.get();
626 Err = Error::success();
630 if (Name.startswith("#1/")) {
632 // We know this is BSD, so getName will work since there is no string table.
633 Expected<StringRef> NameOrErr = C->getName();
635 Err = NameOrErr.takeError();
638 Name = NameOrErr.get();
639 if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
640 // We know that the symbol table is not an external file, but we still
641 // must check any Expected<> return value.
642 Expected<StringRef> BufOrErr = C->getBuffer();
644 Err = BufOrErr.takeError();
647 SymbolTable = BufOrErr.get();
651 else if (Name == "__.SYMDEF_64 SORTED" || Name == "__.SYMDEF_64") {
653 // We know that the symbol table is not an external file, but we still
654 // must check any Expected<> return value.
655 Expected<StringRef> BufOrErr = C->getBuffer();
657 Err = BufOrErr.takeError();
660 SymbolTable = BufOrErr.get();
668 // MIPS 64-bit ELF archives use a special format of a symbol table.
669 // This format is marked by `ar_name` field equals to "/SYM64/".
670 // For detailed description see page 96 in the following document:
671 // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
673 bool has64SymTable = false;
674 if (Name == "/" || Name == "/SYM64/") {
675 // We know that the symbol table is not an external file, but we still
676 // must check any Expected<> return value.
677 Expected<StringRef> BufOrErr = C->getBuffer();
679 Err = BufOrErr.takeError();
682 SymbolTable = BufOrErr.get();
683 if (Name == "/SYM64/")
684 has64SymTable = true;
689 Err = Error::success();
692 Expected<StringRef> NameOrErr = C->getRawName();
694 Err = NameOrErr.takeError();
697 Name = NameOrErr.get();
701 Format = has64SymTable ? K_MIPS64 : K_GNU;
702 // The string table is never an external member, but we still
703 // must check any Expected<> return value.
704 Expected<StringRef> BufOrErr = C->getBuffer();
706 Err = BufOrErr.takeError();
709 StringTable = BufOrErr.get();
713 Err = Error::success();
717 if (Name[0] != '/') {
718 Format = has64SymTable ? K_MIPS64 : K_GNU;
720 Err = Error::success();
725 Err = errorCodeToError(object_error::parse_failed);
730 // We know that the symbol table is not an external file, but we still
731 // must check any Expected<> return value.
732 Expected<StringRef> BufOrErr = C->getBuffer();
734 Err = BufOrErr.takeError();
737 SymbolTable = BufOrErr.get();
744 Err = Error::success();
748 NameOrErr = C->getRawName();
750 Err = NameOrErr.takeError();
753 Name = NameOrErr.get();
756 // The string table is never an external member, but we still
757 // must check any Expected<> return value.
758 Expected<StringRef> BufOrErr = C->getBuffer();
760 Err = BufOrErr.takeError();
763 StringTable = BufOrErr.get();
769 Err = Error::success();
772 Archive::child_iterator Archive::child_begin(Error &Err,
773 bool SkipInternal) const {
778 return child_iterator(Child(this, FirstRegularData,
779 FirstRegularStartOfFile),
782 const char *Loc = Data.getBufferStart() + strlen(Magic);
783 Child C(this, Loc, &Err);
786 return child_iterator(C, &Err);
789 Archive::child_iterator Archive::child_end() const {
790 return child_iterator(Child(nullptr, nullptr, nullptr), nullptr);
793 StringRef Archive::Symbol::getName() const {
794 return Parent->getSymbolTable().begin() + StringIndex;
797 Expected<Archive::Child> Archive::Symbol::getMember() const {
798 const char *Buf = Parent->getSymbolTable().begin();
799 const char *Offsets = Buf;
800 if (Parent->kind() == K_MIPS64 || Parent->kind() == K_DARWIN64)
801 Offsets += sizeof(uint64_t);
803 Offsets += sizeof(uint32_t);
805 if (Parent->kind() == K_GNU) {
806 Offset = read32be(Offsets + SymbolIndex * 4);
807 } else if (Parent->kind() == K_MIPS64) {
808 Offset = read64be(Offsets + SymbolIndex * 8);
809 } else if (Parent->kind() == K_BSD) {
810 // The SymbolIndex is an index into the ranlib structs that start at
811 // Offsets (the first uint32_t is the number of bytes of the ranlib
812 // structs). The ranlib structs are a pair of uint32_t's the first
813 // being a string table offset and the second being the offset into
814 // the archive of the member that defines the symbol. Which is what
816 Offset = read32le(Offsets + SymbolIndex * 8 + 4);
817 } else if (Parent->kind() == K_DARWIN64) {
818 // The SymbolIndex is an index into the ranlib_64 structs that start at
819 // Offsets (the first uint64_t is the number of bytes of the ranlib_64
820 // structs). The ranlib_64 structs are a pair of uint64_t's the first
821 // being a string table offset and the second being the offset into
822 // the archive of the member that defines the symbol. Which is what
824 Offset = read64le(Offsets + SymbolIndex * 16 + 8);
827 uint32_t MemberCount = read32le(Buf);
828 Buf += MemberCount * 4 + 4;
830 uint32_t SymbolCount = read32le(Buf);
831 if (SymbolIndex >= SymbolCount)
832 return errorCodeToError(object_error::parse_failed);
834 // Skip SymbolCount to get to the indices table.
835 const char *Indices = Buf + 4;
837 // Get the index of the offset in the file member offset table for this
839 uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
840 // Subtract 1 since OffsetIndex is 1 based.
843 if (OffsetIndex >= MemberCount)
844 return errorCodeToError(object_error::parse_failed);
846 Offset = read32le(Offsets + OffsetIndex * 4);
849 const char *Loc = Parent->getData().begin() + Offset;
850 Error Err = Error::success();
851 Child C(Parent, Loc, &Err);
853 return std::move(Err);
857 Archive::Symbol Archive::Symbol::getNext() const {
859 if (Parent->kind() == K_BSD) {
860 // t.StringIndex is an offset from the start of the __.SYMDEF or
861 // "__.SYMDEF SORTED" member into the string table for the ranlib
862 // struct indexed by t.SymbolIndex . To change t.StringIndex to the
863 // offset in the string table for t.SymbolIndex+1 we subtract the
864 // its offset from the start of the string table for t.SymbolIndex
865 // and add the offset of the string table for t.SymbolIndex+1.
867 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
868 // which is the number of bytes of ranlib structs that follow. The ranlib
869 // structs are a pair of uint32_t's the first being a string table offset
870 // and the second being the offset into the archive of the member that
871 // define the symbol. After that the next uint32_t is the byte count of
872 // the string table followed by the string table.
873 const char *Buf = Parent->getSymbolTable().begin();
874 uint32_t RanlibCount = 0;
875 RanlibCount = read32le(Buf) / 8;
876 // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
877 // don't change the t.StringIndex as we don't want to reference a ranlib
879 if (t.SymbolIndex + 1 < RanlibCount) {
880 const char *Ranlibs = Buf + 4;
881 uint32_t CurRanStrx = 0;
882 uint32_t NextRanStrx = 0;
883 CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
884 NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
885 t.StringIndex -= CurRanStrx;
886 t.StringIndex += NextRanStrx;
889 // Go to one past next null.
890 t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
896 Archive::symbol_iterator Archive::symbol_begin() const {
897 if (!hasSymbolTable())
898 return symbol_iterator(Symbol(this, 0, 0));
900 const char *buf = getSymbolTable().begin();
901 if (kind() == K_GNU) {
902 uint32_t symbol_count = 0;
903 symbol_count = read32be(buf);
904 buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
905 } else if (kind() == K_MIPS64) {
906 uint64_t symbol_count = read64be(buf);
907 buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
908 } else if (kind() == K_BSD) {
909 // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
910 // which is the number of bytes of ranlib structs that follow. The ranlib
911 // structs are a pair of uint32_t's the first being a string table offset
912 // and the second being the offset into the archive of the member that
913 // define the symbol. After that the next uint32_t is the byte count of
914 // the string table followed by the string table.
915 uint32_t ranlib_count = 0;
916 ranlib_count = read32le(buf) / 8;
917 const char *ranlibs = buf + 4;
918 uint32_t ran_strx = 0;
919 ran_strx = read32le(ranlibs);
920 buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
921 // Skip the byte count of the string table.
922 buf += sizeof(uint32_t);
924 } else if (kind() == K_DARWIN64) {
925 // The __.SYMDEF_64 or "__.SYMDEF_64 SORTED" member starts with a uint64_t
926 // which is the number of bytes of ranlib_64 structs that follow. The
927 // ranlib_64 structs are a pair of uint64_t's the first being a string
928 // table offset and the second being the offset into the archive of the
929 // member that define the symbol. After that the next uint64_t is the byte
930 // count of the string table followed by the string table.
931 uint64_t ranlib_count = 0;
932 ranlib_count = read64le(buf) / 16;
933 const char *ranlibs = buf + 8;
934 uint64_t ran_strx = 0;
935 ran_strx = read64le(ranlibs);
936 buf += sizeof(uint64_t) + (ranlib_count * (2 * (sizeof(uint64_t))));
937 // Skip the byte count of the string table.
938 buf += sizeof(uint64_t);
941 uint32_t member_count = 0;
942 uint32_t symbol_count = 0;
943 member_count = read32le(buf);
944 buf += 4 + (member_count * 4); // Skip offsets.
945 symbol_count = read32le(buf);
946 buf += 4 + (symbol_count * 2); // Skip indices.
948 uint32_t string_start_offset = buf - getSymbolTable().begin();
949 return symbol_iterator(Symbol(this, 0, string_start_offset));
952 Archive::symbol_iterator Archive::symbol_end() const {
953 return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
956 uint32_t Archive::getNumberOfSymbols() const {
957 if (!hasSymbolTable())
959 const char *buf = getSymbolTable().begin();
961 return read32be(buf);
962 if (kind() == K_MIPS64)
963 return read64be(buf);
965 return read32le(buf) / 8;
966 if (kind() == K_DARWIN64)
967 return read64le(buf) / 16;
968 uint32_t member_count = 0;
969 member_count = read32le(buf);
970 buf += 4 + (member_count * 4); // Skip offsets.
971 return read32le(buf);
974 Expected<Optional<Archive::Child>> Archive::findSym(StringRef name) const {
975 Archive::symbol_iterator bs = symbol_begin();
976 Archive::symbol_iterator es = symbol_end();
978 for (; bs != es; ++bs) {
979 StringRef SymName = bs->getName();
980 if (SymName == name) {
981 if (auto MemberOrErr = bs->getMember())
982 return Child(*MemberOrErr);
984 return MemberOrErr.takeError();
987 return Optional<Child>();
990 // Returns true if archive file contains no member file.
991 bool Archive::isEmpty() const { return Data.getBufferSize() == 8; }
993 bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }