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