1 //===- Archive.cpp - ar File Format implementation --------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ArchiveObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Object/Archive.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/Support/Endian.h"
18 #include "llvm/Support/MemoryBuffer.h"
19 #include "llvm/Support/Path.h"
20 
21 using namespace llvm;
22 using namespace object;
23 using namespace llvm::support::endian;
24 
25 static const char *const Magic = "!<arch>\n";
26 static const char *const ThinMagic = "!<thin>\n";
27 
28 void Archive::anchor() { }
29 
30 static Error
31 malformedError(Twine Msg) {
32   std::string StringMsg = "truncated or malformed archive (" + Msg.str() + ")";
33   return make_error<GenericBinaryError>(std::move(StringMsg),
34                                         object_error::parse_failed);
35 }
36 
37 StringRef ArchiveMemberHeader::getName() const {
38   char EndCond;
39   if (Name[0] == '/' || Name[0] == '#')
40     EndCond = ' ';
41   else
42     EndCond = '/';
43   llvm::StringRef::size_type end =
44       llvm::StringRef(Name, sizeof(Name)).find(EndCond);
45   if (end == llvm::StringRef::npos)
46     end = sizeof(Name);
47   assert(end <= sizeof(Name) && end > 0);
48   // Don't include the EndCond if there is one.
49   return llvm::StringRef(Name, end);
50 }
51 
52 Expected<uint32_t> ArchiveMemberHeader::getSize() const {
53   uint32_t Ret;
54   if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret)) {
55     std::string Buf;
56     raw_string_ostream OS(Buf);
57     OS.write_escaped(llvm::StringRef(Size, sizeof(Size)).rtrim(" "));
58     OS.flush();
59     return malformedError("characters in size field in archive header are not "
60                           "all decimal numbers: '" + Buf + "'");
61   }
62   return Ret;
63 }
64 
65 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
66   unsigned Ret;
67   if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(' ').getAsInteger(8, Ret))
68     llvm_unreachable("Access mode is not an octal number.");
69   return static_cast<sys::fs::perms>(Ret);
70 }
71 
72 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
73   unsigned Seconds;
74   if (StringRef(LastModified, sizeof(LastModified)).rtrim(' ')
75           .getAsInteger(10, Seconds))
76     llvm_unreachable("Last modified time not a decimal number.");
77 
78   sys::TimeValue Ret;
79   Ret.fromEpochTime(Seconds);
80   return Ret;
81 }
82 
83 unsigned ArchiveMemberHeader::getUID() const {
84   unsigned Ret;
85   StringRef User = StringRef(UID, sizeof(UID)).rtrim(' ');
86   if (User.empty())
87     return 0;
88   if (User.getAsInteger(10, Ret))
89     llvm_unreachable("UID time not a decimal number.");
90   return Ret;
91 }
92 
93 unsigned ArchiveMemberHeader::getGID() const {
94   unsigned Ret;
95   StringRef Group = StringRef(GID, sizeof(GID)).rtrim(' ');
96   if (Group.empty())
97     return 0;
98   if (Group.getAsInteger(10, Ret))
99     llvm_unreachable("GID time not a decimal number.");
100   return Ret;
101 }
102 
103 Archive::Child::Child(const Archive *Parent, StringRef Data,
104                       uint16_t StartOfFile)
105     : Parent(Parent), Data(Data), StartOfFile(StartOfFile) {}
106 
107 Archive::Child::Child(const Archive *Parent, const char *Start, Error *Err)
108     : Parent(Parent) {
109   if (!Start)
110     return;
111   ErrorAsOutParameter ErrAsOutParam(Err);
112 
113   uint64_t Size = sizeof(ArchiveMemberHeader);
114   Data = StringRef(Start, Size);
115   if (!isThinMember()) {
116     Expected<uint64_t> MemberSize = getRawSize();
117     if (!MemberSize) {
118       if (Err)
119         *Err = MemberSize.takeError();
120       return;
121     }
122     Size += MemberSize.get();
123     Data = StringRef(Start, Size);
124   }
125 
126   // Setup StartOfFile and PaddingBytes.
127   StartOfFile = sizeof(ArchiveMemberHeader);
128   // Don't include attached name.
129   StringRef Name = getRawName();
130   if (Name.startswith("#1/")) {
131     uint64_t NameSize;
132     if (Name.substr(3).rtrim(' ').getAsInteger(10, NameSize))
133       llvm_unreachable("Long name length is not an integer");
134     StartOfFile += NameSize;
135   }
136 }
137 
138 Expected<uint64_t> Archive::Child::getSize() const {
139   if (Parent->IsThin) {
140     Expected<uint32_t> Size = getHeader()->getSize();
141     if (!Size)
142       return Size.takeError();
143     return Size.get();
144   }
145   return Data.size() - StartOfFile;
146 }
147 
148 Expected<uint64_t> Archive::Child::getRawSize() const {
149   return getHeader()->getSize();
150 }
151 
152 bool Archive::Child::isThinMember() const {
153   StringRef Name = getHeader()->getName();
154   return Parent->IsThin && Name != "/" && Name != "//";
155 }
156 
157 ErrorOr<std::string> Archive::Child::getFullName() const {
158   assert(isThinMember());
159   ErrorOr<StringRef> NameOrErr = getName();
160   if (std::error_code EC = NameOrErr.getError())
161     return EC;
162   StringRef Name = *NameOrErr;
163   if (sys::path::is_absolute(Name))
164     return Name;
165 
166   SmallString<128> FullName = sys::path::parent_path(
167       Parent->getMemoryBufferRef().getBufferIdentifier());
168   sys::path::append(FullName, Name);
169   return StringRef(FullName);
170 }
171 
172 ErrorOr<StringRef> Archive::Child::getBuffer() const {
173   if (!isThinMember()) {
174     Expected<uint32_t> Size = getSize();
175     if (!Size)
176       return errorToErrorCode(Size.takeError());
177     return StringRef(Data.data() + StartOfFile, Size.get());
178   }
179   ErrorOr<std::string> FullNameOrEr = getFullName();
180   if (std::error_code EC = FullNameOrEr.getError())
181     return EC;
182   const std::string &FullName = *FullNameOrEr;
183   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
184   if (std::error_code EC = Buf.getError())
185     return EC;
186   Parent->ThinBuffers.push_back(std::move(*Buf));
187   return Parent->ThinBuffers.back()->getBuffer();
188 }
189 
190 Expected<Archive::Child> Archive::Child::getNext() const {
191   size_t SpaceToSkip = Data.size();
192   // If it's odd, add 1 to make it even.
193   if (SpaceToSkip & 1)
194     ++SpaceToSkip;
195 
196   const char *NextLoc = Data.data() + SpaceToSkip;
197 
198   // Check to see if this is at the end of the archive.
199   if (NextLoc == Parent->Data.getBufferEnd())
200     return Child(Parent, nullptr, nullptr);
201 
202   // Check to see if this is past the end of the archive.
203   if (NextLoc > Parent->Data.getBufferEnd())
204     return malformedError("offset to next archive member past the end of the "
205                           "archive");
206 
207   Error Err;
208   Child Ret(Parent, NextLoc, &Err);
209   if (Err)
210     return std::move(Err);
211   return Ret;
212 }
213 
214 uint64_t Archive::Child::getChildOffset() const {
215   const char *a = Parent->Data.getBuffer().data();
216   const char *c = Data.data();
217   uint64_t offset = c - a;
218   return offset;
219 }
220 
221 ErrorOr<StringRef> Archive::Child::getName() const {
222   StringRef name = getRawName();
223   // Check if it's a special name.
224   if (name[0] == '/') {
225     if (name.size() == 1) // Linker member.
226       return name;
227     if (name.size() == 2 && name[1] == '/') // String table.
228       return name;
229     // It's a long name.
230     // Get the offset.
231     std::size_t offset;
232     if (name.substr(1).rtrim(' ').getAsInteger(10, offset))
233       llvm_unreachable("Long name offset is not an integer");
234 
235     // Verify it.
236     if (offset >= Parent->StringTable.size())
237       return object_error::parse_failed;
238     const char *addr = Parent->StringTable.begin() + offset;
239 
240     // GNU long file names end with a "/\n".
241     if (Parent->kind() == K_GNU || Parent->kind() == K_MIPS64) {
242       StringRef::size_type End = StringRef(addr).find('\n');
243       return StringRef(addr, End - 1);
244     }
245     return StringRef(addr);
246   } else if (name.startswith("#1/")) {
247     uint64_t name_size;
248     if (name.substr(3).rtrim(' ').getAsInteger(10, name_size))
249       llvm_unreachable("Long name length is not an ingeter");
250     return Data.substr(sizeof(ArchiveMemberHeader), name_size).rtrim('\0');
251   } else {
252     // It is not a long name so trim the blanks at the end of the name.
253     if (name[name.size() - 1] != '/') {
254       return name.rtrim(' ');
255     }
256   }
257   // It's a simple name.
258   if (name[name.size() - 1] == '/')
259     return name.substr(0, name.size() - 1);
260   return name;
261 }
262 
263 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
264   ErrorOr<StringRef> NameOrErr = getName();
265   if (std::error_code EC = NameOrErr.getError())
266     return EC;
267   StringRef Name = NameOrErr.get();
268   ErrorOr<StringRef> Buf = getBuffer();
269   if (std::error_code EC = Buf.getError())
270     return EC;
271   return MemoryBufferRef(*Buf, Name);
272 }
273 
274 Expected<std::unique_ptr<Binary>>
275 Archive::Child::getAsBinary(LLVMContext *Context) const {
276   ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
277   if (std::error_code EC = BuffOrErr.getError())
278     return errorCodeToError(EC);
279 
280   auto BinaryOrErr = createBinary(BuffOrErr.get(), Context);
281   if (BinaryOrErr)
282     return std::move(*BinaryOrErr);
283   return BinaryOrErr.takeError();
284 }
285 
286 Expected<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
287   Error Err;
288   std::unique_ptr<Archive> Ret(new Archive(Source, Err));
289   if (Err)
290     return std::move(Err);
291   return std::move(Ret);
292 }
293 
294 void Archive::setFirstRegular(const Child &C) {
295   FirstRegularData = C.Data;
296   FirstRegularStartOfFile = C.StartOfFile;
297 }
298 
299 Archive::Archive(MemoryBufferRef Source, Error &Err)
300     : Binary(Binary::ID_Archive, Source) {
301   ErrorAsOutParameter ErrAsOutParam(&Err);
302   StringRef Buffer = Data.getBuffer();
303   // Check for sufficient magic.
304   if (Buffer.startswith(ThinMagic)) {
305     IsThin = true;
306   } else if (Buffer.startswith(Magic)) {
307     IsThin = false;
308   } else {
309     Err = make_error<GenericBinaryError>("File too small to be an archive",
310                                          object_error::invalid_file_type);
311     return;
312   }
313 
314   // Get the special members.
315   child_iterator I = child_begin(Err, false);
316   if (Err)
317     return;
318   child_iterator E = child_end();
319 
320   // This is at least a valid empty archive. Since an empty archive is the
321   // same in all formats, just claim it to be gnu to make sure Format is
322   // initialized.
323   Format = K_GNU;
324 
325   if (I == E) {
326     Err = Error::success();
327     return;
328   }
329   const Child *C = &*I;
330 
331   auto Increment = [&]() {
332     ++I;
333     if (Err)
334       return true;
335     C = &*I;
336     return false;
337   };
338 
339   StringRef Name = C->getRawName();
340 
341   // Below is the pattern that is used to figure out the archive format
342   // GNU archive format
343   //  First member : / (may exist, if it exists, points to the symbol table )
344   //  Second member : // (may exist, if it exists, points to the string table)
345   //  Note : The string table is used if the filename exceeds 15 characters
346   // BSD archive format
347   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
348   //  There is no string table, if the filename exceeds 15 characters or has a
349   //  embedded space, the filename has #1/<size>, The size represents the size
350   //  of the filename that needs to be read after the archive header
351   // COFF archive format
352   //  First member : /
353   //  Second member : / (provides a directory of symbols)
354   //  Third member : // (may exist, if it exists, contains the string table)
355   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
356   //  even if the string table is empty. However, lib.exe does not in fact
357   //  seem to create the third member if there's no member whose filename
358   //  exceeds 15 characters. So the third member is optional.
359 
360   if (Name == "__.SYMDEF" || Name == "__.SYMDEF_64") {
361     if (Name == "__.SYMDEF")
362       Format = K_BSD;
363     else // Name == "__.SYMDEF_64"
364       Format = K_DARWIN64;
365     // We know that the symbol table is not an external file, so we just assert
366     // there is no error.
367     SymbolTable = *C->getBuffer();
368     if (Increment())
369       return;
370     setFirstRegular(*C);
371 
372     Err = Error::success();
373     return;
374   }
375 
376   if (Name.startswith("#1/")) {
377     Format = K_BSD;
378     // We know this is BSD, so getName will work since there is no string table.
379     ErrorOr<StringRef> NameOrErr = C->getName();
380     if (auto ec = NameOrErr.getError()) {
381       Err = errorCodeToError(ec);
382       return;
383     }
384     Name = NameOrErr.get();
385     if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
386       // We know that the symbol table is not an external file, so we just
387       // assert there is no error.
388       SymbolTable = *C->getBuffer();
389       if (Increment())
390         return;
391     }
392     else if (Name == "__.SYMDEF_64 SORTED" || Name == "__.SYMDEF_64") {
393       Format = K_DARWIN64;
394       // We know that the symbol table is not an external file, so we just
395       // assert there is no error.
396       SymbolTable = *C->getBuffer();
397       if (Increment())
398         return;
399     }
400     setFirstRegular(*C);
401     return;
402   }
403 
404   // MIPS 64-bit ELF archives use a special format of a symbol table.
405   // This format is marked by `ar_name` field equals to "/SYM64/".
406   // For detailed description see page 96 in the following document:
407   // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
408 
409   bool has64SymTable = false;
410   if (Name == "/" || Name == "/SYM64/") {
411     // We know that the symbol table is not an external file, so we just assert
412     // there is no error.
413     SymbolTable = *C->getBuffer();
414     if (Name == "/SYM64/")
415       has64SymTable = true;
416 
417     if (Increment())
418       return;
419     if (I == E) {
420       Err = Error::success();
421       return;
422     }
423     Name = C->getRawName();
424   }
425 
426   if (Name == "//") {
427     Format = has64SymTable ? K_MIPS64 : K_GNU;
428     // The string table is never an external member, so we just assert on the
429     // ErrorOr.
430     StringTable = *C->getBuffer();
431     if (Increment())
432       return;
433     setFirstRegular(*C);
434     Err = Error::success();
435     return;
436   }
437 
438   if (Name[0] != '/') {
439     Format = has64SymTable ? K_MIPS64 : K_GNU;
440     setFirstRegular(*C);
441     Err = Error::success();
442     return;
443   }
444 
445   if (Name != "/") {
446     Err = errorCodeToError(object_error::parse_failed);
447     return;
448   }
449 
450   Format = K_COFF;
451   // We know that the symbol table is not an external file, so we just assert
452   // there is no error.
453   SymbolTable = *C->getBuffer();
454 
455   if (Increment())
456     return;
457 
458   if (I == E) {
459     setFirstRegular(*C);
460     Err = Error::success();
461     return;
462   }
463 
464   Name = C->getRawName();
465 
466   if (Name == "//") {
467     // The string table is never an external member, so we just assert on the
468     // ErrorOr.
469     StringTable = *C->getBuffer();
470     if (Increment())
471       return;
472   }
473 
474   setFirstRegular(*C);
475   Err = Error::success();
476 }
477 
478 Archive::child_iterator Archive::child_begin(Error &Err,
479                                              bool SkipInternal) const {
480   if (Data.getBufferSize() == 8) // empty archive.
481     return child_end();
482 
483   if (SkipInternal)
484     return child_iterator(Child(this, FirstRegularData,
485                                 FirstRegularStartOfFile),
486                           &Err);
487 
488   const char *Loc = Data.getBufferStart() + strlen(Magic);
489   Child C(this, Loc, &Err);
490   if (Err)
491     return child_end();
492   return child_iterator(C, &Err);
493 }
494 
495 Archive::child_iterator Archive::child_end() const {
496   return child_iterator(Child(this, nullptr, nullptr), nullptr);
497 }
498 
499 StringRef Archive::Symbol::getName() const {
500   return Parent->getSymbolTable().begin() + StringIndex;
501 }
502 
503 ErrorOr<Archive::Child> Archive::Symbol::getMember() const {
504   const char *Buf = Parent->getSymbolTable().begin();
505   const char *Offsets = Buf;
506   if (Parent->kind() == K_MIPS64 || Parent->kind() == K_DARWIN64)
507     Offsets += sizeof(uint64_t);
508   else
509     Offsets += sizeof(uint32_t);
510   uint32_t Offset = 0;
511   if (Parent->kind() == K_GNU) {
512     Offset = read32be(Offsets + SymbolIndex * 4);
513   } else if (Parent->kind() == K_MIPS64) {
514     Offset = read64be(Offsets + SymbolIndex * 8);
515   } else if (Parent->kind() == K_BSD) {
516     // The SymbolIndex is an index into the ranlib structs that start at
517     // Offsets (the first uint32_t is the number of bytes of the ranlib
518     // structs).  The ranlib structs are a pair of uint32_t's the first
519     // being a string table offset and the second being the offset into
520     // the archive of the member that defines the symbol.  Which is what
521     // is needed here.
522     Offset = read32le(Offsets + SymbolIndex * 8 + 4);
523   } else if (Parent->kind() == K_DARWIN64) {
524     // The SymbolIndex is an index into the ranlib_64 structs that start at
525     // Offsets (the first uint64_t is the number of bytes of the ranlib_64
526     // structs).  The ranlib_64 structs are a pair of uint64_t's the first
527     // being a string table offset and the second being the offset into
528     // the archive of the member that defines the symbol.  Which is what
529     // is needed here.
530     Offset = read64le(Offsets + SymbolIndex * 16 + 8);
531   } else {
532     // Skip offsets.
533     uint32_t MemberCount = read32le(Buf);
534     Buf += MemberCount * 4 + 4;
535 
536     uint32_t SymbolCount = read32le(Buf);
537     if (SymbolIndex >= SymbolCount)
538       return object_error::parse_failed;
539 
540     // Skip SymbolCount to get to the indices table.
541     const char *Indices = Buf + 4;
542 
543     // Get the index of the offset in the file member offset table for this
544     // symbol.
545     uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
546     // Subtract 1 since OffsetIndex is 1 based.
547     --OffsetIndex;
548 
549     if (OffsetIndex >= MemberCount)
550       return object_error::parse_failed;
551 
552     Offset = read32le(Offsets + OffsetIndex * 4);
553   }
554 
555   const char *Loc = Parent->getData().begin() + Offset;
556   Error Err;
557   Child C(Parent, Loc, &Err);
558   if (Err)
559     return errorToErrorCode(std::move(Err));
560   return C;
561 }
562 
563 Archive::Symbol Archive::Symbol::getNext() const {
564   Symbol t(*this);
565   if (Parent->kind() == K_BSD) {
566     // t.StringIndex is an offset from the start of the __.SYMDEF or
567     // "__.SYMDEF SORTED" member into the string table for the ranlib
568     // struct indexed by t.SymbolIndex .  To change t.StringIndex to the
569     // offset in the string table for t.SymbolIndex+1 we subtract the
570     // its offset from the start of the string table for t.SymbolIndex
571     // and add the offset of the string table for t.SymbolIndex+1.
572 
573     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
574     // which is the number of bytes of ranlib structs that follow.  The ranlib
575     // structs are a pair of uint32_t's the first being a string table offset
576     // and the second being the offset into the archive of the member that
577     // define the symbol. After that the next uint32_t is the byte count of
578     // the string table followed by the string table.
579     const char *Buf = Parent->getSymbolTable().begin();
580     uint32_t RanlibCount = 0;
581     RanlibCount = read32le(Buf) / 8;
582     // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
583     // don't change the t.StringIndex as we don't want to reference a ranlib
584     // past RanlibCount.
585     if (t.SymbolIndex + 1 < RanlibCount) {
586       const char *Ranlibs = Buf + 4;
587       uint32_t CurRanStrx = 0;
588       uint32_t NextRanStrx = 0;
589       CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
590       NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
591       t.StringIndex -= CurRanStrx;
592       t.StringIndex += NextRanStrx;
593     }
594   } else {
595     // Go to one past next null.
596     t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
597   }
598   ++t.SymbolIndex;
599   return t;
600 }
601 
602 Archive::symbol_iterator Archive::symbol_begin() const {
603   if (!hasSymbolTable())
604     return symbol_iterator(Symbol(this, 0, 0));
605 
606   const char *buf = getSymbolTable().begin();
607   if (kind() == K_GNU) {
608     uint32_t symbol_count = 0;
609     symbol_count = read32be(buf);
610     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
611   } else if (kind() == K_MIPS64) {
612     uint64_t symbol_count = read64be(buf);
613     buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
614   } else if (kind() == K_BSD) {
615     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
616     // which is the number of bytes of ranlib structs that follow.  The ranlib
617     // structs are a pair of uint32_t's the first being a string table offset
618     // and the second being the offset into the archive of the member that
619     // define the symbol. After that the next uint32_t is the byte count of
620     // the string table followed by the string table.
621     uint32_t ranlib_count = 0;
622     ranlib_count = read32le(buf) / 8;
623     const char *ranlibs = buf + 4;
624     uint32_t ran_strx = 0;
625     ran_strx = read32le(ranlibs);
626     buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
627     // Skip the byte count of the string table.
628     buf += sizeof(uint32_t);
629     buf += ran_strx;
630   } else if (kind() == K_DARWIN64) {
631     // The __.SYMDEF_64 or "__.SYMDEF_64 SORTED" member starts with a uint64_t
632     // which is the number of bytes of ranlib_64 structs that follow.  The
633     // ranlib_64 structs are a pair of uint64_t's the first being a string
634     // table offset and the second being the offset into the archive of the
635     // member that define the symbol. After that the next uint64_t is the byte
636     // count of the string table followed by the string table.
637     uint64_t ranlib_count = 0;
638     ranlib_count = read64le(buf) / 16;
639     const char *ranlibs = buf + 8;
640     uint64_t ran_strx = 0;
641     ran_strx = read64le(ranlibs);
642     buf += sizeof(uint64_t) + (ranlib_count * (2 * (sizeof(uint64_t))));
643     // Skip the byte count of the string table.
644     buf += sizeof(uint64_t);
645     buf += ran_strx;
646   } else {
647     uint32_t member_count = 0;
648     uint32_t symbol_count = 0;
649     member_count = read32le(buf);
650     buf += 4 + (member_count * 4); // Skip offsets.
651     symbol_count = read32le(buf);
652     buf += 4 + (symbol_count * 2); // Skip indices.
653   }
654   uint32_t string_start_offset = buf - getSymbolTable().begin();
655   return symbol_iterator(Symbol(this, 0, string_start_offset));
656 }
657 
658 Archive::symbol_iterator Archive::symbol_end() const {
659   return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
660 }
661 
662 uint32_t Archive::getNumberOfSymbols() const {
663   if (!hasSymbolTable())
664     return 0;
665   const char *buf = getSymbolTable().begin();
666   if (kind() == K_GNU)
667     return read32be(buf);
668   if (kind() == K_MIPS64)
669     return read64be(buf);
670   if (kind() == K_BSD)
671     return read32le(buf) / 8;
672   if (kind() == K_DARWIN64)
673     return read64le(buf) / 16;
674   uint32_t member_count = 0;
675   member_count = read32le(buf);
676   buf += 4 + (member_count * 4); // Skip offsets.
677   return read32le(buf);
678 }
679 
680 Expected<Optional<Archive::Child>> Archive::findSym(StringRef name) const {
681   Archive::symbol_iterator bs = symbol_begin();
682   Archive::symbol_iterator es = symbol_end();
683 
684   for (; bs != es; ++bs) {
685     StringRef SymName = bs->getName();
686     if (SymName == name) {
687       if (auto MemberOrErr = bs->getMember())
688         return Child(*MemberOrErr);
689       else
690         return errorCodeToError(MemberOrErr.getError());
691     }
692   }
693   return Optional<Child>();
694 }
695 
696 bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }
697