1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Builds up (relatively) standard unix archive files (.a) containing LLVM 10 // bitcode or other files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ADT/StringExtras.h" 15 #include "llvm/ADT/StringSwitch.h" 16 #include "llvm/ADT/Triple.h" 17 #include "llvm/BinaryFormat/Magic.h" 18 #include "llvm/IR/LLVMContext.h" 19 #include "llvm/Object/Archive.h" 20 #include "llvm/Object/ArchiveWriter.h" 21 #include "llvm/Object/IRObjectFile.h" 22 #include "llvm/Object/MachO.h" 23 #include "llvm/Object/ObjectFile.h" 24 #include "llvm/Object/SymbolicFile.h" 25 #include "llvm/Support/Chrono.h" 26 #include "llvm/Support/CommandLine.h" 27 #include "llvm/Support/ConvertUTF.h" 28 #include "llvm/Support/Errc.h" 29 #include "llvm/Support/FileSystem.h" 30 #include "llvm/Support/Format.h" 31 #include "llvm/Support/FormatVariadic.h" 32 #include "llvm/Support/Host.h" 33 #include "llvm/Support/InitLLVM.h" 34 #include "llvm/Support/LineIterator.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/Path.h" 37 #include "llvm/Support/Process.h" 38 #include "llvm/Support/StringSaver.h" 39 #include "llvm/Support/TargetSelect.h" 40 #include "llvm/Support/ToolOutputFile.h" 41 #include "llvm/Support/WithColor.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h" 44 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 45 46 #if !defined(_MSC_VER) && !defined(__MINGW32__) 47 #include <unistd.h> 48 #else 49 #include <io.h> 50 #endif 51 52 #ifdef _WIN32 53 #include "llvm/Support/Windows/WindowsSupport.h" 54 #endif 55 56 using namespace llvm; 57 58 // The name this program was invoked as. 59 static StringRef ToolName; 60 61 // The basename of this program. 62 static StringRef Stem; 63 64 const char RanlibHelp[] = R"(OVERVIEW: LLVM Ranlib (llvm-ranlib) 65 66 This program generates an index to speed access to archives 67 68 USAGE: llvm-ranlib <archive-file> 69 70 OPTIONS: 71 -h --help - Display available options 72 -v --version - Display the version of this program 73 -D - Use zero for timestamps and uids/gids (default) 74 -U - Use actual timestamps and uids/gids 75 )"; 76 77 const char ArHelp[] = R"(OVERVIEW: LLVM Archiver 78 79 USAGE: llvm-ar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files] 80 llvm-ar -M [<mri-script] 81 82 OPTIONS: 83 --format - archive format to create 84 =default - default 85 =gnu - gnu 86 =darwin - darwin 87 =bsd - bsd 88 --plugin=<string> - ignored for compatibility 89 -h --help - display this help and exit 90 --rsp-quoting - quoting style for response files 91 =posix - posix 92 =windows - windows 93 --version - print the version and exit 94 @<file> - read options from <file> 95 96 OPERATIONS: 97 d - delete [files] from the archive 98 m - move [files] in the archive 99 p - print [files] found in the archive 100 q - quick append [files] to the archive 101 r - replace or insert [files] into the archive 102 s - act as ranlib 103 t - display contents of archive 104 x - extract [files] from the archive 105 106 MODIFIERS: 107 [a] - put [files] after [relpos] 108 [b] - put [files] before [relpos] (same as [i]) 109 [c] - do not warn if archive had to be created 110 [D] - use zero for timestamps and uids/gids (default) 111 [h] - display this help and exit 112 [i] - put [files] before [relpos] (same as [b]) 113 [l] - ignored for compatibility 114 [L] - add archive's contents 115 [N] - use instance [count] of name 116 [o] - preserve original dates 117 [O] - display member offsets 118 [P] - use full names when matching (implied for thin archives) 119 [s] - create an archive index (cf. ranlib) 120 [S] - do not build a symbol table 121 [T] - create a thin archive 122 [u] - update only [files] newer than archive contents 123 [U] - use actual timestamps and uids/gids 124 [v] - be verbose about actions taken 125 [V] - display the version and exit 126 )"; 127 128 static void printHelpMessage() { 129 if (Stem.contains_insensitive("ranlib")) 130 outs() << RanlibHelp; 131 else if (Stem.contains_insensitive("ar")) 132 outs() << ArHelp; 133 } 134 135 static unsigned MRILineNumber; 136 static bool ParsingMRIScript; 137 138 // Show the error plus the usage message, and exit. 139 LLVM_ATTRIBUTE_NORETURN static void badUsage(Twine Error) { 140 WithColor::error(errs(), ToolName) << Error << "\n"; 141 printHelpMessage(); 142 exit(1); 143 } 144 145 // Show the error message and exit. 146 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) { 147 if (ParsingMRIScript) { 148 WithColor::error(errs(), ToolName) 149 << "script line " << MRILineNumber << ": " << Error << "\n"; 150 } else { 151 WithColor::error(errs(), ToolName) << Error << "\n"; 152 } 153 exit(1); 154 } 155 156 static void failIfError(std::error_code EC, Twine Context = "") { 157 if (!EC) 158 return; 159 160 std::string ContextStr = Context.str(); 161 if (ContextStr.empty()) 162 fail(EC.message()); 163 fail(Context + ": " + EC.message()); 164 } 165 166 static void failIfError(Error E, Twine Context = "") { 167 if (!E) 168 return; 169 170 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) { 171 std::string ContextStr = Context.str(); 172 if (ContextStr.empty()) 173 fail(EIB.message()); 174 fail(Context + ": " + EIB.message()); 175 }); 176 } 177 178 static SmallVector<const char *, 256> PositionalArgs; 179 180 static bool MRI; 181 182 namespace { 183 enum Format { Default, GNU, BSD, DARWIN, Unknown }; 184 } 185 186 static Format FormatType = Default; 187 188 static std::string Options; 189 190 // This enumeration delineates the kinds of operations on an archive 191 // that are permitted. 192 enum ArchiveOperation { 193 Print, ///< Print the contents of the archive 194 Delete, ///< Delete the specified members 195 Move, ///< Move members to end or as given by {a,b,i} modifiers 196 QuickAppend, ///< Quickly append to end of archive 197 ReplaceOrInsert, ///< Replace or Insert members 198 DisplayTable, ///< Display the table of contents 199 Extract, ///< Extract files back to file system 200 CreateSymTab ///< Create a symbol table in an existing archive 201 }; 202 203 // Modifiers to follow operation to vary behavior 204 static bool AddAfter = false; ///< 'a' modifier 205 static bool AddBefore = false; ///< 'b' modifier 206 static bool Create = false; ///< 'c' modifier 207 static bool OriginalDates = false; ///< 'o' modifier 208 static bool DisplayMemberOffsets = false; ///< 'O' modifier 209 static bool CompareFullPath = false; ///< 'P' modifier 210 static bool OnlyUpdate = false; ///< 'u' modifier 211 static bool Verbose = false; ///< 'v' modifier 212 static bool Symtab = true; ///< 's' modifier 213 static bool Deterministic = true; ///< 'D' and 'U' modifiers 214 static bool Thin = false; ///< 'T' modifier 215 static bool AddLibrary = false; ///< 'L' modifier 216 217 // Relative Positional Argument (for insert/move). This variable holds 218 // the name of the archive member to which the 'a', 'b' or 'i' modifier 219 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need 220 // one variable. 221 static std::string RelPos; 222 223 // Count parameter for 'N' modifier. This variable specifies which file should 224 // match for extract/delete operations when there are multiple matches. This is 225 // 1-indexed. A value of 0 is invalid, and implies 'N' is not used. 226 static int CountParam = 0; 227 228 // This variable holds the name of the archive file as given on the 229 // command line. 230 static std::string ArchiveName; 231 232 static std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers; 233 static std::vector<std::unique_ptr<object::Archive>> Archives; 234 235 // This variable holds the list of member files to proecess, as given 236 // on the command line. 237 static std::vector<StringRef> Members; 238 239 // Static buffer to hold StringRefs. 240 static BumpPtrAllocator Alloc; 241 242 // Extract the member filename from the command line for the [relpos] argument 243 // associated with a, b, and i modifiers 244 static void getRelPos() { 245 if (PositionalArgs.empty()) 246 fail("expected [relpos] for 'a', 'b', or 'i' modifier"); 247 RelPos = PositionalArgs[0]; 248 PositionalArgs.erase(PositionalArgs.begin()); 249 } 250 251 // Extract the parameter from the command line for the [count] argument 252 // associated with the N modifier 253 static void getCountParam() { 254 if (PositionalArgs.empty()) 255 badUsage("expected [count] for 'N' modifier"); 256 auto CountParamArg = StringRef(PositionalArgs[0]); 257 if (CountParamArg.getAsInteger(10, CountParam)) 258 badUsage("value for [count] must be numeric, got: " + CountParamArg); 259 if (CountParam < 1) 260 badUsage("value for [count] must be positive, got: " + CountParamArg); 261 PositionalArgs.erase(PositionalArgs.begin()); 262 } 263 264 // Get the archive file name from the command line 265 static void getArchive() { 266 if (PositionalArgs.empty()) 267 badUsage("an archive name must be specified"); 268 ArchiveName = PositionalArgs[0]; 269 PositionalArgs.erase(PositionalArgs.begin()); 270 } 271 272 static object::Archive &readLibrary(const Twine &Library) { 273 auto BufOrErr = MemoryBuffer::getFile(Library, /*IsText=*/false, 274 /*RequiresNullTerminator=*/false); 275 failIfError(BufOrErr.getError(), "could not open library " + Library); 276 ArchiveBuffers.push_back(std::move(*BufOrErr)); 277 auto LibOrErr = 278 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef()); 279 failIfError(errorToErrorCode(LibOrErr.takeError()), 280 "could not parse library"); 281 Archives.push_back(std::move(*LibOrErr)); 282 return *Archives.back(); 283 } 284 285 static void runMRIScript(); 286 287 // Parse the command line options as presented and return the operation 288 // specified. Process all modifiers and check to make sure that constraints on 289 // modifier/operation pairs have not been violated. 290 static ArchiveOperation parseCommandLine() { 291 if (MRI) { 292 if (!PositionalArgs.empty() || !Options.empty()) 293 badUsage("cannot mix -M and other options"); 294 runMRIScript(); 295 } 296 297 // Keep track of number of operations. We can only specify one 298 // per execution. 299 unsigned NumOperations = 0; 300 301 // Keep track of the number of positional modifiers (a,b,i). Only 302 // one can be specified. 303 unsigned NumPositional = 0; 304 305 // Keep track of which operation was requested 306 ArchiveOperation Operation; 307 308 bool MaybeJustCreateSymTab = false; 309 310 for (unsigned i = 0; i < Options.size(); ++i) { 311 switch (Options[i]) { 312 case 'd': 313 ++NumOperations; 314 Operation = Delete; 315 break; 316 case 'm': 317 ++NumOperations; 318 Operation = Move; 319 break; 320 case 'p': 321 ++NumOperations; 322 Operation = Print; 323 break; 324 case 'q': 325 ++NumOperations; 326 Operation = QuickAppend; 327 break; 328 case 'r': 329 ++NumOperations; 330 Operation = ReplaceOrInsert; 331 break; 332 case 't': 333 ++NumOperations; 334 Operation = DisplayTable; 335 break; 336 case 'x': 337 ++NumOperations; 338 Operation = Extract; 339 break; 340 case 'c': 341 Create = true; 342 break; 343 case 'l': /* accepted but unused */ 344 break; 345 case 'o': 346 OriginalDates = true; 347 break; 348 case 'O': 349 DisplayMemberOffsets = true; 350 break; 351 case 'P': 352 CompareFullPath = true; 353 break; 354 case 's': 355 Symtab = true; 356 MaybeJustCreateSymTab = true; 357 break; 358 case 'S': 359 Symtab = false; 360 break; 361 case 'u': 362 OnlyUpdate = true; 363 break; 364 case 'v': 365 Verbose = true; 366 break; 367 case 'a': 368 getRelPos(); 369 AddAfter = true; 370 NumPositional++; 371 break; 372 case 'b': 373 getRelPos(); 374 AddBefore = true; 375 NumPositional++; 376 break; 377 case 'i': 378 getRelPos(); 379 AddBefore = true; 380 NumPositional++; 381 break; 382 case 'D': 383 Deterministic = true; 384 break; 385 case 'U': 386 Deterministic = false; 387 break; 388 case 'N': 389 getCountParam(); 390 break; 391 case 'T': 392 Thin = true; 393 // Thin archives store path names, so P should be forced. 394 CompareFullPath = true; 395 break; 396 case 'L': 397 AddLibrary = true; 398 break; 399 case 'V': 400 cl::PrintVersionMessage(); 401 exit(0); 402 case 'h': 403 printHelpMessage(); 404 exit(0); 405 default: 406 badUsage(std::string("unknown option ") + Options[i]); 407 } 408 } 409 410 // At this point, the next thing on the command line must be 411 // the archive name. 412 getArchive(); 413 414 // Everything on the command line at this point is a member. 415 Members.assign(PositionalArgs.begin(), PositionalArgs.end()); 416 417 if (NumOperations == 0 && MaybeJustCreateSymTab) { 418 NumOperations = 1; 419 Operation = CreateSymTab; 420 if (!Members.empty()) 421 badUsage("the 's' operation takes only an archive as argument"); 422 } 423 424 // Perform various checks on the operation/modifier specification 425 // to make sure we are dealing with a legal request. 426 if (NumOperations == 0) 427 badUsage("you must specify at least one of the operations"); 428 if (NumOperations > 1) 429 badUsage("only one operation may be specified"); 430 if (NumPositional > 1) 431 badUsage("you may only specify one of 'a', 'b', and 'i' modifiers"); 432 if (AddAfter || AddBefore) 433 if (Operation != Move && Operation != ReplaceOrInsert) 434 badUsage("the 'a', 'b' and 'i' modifiers can only be specified with " 435 "the 'm' or 'r' operations"); 436 if (CountParam) 437 if (Operation != Extract && Operation != Delete) 438 badUsage("the 'N' modifier can only be specified with the 'x' or 'd' " 439 "operations"); 440 if (OriginalDates && Operation != Extract) 441 badUsage("the 'o' modifier is only applicable to the 'x' operation"); 442 if (OnlyUpdate && Operation != ReplaceOrInsert) 443 badUsage("the 'u' modifier is only applicable to the 'r' operation"); 444 if (AddLibrary && Operation != QuickAppend) 445 badUsage("the 'L' modifier is only applicable to the 'q' operation"); 446 447 // Return the parsed operation to the caller 448 return Operation; 449 } 450 451 // Implements the 'p' operation. This function traverses the archive 452 // looking for members that match the path list. 453 static void doPrint(StringRef Name, const object::Archive::Child &C) { 454 if (Verbose) 455 outs() << "Printing " << Name << "\n"; 456 457 Expected<StringRef> DataOrErr = C.getBuffer(); 458 failIfError(DataOrErr.takeError()); 459 StringRef Data = *DataOrErr; 460 outs().write(Data.data(), Data.size()); 461 } 462 463 // Utility function for printing out the file mode when the 't' operation is in 464 // verbose mode. 465 static void printMode(unsigned mode) { 466 outs() << ((mode & 004) ? "r" : "-"); 467 outs() << ((mode & 002) ? "w" : "-"); 468 outs() << ((mode & 001) ? "x" : "-"); 469 } 470 471 // Implement the 't' operation. This function prints out just 472 // the file names of each of the members. However, if verbose mode is requested 473 // ('v' modifier) then the file type, permission mode, user, group, size, and 474 // modification time are also printed. 475 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) { 476 if (Verbose) { 477 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 478 failIfError(ModeOrErr.takeError()); 479 sys::fs::perms Mode = ModeOrErr.get(); 480 printMode((Mode >> 6) & 007); 481 printMode((Mode >> 3) & 007); 482 printMode(Mode & 007); 483 Expected<unsigned> UIDOrErr = C.getUID(); 484 failIfError(UIDOrErr.takeError()); 485 outs() << ' ' << UIDOrErr.get(); 486 Expected<unsigned> GIDOrErr = C.getGID(); 487 failIfError(GIDOrErr.takeError()); 488 outs() << '/' << GIDOrErr.get(); 489 Expected<uint64_t> Size = C.getSize(); 490 failIfError(Size.takeError()); 491 outs() << ' ' << format("%6llu", Size.get()); 492 auto ModTimeOrErr = C.getLastModified(); 493 failIfError(ModTimeOrErr.takeError()); 494 // Note: formatv() only handles the default TimePoint<>, which is in 495 // nanoseconds. 496 // TODO: fix format_provider<TimePoint<>> to allow other units. 497 sys::TimePoint<> ModTimeInNs = ModTimeOrErr.get(); 498 outs() << ' ' << formatv("{0:%b %e %H:%M %Y}", ModTimeInNs); 499 outs() << ' '; 500 } 501 502 if (C.getParent()->isThin()) { 503 if (!sys::path::is_absolute(Name)) { 504 StringRef ParentDir = sys::path::parent_path(ArchiveName); 505 if (!ParentDir.empty()) 506 outs() << sys::path::convert_to_slash(ParentDir) << '/'; 507 } 508 outs() << Name; 509 } else { 510 outs() << Name; 511 if (DisplayMemberOffsets) 512 outs() << " 0x" << utohexstr(C.getDataOffset(), true); 513 } 514 outs() << '\n'; 515 } 516 517 static std::string normalizePath(StringRef Path) { 518 return CompareFullPath ? sys::path::convert_to_slash(Path) 519 : std::string(sys::path::filename(Path)); 520 } 521 522 static bool comparePaths(StringRef Path1, StringRef Path2) { 523 // When on Windows this function calls CompareStringOrdinal 524 // as Windows file paths are case-insensitive. 525 // CompareStringOrdinal compares two Unicode strings for 526 // binary equivalence and allows for case insensitivity. 527 #ifdef _WIN32 528 SmallVector<wchar_t, 128> WPath1, WPath2; 529 failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path1), WPath1)); 530 failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path2), WPath2)); 531 532 return CompareStringOrdinal(WPath1.data(), WPath1.size(), WPath2.data(), 533 WPath2.size(), true) == CSTR_EQUAL; 534 #else 535 return normalizePath(Path1) == normalizePath(Path2); 536 #endif 537 } 538 539 // Implement the 'x' operation. This function extracts files back to the file 540 // system. 541 static void doExtract(StringRef Name, const object::Archive::Child &C) { 542 // Retain the original mode. 543 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); 544 failIfError(ModeOrErr.takeError()); 545 sys::fs::perms Mode = ModeOrErr.get(); 546 547 llvm::StringRef outputFilePath = sys::path::filename(Name); 548 if (Verbose) 549 outs() << "x - " << outputFilePath << '\n'; 550 551 int FD; 552 failIfError(sys::fs::openFileForWrite(outputFilePath, FD, 553 sys::fs::CD_CreateAlways, 554 sys::fs::OF_None, Mode), 555 Name); 556 557 { 558 raw_fd_ostream file(FD, false); 559 560 // Get the data and its length 561 Expected<StringRef> BufOrErr = C.getBuffer(); 562 failIfError(BufOrErr.takeError()); 563 StringRef Data = BufOrErr.get(); 564 565 // Write the data. 566 file.write(Data.data(), Data.size()); 567 } 568 569 // If we're supposed to retain the original modification times, etc. do so 570 // now. 571 if (OriginalDates) { 572 auto ModTimeOrErr = C.getLastModified(); 573 failIfError(ModTimeOrErr.takeError()); 574 failIfError( 575 sys::fs::setLastAccessAndModificationTime(FD, ModTimeOrErr.get())); 576 } 577 578 if (close(FD)) 579 fail("Could not close the file"); 580 } 581 582 static bool shouldCreateArchive(ArchiveOperation Op) { 583 switch (Op) { 584 case Print: 585 case Delete: 586 case Move: 587 case DisplayTable: 588 case Extract: 589 case CreateSymTab: 590 return false; 591 592 case QuickAppend: 593 case ReplaceOrInsert: 594 return true; 595 } 596 597 llvm_unreachable("Missing entry in covered switch."); 598 } 599 600 static void performReadOperation(ArchiveOperation Operation, 601 object::Archive *OldArchive) { 602 if (Operation == Extract && OldArchive->isThin()) 603 fail("extracting from a thin archive is not supported"); 604 605 bool Filter = !Members.empty(); 606 StringMap<int> MemberCount; 607 { 608 Error Err = Error::success(); 609 for (auto &C : OldArchive->children(Err)) { 610 Expected<StringRef> NameOrErr = C.getName(); 611 failIfError(NameOrErr.takeError()); 612 StringRef Name = NameOrErr.get(); 613 614 if (Filter) { 615 auto I = find_if(Members, [Name](StringRef Path) { 616 return comparePaths(Name, Path); 617 }); 618 if (I == Members.end()) 619 continue; 620 if (CountParam && ++MemberCount[Name] != CountParam) 621 continue; 622 Members.erase(I); 623 } 624 625 switch (Operation) { 626 default: 627 llvm_unreachable("Not a read operation"); 628 case Print: 629 doPrint(Name, C); 630 break; 631 case DisplayTable: 632 doDisplayTable(Name, C); 633 break; 634 case Extract: 635 doExtract(Name, C); 636 break; 637 } 638 } 639 failIfError(std::move(Err)); 640 } 641 642 if (Members.empty()) 643 return; 644 for (StringRef Name : Members) 645 WithColor::error(errs(), ToolName) << "'" << Name << "' was not found\n"; 646 exit(1); 647 } 648 649 static void addChildMember(std::vector<NewArchiveMember> &Members, 650 const object::Archive::Child &M, 651 bool FlattenArchive = false) { 652 if (Thin && !M.getParent()->isThin()) 653 fail("cannot convert a regular archive to a thin one"); 654 Expected<NewArchiveMember> NMOrErr = 655 NewArchiveMember::getOldMember(M, Deterministic); 656 failIfError(NMOrErr.takeError()); 657 // If the child member we're trying to add is thin, use the path relative to 658 // the archive it's in, so the file resolves correctly. 659 if (Thin && FlattenArchive) { 660 StringSaver Saver(Alloc); 661 Expected<std::string> FileNameOrErr(M.getName()); 662 failIfError(FileNameOrErr.takeError()); 663 if (sys::path::is_absolute(*FileNameOrErr)) { 664 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(*FileNameOrErr)); 665 } else { 666 FileNameOrErr = M.getFullName(); 667 failIfError(FileNameOrErr.takeError()); 668 Expected<std::string> PathOrErr = 669 computeArchiveRelativePath(ArchiveName, *FileNameOrErr); 670 NMOrErr->MemberName = Saver.save( 671 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(*FileNameOrErr)); 672 } 673 } 674 if (FlattenArchive && 675 identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) { 676 Expected<std::string> FileNameOrErr = M.getFullName(); 677 failIfError(FileNameOrErr.takeError()); 678 object::Archive &Lib = readLibrary(*FileNameOrErr); 679 // When creating thin archives, only flatten if the member is also thin. 680 if (!Thin || Lib.isThin()) { 681 Error Err = Error::success(); 682 // Only Thin archives are recursively flattened. 683 for (auto &Child : Lib.children(Err)) 684 addChildMember(Members, Child, /*FlattenArchive=*/Thin); 685 failIfError(std::move(Err)); 686 return; 687 } 688 } 689 Members.push_back(std::move(*NMOrErr)); 690 } 691 692 static void addMember(std::vector<NewArchiveMember> &Members, 693 StringRef FileName, bool FlattenArchive = false) { 694 Expected<NewArchiveMember> NMOrErr = 695 NewArchiveMember::getFile(FileName, Deterministic); 696 failIfError(NMOrErr.takeError(), FileName); 697 StringSaver Saver(Alloc); 698 // For regular archives, use the basename of the object path for the member 699 // name. For thin archives, use the full relative paths so the file resolves 700 // correctly. 701 if (!Thin) { 702 NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName); 703 } else { 704 if (sys::path::is_absolute(FileName)) 705 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName)); 706 else { 707 Expected<std::string> PathOrErr = 708 computeArchiveRelativePath(ArchiveName, FileName); 709 NMOrErr->MemberName = Saver.save( 710 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName)); 711 } 712 } 713 714 if (FlattenArchive && 715 identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) { 716 object::Archive &Lib = readLibrary(FileName); 717 // When creating thin archives, only flatten if the member is also thin. 718 if (!Thin || Lib.isThin()) { 719 Error Err = Error::success(); 720 // Only Thin archives are recursively flattened. 721 for (auto &Child : Lib.children(Err)) 722 addChildMember(Members, Child, /*FlattenArchive=*/Thin); 723 failIfError(std::move(Err)); 724 return; 725 } 726 } 727 Members.push_back(std::move(*NMOrErr)); 728 } 729 730 enum InsertAction { 731 IA_AddOldMember, 732 IA_AddNewMember, 733 IA_Delete, 734 IA_MoveOldMember, 735 IA_MoveNewMember 736 }; 737 738 static InsertAction computeInsertAction(ArchiveOperation Operation, 739 const object::Archive::Child &Member, 740 StringRef Name, 741 std::vector<StringRef>::iterator &Pos, 742 StringMap<int> &MemberCount) { 743 if (Operation == QuickAppend || Members.empty()) 744 return IA_AddOldMember; 745 auto MI = find_if( 746 Members, [Name](StringRef Path) { return comparePaths(Name, Path); }); 747 748 if (MI == Members.end()) 749 return IA_AddOldMember; 750 751 Pos = MI; 752 753 if (Operation == Delete) { 754 if (CountParam && ++MemberCount[Name] != CountParam) 755 return IA_AddOldMember; 756 return IA_Delete; 757 } 758 759 if (Operation == Move) 760 return IA_MoveOldMember; 761 762 if (Operation == ReplaceOrInsert) { 763 if (!OnlyUpdate) { 764 if (RelPos.empty()) 765 return IA_AddNewMember; 766 return IA_MoveNewMember; 767 } 768 769 // We could try to optimize this to a fstat, but it is not a common 770 // operation. 771 sys::fs::file_status Status; 772 failIfError(sys::fs::status(*MI, Status), *MI); 773 auto ModTimeOrErr = Member.getLastModified(); 774 failIfError(ModTimeOrErr.takeError()); 775 if (Status.getLastModificationTime() < ModTimeOrErr.get()) { 776 if (RelPos.empty()) 777 return IA_AddOldMember; 778 return IA_MoveOldMember; 779 } 780 781 if (RelPos.empty()) 782 return IA_AddNewMember; 783 return IA_MoveNewMember; 784 } 785 llvm_unreachable("No such operation"); 786 } 787 788 // We have to walk this twice and computing it is not trivial, so creating an 789 // explicit std::vector is actually fairly efficient. 790 static std::vector<NewArchiveMember> 791 computeNewArchiveMembers(ArchiveOperation Operation, 792 object::Archive *OldArchive) { 793 std::vector<NewArchiveMember> Ret; 794 std::vector<NewArchiveMember> Moved; 795 int InsertPos = -1; 796 if (OldArchive) { 797 Error Err = Error::success(); 798 StringMap<int> MemberCount; 799 for (auto &Child : OldArchive->children(Err)) { 800 int Pos = Ret.size(); 801 Expected<StringRef> NameOrErr = Child.getName(); 802 failIfError(NameOrErr.takeError()); 803 std::string Name = std::string(NameOrErr.get()); 804 if (comparePaths(Name, RelPos)) { 805 assert(AddAfter || AddBefore); 806 if (AddBefore) 807 InsertPos = Pos; 808 else 809 InsertPos = Pos + 1; 810 } 811 812 std::vector<StringRef>::iterator MemberI = Members.end(); 813 InsertAction Action = 814 computeInsertAction(Operation, Child, Name, MemberI, MemberCount); 815 switch (Action) { 816 case IA_AddOldMember: 817 addChildMember(Ret, Child, /*FlattenArchive=*/Thin); 818 break; 819 case IA_AddNewMember: 820 addMember(Ret, *MemberI); 821 break; 822 case IA_Delete: 823 break; 824 case IA_MoveOldMember: 825 addChildMember(Moved, Child, /*FlattenArchive=*/Thin); 826 break; 827 case IA_MoveNewMember: 828 addMember(Moved, *MemberI); 829 break; 830 } 831 // When processing elements with the count param, we need to preserve the 832 // full members list when iterating over all archive members. For 833 // instance, "llvm-ar dN 2 archive.a member.o" should delete the second 834 // file named member.o it sees; we are not done with member.o the first 835 // time we see it in the archive. 836 if (MemberI != Members.end() && !CountParam) 837 Members.erase(MemberI); 838 } 839 failIfError(std::move(Err)); 840 } 841 842 if (Operation == Delete) 843 return Ret; 844 845 if (!RelPos.empty() && InsertPos == -1) 846 fail("insertion point not found"); 847 848 if (RelPos.empty()) 849 InsertPos = Ret.size(); 850 851 assert(unsigned(InsertPos) <= Ret.size()); 852 int Pos = InsertPos; 853 for (auto &M : Moved) { 854 Ret.insert(Ret.begin() + Pos, std::move(M)); 855 ++Pos; 856 } 857 858 if (AddLibrary) { 859 assert(Operation == QuickAppend); 860 for (auto &Member : Members) 861 addMember(Ret, Member, /*FlattenArchive=*/true); 862 return Ret; 863 } 864 865 std::vector<NewArchiveMember> NewMembers; 866 for (auto &Member : Members) 867 addMember(NewMembers, Member, /*FlattenArchive=*/Thin); 868 Ret.reserve(Ret.size() + NewMembers.size()); 869 std::move(NewMembers.begin(), NewMembers.end(), 870 std::inserter(Ret, std::next(Ret.begin(), InsertPos))); 871 872 return Ret; 873 } 874 875 static object::Archive::Kind getDefaultForHost() { 876 return Triple(sys::getProcessTriple()).isOSDarwin() 877 ? object::Archive::K_DARWIN 878 : object::Archive::K_GNU; 879 } 880 881 static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) { 882 auto MemBufferRef = Member.Buf->getMemBufferRef(); 883 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject = 884 object::ObjectFile::createObjectFile(MemBufferRef); 885 886 if (OptionalObject) 887 return isa<object::MachOObjectFile>(**OptionalObject) 888 ? object::Archive::K_DARWIN 889 : object::Archive::K_GNU; 890 891 // squelch the error in case we had a non-object file 892 consumeError(OptionalObject.takeError()); 893 894 // If we're adding a bitcode file to the archive, detect the Archive kind 895 // based on the target triple. 896 LLVMContext Context; 897 if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) { 898 if (auto ObjOrErr = object::SymbolicFile::createSymbolicFile( 899 MemBufferRef, file_magic::bitcode, &Context)) { 900 auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr); 901 return Triple(IRObject.getTargetTriple()).isOSDarwin() 902 ? object::Archive::K_DARWIN 903 : object::Archive::K_GNU; 904 } else { 905 // Squelch the error in case this was not a SymbolicFile. 906 consumeError(ObjOrErr.takeError()); 907 } 908 } 909 910 return getDefaultForHost(); 911 } 912 913 static void performWriteOperation(ArchiveOperation Operation, 914 object::Archive *OldArchive, 915 std::unique_ptr<MemoryBuffer> OldArchiveBuf, 916 std::vector<NewArchiveMember> *NewMembersP) { 917 std::vector<NewArchiveMember> NewMembers; 918 if (!NewMembersP) 919 NewMembers = computeNewArchiveMembers(Operation, OldArchive); 920 921 object::Archive::Kind Kind; 922 switch (FormatType) { 923 case Default: 924 if (Thin) 925 Kind = object::Archive::K_GNU; 926 else if (OldArchive) 927 Kind = OldArchive->kind(); 928 else if (NewMembersP) 929 Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front()) 930 : getDefaultForHost(); 931 else 932 Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front()) 933 : getDefaultForHost(); 934 break; 935 case GNU: 936 Kind = object::Archive::K_GNU; 937 break; 938 case BSD: 939 if (Thin) 940 fail("only the gnu format has a thin mode"); 941 Kind = object::Archive::K_BSD; 942 break; 943 case DARWIN: 944 if (Thin) 945 fail("only the gnu format has a thin mode"); 946 Kind = object::Archive::K_DARWIN; 947 break; 948 case Unknown: 949 llvm_unreachable(""); 950 } 951 952 Error E = 953 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab, 954 Kind, Deterministic, Thin, std::move(OldArchiveBuf)); 955 failIfError(std::move(E), ArchiveName); 956 } 957 958 static void createSymbolTable(object::Archive *OldArchive) { 959 // When an archive is created or modified, if the s option is given, the 960 // resulting archive will have a current symbol table. If the S option 961 // is given, it will have no symbol table. 962 // In summary, we only need to update the symbol table if we have none. 963 // This is actually very common because of broken build systems that think 964 // they have to run ranlib. 965 if (OldArchive->hasSymbolTable()) 966 return; 967 968 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr); 969 } 970 971 static void performOperation(ArchiveOperation Operation, 972 object::Archive *OldArchive, 973 std::unique_ptr<MemoryBuffer> OldArchiveBuf, 974 std::vector<NewArchiveMember> *NewMembers) { 975 switch (Operation) { 976 case Print: 977 case DisplayTable: 978 case Extract: 979 performReadOperation(Operation, OldArchive); 980 return; 981 982 case Delete: 983 case Move: 984 case QuickAppend: 985 case ReplaceOrInsert: 986 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf), 987 NewMembers); 988 return; 989 case CreateSymTab: 990 createSymbolTable(OldArchive); 991 return; 992 } 993 llvm_unreachable("Unknown operation."); 994 } 995 996 static int performOperation(ArchiveOperation Operation, 997 std::vector<NewArchiveMember> *NewMembers) { 998 // Create or open the archive object. 999 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile( 1000 ArchiveName, /*IsText=*/false, /*RequiresNullTerminator=*/false); 1001 std::error_code EC = Buf.getError(); 1002 if (EC && EC != errc::no_such_file_or_directory) 1003 fail("unable to open '" + ArchiveName + "': " + EC.message()); 1004 1005 if (!EC) { 1006 Error Err = Error::success(); 1007 object::Archive Archive(Buf.get()->getMemBufferRef(), Err); 1008 failIfError(std::move(Err), "unable to load '" + ArchiveName + "'"); 1009 if (Archive.isThin()) 1010 CompareFullPath = true; 1011 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers); 1012 return 0; 1013 } 1014 1015 assert(EC == errc::no_such_file_or_directory); 1016 1017 if (!shouldCreateArchive(Operation)) { 1018 failIfError(EC, Twine("unable to load '") + ArchiveName + "'"); 1019 } else { 1020 if (!Create) { 1021 // Produce a warning if we should and we're creating the archive 1022 WithColor::warning(errs(), ToolName) 1023 << "creating " << ArchiveName << "\n"; 1024 } 1025 } 1026 1027 performOperation(Operation, nullptr, nullptr, NewMembers); 1028 return 0; 1029 } 1030 1031 static void runMRIScript() { 1032 enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid }; 1033 1034 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN(); 1035 failIfError(Buf.getError()); 1036 const MemoryBuffer &Ref = *Buf.get(); 1037 bool Saved = false; 1038 std::vector<NewArchiveMember> NewMembers; 1039 ParsingMRIScript = true; 1040 1041 for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) { 1042 ++MRILineNumber; 1043 StringRef Line = *I; 1044 Line = Line.split(';').first; 1045 Line = Line.split('*').first; 1046 Line = Line.trim(); 1047 if (Line.empty()) 1048 continue; 1049 StringRef CommandStr, Rest; 1050 std::tie(CommandStr, Rest) = Line.split(' '); 1051 Rest = Rest.trim(); 1052 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"') 1053 Rest = Rest.drop_front().drop_back(); 1054 auto Command = StringSwitch<MRICommand>(CommandStr.lower()) 1055 .Case("addlib", MRICommand::AddLib) 1056 .Case("addmod", MRICommand::AddMod) 1057 .Case("create", MRICommand::Create) 1058 .Case("createthin", MRICommand::CreateThin) 1059 .Case("delete", MRICommand::Delete) 1060 .Case("save", MRICommand::Save) 1061 .Case("end", MRICommand::End) 1062 .Default(MRICommand::Invalid); 1063 1064 switch (Command) { 1065 case MRICommand::AddLib: { 1066 object::Archive &Lib = readLibrary(Rest); 1067 { 1068 Error Err = Error::success(); 1069 for (auto &Member : Lib.children(Err)) 1070 addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin); 1071 failIfError(std::move(Err)); 1072 } 1073 break; 1074 } 1075 case MRICommand::AddMod: 1076 addMember(NewMembers, Rest); 1077 break; 1078 case MRICommand::CreateThin: 1079 Thin = true; 1080 LLVM_FALLTHROUGH; 1081 case MRICommand::Create: 1082 Create = true; 1083 if (!ArchiveName.empty()) 1084 fail("editing multiple archives not supported"); 1085 if (Saved) 1086 fail("file already saved"); 1087 ArchiveName = std::string(Rest); 1088 break; 1089 case MRICommand::Delete: { 1090 llvm::erase_if(NewMembers, [=](NewArchiveMember &M) { 1091 return comparePaths(M.MemberName, Rest); 1092 }); 1093 break; 1094 } 1095 case MRICommand::Save: 1096 Saved = true; 1097 break; 1098 case MRICommand::End: 1099 break; 1100 case MRICommand::Invalid: 1101 fail("unknown command: " + CommandStr); 1102 } 1103 } 1104 1105 ParsingMRIScript = false; 1106 1107 // Nothing to do if not saved. 1108 if (Saved) 1109 performOperation(ReplaceOrInsert, &NewMembers); 1110 exit(0); 1111 } 1112 1113 static bool handleGenericOption(StringRef arg) { 1114 if (arg == "-help" || arg == "--help" || arg == "-h") { 1115 printHelpMessage(); 1116 return true; 1117 } 1118 if (arg == "-version" || arg == "--version") { 1119 cl::PrintVersionMessage(); 1120 return true; 1121 } 1122 return false; 1123 } 1124 1125 static const char *matchFlagWithArg(StringRef Expected, 1126 ArrayRef<const char *>::iterator &ArgIt, 1127 ArrayRef<const char *> Args) { 1128 StringRef Arg = *ArgIt; 1129 1130 if (Arg.startswith("--")) 1131 Arg = Arg.substr(2); 1132 else if (Arg.startswith("-")) 1133 Arg = Arg.substr(1); 1134 1135 size_t len = Expected.size(); 1136 if (Arg == Expected) { 1137 if (++ArgIt == Args.end()) 1138 fail(std::string(Expected) + " requires an argument"); 1139 1140 return *ArgIt; 1141 } 1142 if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=') 1143 return Arg.data() + len + 1; 1144 1145 return nullptr; 1146 } 1147 1148 static cl::TokenizerCallback getRspQuoting(ArrayRef<const char *> ArgsArr) { 1149 cl::TokenizerCallback Ret = 1150 Triple(sys::getProcessTriple()).getOS() == Triple::Win32 1151 ? cl::TokenizeWindowsCommandLine 1152 : cl::TokenizeGNUCommandLine; 1153 1154 for (ArrayRef<const char *>::iterator ArgIt = ArgsArr.begin(); 1155 ArgIt != ArgsArr.end(); ++ArgIt) { 1156 if (const char *Match = matchFlagWithArg("rsp-quoting", ArgIt, ArgsArr)) { 1157 StringRef MatchRef = Match; 1158 if (MatchRef == "posix") 1159 Ret = cl::TokenizeGNUCommandLine; 1160 else if (MatchRef == "windows") 1161 Ret = cl::TokenizeWindowsCommandLine; 1162 else 1163 fail(std::string("Invalid response file quoting style ") + Match); 1164 } 1165 } 1166 1167 return Ret; 1168 } 1169 1170 static int ar_main(int argc, char **argv) { 1171 SmallVector<const char *, 0> Argv(argv + 1, argv + argc); 1172 StringSaver Saver(Alloc); 1173 1174 cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv); 1175 1176 for (ArrayRef<const char *>::iterator ArgIt = Argv.begin(); 1177 ArgIt != Argv.end(); ++ArgIt) { 1178 const char *Match = nullptr; 1179 1180 if (handleGenericOption(*ArgIt)) 1181 return 0; 1182 if (strcmp(*ArgIt, "--") == 0) { 1183 ++ArgIt; 1184 for (; ArgIt != Argv.end(); ++ArgIt) 1185 PositionalArgs.push_back(*ArgIt); 1186 break; 1187 } 1188 1189 if (*ArgIt[0] != '-') { 1190 if (Options.empty()) 1191 Options += *ArgIt; 1192 else 1193 PositionalArgs.push_back(*ArgIt); 1194 continue; 1195 } 1196 1197 if (strcmp(*ArgIt, "-M") == 0) { 1198 MRI = true; 1199 continue; 1200 } 1201 1202 Match = matchFlagWithArg("format", ArgIt, Argv); 1203 if (Match) { 1204 FormatType = StringSwitch<Format>(Match) 1205 .Case("default", Default) 1206 .Case("gnu", GNU) 1207 .Case("darwin", DARWIN) 1208 .Case("bsd", BSD) 1209 .Default(Unknown); 1210 if (FormatType == Unknown) 1211 fail(std::string("Invalid format ") + Match); 1212 continue; 1213 } 1214 1215 if (matchFlagWithArg("plugin", ArgIt, Argv) || 1216 matchFlagWithArg("rsp-quoting", ArgIt, Argv)) 1217 continue; 1218 1219 Options += *ArgIt + 1; 1220 } 1221 1222 ArchiveOperation Operation = parseCommandLine(); 1223 return performOperation(Operation, nullptr); 1224 } 1225 1226 static int ranlib_main(int argc, char **argv) { 1227 bool ArchiveSpecified = false; 1228 for (int i = 1; i < argc; ++i) { 1229 StringRef arg(argv[i]); 1230 if (handleGenericOption(arg)) { 1231 return 0; 1232 } else if (arg.consume_front("-")) { 1233 // Handle the -D/-U flag 1234 while (!arg.empty()) { 1235 if (arg.front() == 'D') { 1236 Deterministic = true; 1237 } else if (arg.front() == 'U') { 1238 Deterministic = false; 1239 } else if (arg.front() == 'h') { 1240 printHelpMessage(); 1241 return 0; 1242 } else if (arg.front() == 'v') { 1243 cl::PrintVersionMessage(); 1244 return 0; 1245 } else { 1246 // TODO: GNU ranlib also supports a -t flag 1247 fail("Invalid option: '-" + arg + "'"); 1248 } 1249 arg = arg.drop_front(1); 1250 } 1251 } else { 1252 if (ArchiveSpecified) 1253 fail("exactly one archive should be specified"); 1254 ArchiveSpecified = true; 1255 ArchiveName = arg.str(); 1256 } 1257 } 1258 if (!ArchiveSpecified) { 1259 badUsage("an archive name must be specified"); 1260 } 1261 return performOperation(CreateSymTab, nullptr); 1262 } 1263 1264 int main(int argc, char **argv) { 1265 InitLLVM X(argc, argv); 1266 ToolName = argv[0]; 1267 1268 llvm::InitializeAllTargetInfos(); 1269 llvm::InitializeAllTargetMCs(); 1270 llvm::InitializeAllAsmParsers(); 1271 1272 Stem = sys::path::stem(ToolName); 1273 auto Is = [](StringRef Tool) { 1274 // We need to recognize the following filenames. 1275 // 1276 // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe) 1277 // dlltool.exe -> dlltool 1278 // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar 1279 auto I = Stem.rfind_insensitive(Tool); 1280 return I != StringRef::npos && 1281 (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()])); 1282 }; 1283 1284 if (Is("dlltool")) 1285 return dlltoolDriverMain(makeArrayRef(argv, argc)); 1286 if (Is("ranlib")) 1287 return ranlib_main(argc, argv); 1288 if (Is("lib")) 1289 return libDriverMain(makeArrayRef(argv, argc)); 1290 if (Is("ar")) 1291 return ar_main(argc, argv); 1292 1293 fail("not ranlib, ar, lib or dlltool"); 1294 } 1295