LLVM API Documentation

Archive.cpp
Go to the documentation of this file.
00001 //===- Archive.cpp - ar File Format implementation --------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the ArchiveObjectFile class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/Object/Archive.h"
00015 #include "llvm/ADT/APInt.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/ADT/Twine.h"
00018 #include "llvm/Support/Endian.h"
00019 #include "llvm/Support/MemoryBuffer.h"
00020 
00021 using namespace llvm;
00022 using namespace object;
00023 
00024 static const char *const Magic = "!<arch>\n";
00025 
00026 void Archive::anchor() { }
00027 
00028 StringRef ArchiveMemberHeader::getName() const {
00029   char EndCond;
00030   if (Name[0] == '/' || Name[0] == '#')
00031     EndCond = ' ';
00032   else
00033     EndCond = '/';
00034   llvm::StringRef::size_type end =
00035       llvm::StringRef(Name, sizeof(Name)).find(EndCond);
00036   if (end == llvm::StringRef::npos)
00037     end = sizeof(Name);
00038   assert(end <= sizeof(Name) && end > 0);
00039   // Don't include the EndCond if there is one.
00040   return llvm::StringRef(Name, end);
00041 }
00042 
00043 uint32_t ArchiveMemberHeader::getSize() const {
00044   uint32_t Ret;
00045   if (llvm::StringRef(Size, sizeof(Size)).rtrim(" ").getAsInteger(10, Ret))
00046     llvm_unreachable("Size is not a decimal number.");
00047   return Ret;
00048 }
00049 
00050 sys::fs::perms ArchiveMemberHeader::getAccessMode() const {
00051   unsigned Ret;
00052   if (StringRef(AccessMode, sizeof(AccessMode)).rtrim(" ").getAsInteger(8, Ret))
00053     llvm_unreachable("Access mode is not an octal number.");
00054   return static_cast<sys::fs::perms>(Ret);
00055 }
00056 
00057 sys::TimeValue ArchiveMemberHeader::getLastModified() const {
00058   unsigned Seconds;
00059   if (StringRef(LastModified, sizeof(LastModified)).rtrim(" ")
00060           .getAsInteger(10, Seconds))
00061     llvm_unreachable("Last modified time not a decimal number.");
00062 
00063   sys::TimeValue Ret;
00064   Ret.fromEpochTime(Seconds);
00065   return Ret;
00066 }
00067 
00068 unsigned ArchiveMemberHeader::getUID() const {
00069   unsigned Ret;
00070   if (StringRef(UID, sizeof(UID)).rtrim(" ").getAsInteger(10, Ret))
00071     llvm_unreachable("UID time not a decimal number.");
00072   return Ret;
00073 }
00074 
00075 unsigned ArchiveMemberHeader::getGID() const {
00076   unsigned Ret;
00077   if (StringRef(GID, sizeof(GID)).rtrim(" ").getAsInteger(10, Ret))
00078     llvm_unreachable("GID time not a decimal number.");
00079   return Ret;
00080 }
00081 
00082 Archive::Child::Child(const Archive *Parent, const char *Start)
00083     : Parent(Parent) {
00084   if (!Start)
00085     return;
00086 
00087   const ArchiveMemberHeader *Header =
00088       reinterpret_cast<const ArchiveMemberHeader *>(Start);
00089   Data = StringRef(Start, sizeof(ArchiveMemberHeader) + Header->getSize());
00090 
00091   // Setup StartOfFile and PaddingBytes.
00092   StartOfFile = sizeof(ArchiveMemberHeader);
00093   // Don't include attached name.
00094   StringRef Name = Header->getName();
00095   if (Name.startswith("#1/")) {
00096     uint64_t NameSize;
00097     if (Name.substr(3).rtrim(" ").getAsInteger(10, NameSize))
00098       llvm_unreachable("Long name length is not an integer");
00099     StartOfFile += NameSize;
00100   }
00101 }
00102 
00103 Archive::Child Archive::Child::getNext() const {
00104   size_t SpaceToSkip = Data.size();
00105   // If it's odd, add 1 to make it even.
00106   if (SpaceToSkip & 1)
00107     ++SpaceToSkip;
00108 
00109   const char *NextLoc = Data.data() + SpaceToSkip;
00110 
00111   // Check to see if this is past the end of the archive.
00112   if (NextLoc >= Parent->Data.getBufferEnd())
00113     return Child(Parent, nullptr);
00114 
00115   return Child(Parent, NextLoc);
00116 }
00117 
00118 ErrorOr<StringRef> Archive::Child::getName() const {
00119   StringRef name = getRawName();
00120   // Check if it's a special name.
00121   if (name[0] == '/') {
00122     if (name.size() == 1) // Linker member.
00123       return name;
00124     if (name.size() == 2 && name[1] == '/') // String table.
00125       return name;
00126     // It's a long name.
00127     // Get the offset.
00128     std::size_t offset;
00129     if (name.substr(1).rtrim(" ").getAsInteger(10, offset))
00130       llvm_unreachable("Long name offset is not an integer");
00131     const char *addr = Parent->StringTable->Data.begin()
00132                        + sizeof(ArchiveMemberHeader)
00133                        + offset;
00134     // Verify it.
00135     if (Parent->StringTable == Parent->child_end()
00136         || addr < (Parent->StringTable->Data.begin()
00137                    + sizeof(ArchiveMemberHeader))
00138         || addr > (Parent->StringTable->Data.begin()
00139                    + sizeof(ArchiveMemberHeader)
00140                    + Parent->StringTable->getSize()))
00141       return object_error::parse_failed;
00142 
00143     // GNU long file names end with a /.
00144     if (Parent->kind() == K_GNU) {
00145       StringRef::size_type End = StringRef(addr).find('/');
00146       return StringRef(addr, End);
00147     }
00148     return StringRef(addr);
00149   } else if (name.startswith("#1/")) {
00150     uint64_t name_size;
00151     if (name.substr(3).rtrim(" ").getAsInteger(10, name_size))
00152       llvm_unreachable("Long name length is not an ingeter");
00153     return Data.substr(sizeof(ArchiveMemberHeader), name_size)
00154         .rtrim(StringRef("\0", 1));
00155   }
00156   // It's a simple name.
00157   if (name[name.size() - 1] == '/')
00158     return name.substr(0, name.size() - 1);
00159   return name;
00160 }
00161 
00162 ErrorOr<MemoryBufferRef> Archive::Child::getMemoryBufferRef() const {
00163   ErrorOr<StringRef> NameOrErr = getName();
00164   if (std::error_code EC = NameOrErr.getError())
00165     return EC;
00166   StringRef Name = NameOrErr.get();
00167   return MemoryBufferRef(getBuffer(), Name);
00168 }
00169 
00170 ErrorOr<std::unique_ptr<Binary>>
00171 Archive::Child::getAsBinary(LLVMContext *Context) const {
00172   ErrorOr<MemoryBufferRef> BuffOrErr = getMemoryBufferRef();
00173   if (std::error_code EC = BuffOrErr.getError())
00174     return EC;
00175 
00176   return createBinary(BuffOrErr.get(), Context);
00177 }
00178 
00179 ErrorOr<std::unique_ptr<Archive>> Archive::create(MemoryBufferRef Source) {
00180   std::error_code EC;
00181   std::unique_ptr<Archive> Ret(new Archive(Source, EC));
00182   if (EC)
00183     return EC;
00184   return std::move(Ret);
00185 }
00186 
00187 Archive::Archive(MemoryBufferRef Source, std::error_code &ec)
00188     : Binary(Binary::ID_Archive, Source), SymbolTable(child_end()) {
00189   // Check for sufficient magic.
00190   if (Data.getBufferSize() < 8 ||
00191       StringRef(Data.getBufferStart(), 8) != Magic) {
00192     ec = object_error::invalid_file_type;
00193     return;
00194   }
00195 
00196   // Get the special members.
00197   child_iterator i = child_begin(false);
00198   child_iterator e = child_end();
00199 
00200   if (i == e) {
00201     ec = object_error::success;
00202     return;
00203   }
00204 
00205   StringRef Name = i->getRawName();
00206 
00207   // Below is the pattern that is used to figure out the archive format
00208   // GNU archive format
00209   //  First member : / (may exist, if it exists, points to the symbol table )
00210   //  Second member : // (may exist, if it exists, points to the string table)
00211   //  Note : The string table is used if the filename exceeds 15 characters
00212   // BSD archive format
00213   //  First member : __.SYMDEF or "__.SYMDEF SORTED" (the symbol table)
00214   //  There is no string table, if the filename exceeds 15 characters or has a
00215   //  embedded space, the filename has #1/<size>, The size represents the size
00216   //  of the filename that needs to be read after the archive header
00217   // COFF archive format
00218   //  First member : /
00219   //  Second member : / (provides a directory of symbols)
00220   //  Third member : // (may exist, if it exists, contains the string table)
00221   //  Note: Microsoft PE/COFF Spec 8.3 says that the third member is present
00222   //  even if the string table is empty. However, lib.exe does not in fact
00223   //  seem to create the third member if there's no member whose filename
00224   //  exceeds 15 characters. So the third member is optional.
00225 
00226   if (Name == "__.SYMDEF") {
00227     Format = K_BSD;
00228     SymbolTable = i;
00229     ++i;
00230     FirstRegular = i;
00231     ec = object_error::success;
00232     return;
00233   }
00234 
00235   if (Name.startswith("#1/")) {
00236     Format = K_BSD;
00237     // We know this is BSD, so getName will work since there is no string table.
00238     ErrorOr<StringRef> NameOrErr = i->getName();
00239     ec = NameOrErr.getError();
00240     if (ec)
00241       return;
00242     Name = NameOrErr.get();
00243     if (Name == "__.SYMDEF SORTED") {
00244       SymbolTable = i;
00245       ++i;
00246     }
00247     FirstRegular = i;
00248     return;
00249   }
00250 
00251   if (Name == "/") {
00252     SymbolTable = i;
00253 
00254     ++i;
00255     if (i == e) {
00256       ec = object_error::parse_failed;
00257       return;
00258     }
00259     Name = i->getRawName();
00260   }
00261 
00262   if (Name == "//") {
00263     Format = K_GNU;
00264     StringTable = i;
00265     ++i;
00266     FirstRegular = i;
00267     ec = object_error::success;
00268     return;
00269   }
00270 
00271   if (Name[0] != '/') {
00272     Format = K_GNU;
00273     FirstRegular = i;
00274     ec = object_error::success;
00275     return;
00276   }
00277 
00278   if (Name != "/") {
00279     ec = object_error::parse_failed;
00280     return;
00281   }
00282 
00283   Format = K_COFF;
00284   SymbolTable = i;
00285 
00286   ++i;
00287   if (i == e) {
00288     FirstRegular = i;
00289     ec = object_error::success;
00290     return;
00291   }
00292 
00293   Name = i->getRawName();
00294 
00295   if (Name == "//") {
00296     StringTable = i;
00297     ++i;
00298   }
00299 
00300   FirstRegular = i;
00301   ec = object_error::success;
00302 }
00303 
00304 Archive::child_iterator Archive::child_begin(bool SkipInternal) const {
00305   if (Data.getBufferSize() == 8) // empty archive.
00306     return child_end();
00307 
00308   if (SkipInternal)
00309     return FirstRegular;
00310 
00311   const char *Loc = Data.getBufferStart() + strlen(Magic);
00312   Child c(this, Loc);
00313   return c;
00314 }
00315 
00316 Archive::child_iterator Archive::child_end() const {
00317   return Child(this, nullptr);
00318 }
00319 
00320 StringRef Archive::Symbol::getName() const {
00321   return Parent->SymbolTable->getBuffer().begin() + StringIndex;
00322 }
00323 
00324 ErrorOr<Archive::child_iterator> Archive::Symbol::getMember() const {
00325   const char *Buf = Parent->SymbolTable->getBuffer().begin();
00326   const char *Offsets = Buf + 4;
00327   uint32_t Offset = 0;
00328   if (Parent->kind() == K_GNU) {
00329     Offset = *(reinterpret_cast<const support::ubig32_t*>(Offsets)
00330                + SymbolIndex);
00331   } else if (Parent->kind() == K_BSD) {
00332     // The SymbolIndex is an index into the ranlib structs that start at
00333     // Offsets (the first uint32_t is the number of bytes of the ranlib
00334     // structs).  The ranlib structs are a pair of uint32_t's the first
00335     // being a string table offset and the second being the offset into
00336     // the archive of the member that defines the symbol.  Which is what
00337     // is needed here.
00338     Offset = *(reinterpret_cast<const support::ulittle32_t *>(Offsets) +
00339                (SymbolIndex * 2) + 1);
00340   } else {
00341     uint32_t MemberCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
00342     
00343     // Skip offsets.
00344     Buf += sizeof(support::ulittle32_t)
00345            + (MemberCount * sizeof(support::ulittle32_t));
00346 
00347     uint32_t SymbolCount = *reinterpret_cast<const support::ulittle32_t*>(Buf);
00348 
00349     if (SymbolIndex >= SymbolCount)
00350       return object_error::parse_failed;
00351 
00352     // Skip SymbolCount to get to the indices table.
00353     const char *Indices = Buf + sizeof(support::ulittle32_t);
00354 
00355     // Get the index of the offset in the file member offset table for this
00356     // symbol.
00357     uint16_t OffsetIndex =
00358       *(reinterpret_cast<const support::ulittle16_t*>(Indices)
00359         + SymbolIndex);
00360     // Subtract 1 since OffsetIndex is 1 based.
00361     --OffsetIndex;
00362 
00363     if (OffsetIndex >= MemberCount)
00364       return object_error::parse_failed;
00365 
00366     Offset = *(reinterpret_cast<const support::ulittle32_t*>(Offsets)
00367                + OffsetIndex);
00368   }
00369 
00370   const char *Loc = Parent->getData().begin() + Offset;
00371   child_iterator Iter(Child(Parent, Loc));
00372   return Iter;
00373 }
00374 
00375 Archive::Symbol Archive::Symbol::getNext() const {
00376   Symbol t(*this);
00377   if (Parent->kind() == K_BSD) {
00378     // t.StringIndex is an offset from the start of the __.SYMDEF or
00379     // "__.SYMDEF SORTED" member into the string table for the ranlib
00380     // struct indexed by t.SymbolIndex .  To change t.StringIndex to the
00381     // offset in the string table for t.SymbolIndex+1 we subtract the
00382     // its offset from the start of the string table for t.SymbolIndex
00383     // and add the offset of the string table for t.SymbolIndex+1.
00384 
00385     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
00386     // which is the number of bytes of ranlib structs that follow.  The ranlib
00387     // structs are a pair of uint32_t's the first being a string table offset
00388     // and the second being the offset into the archive of the member that
00389     // define the symbol. After that the next uint32_t is the byte count of
00390     // the string table followed by the string table.
00391     const char *Buf = Parent->SymbolTable->getBuffer().begin();
00392     uint32_t RanlibCount = 0;
00393     RanlibCount = (*reinterpret_cast<const support::ulittle32_t *>(Buf)) /
00394                   (sizeof(uint32_t) * 2);
00395     // If t.SymbolIndex + 1 will be past the count of symbols (the RanlibCount)
00396     // don't change the t.StringIndex as we don't want to reference a ranlib
00397     // past RanlibCount.
00398     if (t.SymbolIndex + 1 < RanlibCount) {
00399       const char *Ranlibs = Buf + 4;
00400       uint32_t CurRanStrx = 0;
00401       uint32_t NextRanStrx = 0;
00402       CurRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
00403                      (t.SymbolIndex * 2));
00404       NextRanStrx = *(reinterpret_cast<const support::ulittle32_t *>(Ranlibs) +
00405                       ((t.SymbolIndex + 1) * 2));
00406       t.StringIndex -= CurRanStrx;
00407       t.StringIndex += NextRanStrx;
00408     }
00409   } else {
00410     // Go to one past next null.
00411     t.StringIndex =
00412         Parent->SymbolTable->getBuffer().find('\0', t.StringIndex) + 1;
00413   }
00414   ++t.SymbolIndex;
00415   return t;
00416 }
00417 
00418 Archive::symbol_iterator Archive::symbol_begin() const {
00419   if (!hasSymbolTable())
00420     return symbol_iterator(Symbol(this, 0, 0));
00421 
00422   const char *buf = SymbolTable->getBuffer().begin();
00423   if (kind() == K_GNU) {
00424     uint32_t symbol_count = 0;
00425     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
00426     buf += sizeof(uint32_t) + (symbol_count * (sizeof(uint32_t)));
00427   } else if (kind() == K_BSD) {
00428     // The __.SYMDEF or "__.SYMDEF SORTED" member starts with a uint32_t
00429     // which is the number of bytes of ranlib structs that follow.  The ranlib
00430     // structs are a pair of uint32_t's the first being a string table offset
00431     // and the second being the offset into the archive of the member that
00432     // define the symbol. After that the next uint32_t is the byte count of
00433     // the string table followed by the string table.
00434     uint32_t ranlib_count = 0;
00435     ranlib_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
00436                    (sizeof(uint32_t) * 2);
00437     const char *ranlibs = buf + 4;
00438     uint32_t ran_strx = 0;
00439     ran_strx = *(reinterpret_cast<const support::ulittle32_t *>(ranlibs));
00440     buf += sizeof(uint32_t) + (ranlib_count * (2 * (sizeof(uint32_t))));
00441     // Skip the byte count of the string table.
00442     buf += sizeof(uint32_t);
00443     buf += ran_strx;
00444   } else {
00445     uint32_t member_count = 0;
00446     uint32_t symbol_count = 0;
00447     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
00448     buf += 4 + (member_count * 4); // Skip offsets.
00449     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
00450     buf += 4 + (symbol_count * 2); // Skip indices.
00451   }
00452   uint32_t string_start_offset = buf - SymbolTable->getBuffer().begin();
00453   return symbol_iterator(Symbol(this, 0, string_start_offset));
00454 }
00455 
00456 Archive::symbol_iterator Archive::symbol_end() const {
00457   if (!hasSymbolTable())
00458     return symbol_iterator(Symbol(this, 0, 0));
00459 
00460   const char *buf = SymbolTable->getBuffer().begin();
00461   uint32_t symbol_count = 0;
00462   if (kind() == K_GNU) {
00463     symbol_count = *reinterpret_cast<const support::ubig32_t*>(buf);
00464   } else if (kind() == K_BSD) {
00465     symbol_count = (*reinterpret_cast<const support::ulittle32_t *>(buf)) /
00466                    (sizeof(uint32_t) * 2);
00467   } else {
00468     uint32_t member_count = 0;
00469     member_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
00470     buf += 4 + (member_count * 4); // Skip offsets.
00471     symbol_count = *reinterpret_cast<const support::ulittle32_t*>(buf);
00472   }
00473   return symbol_iterator(
00474     Symbol(this, symbol_count, 0));
00475 }
00476 
00477 Archive::child_iterator Archive::findSym(StringRef name) const {
00478   Archive::symbol_iterator bs = symbol_begin();
00479   Archive::symbol_iterator es = symbol_end();
00480 
00481   for (; bs != es; ++bs) {
00482     StringRef SymName = bs->getName();
00483     if (SymName == name) {
00484       ErrorOr<Archive::child_iterator> ResultOrErr = bs->getMember();
00485       // FIXME: Should we really eat the error?
00486       if (ResultOrErr.getError())
00487         return child_end();
00488       return ResultOrErr.get();
00489     }
00490   }
00491   return child_end();
00492 }
00493 
00494 bool Archive::hasSymbolTable() const {
00495   return SymbolTable != child_end();
00496 }