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