xref: /llvm-project/llvm/lib/Object/Archive.cpp (revision 85a2c50ec4979b87267e4f2068f2921beb0b98f2)
1 //===- Archive.cpp - ar File Format implementation ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ArchiveObjectFile class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Object/Archive.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/Object/Binary.h"
18 #include "llvm/Object/Error.h"
19 #include "llvm/Support/Chrono.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/Error.h"
22 #include "llvm/Support/ErrorOr.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/TargetParser/Host.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <memory>
34 #include <string>
35 #include <system_error>
36 
37 using namespace llvm;
38 using namespace object;
39 using namespace llvm::support::endian;
40 
41 void Archive::anchor() {}
42 
43 static Error malformedError(Twine Msg) {
44   std::string StringMsg = "truncated or malformed archive (" + Msg.str() + ")";
45   return make_error<GenericBinaryError>(std::move(StringMsg),
46                                         object_error::parse_failed);
47 }
48 
49 static Error
50 createMemberHeaderParseError(const AbstractArchiveMemberHeader *ArMemHeader,
51                              const char *RawHeaderPtr, uint64_t Size) {
52   StringRef Msg("remaining size of archive too small for next archive "
53                 "member header ");
54 
55   Expected<StringRef> NameOrErr = ArMemHeader->getName(Size);
56   if (NameOrErr)
57     return malformedError(Msg + "for " + *NameOrErr);
58 
59   consumeError(NameOrErr.takeError());
60   uint64_t Offset = RawHeaderPtr - ArMemHeader->Parent->getData().data();
61   return malformedError(Msg + "at offset " + Twine(Offset));
62 }
63 
64 template <class T, std::size_t N>
65 StringRef getFieldRawString(const T (&Field)[N]) {
66   return StringRef(Field, N).rtrim(" ");
67 }
68 
69 template <class T>
70 StringRef CommonArchiveMemberHeader<T>::getRawAccessMode() const {
71   return getFieldRawString(ArMemHdr->AccessMode);
72 }
73 
74 template <class T>
75 StringRef CommonArchiveMemberHeader<T>::getRawLastModified() const {
76   return getFieldRawString(ArMemHdr->LastModified);
77 }
78 
79 template <class T> StringRef CommonArchiveMemberHeader<T>::getRawUID() const {
80   return getFieldRawString(ArMemHdr->UID);
81 }
82 
83 template <class T> StringRef CommonArchiveMemberHeader<T>::getRawGID() const {
84   return getFieldRawString(ArMemHdr->GID);
85 }
86 
87 template <class T> uint64_t CommonArchiveMemberHeader<T>::getOffset() const {
88   return reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
89 }
90 
91 template class object::CommonArchiveMemberHeader<UnixArMemHdrType>;
92 template class object::CommonArchiveMemberHeader<BigArMemHdrType>;
93 
94 ArchiveMemberHeader::ArchiveMemberHeader(const Archive *Parent,
95                                          const char *RawHeaderPtr,
96                                          uint64_t Size, Error *Err)
97     : CommonArchiveMemberHeader<UnixArMemHdrType>(
98           Parent, reinterpret_cast<const UnixArMemHdrType *>(RawHeaderPtr)) {
99   if (RawHeaderPtr == nullptr)
100     return;
101   ErrorAsOutParameter ErrAsOutParam(Err);
102 
103   if (Size < getSizeOf()) {
104     *Err = createMemberHeaderParseError(this, RawHeaderPtr, Size);
105     return;
106   }
107   if (ArMemHdr->Terminator[0] != '`' || ArMemHdr->Terminator[1] != '\n') {
108     if (Err) {
109       std::string Buf;
110       raw_string_ostream OS(Buf);
111       OS.write_escaped(
112           StringRef(ArMemHdr->Terminator, sizeof(ArMemHdr->Terminator)));
113       OS.flush();
114       std::string Msg("terminator characters in archive member \"" + Buf +
115                       "\" not the correct \"`\\n\" values for the archive "
116                       "member header ");
117       Expected<StringRef> NameOrErr = getName(Size);
118       if (!NameOrErr) {
119         consumeError(NameOrErr.takeError());
120         uint64_t Offset = RawHeaderPtr - Parent->getData().data();
121         *Err = malformedError(Msg + "at offset " + Twine(Offset));
122       } else
123         *Err = malformedError(Msg + "for " + NameOrErr.get());
124     }
125     return;
126   }
127 }
128 
129 BigArchiveMemberHeader::BigArchiveMemberHeader(const Archive *Parent,
130                                                const char *RawHeaderPtr,
131                                                uint64_t Size, Error *Err)
132     : CommonArchiveMemberHeader<BigArMemHdrType>(
133           Parent, reinterpret_cast<const BigArMemHdrType *>(RawHeaderPtr)) {
134   if (RawHeaderPtr == nullptr)
135     return;
136   ErrorAsOutParameter ErrAsOutParam(Err);
137 
138   if (RawHeaderPtr + getSizeOf() >= Parent->getData().end()) {
139     if (Err)
140       *Err = malformedError("malformed AIX big archive: remaining buffer is "
141                             "unable to contain next archive member");
142     return;
143   }
144 
145   if (Size < getSizeOf()) {
146     Error SubErr = createMemberHeaderParseError(this, RawHeaderPtr, Size);
147     if (Err)
148       *Err = std::move(SubErr);
149   }
150 }
151 
152 // This gets the raw name from the ArMemHdr->Name field and checks that it is
153 // valid for the kind of archive.  If it is not valid it returns an Error.
154 Expected<StringRef> ArchiveMemberHeader::getRawName() const {
155   char EndCond;
156   auto Kind = Parent->kind();
157   if (Kind == Archive::K_BSD || Kind == Archive::K_DARWIN64) {
158     if (ArMemHdr->Name[0] == ' ') {
159       uint64_t Offset =
160           reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
161       return malformedError("name contains a leading space for archive member "
162                             "header at offset " +
163                             Twine(Offset));
164     }
165     EndCond = ' ';
166   } else if (ArMemHdr->Name[0] == '/' || ArMemHdr->Name[0] == '#')
167     EndCond = ' ';
168   else
169     EndCond = '/';
170   StringRef::size_type end =
171       StringRef(ArMemHdr->Name, sizeof(ArMemHdr->Name)).find(EndCond);
172   if (end == StringRef::npos)
173     end = sizeof(ArMemHdr->Name);
174   assert(end <= sizeof(ArMemHdr->Name) && end > 0);
175   // Don't include the EndCond if there is one.
176   return StringRef(ArMemHdr->Name, end);
177 }
178 
179 Expected<uint64_t>
180 getArchiveMemberDecField(Twine FieldName, const StringRef RawField,
181                          const Archive *Parent,
182                          const AbstractArchiveMemberHeader *MemHeader) {
183   uint64_t Value;
184   if (RawField.getAsInteger(10, Value)) {
185     uint64_t Offset = MemHeader->getOffset();
186     return malformedError("characters in " + FieldName +
187                           " field in archive member header are not "
188                           "all decimal numbers: '" +
189                           RawField +
190                           "' for the archive "
191                           "member header at offset " +
192                           Twine(Offset));
193   }
194   return Value;
195 }
196 
197 Expected<uint64_t>
198 getArchiveMemberOctField(Twine FieldName, const StringRef RawField,
199                          const Archive *Parent,
200                          const AbstractArchiveMemberHeader *MemHeader) {
201   uint64_t Value;
202   if (RawField.getAsInteger(8, Value)) {
203     uint64_t Offset = MemHeader->getOffset();
204     return malformedError("characters in " + FieldName +
205                           " field in archive member header are not "
206                           "all octal numbers: '" +
207                           RawField +
208                           "' for the archive "
209                           "member header at offset " +
210                           Twine(Offset));
211   }
212   return Value;
213 }
214 
215 Expected<StringRef> BigArchiveMemberHeader::getRawName() const {
216   Expected<uint64_t> NameLenOrErr = getArchiveMemberDecField(
217       "NameLen", getFieldRawString(ArMemHdr->NameLen), Parent, this);
218   if (!NameLenOrErr)
219     // TODO: Out-of-line.
220     return NameLenOrErr.takeError();
221   uint64_t NameLen = NameLenOrErr.get();
222 
223   // If the name length is odd, pad with '\0' to get an even length. After
224   // padding, there is the name terminator "`\n".
225   uint64_t NameLenWithPadding = alignTo(NameLen, 2);
226   StringRef NameTerminator = "`\n";
227   StringRef NameStringWithNameTerminator =
228       StringRef(ArMemHdr->Name, NameLenWithPadding + NameTerminator.size());
229   if (!NameStringWithNameTerminator.endswith(NameTerminator)) {
230     uint64_t Offset =
231         reinterpret_cast<const char *>(ArMemHdr->Name + NameLenWithPadding) -
232         Parent->getData().data();
233     // TODO: Out-of-line.
234     return malformedError(
235         "name does not have name terminator \"`\\n\" for archive member"
236         "header at offset " +
237         Twine(Offset));
238   }
239   return StringRef(ArMemHdr->Name, NameLen);
240 }
241 
242 // member including the header, so the size of any name following the header
243 // is checked to make sure it does not overflow.
244 Expected<StringRef> ArchiveMemberHeader::getName(uint64_t Size) const {
245 
246   // This can be called from the ArchiveMemberHeader constructor when the
247   // archive header is truncated to produce an error message with the name.
248   // Make sure the name field is not truncated.
249   if (Size < offsetof(UnixArMemHdrType, Name) + sizeof(ArMemHdr->Name)) {
250     uint64_t ArchiveOffset =
251         reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
252     return malformedError("archive header truncated before the name field "
253                           "for archive member header at offset " +
254                           Twine(ArchiveOffset));
255   }
256 
257   // The raw name itself can be invalid.
258   Expected<StringRef> NameOrErr = getRawName();
259   if (!NameOrErr)
260     return NameOrErr.takeError();
261   StringRef Name = NameOrErr.get();
262 
263   // Check if it's a special name.
264   if (Name[0] == '/') {
265     if (Name.size() == 1) // Linker member.
266       return Name;
267     if (Name.size() == 2 && Name[1] == '/') // String table.
268       return Name;
269     // System libraries from the Windows SDK for Windows 11 contain this symbol.
270     // It looks like a CFG guard: we just skip it for now.
271     if (Name.equals("/<XFGHASHMAP>/"))
272       return Name;
273     // Some libraries (e.g., arm64rt.lib) from the Windows WDK
274     // (version 10.0.22000.0) contain this undocumented special member.
275     if (Name.equals("/<ECSYMBOLS>/"))
276       return Name;
277     // It's a long name.
278     // Get the string table offset.
279     std::size_t StringOffset;
280     if (Name.substr(1).rtrim(' ').getAsInteger(10, StringOffset)) {
281       std::string Buf;
282       raw_string_ostream OS(Buf);
283       OS.write_escaped(Name.substr(1).rtrim(' '));
284       OS.flush();
285       uint64_t ArchiveOffset =
286           reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
287       return malformedError("long name offset characters after the '/' are "
288                             "not all decimal numbers: '" +
289                             Buf + "' for archive member header at offset " +
290                             Twine(ArchiveOffset));
291     }
292 
293     // Verify it.
294     if (StringOffset >= Parent->getStringTable().size()) {
295       uint64_t ArchiveOffset =
296           reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
297       return malformedError("long name offset " + Twine(StringOffset) +
298                             " past the end of the string table for archive "
299                             "member header at offset " +
300                             Twine(ArchiveOffset));
301     }
302 
303     // GNU long file names end with a "/\n".
304     if (Parent->kind() == Archive::K_GNU ||
305         Parent->kind() == Archive::K_GNU64) {
306       size_t End = Parent->getStringTable().find('\n', /*From=*/StringOffset);
307       if (End == StringRef::npos || End < 1 ||
308           Parent->getStringTable()[End - 1] != '/') {
309         return malformedError("string table at long name offset " +
310                               Twine(StringOffset) + "not terminated");
311       }
312       return Parent->getStringTable().slice(StringOffset, End - 1);
313     }
314     return Parent->getStringTable().begin() + StringOffset;
315   }
316 
317   if (Name.startswith("#1/")) {
318     uint64_t NameLength;
319     if (Name.substr(3).rtrim(' ').getAsInteger(10, NameLength)) {
320       std::string Buf;
321       raw_string_ostream OS(Buf);
322       OS.write_escaped(Name.substr(3).rtrim(' '));
323       OS.flush();
324       uint64_t ArchiveOffset =
325           reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
326       return malformedError("long name length characters after the #1/ are "
327                             "not all decimal numbers: '" +
328                             Buf + "' for archive member header at offset " +
329                             Twine(ArchiveOffset));
330     }
331     if (getSizeOf() + NameLength > Size) {
332       uint64_t ArchiveOffset =
333           reinterpret_cast<const char *>(ArMemHdr) - Parent->getData().data();
334       return malformedError("long name length: " + Twine(NameLength) +
335                             " extends past the end of the member or archive "
336                             "for archive member header at offset " +
337                             Twine(ArchiveOffset));
338     }
339     return StringRef(reinterpret_cast<const char *>(ArMemHdr) + getSizeOf(),
340                      NameLength)
341         .rtrim('\0');
342   }
343 
344   // It is not a long name so trim the blanks at the end of the name.
345   if (Name[Name.size() - 1] != '/')
346     return Name.rtrim(' ');
347 
348   // It's a simple name.
349   return Name.drop_back(1);
350 }
351 
352 Expected<StringRef> BigArchiveMemberHeader::getName(uint64_t Size) const {
353   return getRawName();
354 }
355 
356 Expected<uint64_t> ArchiveMemberHeader::getSize() const {
357   return getArchiveMemberDecField("size", getFieldRawString(ArMemHdr->Size),
358                                   Parent, this);
359 }
360 
361 Expected<uint64_t> BigArchiveMemberHeader::getSize() const {
362   Expected<uint64_t> SizeOrErr = getArchiveMemberDecField(
363       "size", getFieldRawString(ArMemHdr->Size), Parent, this);
364   if (!SizeOrErr)
365     return SizeOrErr.takeError();
366 
367   Expected<uint64_t> NameLenOrErr = getRawNameSize();
368   if (!NameLenOrErr)
369     return NameLenOrErr.takeError();
370 
371   return *SizeOrErr + alignTo(*NameLenOrErr, 2);
372 }
373 
374 Expected<uint64_t> BigArchiveMemberHeader::getRawNameSize() const {
375   return getArchiveMemberDecField(
376       "NameLen", getFieldRawString(ArMemHdr->NameLen), Parent, this);
377 }
378 
379 Expected<uint64_t> BigArchiveMemberHeader::getNextOffset() const {
380   return getArchiveMemberDecField(
381       "NextOffset", getFieldRawString(ArMemHdr->NextOffset), Parent, this);
382 }
383 
384 Expected<sys::fs::perms> AbstractArchiveMemberHeader::getAccessMode() const {
385   Expected<uint64_t> AccessModeOrErr =
386       getArchiveMemberOctField("AccessMode", getRawAccessMode(), Parent, this);
387   if (!AccessModeOrErr)
388     return AccessModeOrErr.takeError();
389   return static_cast<sys::fs::perms>(*AccessModeOrErr);
390 }
391 
392 Expected<sys::TimePoint<std::chrono::seconds>>
393 AbstractArchiveMemberHeader::getLastModified() const {
394   Expected<uint64_t> SecondsOrErr = getArchiveMemberDecField(
395       "LastModified", getRawLastModified(), Parent, this);
396 
397   if (!SecondsOrErr)
398     return SecondsOrErr.takeError();
399 
400   return sys::toTimePoint(*SecondsOrErr);
401 }
402 
403 Expected<unsigned> AbstractArchiveMemberHeader::getUID() const {
404   StringRef User = getRawUID();
405   if (User.empty())
406     return 0;
407   return getArchiveMemberDecField("UID", User, Parent, this);
408 }
409 
410 Expected<unsigned> AbstractArchiveMemberHeader::getGID() const {
411   StringRef Group = getRawGID();
412   if (Group.empty())
413     return 0;
414   return getArchiveMemberDecField("GID", Group, Parent, this);
415 }
416 
417 Expected<bool> ArchiveMemberHeader::isThin() const {
418   Expected<StringRef> NameOrErr = getRawName();
419   if (!NameOrErr)
420     return NameOrErr.takeError();
421   StringRef Name = NameOrErr.get();
422   return Parent->isThin() && Name != "/" && Name != "//" && Name != "/SYM64/";
423 }
424 
425 Expected<const char *> ArchiveMemberHeader::getNextChildLoc() const {
426   uint64_t Size = getSizeOf();
427   Expected<bool> isThinOrErr = isThin();
428   if (!isThinOrErr)
429     return isThinOrErr.takeError();
430 
431   bool isThin = isThinOrErr.get();
432   if (!isThin) {
433     Expected<uint64_t> MemberSize = getSize();
434     if (!MemberSize)
435       return MemberSize.takeError();
436 
437     Size += MemberSize.get();
438   }
439 
440   // If Size is odd, add 1 to make it even.
441   const char *NextLoc =
442       reinterpret_cast<const char *>(ArMemHdr) + alignTo(Size, 2);
443 
444   if (NextLoc == Parent->getMemoryBufferRef().getBufferEnd())
445     return nullptr;
446 
447   return NextLoc;
448 }
449 
450 Expected<const char *> BigArchiveMemberHeader::getNextChildLoc() const {
451   if (getOffset() ==
452       static_cast<const BigArchive *>(Parent)->getLastChildOffset())
453     return nullptr;
454 
455   Expected<uint64_t> NextOffsetOrErr = getNextOffset();
456   if (!NextOffsetOrErr)
457     return NextOffsetOrErr.takeError();
458   return Parent->getData().data() + NextOffsetOrErr.get();
459 }
460 
461 Archive::Child::Child(const Archive *Parent, StringRef Data,
462                       uint16_t StartOfFile)
463     : Parent(Parent), Data(Data), StartOfFile(StartOfFile) {
464   Header = Parent->createArchiveMemberHeader(Data.data(), Data.size(), nullptr);
465 }
466 
467 Archive::Child::Child(const Archive *Parent, const char *Start, Error *Err)
468     : Parent(Parent) {
469   if (!Start) {
470     Header = nullptr;
471     return;
472   }
473 
474   Header = Parent->createArchiveMemberHeader(
475       Start,
476       Parent ? Parent->getData().size() - (Start - Parent->getData().data())
477              : 0,
478       Err);
479 
480   // If we are pointed to real data, Start is not a nullptr, then there must be
481   // a non-null Err pointer available to report malformed data on.  Only in
482   // the case sentinel value is being constructed is Err is permitted to be a
483   // nullptr.
484   assert(Err && "Err can't be nullptr if Start is not a nullptr");
485 
486   ErrorAsOutParameter ErrAsOutParam(Err);
487 
488   // If there was an error in the construction of the Header
489   // then just return with the error now set.
490   if (*Err)
491     return;
492 
493   uint64_t Size = Header->getSizeOf();
494   Data = StringRef(Start, Size);
495   Expected<bool> isThinOrErr = isThinMember();
496   if (!isThinOrErr) {
497     *Err = isThinOrErr.takeError();
498     return;
499   }
500   bool isThin = isThinOrErr.get();
501   if (!isThin) {
502     Expected<uint64_t> MemberSize = getRawSize();
503     if (!MemberSize) {
504       *Err = MemberSize.takeError();
505       return;
506     }
507     Size += MemberSize.get();
508     Data = StringRef(Start, Size);
509   }
510 
511   // Setup StartOfFile and PaddingBytes.
512   StartOfFile = Header->getSizeOf();
513   // Don't include attached name.
514   Expected<StringRef> NameOrErr = getRawName();
515   if (!NameOrErr) {
516     *Err = NameOrErr.takeError();
517     return;
518   }
519   StringRef Name = NameOrErr.get();
520 
521   if (Parent->kind() == Archive::K_AIXBIG) {
522     // The actual start of the file is after the name and any necessary
523     // even-alignment padding.
524     StartOfFile += ((Name.size() + 1) >> 1) << 1;
525   } else if (Name.startswith("#1/")) {
526     uint64_t NameSize;
527     StringRef RawNameSize = Name.substr(3).rtrim(' ');
528     if (RawNameSize.getAsInteger(10, NameSize)) {
529       uint64_t Offset = Start - Parent->getData().data();
530       *Err = malformedError("long name length characters after the #1/ are "
531                             "not all decimal numbers: '" +
532                             RawNameSize +
533                             "' for archive member header at offset " +
534                             Twine(Offset));
535       return;
536     }
537     StartOfFile += NameSize;
538   }
539 }
540 
541 Expected<uint64_t> Archive::Child::getSize() const {
542   if (Parent->IsThin)
543     return Header->getSize();
544   return Data.size() - StartOfFile;
545 }
546 
547 Expected<uint64_t> Archive::Child::getRawSize() const {
548   return Header->getSize();
549 }
550 
551 Expected<bool> Archive::Child::isThinMember() const { return Header->isThin(); }
552 
553 Expected<std::string> Archive::Child::getFullName() const {
554   Expected<bool> isThin = isThinMember();
555   if (!isThin)
556     return isThin.takeError();
557   assert(isThin.get());
558   Expected<StringRef> NameOrErr = getName();
559   if (!NameOrErr)
560     return NameOrErr.takeError();
561   StringRef Name = *NameOrErr;
562   if (sys::path::is_absolute(Name))
563     return std::string(Name);
564 
565   SmallString<128> FullName = sys::path::parent_path(
566       Parent->getMemoryBufferRef().getBufferIdentifier());
567   sys::path::append(FullName, Name);
568   return std::string(FullName.str());
569 }
570 
571 Expected<StringRef> Archive::Child::getBuffer() const {
572   Expected<bool> isThinOrErr = isThinMember();
573   if (!isThinOrErr)
574     return isThinOrErr.takeError();
575   bool isThin = isThinOrErr.get();
576   if (!isThin) {
577     Expected<uint64_t> Size = getSize();
578     if (!Size)
579       return Size.takeError();
580     return StringRef(Data.data() + StartOfFile, Size.get());
581   }
582   Expected<std::string> FullNameOrErr = getFullName();
583   if (!FullNameOrErr)
584     return FullNameOrErr.takeError();
585   const std::string &FullName = *FullNameOrErr;
586   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
587   if (std::error_code EC = Buf.getError())
588     return errorCodeToError(EC);
589   Parent->ThinBuffers.push_back(std::move(*Buf));
590   return Parent->ThinBuffers.back()->getBuffer();
591 }
592 
593 Expected<Archive::Child> Archive::Child::getNext() const {
594   Expected<const char *> NextLocOrErr = Header->getNextChildLoc();
595   if (!NextLocOrErr)
596     return NextLocOrErr.takeError();
597 
598   const char *NextLoc = *NextLocOrErr;
599 
600   // Check to see if this is at the end of the archive.
601   if (NextLoc == nullptr)
602     return Child(nullptr, nullptr, nullptr);
603 
604   // Check to see if this is past the end of the archive.
605   if (NextLoc > Parent->Data.getBufferEnd()) {
606     std::string Msg("offset to next archive member past the end of the archive "
607                     "after member ");
608     Expected<StringRef> NameOrErr = getName();
609     if (!NameOrErr) {
610       consumeError(NameOrErr.takeError());
611       uint64_t Offset = Data.data() - Parent->getData().data();
612       return malformedError(Msg + "at offset " + Twine(Offset));
613     } else
614       return malformedError(Msg + NameOrErr.get());
615   }
616 
617   Error Err = Error::success();
618   Child Ret(Parent, NextLoc, &Err);
619   if (Err)
620     return std::move(Err);
621   return Ret;
622 }
623 
624 uint64_t Archive::Child::getChildOffset() const {
625   const char *a = Parent->Data.getBuffer().data();
626   const char *c = Data.data();
627   uint64_t offset = c - a;
628   return offset;
629 }
630 
631 Expected<StringRef> Archive::Child::getName() const {
632   Expected<uint64_t> RawSizeOrErr = getRawSize();
633   if (!RawSizeOrErr)
634     return RawSizeOrErr.takeError();
635   uint64_t RawSize = RawSizeOrErr.get();
636   Expected<StringRef> NameOrErr =
637       Header->getName(Header->getSizeOf() + RawSize);
638   if (!NameOrErr)
639     return NameOrErr.takeError();
640   StringRef Name = NameOrErr.get();
641   return Name;
642 }
643 
644 Expected<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
645   Expected<StringRef> NameOrErr = getName();
646   if (!NameOrErr)
647     return NameOrErr.takeError();
648   StringRef Name = NameOrErr.get();
649   Expected<StringRef> Buf = getBuffer();
650   if (!Buf)
651     return createFileError(Name, Buf.takeError());
652   return MemoryBufferRef(*Buf, Name);
653 }
654 
655 Expected<std::unique_ptr<Binary>>
656 Archive::Child::getAsBinary(LLVMContext *Context) const {
657   Expected<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
658   if (!BuffOrErr)
659     return BuffOrErr.takeError();
660 
661   auto BinaryOrErr = createBinary(BuffOrErr.get(), Context);
662   if (BinaryOrErr)
663     return std::move(*BinaryOrErr);
664   return BinaryOrErr.takeError();
665 }
666 
667 Expected<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
668   Error Err = Error::success();
669   std::unique_ptr<Archive> Ret;
670   StringRef Buffer = Source.getBuffer();
671 
672   if (Buffer.startswith(BigArchiveMagic))
673     Ret = std::make_unique<BigArchive>(Source, Err);
674   else
675     Ret = std::make_unique<Archive>(Source, Err);
676 
677   if (Err)
678     return std::move(Err);
679   return std::move(Ret);
680 }
681 
682 std::unique_ptr<AbstractArchiveMemberHeader>
683 Archive::createArchiveMemberHeader(const char *RawHeaderPtr, uint64_t Size,
684                                    Error *Err) const {
685   ErrorAsOutParameter ErrAsOutParam(Err);
686   if (kind() != K_AIXBIG)
687     return std::make_unique<ArchiveMemberHeader>(this, RawHeaderPtr, Size, Err);
688   return std::make_unique<BigArchiveMemberHeader>(this, RawHeaderPtr, Size,
689                                                   Err);
690 }
691 
692 uint64_t Archive::getArchiveMagicLen() const {
693   if (isThin())
694     return sizeof(ThinArchiveMagic) - 1;
695 
696   if (Kind() == K_AIXBIG)
697     return sizeof(BigArchiveMagic) - 1;
698 
699   return sizeof(ArchiveMagic) - 1;
700 }
701 
702 void Archive::setFirstRegular(const Child &C) {
703   FirstRegularData = C.Data;
704   FirstRegularStartOfFile = C.StartOfFile;
705 }
706 
707 Archive::Archive(MemoryBufferRef Source, Error &Err)
708     : Binary(Binary::ID_Archive, Source) {
709   ErrorAsOutParameter ErrAsOutParam(&Err);
710   StringRef Buffer = Data.getBuffer();
711   // Check for sufficient magic.
712   if (Buffer.startswith(ThinArchiveMagic)) {
713     IsThin = true;
714   } else if (Buffer.startswith(ArchiveMagic)) {
715     IsThin = false;
716   } else if (Buffer.startswith(BigArchiveMagic)) {
717     Format = K_AIXBIG;
718     IsThin = false;
719     return;
720   } else {
721     Err = make_error<GenericBinaryError>("file too small to be an archive",
722                                          object_error::invalid_file_type);
723     return;
724   }
725 
726   // Make sure Format is initialized before any call to
727   // ArchiveMemberHeader::getName() is made.  This could be a valid empty
728   // archive which is the same in all formats.  So claiming it to be gnu to is
729   // fine if not totally correct before we look for a string table or table of
730   // contents.
731   Format = K_GNU;
732 
733   // Get the special members.
734   child_iterator I = child_begin(Err, false);
735   if (Err)
736     return;
737   child_iterator E = child_end();
738 
739   // See if this is a valid empty archive and if so return.
740   if (I == E) {
741     Err = Error::success();
742     return;
743   }
744   const Child *C = &*I;
745 
746   auto Increment = [&]() {
747     ++I;
748     if (Err)
749       return true;
750     C = &*I;
751     return false;
752   };
753 
754   Expected<StringRef> NameOrErr = C->getRawName();
755   if (!NameOrErr) {
756     Err = NameOrErr.takeError();
757     return;
758   }
759   StringRef Name = NameOrErr.get();
760 
761   // Below is the pattern that is used to figure out the archive format
762   // GNU archive format
763   //  First member : / (may exist, if it exists, points to the symbol table )
764   //  Second member : // (may exist, if it exists, points to the string table)
765   //  Note : The string table is used if the filename exceeds 15 characters
766   // BSD archive format
767   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
768   //  There is no string table, if the filename exceeds 15 characters or has a
769   //  embedded space, the filename has #1/<size>, The size represents the size
770   //  of the filename that needs to be read after the archive header
771   // COFF archive format
772   //  First member : /
773   //  Second member : / (provides a directory of symbols)
774   //  Third member : // (may exist, if it exists, contains the string table)
775   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
776   //  even if the string table is empty. However, lib.exe does not in fact
777   //  seem to create the third member if there's no member whose filename
778   //  exceeds 15 characters. So the third member is optional.
779 
780   if (Name == "__.SYMDEF" || Name == "__.SYMDEF_64") {
781     if (Name == "__.SYMDEF")
782       Format = K_BSD;
783     else // Name == "__.SYMDEF_64"
784       Format = K_DARWIN64;
785     // We know that the symbol table is not an external file, but we still must
786     // check any Expected<> return value.
787     Expected<StringRef> BufOrErr = C->getBuffer();
788     if (!BufOrErr) {
789       Err = BufOrErr.takeError();
790       return;
791     }
792     SymbolTable = BufOrErr.get();
793     if (Increment())
794       return;
795     setFirstRegular(*C);
796 
797     Err = Error::success();
798     return;
799   }
800 
801   if (Name.startswith("#1/")) {
802     Format = K_BSD;
803     // We know this is BSD, so getName will work since there is no string table.
804     Expected<StringRef> NameOrErr = C->getName();
805     if (!NameOrErr) {
806       Err = NameOrErr.takeError();
807       return;
808     }
809     Name = NameOrErr.get();
810     if (Name == "__.SYMDEF SORTED" || Name == "__.SYMDEF") {
811       // We know that the symbol table is not an external file, but we still
812       // must check any Expected<> return value.
813       Expected<StringRef> BufOrErr = C->getBuffer();
814       if (!BufOrErr) {
815         Err = BufOrErr.takeError();
816         return;
817       }
818       SymbolTable = BufOrErr.get();
819       if (Increment())
820         return;
821     } else if (Name == "__.SYMDEF_64 SORTED" || Name == "__.SYMDEF_64") {
822       Format = K_DARWIN64;
823       // We know that the symbol table is not an external file, but we still
824       // must check any Expected<> return value.
825       Expected<StringRef> BufOrErr = C->getBuffer();
826       if (!BufOrErr) {
827         Err = BufOrErr.takeError();
828         return;
829       }
830       SymbolTable = BufOrErr.get();
831       if (Increment())
832         return;
833     }
834     setFirstRegular(*C);
835     return;
836   }
837 
838   // MIPS 64-bit ELF archives use a special format of a symbol table.
839   // This format is marked by `ar_name` field equals to "/SYM64/".
840   // For detailed description see page 96 in the following document:
841   // http://techpubs.sgi.com/library/manuals/4000/007-4658-001/pdf/007-4658-001.pdf
842 
843   bool has64SymTable = false;
844   if (Name == "/" || Name == "/SYM64/") {
845     // We know that the symbol table is not an external file, but we still
846     // must check any Expected<> return value.
847     Expected<StringRef> BufOrErr = C->getBuffer();
848     if (!BufOrErr) {
849       Err = BufOrErr.takeError();
850       return;
851     }
852     SymbolTable = BufOrErr.get();
853     if (Name == "/SYM64/")
854       has64SymTable = true;
855 
856     if (Increment())
857       return;
858     if (I == E) {
859       Err = Error::success();
860       return;
861     }
862     Expected<StringRef> NameOrErr = C->getRawName();
863     if (!NameOrErr) {
864       Err = NameOrErr.takeError();
865       return;
866     }
867     Name = NameOrErr.get();
868   }
869 
870   if (Name == "//") {
871     Format = has64SymTable ? K_GNU64 : K_GNU;
872     // The string table is never an external member, but we still
873     // must check any Expected<> return value.
874     Expected<StringRef> BufOrErr = C->getBuffer();
875     if (!BufOrErr) {
876       Err = BufOrErr.takeError();
877       return;
878     }
879     StringTable = BufOrErr.get();
880     if (Increment())
881       return;
882     setFirstRegular(*C);
883     Err = Error::success();
884     return;
885   }
886 
887   if (Name[0] != '/') {
888     Format = has64SymTable ? K_GNU64 : K_GNU;
889     setFirstRegular(*C);
890     Err = Error::success();
891     return;
892   }
893 
894   if (Name != "/") {
895     Err = errorCodeToError(object_error::parse_failed);
896     return;
897   }
898 
899   Format = K_COFF;
900   // We know that the symbol table is not an external file, but we still
901   // must check any Expected<> return value.
902   Expected<StringRef> BufOrErr = C->getBuffer();
903   if (!BufOrErr) {
904     Err = BufOrErr.takeError();
905     return;
906   }
907   SymbolTable = BufOrErr.get();
908 
909   if (Increment())
910     return;
911 
912   if (I == E) {
913     setFirstRegular(*C);
914     Err = Error::success();
915     return;
916   }
917 
918   NameOrErr = C->getRawName();
919   if (!NameOrErr) {
920     Err = NameOrErr.takeError();
921     return;
922   }
923   Name = NameOrErr.get();
924 
925   if (Name == "//") {
926     // The string table is never an external member, but we still
927     // must check any Expected<> return value.
928     Expected<StringRef> BufOrErr = C->getBuffer();
929     if (!BufOrErr) {
930       Err = BufOrErr.takeError();
931       return;
932     }
933     StringTable = BufOrErr.get();
934     if (Increment())
935       return;
936 
937     if (I == E) {
938       setFirstRegular(*C);
939       Err = Error::success();
940       return;
941     }
942 
943     NameOrErr = C->getRawName();
944     if (!NameOrErr) {
945       Err = NameOrErr.takeError();
946       return;
947     }
948     Name = NameOrErr.get();
949   }
950 
951   if (Name == "/<ECSYMBOLS>/") {
952     // ARM64EC-aware libraries contain an additional special member with
953     // an EC symbol map after the string table. Its format is similar to a
954     // regular symbol map, except it doesn't contain member offsets. Its indexes
955     // refer to member offsets from the regular symbol table instead.
956     Expected<StringRef> BufOrErr = C->getBuffer();
957     if (!BufOrErr) {
958       Err = BufOrErr.takeError();
959       return;
960     }
961     ECSymbolTable = BufOrErr.get();
962     if (Increment())
963       return;
964   }
965 
966   setFirstRegular(*C);
967   Err = Error::success();
968 }
969 
970 object::Archive::Kind Archive::getDefaultKindForHost() {
971   Triple HostTriple(sys::getProcessTriple());
972   return HostTriple.isOSDarwin()
973              ? object::Archive::K_DARWIN
974              : (HostTriple.isOSAIX() ? object::Archive::K_AIXBIG
975                                      : object::Archive::K_GNU);
976 }
977 
978 Archive::child_iterator Archive::child_begin(Error &Err,
979                                              bool SkipInternal) const {
980   if (isEmpty())
981     return child_end();
982 
983   if (SkipInternal)
984     return child_iterator::itr(
985         Child(this, FirstRegularData, FirstRegularStartOfFile), Err);
986 
987   const char *Loc = Data.getBufferStart() + getFirstChildOffset();
988   Child C(this, Loc, &Err);
989   if (Err)
990     return child_end();
991   return child_iterator::itr(C, Err);
992 }
993 
994 Archive::child_iterator Archive::child_end() const {
995   return child_iterator::end(Child(nullptr, nullptr, nullptr));
996 }
997 
998 bool Archive::Symbol::isECSymbol() const {
999   // Symbols use SymbolCount..SymbolCount+getNumberOfECSymbols() for EC symbol
1000   // indexes.
1001   uint32_t SymbolCount = Parent->getNumberOfSymbols();
1002   return SymbolCount <= SymbolIndex &&
1003          SymbolIndex < SymbolCount + Parent->getNumberOfECSymbols();
1004 }
1005 
1006 StringRef Archive::Symbol::getName() const {
1007   if (isECSymbol())
1008     return Parent->ECSymbolTable.begin() + StringIndex;
1009   return Parent->getSymbolTable().begin() + StringIndex;
1010 }
1011 
1012 Expected<Archive::Child> Archive::Symbol::getMember() const {
1013   const char *Buf = Parent->getSymbolTable().begin();
1014   const char *Offsets = Buf;
1015   if (Parent->kind() == K_GNU64 || Parent->kind() == K_DARWIN64 ||
1016       Parent->kind() == K_AIXBIG)
1017     Offsets += sizeof(uint64_t);
1018   else
1019     Offsets += sizeof(uint32_t);
1020   uint64_t Offset = 0;
1021   if (Parent->kind() == K_GNU) {
1022     Offset = read32be(Offsets + SymbolIndex * 4);
1023   } else if (Parent->kind() == K_GNU64 || Parent->kind() == K_AIXBIG) {
1024     Offset = read64be(Offsets + SymbolIndex * 8);
1025   } else if (Parent->kind() == K_BSD) {
1026     // The SymbolIndex is an index into the ranlib structs that start at
1027     // Offsets (the first uint32_t is the number of bytes of the ranlib
1028     // structs).  The ranlib structs are a pair of uint32_t's the first
1029     // being a string table offset and the second being the offset into
1030     // the archive of the member that defines the symbol.  Which is what
1031     // is needed here.
1032     Offset = read32le(Offsets + SymbolIndex * 8 + 4);
1033   } else if (Parent->kind() == K_DARWIN64) {
1034     // The SymbolIndex is an index into the ranlib_64 structs that start at
1035     // Offsets (the first uint64_t is the number of bytes of the ranlib_64
1036     // structs).  The ranlib_64 structs are a pair of uint64_t's the first
1037     // being a string table offset and the second being the offset into
1038     // the archive of the member that defines the symbol.  Which is what
1039     // is needed here.
1040     Offset = read64le(Offsets + SymbolIndex * 16 + 8);
1041   } else {
1042     // Skip offsets.
1043     uint32_t MemberCount = read32le(Buf);
1044     Buf += MemberCount * 4 + 4;
1045 
1046     uint32_t SymbolCount = read32le(Buf);
1047     uint16_t OffsetIndex;
1048     if (SymbolIndex < SymbolCount) {
1049       // Skip SymbolCount to get to the indices table.
1050       const char *Indices = Buf + 4;
1051 
1052       // Get the index of the offset in the file member offset table for this
1053       // symbol.
1054       OffsetIndex = read16le(Indices + SymbolIndex * 2);
1055     } else if (isECSymbol()) {
1056       // Skip SymbolCount to get to the indices table.
1057       const char *Indices = Parent->ECSymbolTable.begin() + 4;
1058 
1059       // Get the index of the offset in the file member offset table for this
1060       // symbol.
1061       OffsetIndex = read16le(Indices + (SymbolIndex - SymbolCount) * 2);
1062     } else {
1063       return errorCodeToError(object_error::parse_failed);
1064     }
1065     // Subtract 1 since OffsetIndex is 1 based.
1066     --OffsetIndex;
1067 
1068     if (OffsetIndex >= MemberCount)
1069       return errorCodeToError(object_error::parse_failed);
1070 
1071     Offset = read32le(Offsets + OffsetIndex * 4);
1072   }
1073 
1074   const char *Loc = Parent->getData().begin() + Offset;
1075   Error Err = Error::success();
1076   Child C(Parent, Loc, &Err);
1077   if (Err)
1078     return std::move(Err);
1079   return C;
1080 }
1081 
1082 Archive::Symbol Archive::Symbol::getNext() const {
1083   Symbol t(*this);
1084   if (Parent->kind() == K_BSD) {
1085     // t.StringIndex is an offset from the start of the __.SYMDEF or
1086     // "__.SYMDEF SORTED" member into the string table for the ranlib
1087     // struct indexed by t.SymbolIndex .  To change t.StringIndex to the
1088     // offset in the string table for t.SymbolIndex+1 we subtract the
1089     // its offset from the start of the string table for t.SymbolIndex
1090     // and add the offset of the string table for t.SymbolIndex+1.
1091 
1092     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
1093     // which is the number of bytes of ranlib structs that follow.  The ranlib
1094     // structs are a pair of uint32_t's the first being a string table offset
1095     // and the second being the offset into the archive of the member that
1096     // define the symbol. After that the next uint32_t is the byte count of
1097     // the string table followed by the string table.
1098     const char *Buf = Parent->getSymbolTable().begin();
1099     uint32_t RanlibCount = 0;
1100     RanlibCount = read32le(Buf) / 8;
1101     // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
1102     // don't change the t.StringIndex as we don't want to reference a ranlib
1103     // past RanlibCount.
1104     if (t.SymbolIndex + 1 < RanlibCount) {
1105       const char *Ranlibs = Buf + 4;
1106       uint32_t CurRanStrx = 0;
1107       uint32_t NextRanStrx = 0;
1108       CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
1109       NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
1110       t.StringIndex -= CurRanStrx;
1111       t.StringIndex += NextRanStrx;
1112     }
1113   } else if (t.isECSymbol()) {
1114     // Go to one past next null.
1115     t.StringIndex = Parent->ECSymbolTable.find('\0', t.StringIndex) + 1;
1116   } else {
1117     // Go to one past next null.
1118     t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
1119   }
1120   ++t.SymbolIndex;
1121   return t;
1122 }
1123 
1124 Archive::symbol_iterator Archive::symbol_begin() const {
1125   if (!hasSymbolTable())
1126     return symbol_iterator(Symbol(this, 0, 0));
1127 
1128   const char *buf = getSymbolTable().begin();
1129   if (kind() == K_GNU) {
1130     uint32_t symbol_count = 0;
1131     symbol_count = read32be(buf);
1132     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
1133   } else if (kind() == K_GNU64) {
1134     uint64_t symbol_count = read64be(buf);
1135     buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
1136   } else if (kind() == K_BSD) {
1137     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
1138     // which is the number of bytes of ranlib structs that follow.  The ranlib
1139     // structs are a pair of uint32_t's the first being a string table offset
1140     // and the second being the offset into the archive of the member that
1141     // define the symbol. After that the next uint32_t is the byte count of
1142     // the string table followed by the string table.
1143     uint32_t ranlib_count = 0;
1144     ranlib_count = read32le(buf) / 8;
1145     const char *ranlibs = buf + 4;
1146     uint32_t ran_strx = 0;
1147     ran_strx = read32le(ranlibs);
1148     buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
1149     // Skip the byte count of the string table.
1150     buf += sizeof(uint32_t);
1151     buf += ran_strx;
1152   } else if (kind() == K_DARWIN64) {
1153     // The __.SYMDEF_64 or "__.SYMDEF_64 SORTED" member starts with a uint64_t
1154     // which is the number of bytes of ranlib_64 structs that follow.  The
1155     // ranlib_64 structs are a pair of uint64_t's the first being a string
1156     // table offset and the second being the offset into the archive of the
1157     // member that define the symbol. After that the next uint64_t is the byte
1158     // count of the string table followed by the string table.
1159     uint64_t ranlib_count = 0;
1160     ranlib_count = read64le(buf) / 16;
1161     const char *ranlibs = buf + 8;
1162     uint64_t ran_strx = 0;
1163     ran_strx = read64le(ranlibs);
1164     buf += sizeof(uint64_t) + (ranlib_count * (2 * (sizeof(uint64_t))));
1165     // Skip the byte count of the string table.
1166     buf += sizeof(uint64_t);
1167     buf += ran_strx;
1168   } else if (kind() == K_AIXBIG) {
1169     buf = getStringTable().begin();
1170   } else {
1171     uint32_t member_count = 0;
1172     uint32_t symbol_count = 0;
1173     member_count = read32le(buf);
1174     buf += 4 + (member_count * 4); // Skip offsets.
1175     symbol_count = read32le(buf);
1176     buf += 4 + (symbol_count * 2); // Skip indices.
1177   }
1178   uint32_t string_start_offset = buf - getSymbolTable().begin();
1179   return symbol_iterator(Symbol(this, 0, string_start_offset));
1180 }
1181 
1182 Archive::symbol_iterator Archive::symbol_end() const {
1183   return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
1184 }
1185 
1186 Expected<iterator_range<Archive::symbol_iterator>> Archive::ec_symbols() const {
1187   uint32_t Count = 0;
1188 
1189   // Validate EC symbol table.
1190   if (!ECSymbolTable.empty()) {
1191     if (ECSymbolTable.size() < sizeof(uint32_t))
1192       return malformedError("invalid EC symbols size (" +
1193                             Twine(ECSymbolTable.size()) + ")");
1194     if (SymbolTable.size() < sizeof(uint32_t))
1195       return malformedError("invalid symbols size (" +
1196                             Twine(ECSymbolTable.size()) + ")");
1197 
1198     Count = read32le(ECSymbolTable.begin());
1199     size_t StringIndex = sizeof(uint32_t) + Count * sizeof(uint16_t);
1200     if (ECSymbolTable.size() < StringIndex)
1201       return malformedError("invalid EC symbols size. Size was " +
1202                             Twine(ECSymbolTable.size()) + ", but expected " +
1203                             Twine(StringIndex));
1204 
1205     uint32_t MemberCount = read32le(SymbolTable.begin());
1206     const char *Indexes = ECSymbolTable.begin() + sizeof(uint32_t);
1207 
1208     for (uint32_t i = 0; i < Count; ++i) {
1209       uint16_t Index = read16le(Indexes + i * sizeof(uint16_t));
1210       if (!Index)
1211         return malformedError("invalid EC symbol index 0");
1212       if (Index > MemberCount)
1213         return malformedError("invalid EC symbol index " + Twine(Index) +
1214                               " is larger than member count " +
1215                               Twine(MemberCount));
1216 
1217       StringIndex = ECSymbolTable.find('\0', StringIndex);
1218       if (StringIndex == StringRef::npos)
1219         return malformedError("malformed EC symbol names: not null-terminated");
1220       ++StringIndex;
1221     }
1222   }
1223 
1224   uint32_t SymbolCount = getNumberOfSymbols();
1225   return make_range(
1226       symbol_iterator(Symbol(this, SymbolCount,
1227                              sizeof(uint32_t) + Count * sizeof(uint16_t))),
1228       symbol_iterator(Symbol(this, SymbolCount + Count, 0)));
1229 }
1230 
1231 uint32_t Archive::getNumberOfSymbols() const {
1232   if (!hasSymbolTable())
1233     return 0;
1234   const char *buf = getSymbolTable().begin();
1235   if (kind() == K_GNU)
1236     return read32be(buf);
1237   if (kind() == K_GNU64 || kind() == K_AIXBIG)
1238     return read64be(buf);
1239   if (kind() == K_BSD)
1240     return read32le(buf) / 8;
1241   if (kind() == K_DARWIN64)
1242     return read64le(buf) / 16;
1243   uint32_t member_count = 0;
1244   member_count = read32le(buf);
1245   buf += 4 + (member_count * 4); // Skip offsets.
1246   return read32le(buf);
1247 }
1248 
1249 uint32_t Archive::getNumberOfECSymbols() const {
1250   if (ECSymbolTable.size() < sizeof(uint32_t))
1251     return 0;
1252   return read32le(ECSymbolTable.begin());
1253 }
1254 
1255 Expected<std::optional<Archive::Child>> Archive::findSym(StringRef name) const {
1256   Archive::symbol_iterator bs = symbol_begin();
1257   Archive::symbol_iterator es = symbol_end();
1258 
1259   for (; bs != es; ++bs) {
1260     StringRef SymName = bs->getName();
1261     if (SymName == name) {
1262       if (auto MemberOrErr = bs->getMember())
1263         return Child(*MemberOrErr);
1264       else
1265         return MemberOrErr.takeError();
1266     }
1267   }
1268   return std::nullopt;
1269 }
1270 
1271 // Returns true if archive file contains no member file.
1272 bool Archive::isEmpty() const {
1273   return Data.getBufferSize() == getArchiveMagicLen();
1274 }
1275 
1276 bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }
1277 
1278 BigArchive::BigArchive(MemoryBufferRef Source, Error &Err)
1279     : Archive(Source, Err) {
1280   ErrorAsOutParameter ErrAsOutParam(&Err);
1281   StringRef Buffer = Data.getBuffer();
1282   ArFixLenHdr = reinterpret_cast<const FixLenHdr *>(Buffer.data());
1283   uint64_t BufferSize = Data.getBufferSize();
1284 
1285   if (BufferSize < sizeof(FixLenHdr)) {
1286     Err = malformedError("malformed AIX big archive: incomplete fixed length "
1287                          "header, the archive is only" +
1288                          Twine(BufferSize) + " byte(s)");
1289     return;
1290   }
1291 
1292   StringRef RawOffset = getFieldRawString(ArFixLenHdr->FirstChildOffset);
1293   if (RawOffset.getAsInteger(10, FirstChildOffset))
1294     // TODO: Out-of-line.
1295     Err = malformedError("malformed AIX big archive: first member offset \"" +
1296                          RawOffset + "\" is not a number");
1297 
1298   RawOffset = getFieldRawString(ArFixLenHdr->LastChildOffset);
1299   if (RawOffset.getAsInteger(10, LastChildOffset))
1300     // TODO: Out-of-line.
1301     Err = malformedError("malformed AIX big archive: last member offset \"" +
1302                          RawOffset + "\" is not a number");
1303 
1304   // Calculate the global symbol table.
1305   uint64_t GlobSymOffset = 0;
1306   RawOffset = getFieldRawString(ArFixLenHdr->GlobSymOffset);
1307   if (RawOffset.getAsInteger(10, GlobSymOffset))
1308     // TODO: add test case.
1309     Err = malformedError(
1310         "malformed AIX big archive: global symbol table offset \"" + RawOffset +
1311         "\" is not a number");
1312 
1313   if (Err)
1314     return;
1315 
1316   if (GlobSymOffset > 0) {
1317     uint64_t GlobalSymTblContentOffset =
1318         GlobSymOffset + sizeof(BigArMemHdrType);
1319     if (GlobalSymTblContentOffset > BufferSize) {
1320       Err = malformedError("global symbol table header at offset 0x" +
1321                            Twine::utohexstr(GlobSymOffset) + " and size 0x" +
1322                            Twine::utohexstr(sizeof(BigArMemHdrType)) +
1323                            " goes past the end of file");
1324       return;
1325     }
1326 
1327     const char *GlobSymTblLoc = Data.getBufferStart() + GlobSymOffset;
1328     const BigArMemHdrType *GlobalSymHdr =
1329         reinterpret_cast<const BigArMemHdrType *>(GlobSymTblLoc);
1330     RawOffset = getFieldRawString(GlobalSymHdr->Size);
1331     uint64_t Size;
1332     if (RawOffset.getAsInteger(10, Size)) {
1333       // TODO: add test case.
1334       Err = malformedError(
1335           "malformed AIX big archive: global symbol table size \"" + RawOffset +
1336           "\" is not a number");
1337       return;
1338     }
1339     if (GlobalSymTblContentOffset + Size > BufferSize) {
1340       Err = malformedError("global symbol table content at offset 0x" +
1341                            Twine::utohexstr(GlobalSymTblContentOffset) +
1342                            " and size 0x" + Twine::utohexstr(Size) +
1343                            " goes past the end of file");
1344       return;
1345     }
1346     SymbolTable = StringRef(GlobSymTblLoc + sizeof(BigArMemHdrType), Size);
1347     unsigned SymNum = getNumberOfSymbols();
1348     unsigned SymOffsetsSize = 8 * (SymNum + 1);
1349     uint64_t SymbolTableStringSize = Size - SymOffsetsSize;
1350     StringTable =
1351         StringRef(GlobSymTblLoc + sizeof(BigArMemHdrType) + SymOffsetsSize,
1352                   SymbolTableStringSize);
1353   }
1354 
1355   child_iterator I = child_begin(Err, false);
1356   if (Err)
1357     return;
1358   child_iterator E = child_end();
1359   if (I == E) {
1360     Err = Error::success();
1361     return;
1362   }
1363   setFirstRegular(*I);
1364   Err = Error::success();
1365 }
1366