LCOV - code coverage report
Current view: top level - lib/Object - Archive.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 497 574 86.6 %
Date: 2017-09-14 15:23:50 Functions: 36 37 97.3 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- Archive.cpp - ar File Format implementation ------------------------===//
       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/Optional.h"
      16             : #include "llvm/ADT/SmallString.h"
      17             : #include "llvm/ADT/StringRef.h"
      18             : #include "llvm/ADT/Twine.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"
      29             : #include <algorithm>
      30             : #include <cassert>
      31             : #include <cstddef>
      32             : #include <cstdint>
      33             : #include <cstring>
      34             : #include <memory>
      35             : #include <string>
      36             : #include <system_error>
      37             : 
      38             : using namespace llvm;
      39             : using namespace object;
      40             : using namespace llvm::support::endian;
      41             : 
      42             : static const char *const Magic = "!<arch>\n";
      43             : static const char *const ThinMagic = "!<thin>\n";
      44             : 
      45           0 : void Archive::anchor() {}
      46             : 
      47             : static Error
      48          18 : malformedError(Twine Msg) {
      49          72 :   std::string StringMsg = "truncated or malformed archive (" + Msg.str() + ")";
      50          18 :   return make_error<GenericBinaryError>(std::move(StringMsg),
      51          72 :                                         object_error::parse_failed);
      52             : }
      53             : 
      54        2842 : ArchiveMemberHeader::ArchiveMemberHeader(const Archive *Parent,
      55             :                                          const char *RawHeaderPtr,
      56        2842 :                                          uint64_t Size, Error *Err)
      57             :     : Parent(Parent),
      58        2842 :       ArMemHdr(reinterpret_cast<const ArMemHdrType *>(RawHeaderPtr)) {
      59        2842 :   if (RawHeaderPtr == nullptr)
      60             :     return;
      61        1865 :   ErrorAsOutParameter ErrAsOutParam(Err);
      62             : 
      63        1865 :   if (Size < sizeof(ArMemHdrType)) {
      64           1 :     if (Err) {
      65             :       std::string Msg("remaining size of archive too small for next archive "
      66           3 :                       "member header ");
      67           2 :       Expected<StringRef> NameOrErr = getName(Size);
      68           1 :       if (!NameOrErr) {
      69           0 :         consumeError(NameOrErr.takeError());
      70           0 :         uint64_t Offset = RawHeaderPtr - Parent->getData().data();
      71           0 :         *Err = malformedError(Msg + "at offset " + Twine(Offset));
      72             :       } else
      73           7 :         *Err = malformedError(Msg + "for " + NameOrErr.get());
      74             :     }
      75             :     return;
      76             :   }
      77        1864 :   if (ArMemHdr->Terminator[0] != '`' || ArMemHdr->Terminator[1] != '\n') {
      78           1 :     if (Err) {
      79           2 :       std::string Buf;
      80           2 :       raw_string_ostream OS(Buf);
      81           1 :       OS.write_escaped(StringRef(ArMemHdr->Terminator,
      82           3 :                                  sizeof(ArMemHdr->Terminator)));
      83           1 :       OS.flush();
      84           2 :       std::string Msg("terminator characters in archive member \"" + Buf +
      85             :                       "\" not the correct \"`\\n\" values for the archive "
      86           2 :                       "member header ");
      87           2 :       Expected<StringRef> NameOrErr = getName(Size);
      88           1 :       if (!NameOrErr) {
      89           0 :         consumeError(NameOrErr.takeError());
      90           0 :         uint64_t Offset = RawHeaderPtr - Parent->getData().data();
      91           0 :         *Err = malformedError(Msg + "at offset " + Twine(Offset));
      92             :       } else
      93           7 :         *Err = malformedError(Msg + "for " + NameOrErr.get());
      94             :     }
      95             :     return;
      96             :   }
      97             : }
      98             : 
      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        6099 : Expected<StringRef> ArchiveMemberHeader::getRawName() const {
     102             :   char EndCond;
     103       12198 :   auto Kind = Parent->kind();
     104        6099 :   if (Kind == Archive::K_BSD || Kind == Archive::K_DARWIN64) {
     105         934 :     if (ArMemHdr->Name[0] == ' ') {
     106           2 :       uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
     107           3 :                         Parent->getData().data();
     108           3 :       return malformedError("name contains a leading space for archive member "
     109           3 :                             "header at offset " + Twine(Offset));
     110             :     }
     111             :     EndCond = ' ';
     112             :   }
     113        5165 :   else if (ArMemHdr->Name[0] == '/' || ArMemHdr->Name[0] == '#')
     114             :     EndCond = ' ';
     115             :   else
     116        1551 :     EndCond = '/';
     117             :   StringRef::size_type end =
     118       18294 :       StringRef(ArMemHdr->Name, sizeof(ArMemHdr->Name)).find(EndCond);
     119        5994 :   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       12196 :   return StringRef(ArMemHdr->Name, end);
     124             : }
     125             : 
     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        1126 : Expected<StringRef> ArchiveMemberHeader::getName(uint64_t Size) const {
     130             : 
     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        1126 :   if (Size < offsetof(ArMemHdrType, Name) + sizeof(ArMemHdr->Name)) {
     135           0 :     uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
     136           0 :                       Parent->getData().data();
     137           0 :     return malformedError("archive header truncated before the name field "
     138             :                           "for archive member header at offset " +
     139           0 :                           Twine(ArchiveOffset));
     140             :   }
     141             : 
     142             :   // The raw name itself can be invalid.
     143        1126 :   Expected<StringRef> NameOrErr = getRawName();
     144        1126 :   if (!NameOrErr)
     145           0 :     return NameOrErr.takeError();
     146        1126 :   StringRef Name = NameOrErr.get();
     147             : 
     148             :   // Check if it's a special name.
     149        2252 :   if (Name[0] == '/') {
     150         380 :     if (Name.size() == 1) // Linker member.
     151             :       return Name;
     152         585 :     if (Name.size() == 2 && Name[1] == '/') // String table.
     153             :       return Name;
     154             :     // It's a long name.
     155             :     // Get the string table offset.
     156             :     std::size_t StringOffset;
     157         760 :     if (Name.substr(1).rtrim(' ').getAsInteger(10, StringOffset)) {
     158           4 :       std::string Buf;
     159           4 :       raw_string_ostream OS(Buf);
     160           2 :       OS.write_escaped(Name.substr(1).rtrim(' '));
     161           2 :       OS.flush();
     162           4 :       uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
     163           6 :                                Parent->getData().data();
     164           6 :       return malformedError("long name offset characters after the '/' are "
     165           6 :                             "not all decimal numbers: '" + Buf + "' for "
     166             :                             "archive member header at offset " +
     167           6 :                             Twine(ArchiveOffset));
     168             :     }
     169             : 
     170             :     // Verify it.
     171         378 :     if (StringOffset >= Parent->getStringTable().size()) {
     172           4 :       uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
     173           6 :                                Parent->getData().data();
     174          12 :       return malformedError("long name offset " + Twine(StringOffset) + " past "
     175             :                             "the end of the string table for archive member "
     176           8 :                             "header at offset " + Twine(ArchiveOffset));
     177             :     }
     178         376 :     const char *addr = Parent->getStringTable().begin() + StringOffset;
     179             : 
     180             :     // GNU long file names end with a "/\n".
     181         819 :     if (Parent->kind() == Archive::K_GNU ||
     182          67 :         Parent->kind() == Archive::K_MIPS64) {
     183         927 :       StringRef::size_type End = StringRef(addr).find('\n');
     184         618 :       return StringRef(addr, End - 1);
     185             :     }
     186             :     return addr;
     187             :   }
     188             : 
     189        1111 :   if (Name.startswith("#1/")) {
     190             :     uint64_t NameLength;
     191         730 :     if (Name.substr(3).rtrim(' ').getAsInteger(10, NameLength)) {
     192           0 :       std::string Buf;
     193           0 :       raw_string_ostream OS(Buf);
     194           0 :       OS.write_escaped(Name.substr(3).rtrim(' '));
     195           0 :       OS.flush();
     196           0 :       uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
     197           0 :                         Parent->getData().data();
     198           0 :       return malformedError("long name length characters after the #1/ are "
     199           0 :                             "not all decimal numbers: '" + Buf + "' for "
     200             :                             "archive member header at offset " +
     201           0 :                             Twine(ArchiveOffset));
     202             :     }
     203         365 :     if (getSizeOf() + NameLength > Size) {
     204           6 :       uint64_t ArchiveOffset = reinterpret_cast<const char *>(ArMemHdr) -
     205           9 :                         Parent->getData().data();
     206          18 :       return malformedError("long name length: " + Twine(NameLength) +
     207             :                             " extends past the end of the member or archive "
     208           6 :                             "for archive member header at offset " +
     209           9 :                             Twine(ArchiveOffset));
     210             :     }
     211        1086 :     return StringRef(reinterpret_cast<const char *>(ArMemHdr) + getSizeOf(),
     212         724 :                      NameLength).rtrim('\0');
     213             :   }
     214             : 
     215             :   // It is not a long name so trim the blanks at the end of the name.
     216         762 :   if (Name[Name.size() - 1] != '/')
     217         762 :     return Name.rtrim(' ');
     218             : 
     219             :   // It's a simple name.
     220           0 :   return Name.drop_back(1);
     221             : }
     222             : 
     223        2728 : Expected<uint32_t> ArchiveMemberHeader::getSize() const {
     224             :   uint32_t Ret;
     225        8184 :   if (StringRef(ArMemHdr->Size,
     226        5456 :                 sizeof(ArMemHdr->Size)).rtrim(" ").getAsInteger(10, Ret)) {
     227           4 :     std::string Buf;
     228           4 :     raw_string_ostream OS(Buf);
     229           8 :     OS.write_escaped(StringRef(ArMemHdr->Size,
     230           4 :                                sizeof(ArMemHdr->Size)).rtrim(" "));
     231           2 :     OS.flush();
     232           4 :     uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
     233           6 :                       Parent->getData().data();
     234           6 :     return malformedError("characters in size field in archive header are not "
     235           6 :                           "all decimal numbers: '" + Buf + "' for archive "
     236           6 :                           "member header at offset " + Twine(Offset));
     237             :   }
     238             :   return Ret;
     239             : }
     240             : 
     241          57 : Expected<sys::fs::perms> ArchiveMemberHeader::getAccessMode() const {
     242             :   unsigned Ret;
     243         171 :   if (StringRef(ArMemHdr->AccessMode,
     244         114 :                 sizeof(ArMemHdr->AccessMode)).rtrim(' ').getAsInteger(8, Ret)) {
     245           2 :     std::string Buf;
     246           2 :     raw_string_ostream OS(Buf);
     247           4 :     OS.write_escaped(StringRef(ArMemHdr->AccessMode,
     248           2 :                                sizeof(ArMemHdr->AccessMode)).rtrim(" "));
     249           1 :     OS.flush();
     250           2 :     uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
     251           3 :                       Parent->getData().data();
     252           3 :     return malformedError("characters in AccessMode field in archive header "
     253           3 :                           "are not all decimal numbers: '" + Buf + "' for the "
     254           3 :                           "archive member header at offset " + Twine(Offset));
     255             :   }
     256         112 :   return static_cast<sys::fs::perms>(Ret);
     257             : }
     258             : 
     259             : Expected<sys::TimePoint<std::chrono::seconds>>
     260          91 : ArchiveMemberHeader::getLastModified() const {
     261             :   unsigned Seconds;
     262         273 :   if (StringRef(ArMemHdr->LastModified,
     263         182 :                 sizeof(ArMemHdr->LastModified)).rtrim(' ')
     264          91 :           .getAsInteger(10, Seconds)) {
     265           2 :     std::string Buf;
     266           2 :     raw_string_ostream OS(Buf);
     267           4 :     OS.write_escaped(StringRef(ArMemHdr->LastModified,
     268           2 :                                sizeof(ArMemHdr->LastModified)).rtrim(" "));
     269           1 :     OS.flush();
     270           2 :     uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
     271           3 :                       Parent->getData().data();
     272           3 :     return malformedError("characters in LastModified field in archive header "
     273           3 :                           "are not all decimal numbers: '" + Buf + "' for the "
     274           3 :                           "archive member header at offset " + Twine(Offset));
     275             :   }
     276             : 
     277         270 :   return sys::toTimePoint(Seconds);
     278             : }
     279             : 
     280          48 : Expected<unsigned> ArchiveMemberHeader::getUID() const {
     281             :   unsigned Ret;
     282          96 :   StringRef User = StringRef(ArMemHdr->UID, sizeof(ArMemHdr->UID)).rtrim(' ');
     283          48 :   if (User.empty())
     284           2 :     return 0;
     285          47 :   if (User.getAsInteger(10, Ret)) {
     286           2 :     std::string Buf;
     287           2 :     raw_string_ostream OS(Buf);
     288           1 :     OS.write_escaped(User);
     289           1 :     OS.flush();
     290           2 :     uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
     291           3 :                       Parent->getData().data();
     292           3 :     return malformedError("characters in UID field in archive header "
     293           3 :                           "are not all decimal numbers: '" + Buf + "' for the "
     294           3 :                           "archive member header at offset " + Twine(Offset));
     295             :   }
     296             :   return Ret;
     297             : }
     298             : 
     299          47 : Expected<unsigned> ArchiveMemberHeader::getGID() const {
     300             :   unsigned Ret;
     301          94 :   StringRef Group = StringRef(ArMemHdr->GID, sizeof(ArMemHdr->GID)).rtrim(' ');
     302          47 :   if (Group.empty())
     303           2 :     return 0;
     304          46 :   if (Group.getAsInteger(10, Ret)) {
     305           2 :     std::string Buf;
     306           2 :     raw_string_ostream OS(Buf);
     307           1 :     OS.write_escaped(Group);
     308           1 :     OS.flush();
     309           2 :     uint64_t Offset = reinterpret_cast<const char *>(ArMemHdr) -
     310           3 :                       Parent->getData().data();
     311           3 :     return malformedError("characters in GID field in archive header "
     312           3 :                           "are not all decimal numbers: '" + Buf + "' for the "
     313           3 :                           "archive member header at offset " + Twine(Offset));
     314             :   }
     315             :   return Ret;
     316             : }
     317             : 
     318         272 : Archive::Child::Child(const Archive *Parent, StringRef Data,
     319         272 :                       uint16_t StartOfFile)
     320             :     : Parent(Parent), Header(Parent, Data.data(), Data.size(), nullptr),
     321         816 :       Data(Data), StartOfFile(StartOfFile) {
     322         272 : }
     323             : 
     324        2570 : Archive::Child::Child(const Archive *Parent, const char *Start, Error *Err)
     325             :     : Parent(Parent),
     326             :       Header(Parent, Start,
     327             :              Parent
     328        7352 :                ? Parent->getData().size() - (Start - Parent->getData().data())
     329        9304 :                : 0, Err) {
     330        2570 :   if (!Start)
     331         982 :     return;
     332             : 
     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
     336             :   // nullptr.
     337             :   assert(Err && "Err can't be nullptr if Start is not a nullptr");
     338             : 
     339        3182 :   ErrorAsOutParameter ErrAsOutParam(Err);
     340             : 
     341             :   // If there was an error in the construction of the Header 
     342             :   // then just return with the error now set.
     343        1594 :   if (*Err)
     344             :     return;
     345             : 
     346        1592 :   uint64_t Size = Header.getSizeOf();
     347        1592 :   Data = StringRef(Start, Size);
     348        3180 :   Expected<bool> isThinOrErr = isThinMember();
     349        1592 :   if (!isThinOrErr) {
     350           3 :     *Err = isThinOrErr.takeError();
     351           1 :     return;
     352             :   }
     353        1591 :   bool isThin = isThinOrErr.get();
     354        1591 :   if (!isThin) {
     355        3104 :     Expected<uint64_t> MemberSize = getRawSize();
     356        1553 :     if (!MemberSize) {
     357           6 :       *Err = MemberSize.takeError();
     358           2 :       return;
     359             :     }
     360        1551 :     Size += MemberSize.get();
     361        1551 :     Data = StringRef(Start, Size);
     362             :   }
     363             : 
     364             :   // Setup StartOfFile and PaddingBytes.
     365        1589 :   StartOfFile = Header.getSizeOf();
     366             :   // Don't include attached name.
     367        3177 :   Expected<StringRef> NameOrErr = getRawName();
     368        1589 :   if (!NameOrErr){
     369           0 :     *Err = NameOrErr.takeError();
     370           0 :     return;
     371             :   }
     372        1589 :   StringRef Name = NameOrErr.get();
     373        1880 :   if (Name.startswith("#1/")) {
     374             :     uint64_t NameSize;
     375         582 :     if (Name.substr(3).rtrim(' ').getAsInteger(10, NameSize)) {
     376           2 :       std::string Buf;
     377           2 :       raw_string_ostream OS(Buf);
     378           1 :       OS.write_escaped(Name.substr(3).rtrim(' '));
     379           1 :       OS.flush();
     380           2 :       uint64_t Offset = Start - Parent->getData().data();
     381           4 :       *Err = malformedError("long name length characters after the #1/ are "
     382           3 :                             "not all decimal numbers: '" + Buf + "' for "
     383             :                             "archive member header at offset " +
     384           2 :                             Twine(Offset));
     385             :       return;
     386             :     }
     387         290 :     StartOfFile += NameSize;
     388             :   }
     389             : }
     390             : 
     391        1094 : Expected<uint64_t> Archive::Child::getSize() const {
     392        1094 :   if (Parent->IsThin) {
     393          64 :     Expected<uint32_t> Size = Header.getSize();
     394          32 :     if (!Size)
     395           0 :       return Size.takeError();
     396          32 :     return Size.get();
     397             :   }
     398        3186 :   return Data.size() - StartOfFile;
     399             : }
     400             : 
     401        2696 : Expected<uint64_t> Archive::Child::getRawSize() const {
     402        8088 :   return Header.getSize();
     403             : }
     404             : 
     405        2695 : Expected<bool> Archive::Child::isThinMember() const {
     406        5390 :   Expected<StringRef> NameOrErr = Header.getRawName();
     407        2695 :   if (!NameOrErr)
     408           3 :     return NameOrErr.takeError();
     409        2694 :   StringRef Name = NameOrErr.get();
     410        8187 :   return Parent->IsThin && Name != "/" && Name != "//";
     411             : }
     412             : 
     413          18 : Expected<std::string> Archive::Child::getFullName() const {
     414          36 :   Expected<bool> isThin = isThinMember();
     415          18 :   if (!isThin)
     416           0 :     return isThin.takeError();
     417             :   assert(isThin.get());
     418          18 :   Expected<StringRef> NameOrErr = getName();
     419          18 :   if (!NameOrErr)
     420           0 :     return NameOrErr.takeError();
     421          18 :   StringRef Name = *NameOrErr;
     422          18 :   if (sys::path::is_absolute(Name))
     423             :     return Name;
     424             : 
     425             :   SmallString<128> FullName = sys::path::parent_path(
     426          24 :       Parent->getMemoryBufferRef().getBufferIdentifier());
     427          48 :   sys::path::append(FullName, Name);
     428          24 :   return StringRef(FullName);
     429             : }
     430             : 
     431        1085 : Expected<StringRef> Archive::Child::getBuffer() const {
     432        2170 :   Expected<bool> isThinOrErr = isThinMember();
     433        1085 :   if (!isThinOrErr)
     434           0 :     return isThinOrErr.takeError();
     435        1085 :   bool isThin = isThinOrErr.get();
     436        1085 :   if (!isThin) {
     437        4272 :     Expected<uint32_t> Size = getSize();
     438        1068 :     if (!Size)
     439           0 :       return Size.takeError();
     440        3204 :     return StringRef(Data.data() + StartOfFile, Size.get());
     441             :   }
     442          34 :   Expected<std::string> FullNameOrErr = getFullName();
     443          17 :   if (!FullNameOrErr)
     444           0 :     return FullNameOrErr.takeError();
     445          17 :   const std::string &FullName = *FullNameOrErr;
     446          17 :   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(FullName);
     447          17 :   if (std::error_code EC = Buf.getError())
     448           3 :     return errorCodeToError(EC);
     449          48 :   Parent->ThinBuffers.push_back(std::move(*Buf));
     450          80 :   return Parent->ThinBuffers.back()->getBuffer();
     451             : }
     452             : 
     453        1173 : Expected<Archive::Child> Archive::Child::getNext() const {
     454        2346 :   size_t SpaceToSkip = Data.size();
     455             :   // If it's odd, add 1 to make it even.
     456        1173 :   if (SpaceToSkip & 1)
     457         160 :     ++SpaceToSkip;
     458             : 
     459        2346 :   const char *NextLoc = Data.data() + SpaceToSkip;
     460             : 
     461             :   // Check to see if this is at the end of the archive.
     462        2346 :   if (NextLoc == Parent->Data.getBufferEnd())
     463         534 :     return Child(nullptr, nullptr, nullptr);
     464             : 
     465             :   // Check to see if this is past the end of the archive.
     466        1812 :   if (NextLoc > Parent->Data.getBufferEnd()) {
     467             :     std::string Msg("offset to next archive member past the end of the archive "
     468           3 :                     "after member ");
     469           2 :     Expected<StringRef> NameOrErr = getName();
     470           1 :     if (!NameOrErr) {
     471           0 :       consumeError(NameOrErr.takeError());
     472           0 :       uint64_t Offset = Data.data() - Parent->getData().data();
     473           0 :       return malformedError(Msg + "at offset " + Twine(Offset));
     474             :     } else
     475           6 :       return malformedError(Msg + NameOrErr.get());
     476             :   }
     477             : 
     478        1810 :   Error Err = Error::success();
     479         905 :   Child Ret(Parent, NextLoc, &Err);
     480         905 :   if (Err)
     481          12 :     return std::move(Err);
     482             :   return Ret;
     483             : }
     484             : 
     485         210 : uint64_t Archive::Child::getChildOffset() const {
     486         210 :   const char *a = Parent->Data.getBuffer().data();
     487         420 :   const char *c = Data.data();
     488         210 :   uint64_t offset = c - a;
     489         210 :   return offset;
     490             : }
     491             : 
     492        1124 : Expected<StringRef> Archive::Child::getName() const {
     493        2248 :   Expected<uint64_t> RawSizeOrErr = getRawSize();
     494        1124 :   if (!RawSizeOrErr)
     495           0 :     return RawSizeOrErr.takeError();
     496        1124 :   uint64_t RawSize = RawSizeOrErr.get();
     497        1124 :   Expected<StringRef> NameOrErr = Header.getName(Header.getSizeOf() + RawSize);
     498        1124 :   if (!NameOrErr)
     499          21 :     return NameOrErr.takeError();
     500        1117 :   StringRef Name = NameOrErr.get();
     501             :   return Name;
     502             : }
     503             : 
     504         502 : Expected<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
     505        1004 :   Expected<StringRef> NameOrErr = getName();
     506         502 :   if (!NameOrErr)
     507           9 :     return NameOrErr.takeError();
     508         499 :   StringRef Name = NameOrErr.get();
     509         499 :   Expected<StringRef> Buf = getBuffer();
     510         499 :   if (!Buf)
     511           0 :     return Buf.takeError();
     512         998 :   return MemoryBufferRef(*Buf, Name);
     513             : }
     514             : 
     515             : Expected<std::unique_ptr<Binary>>
     516         215 : Archive::Child::getAsBinary(LLVMContext *Context) const {
     517         430 :   Expected<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
     518         215 :   if (!BuffOrErr)
     519           9 :     return BuffOrErr.takeError();
     520             : 
     521         424 :   auto BinaryOrErr = createBinary(BuffOrErr.get(), Context);
     522         212 :   if (BinaryOrErr)
     523         199 :     return std::move(*BinaryOrErr);
     524          39 :   return BinaryOrErr.takeError();
     525             : }
     526             : 
     527         302 : Expected<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
     528         906 :   Error Err = Error::success();
     529         906 :   std::unique_ptr<Archive> Ret(new Archive(Source, Err));
     530         302 :   if (Err)
     531          20 :     return std::move(Err);
     532         297 :   return std::move(Ret);
     533             : }
     534             : 
     535         402 : void Archive::setFirstRegular(const Child &C) {
     536         402 :   FirstRegularData = C.Data;
     537         402 :   FirstRegularStartOfFile = C.StartOfFile;
     538         402 : }
     539             : 
     540         412 : Archive::Archive(MemoryBufferRef Source, Error &Err)
     541        2060 :     : Binary(Binary::ID_Archive, Source) {
     542         449 :   ErrorAsOutParameter ErrAsOutParam(&Err);
     543         412 :   StringRef Buffer = Data.getBuffer();
     544             :   // Check for sufficient magic.
     545         428 :   if (Buffer.startswith(ThinMagic)) {
     546          16 :     IsThin = true;
     547         791 :   } else if (Buffer.startswith(Magic)) {
     548         395 :     IsThin = false;
     549             :   } else {
     550           4 :     Err = make_error<GenericBinaryError>("File too small to be an archive",
     551             :                                          object_error::invalid_file_type);
     552         376 :     return;
     553             :   }
     554             : 
     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
     559             :   // contents.
     560         411 :   Format = K_GNU;
     561             : 
     562             :   // Get the special members.
     563         411 :   child_iterator I = child_begin(Err, false);
     564         411 :   if (Err)
     565             :     return;
     566         408 :   child_iterator E = child_end();
     567             : 
     568             :   // See if this is a valid empty archive and if so return.
     569         408 :   if (I == E) {
     570          12 :     Err = Error::success();
     571           4 :     return;
     572             :   }
     573         404 :   const Child *C = &*I;
     574             : 
     575         559 :   auto Increment = [&]() {
     576        1117 :     ++I;
     577        1118 :     if (Err)
     578             :       return true;
     579        1116 :     C = &*I;
     580         558 :     return false;
     581         404 :   };
     582             : 
     583         845 :   Expected<StringRef> NameOrErr = C->getRawName();
     584         404 :   if (!NameOrErr) {
     585           0 :     Err = NameOrErr.takeError();
     586           0 :     return;
     587             :   }
     588         404 :   StringRef Name = NameOrErr.get();
     589             : 
     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
     601             :   //  First member : /
     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.
     608             : 
     609         808 :   if (Name == "__.SYMDEF" || Name == "__.SYMDEF_64") {
     610           0 :     if (Name == "__.SYMDEF")
     611           0 :       Format = K_BSD;
     612             :     else // Name == "__.SYMDEF_64"
     613           0 :       Format = K_DARWIN64;
     614             :     // We know that the symbol table is not an external file, but we still must
     615             :     // check any Expected<> return value.
     616           0 :     Expected<StringRef> BufOrErr = C->getBuffer();
     617           0 :     if (!BufOrErr) {
     618           0 :       Err = BufOrErr.takeError();
     619           0 :       return;
     620             :     }
     621           0 :     SymbolTable = BufOrErr.get();
     622           0 :     if (Increment())
     623             :       return;
     624           0 :     setFirstRegular(*C);
     625             : 
     626           0 :     Err = Error::success();
     627           0 :     return;
     628             :   }
     629             : 
     630         500 :   if (Name.startswith("#1/")) {
     631          96 :     Format = K_BSD;
     632             :     // We know this is BSD, so getName will work since there is no string table.
     633         192 :     Expected<StringRef> NameOrErr = C->getName();
     634          96 :     if (!NameOrErr) {
     635           0 :       Err = NameOrErr.takeError();
     636           0 :       return;
     637             :     }
     638          96 :     Name = NameOrErr.get();
     639         107 :     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         179 :       Expected<StringRef> BufOrErr = C->getBuffer();
     643          90 :       if (!BufOrErr) {
     644           0 :         Err = BufOrErr.takeError();
     645           1 :         return;
     646             :       }
     647          90 :       SymbolTable = BufOrErr.get();
     648          90 :       if (Increment())
     649             :         return;
     650             :     }
     651          12 :     else if (Name == "__.SYMDEF_64 SORTED" || Name == "__.SYMDEF_64") {
     652           1 :       Format = K_DARWIN64;
     653             :       // We know that the symbol table is not an external file, but we still
     654             :       // must check any Expected<> return value.
     655           2 :       Expected<StringRef> BufOrErr = C->getBuffer();
     656           1 :       if (!BufOrErr) {
     657           0 :         Err = BufOrErr.takeError();
     658           0 :         return;
     659             :       }
     660           1 :       SymbolTable = BufOrErr.get();
     661           1 :       if (Increment())
     662             :         return;
     663             :     }
     664          95 :     setFirstRegular(*C);
     665          95 :     return;
     666             :   }
     667             : 
     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
     672             : 
     673         308 :   bool has64SymTable = false;
     674         372 :   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         487 :     Expected<StringRef> BufOrErr = C->getBuffer();
     678         244 :     if (!BufOrErr) {
     679           0 :       Err = BufOrErr.takeError();
     680           1 :       return;
     681             :     }
     682         244 :     SymbolTable = BufOrErr.get();
     683         244 :     if (Name == "/SYM64/")
     684             :       has64SymTable = true;
     685             : 
     686         244 :     if (Increment())
     687             :       return;
     688         244 :     if (I == E) {
     689           3 :       Err = Error::success();
     690           1 :       return;
     691             :     }
     692         729 :     Expected<StringRef> NameOrErr = C->getRawName();
     693         243 :     if (!NameOrErr) {
     694           0 :       Err = NameOrErr.takeError();
     695             :       return;
     696             :     }
     697         243 :     Name = NameOrErr.get();
     698             :   }
     699             : 
     700         487 :   if (Name == "//") {
     701         180 :     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         360 :     Expected<StringRef> BufOrErr = C->getBuffer();
     705         180 :     if (!BufOrErr) {
     706           0 :       Err = BufOrErr.takeError();
     707           0 :       return;
     708             :     }
     709         180 :     StringTable = BufOrErr.get();
     710         180 :     if (Increment())
     711             :       return;
     712         180 :     setFirstRegular(*C);
     713         540 :     Err = Error::success();
     714         180 :     return;
     715             :   }
     716             : 
     717         254 :   if (Name[0] != '/') {
     718          90 :     Format = has64SymTable ? K_MIPS64 : K_GNU;
     719          90 :     setFirstRegular(*C);
     720         270 :     Err = Error::success();
     721          90 :     return;
     722             :   }
     723             : 
     724          74 :   if (Name != "/") {
     725           0 :     Err = errorCodeToError(object_error::parse_failed);
     726           0 :     return;
     727             :   }
     728             : 
     729          37 :   Format = K_COFF;
     730             :   // We know that the symbol table is not an external file, but we still
     731             :   // must check any Expected<> return value.
     732          74 :   Expected<StringRef> BufOrErr = C->getBuffer();
     733          37 :   if (!BufOrErr) {
     734           0 :     Err = BufOrErr.takeError();
     735           0 :     return;
     736             :   }
     737          37 :   SymbolTable = BufOrErr.get();
     738             : 
     739          37 :   if (Increment())
     740             :     return;
     741             : 
     742          37 :   if (I == E) {
     743           0 :     setFirstRegular(*C);
     744           0 :     Err = Error::success();
     745           0 :     return;
     746             :   }
     747             : 
     748         148 :   NameOrErr = C->getRawName();
     749          37 :   if (!NameOrErr) {
     750           0 :     Err = NameOrErr.takeError();
     751           0 :     return;
     752             :   }
     753          37 :   Name = NameOrErr.get();
     754             : 
     755          44 :   if (Name == "//") {
     756             :     // The string table is never an external member, but we still
     757             :     // must check any Expected<> return value.
     758          14 :     Expected<StringRef> BufOrErr = C->getBuffer();
     759           7 :     if (!BufOrErr) {
     760           0 :       Err = BufOrErr.takeError();
     761           0 :       return;
     762             :     }
     763           7 :     StringTable = BufOrErr.get();
     764           7 :     if (Increment())
     765             :       return;
     766             :   }
     767             : 
     768          37 :   setFirstRegular(*C);
     769         111 :   Err = Error::success();
     770             : }
     771             : 
     772         699 : Archive::child_iterator Archive::child_begin(Error &Err,
     773             :                                              bool SkipInternal) const {
     774         699 :   if (isEmpty())
     775           6 :     return child_end();
     776             : 
     777         693 :   if (SkipInternal)
     778         544 :     return child_iterator(Child(this, FirstRegularData,
     779         272 :                                 FirstRegularStartOfFile),
     780         272 :                           &Err);
     781             : 
     782         842 :   const char *Loc = Data.getBufferStart() + strlen(Magic);
     783         421 :   Child C(this, Loc, &Err);
     784         421 :   if (Err)
     785           3 :     return child_end();
     786             :   return child_iterator(C, &Err);
     787             : }
     788             : 
     789         709 : Archive::child_iterator Archive::child_end() const {
     790        1418 :   return child_iterator(Child(nullptr, nullptr, nullptr), nullptr);
     791             : }
     792             : 
     793        1131 : StringRef Archive::Symbol::getName() const {
     794        2262 :   return Parent->getSymbolTable().begin() + StringIndex;
     795             : }
     796             : 
     797         268 : Expected<Archive::Child> Archive::Symbol::getMember() const {
     798         268 :   const char *Buf = Parent->getSymbolTable().begin();
     799         268 :   const char *Offsets = Buf;
     800         536 :   if (Parent->kind() == K_MIPS64 || Parent->kind() == K_DARWIN64)
     801           2 :     Offsets += sizeof(uint64_t);
     802             :   else
     803         266 :     Offsets += sizeof(uint32_t);
     804         268 :   uint32_t Offset = 0;
     805         268 :   if (Parent->kind() == K_GNU) {
     806         274 :     Offset = read32be(Offsets + SymbolIndex * 4);
     807         131 :   } else if (Parent->kind() == K_MIPS64) {
     808           0 :     Offset = read64be(Offsets + SymbolIndex * 8);
     809         131 :   } 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
     815             :     // is needed here.
     816          32 :     Offset = read32le(Offsets + SymbolIndex * 8 + 4);
     817         115 :   } 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
     823             :     // is needed here.
     824           4 :     Offset = read64le(Offsets + SymbolIndex * 16 + 8);
     825             :   } else {
     826             :     // Skip offsets.
     827         113 :     uint32_t MemberCount = read32le(Buf);
     828         113 :     Buf += MemberCount * 4 + 4;
     829             : 
     830         113 :     uint32_t SymbolCount = read32le(Buf);
     831         113 :     if (SymbolIndex >= SymbolCount)
     832           0 :       return errorCodeToError(object_error::parse_failed);
     833             : 
     834             :     // Skip SymbolCount to get to the indices table.
     835         113 :     const char *Indices = Buf + 4;
     836             : 
     837             :     // Get the index of the offset in the file member offset table for this
     838             :     // symbol.
     839         226 :     uint16_t OffsetIndex = read16le(Indices + SymbolIndex * 2);
     840             :     // Subtract 1 since OffsetIndex is 1 based.
     841         113 :     --OffsetIndex;
     842             : 
     843         113 :     if (OffsetIndex >= MemberCount)
     844           0 :       return errorCodeToError(object_error::parse_failed);
     845             : 
     846         226 :     Offset = read32le(Offsets + OffsetIndex * 4);
     847             :   }
     848             : 
     849         268 :   const char *Loc = Parent->getData().begin() + Offset;
     850         536 :   Error Err = Error::success();
     851         268 :   Child C(Parent, Loc, &Err);
     852         268 :   if (Err)
     853           0 :     return std::move(Err);
     854             :   return C;
     855             : }
     856             : 
     857         562 : Archive::Symbol Archive::Symbol::getNext() const {
     858         562 :   Symbol t(*this);
     859        1124 :   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.
     866             : 
     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          16 :     const char *Buf = Parent->getSymbolTable().begin();
     874          16 :     uint32_t RanlibCount = 0;
     875          16 :     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
     878             :     // past RanlibCount.
     879          16 :     if (t.SymbolIndex + 1 < RanlibCount) {
     880           4 :       const char *Ranlibs = Buf + 4;
     881           4 :       uint32_t CurRanStrx = 0;
     882           4 :       uint32_t NextRanStrx = 0;
     883           8 :       CurRanStrx = read32le(Ranlibs + t.SymbolIndex * 8);
     884           8 :       NextRanStrx = read32le(Ranlibs + (t.SymbolIndex + 1) * 8);
     885           4 :       t.StringIndex -= CurRanStrx;
     886           4 :       t.StringIndex += NextRanStrx;
     887             :     }
     888             :   } else {
     889             :     // Go to one past next null.
     890        1092 :     t.StringIndex = Parent->getSymbolTable().find('\0', t.StringIndex) + 1;
     891             :   }
     892         562 :   ++t.SymbolIndex;
     893         562 :   return t;
     894             : }
     895             : 
     896         162 : Archive::symbol_iterator Archive::symbol_begin() const {
     897         162 :   if (!hasSymbolTable())
     898           5 :     return symbol_iterator(Symbol(this, 0, 0));
     899             : 
     900         157 :   const char *buf = getSymbolTable().begin();
     901         157 :   if (kind() == K_GNU) {
     902         116 :     uint32_t symbol_count = 0;
     903         116 :     symbol_count = read32be(buf);
     904         116 :     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
     905          41 :   } else if (kind() == K_MIPS64) {
     906           0 :     uint64_t symbol_count = read64be(buf);
     907           0 :     buf += sizeof(uint64_t) + (symbol_count * (sizeof(uint64_t)));
     908          41 :   } 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          12 :     uint32_t ranlib_count = 0;
     916          12 :     ranlib_count = read32le(buf) / 8;
     917          12 :     const char *ranlibs = buf + 4;
     918          12 :     uint32_t ran_strx = 0;
     919          12 :     ran_strx = read32le(ranlibs);
     920          12 :     buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
     921             :     // Skip the byte count of the string table.
     922          12 :     buf += sizeof(uint32_t);
     923          12 :     buf += ran_strx;
     924          29 :   } 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           1 :     uint64_t ranlib_count = 0;
     932           1 :     ranlib_count = read64le(buf) / 16;
     933           1 :     const char *ranlibs = buf + 8;
     934           1 :     uint64_t ran_strx = 0;
     935           1 :     ran_strx = read64le(ranlibs);
     936           1 :     buf += sizeof(uint64_t) + (ranlib_count * (2 * (sizeof(uint64_t))));
     937             :     // Skip the byte count of the string table.
     938           1 :     buf += sizeof(uint64_t);
     939           1 :     buf += ran_strx;
     940             :   } else {
     941          28 :     uint32_t member_count = 0;
     942          28 :     uint32_t symbol_count = 0;
     943          28 :     member_count = read32le(buf);
     944          28 :     buf += 4 + (member_count * 4); // Skip offsets.
     945          28 :     symbol_count = read32le(buf);
     946          28 :     buf += 4 + (symbol_count * 2); // Skip indices.
     947             :   }
     948         157 :   uint32_t string_start_offset = buf - getSymbolTable().begin();
     949         157 :   return symbol_iterator(Symbol(this, 0, string_start_offset));
     950             : }
     951             : 
     952         162 : Archive::symbol_iterator Archive::symbol_end() const {
     953         162 :   return symbol_iterator(Symbol(this, getNumberOfSymbols(), 0));
     954             : }
     955             : 
     956         231 : uint32_t Archive::getNumberOfSymbols() const {
     957         231 :   if (!hasSymbolTable())
     958             :     return 0;
     959         224 :   const char *buf = getSymbolTable().begin();
     960         224 :   if (kind() == K_GNU)
     961         183 :     return read32be(buf);
     962          41 :   if (kind() == K_MIPS64)
     963           0 :     return read64be(buf);
     964          41 :   if (kind() == K_BSD)
     965          12 :     return read32le(buf) / 8;
     966          29 :   if (kind() == K_DARWIN64)
     967           1 :     return read64le(buf) / 16;
     968          28 :   uint32_t member_count = 0;
     969          28 :   member_count = read32le(buf);
     970          28 :   buf += 4 + (member_count * 4); // Skip offsets.
     971          28 :   return read32le(buf);
     972             : }
     973             : 
     974           5 : Expected<Optional<Archive::Child>> Archive::findSym(StringRef name) const {
     975           5 :   Archive::symbol_iterator bs = symbol_begin();
     976           5 :   Archive::symbol_iterator es = symbol_end();
     977             : 
     978           9 :   for (; bs != es; ++bs) {
     979           8 :     StringRef SymName = bs->getName();
     980             :     if (SymName == name) {
     981          12 :       if (auto MemberOrErr = bs->getMember())
     982           8 :         return Child(*MemberOrErr);
     983             :       else
     984           0 :         return MemberOrErr.takeError();
     985             :     }
     986             :   }
     987           3 :   return Optional<Child>();
     988             : }
     989             : 
     990             : // Returns true if archive file contains no member file.
     991        1548 : bool Archive::isEmpty() const { return Data.getBufferSize() == 8; }
     992             : 
     993         938 : bool Archive::hasSymbolTable() const { return !SymbolTable.empty(); }

Generated by: LCOV version 1.13