1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Builds up (relatively) standard unix archive files (.a) containing LLVM
10 // bitcode or other files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/StringExtras.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/Object/Archive.h"
19 #include "llvm/Object/ArchiveWriter.h"
20 #include "llvm/Object/MachO.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/Chrono.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Errc.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/FormatVariadic.h"
28 #include "llvm/Support/InitLLVM.h"
29 #include "llvm/Support/LineIterator.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/StringSaver.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include "llvm/Support/WithColor.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
39 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
41 #if !defined(_MSC_VER) && !defined(__MINGW32__)
48 #include "llvm/Support/Windows/WindowsSupport.h"
53 // The name this program was invoked as.
54 static StringRef ToolName;
56 // The basename of this program.
57 static StringRef Stem;
59 const char RanlibHelp[] = R"(OVERVIEW: LLVM Ranlib (llvm-ranlib)
61 This program generates an index to speed access to archives
63 USAGE: llvm-ranlib <archive-file>
66 -h --help - Display available options
67 -v --version - Display the version of this program
68 -D - Use zero for timestamps and uids/gids (default)
69 -U - Use actual timestamps and uids/gids
72 const char ArHelp[] = R"(OVERVIEW: LLVM Archiver
74 USAGE: llvm-ar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files]
75 llvm-ar -M [<mri-script]
78 --format - archive format to create
83 --plugin=<string> - ignored for compatibility
84 -h --help - display this help and exit
85 --version - print the version and exit
86 @<file> - read options from <file>
89 d - delete [files] from the archive
90 m - move [files] in the archive
91 p - print [files] found in the archive
92 q - quick append [files] to the archive
93 r - replace or insert [files] into the archive
95 t - display contents of archive
96 x - extract [files] from the archive
99 [a] - put [files] after [relpos]
100 [b] - put [files] before [relpos] (same as [i])
101 [c] - do not warn if archive had to be created
102 [D] - use zero for timestamps and uids/gids (default)
103 [h] - display this help and exit
104 [i] - put [files] before [relpos] (same as [b])
105 [l] - ignored for compatibility
106 [L] - add archive's contents
107 [N] - use instance [count] of name
108 [o] - preserve original dates
109 [O] - display member offsets
110 [P] - use full names when matching (implied for thin archives)
111 [s] - create an archive index (cf. ranlib)
112 [S] - do not build a symbol table
113 [T] - create a thin archive
114 [u] - update only [files] newer than archive contents
115 [U] - use actual timestamps and uids/gids
116 [v] - be verbose about actions taken
117 [V] - display the version and exit
120 void printHelpMessage() {
121 if (Stem.contains_lower("ranlib"))
122 outs() << RanlibHelp;
123 else if (Stem.contains_lower("ar"))
127 static unsigned MRILineNumber;
128 static bool ParsingMRIScript;
130 // Show the error plus the usage message, and exit.
131 LLVM_ATTRIBUTE_NORETURN static void badUsage(Twine Error) {
132 WithColor::error(errs(), ToolName) << Error << "\n";
137 // Show the error message and exit.
138 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
139 if (ParsingMRIScript) {
140 WithColor::error(errs(), ToolName)
141 << "script line " << MRILineNumber << ": " << Error << "\n";
143 WithColor::error(errs(), ToolName) << Error << "\n";
148 static void failIfError(std::error_code EC, Twine Context = "") {
152 std::string ContextStr = Context.str();
153 if (ContextStr.empty())
155 fail(Context + ": " + EC.message());
158 static void failIfError(Error E, Twine Context = "") {
162 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
163 std::string ContextStr = Context.str();
164 if (ContextStr.empty())
166 fail(Context + ": " + EIB.message());
170 static SmallVector<const char *, 256> PositionalArgs;
175 enum Format { Default, GNU, BSD, DARWIN, Unknown };
178 static Format FormatType = Default;
180 static std::string Options;
182 // This enumeration delineates the kinds of operations on an archive
183 // that are permitted.
184 enum ArchiveOperation {
185 Print, ///< Print the contents of the archive
186 Delete, ///< Delete the specified members
187 Move, ///< Move members to end or as given by {a,b,i} modifiers
188 QuickAppend, ///< Quickly append to end of archive
189 ReplaceOrInsert, ///< Replace or Insert members
190 DisplayTable, ///< Display the table of contents
191 Extract, ///< Extract files back to file system
192 CreateSymTab ///< Create a symbol table in an existing archive
195 // Modifiers to follow operation to vary behavior
196 static bool AddAfter = false; ///< 'a' modifier
197 static bool AddBefore = false; ///< 'b' modifier
198 static bool Create = false; ///< 'c' modifier
199 static bool OriginalDates = false; ///< 'o' modifier
200 static bool DisplayMemberOffsets = false; ///< 'O' modifier
201 static bool CompareFullPath = false; ///< 'P' modifier
202 static bool OnlyUpdate = false; ///< 'u' modifier
203 static bool Verbose = false; ///< 'v' modifier
204 static bool Symtab = true; ///< 's' modifier
205 static bool Deterministic = true; ///< 'D' and 'U' modifiers
206 static bool Thin = false; ///< 'T' modifier
207 static bool AddLibrary = false; ///< 'L' modifier
209 // Relative Positional Argument (for insert/move). This variable holds
210 // the name of the archive member to which the 'a', 'b' or 'i' modifier
211 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
213 static std::string RelPos;
215 // Count parameter for 'N' modifier. This variable specifies which file should
216 // match for extract/delete operations when there are multiple matches. This is
217 // 1-indexed. A value of 0 is invalid, and implies 'N' is not used.
218 static int CountParam = 0;
220 // This variable holds the name of the archive file as given on the
222 static std::string ArchiveName;
224 static std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
225 static std::vector<std::unique_ptr<object::Archive>> Archives;
227 // This variable holds the list of member files to proecess, as given
228 // on the command line.
229 static std::vector<StringRef> Members;
231 // Static buffer to hold StringRefs.
232 static BumpPtrAllocator Alloc;
234 // Extract the member filename from the command line for the [relpos] argument
235 // associated with a, b, and i modifiers
236 static void getRelPos() {
237 if (PositionalArgs.empty())
238 fail("expected [relpos] for 'a', 'b', or 'i' modifier");
239 RelPos = PositionalArgs[0];
240 PositionalArgs.erase(PositionalArgs.begin());
243 // Extract the parameter from the command line for the [count] argument
244 // associated with the N modifier
245 static void getCountParam() {
246 if (PositionalArgs.empty())
247 badUsage("expected [count] for 'N' modifier");
248 auto CountParamArg = StringRef(PositionalArgs[0]);
249 if (CountParamArg.getAsInteger(10, CountParam))
250 badUsage("value for [count] must be numeric, got: " + CountParamArg);
252 badUsage("value for [count] must be positive, got: " + CountParamArg);
253 PositionalArgs.erase(PositionalArgs.begin());
256 // Get the archive file name from the command line
257 static void getArchive() {
258 if (PositionalArgs.empty())
259 badUsage("an archive name must be specified");
260 ArchiveName = PositionalArgs[0];
261 PositionalArgs.erase(PositionalArgs.begin());
264 static object::Archive &readLibrary(const Twine &Library) {
265 auto BufOrErr = MemoryBuffer::getFile(Library, -1, false);
266 failIfError(BufOrErr.getError(), "could not open library " + Library);
267 ArchiveBuffers.push_back(std::move(*BufOrErr));
269 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
270 failIfError(errorToErrorCode(LibOrErr.takeError()),
271 "could not parse library");
272 Archives.push_back(std::move(*LibOrErr));
273 return *Archives.back();
276 static void runMRIScript();
278 // Parse the command line options as presented and return the operation
279 // specified. Process all modifiers and check to make sure that constraints on
280 // modifier/operation pairs have not been violated.
281 static ArchiveOperation parseCommandLine() {
283 if (!PositionalArgs.empty() || !Options.empty())
284 badUsage("cannot mix -M and other options");
288 // Keep track of number of operations. We can only specify one
290 unsigned NumOperations = 0;
292 // Keep track of the number of positional modifiers (a,b,i). Only
293 // one can be specified.
294 unsigned NumPositional = 0;
296 // Keep track of which operation was requested
297 ArchiveOperation Operation;
299 bool MaybeJustCreateSymTab = false;
301 for (unsigned i = 0; i < Options.size(); ++i) {
302 switch (Options[i]) {
317 Operation = QuickAppend;
321 Operation = ReplaceOrInsert;
325 Operation = DisplayTable;
334 case 'l': /* accepted but unused */
337 OriginalDates = true;
340 DisplayMemberOffsets = true;
343 CompareFullPath = true;
347 MaybeJustCreateSymTab = true;
374 Deterministic = true;
377 Deterministic = false;
384 // Thin archives store path names, so P should be forced.
385 CompareFullPath = true;
391 cl::PrintVersionMessage();
397 badUsage(std::string("unknown option ") + Options[i]);
401 // At this point, the next thing on the command line must be
405 // Everything on the command line at this point is a member.
406 Members.assign(PositionalArgs.begin(), PositionalArgs.end());
408 if (NumOperations == 0 && MaybeJustCreateSymTab) {
410 Operation = CreateSymTab;
411 if (!Members.empty())
412 badUsage("the 's' operation takes only an archive as argument");
415 // Perform various checks on the operation/modifier specification
416 // to make sure we are dealing with a legal request.
417 if (NumOperations == 0)
418 badUsage("you must specify at least one of the operations");
419 if (NumOperations > 1)
420 badUsage("only one operation may be specified");
421 if (NumPositional > 1)
422 badUsage("you may only specify one of 'a', 'b', and 'i' modifiers");
423 if (AddAfter || AddBefore)
424 if (Operation != Move && Operation != ReplaceOrInsert)
425 badUsage("the 'a', 'b' and 'i' modifiers can only be specified with "
426 "the 'm' or 'r' operations");
428 if (Operation != Extract && Operation != Delete)
429 badUsage("the 'N' modifier can only be specified with the 'x' or 'd' "
431 if (OriginalDates && Operation != Extract)
432 badUsage("the 'o' modifier is only applicable to the 'x' operation");
433 if (OnlyUpdate && Operation != ReplaceOrInsert)
434 badUsage("the 'u' modifier is only applicable to the 'r' operation");
435 if (AddLibrary && Operation != QuickAppend)
436 badUsage("the 'L' modifier is only applicable to the 'q' operation");
438 // Return the parsed operation to the caller
442 // Implements the 'p' operation. This function traverses the archive
443 // looking for members that match the path list.
444 static void doPrint(StringRef Name, const object::Archive::Child &C) {
446 outs() << "Printing " << Name << "\n";
448 Expected<StringRef> DataOrErr = C.getBuffer();
449 failIfError(DataOrErr.takeError());
450 StringRef Data = *DataOrErr;
451 outs().write(Data.data(), Data.size());
454 // Utility function for printing out the file mode when the 't' operation is in
456 static void printMode(unsigned mode) {
457 outs() << ((mode & 004) ? "r" : "-");
458 outs() << ((mode & 002) ? "w" : "-");
459 outs() << ((mode & 001) ? "x" : "-");
462 // Implement the 't' operation. This function prints out just
463 // the file names of each of the members. However, if verbose mode is requested
464 // ('v' modifier) then the file type, permission mode, user, group, size, and
465 // modification time are also printed.
466 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
468 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
469 failIfError(ModeOrErr.takeError());
470 sys::fs::perms Mode = ModeOrErr.get();
471 printMode((Mode >> 6) & 007);
472 printMode((Mode >> 3) & 007);
473 printMode(Mode & 007);
474 Expected<unsigned> UIDOrErr = C.getUID();
475 failIfError(UIDOrErr.takeError());
476 outs() << ' ' << UIDOrErr.get();
477 Expected<unsigned> GIDOrErr = C.getGID();
478 failIfError(GIDOrErr.takeError());
479 outs() << '/' << GIDOrErr.get();
480 Expected<uint64_t> Size = C.getSize();
481 failIfError(Size.takeError());
482 outs() << ' ' << format("%6llu", Size.get());
483 auto ModTimeOrErr = C.getLastModified();
484 failIfError(ModTimeOrErr.takeError());
485 // Note: formatv() only handles the default TimePoint<>, which is in
487 // TODO: fix format_provider<TimePoint<>> to allow other units.
488 sys::TimePoint<> ModTimeInNs = ModTimeOrErr.get();
489 outs() << ' ' << formatv("{0:%b %e %H:%M %Y}", ModTimeInNs);
493 if (C.getParent()->isThin()) {
494 if (!sys::path::is_absolute(Name)) {
495 StringRef ParentDir = sys::path::parent_path(ArchiveName);
496 if (!ParentDir.empty())
497 outs() << sys::path::convert_to_slash(ParentDir) << '/';
502 if (DisplayMemberOffsets)
503 outs() << " 0x" << utohexstr(C.getDataOffset(), true);
508 static std::string normalizePath(StringRef Path) {
509 return CompareFullPath ? sys::path::convert_to_slash(Path)
510 : std::string(sys::path::filename(Path));
513 static bool comparePaths(StringRef Path1, StringRef Path2) {
514 // When on Windows this function calls CompareStringOrdinal
515 // as Windows file paths are case-insensitive.
516 // CompareStringOrdinal compares two Unicode strings for
517 // binary equivalence and allows for case insensitivity.
519 SmallVector<wchar_t, 128> WPath1, WPath2;
520 failIfError(sys::path::widenPath(normalizePath(Path1), WPath1));
521 failIfError(sys::path::widenPath(normalizePath(Path2), WPath2));
523 return CompareStringOrdinal(WPath1.data(), WPath1.size(), WPath2.data(),
524 WPath2.size(), true) == CSTR_EQUAL;
526 return normalizePath(Path1) == normalizePath(Path2);
530 // Implement the 'x' operation. This function extracts files back to the file
532 static void doExtract(StringRef Name, const object::Archive::Child &C) {
533 // Retain the original mode.
534 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
535 failIfError(ModeOrErr.takeError());
536 sys::fs::perms Mode = ModeOrErr.get();
538 llvm::StringRef outputFilePath = sys::path::filename(Name);
540 outs() << "x - " << outputFilePath << '\n';
543 failIfError(sys::fs::openFileForWrite(outputFilePath, FD,
544 sys::fs::CD_CreateAlways,
545 sys::fs::OF_None, Mode),
549 raw_fd_ostream file(FD, false);
551 // Get the data and its length
552 Expected<StringRef> BufOrErr = C.getBuffer();
553 failIfError(BufOrErr.takeError());
554 StringRef Data = BufOrErr.get();
557 file.write(Data.data(), Data.size());
560 // If we're supposed to retain the original modification times, etc. do so
563 auto ModTimeOrErr = C.getLastModified();
564 failIfError(ModTimeOrErr.takeError());
566 sys::fs::setLastAccessAndModificationTime(FD, ModTimeOrErr.get()));
570 fail("Could not close the file");
573 static bool shouldCreateArchive(ArchiveOperation Op) {
584 case ReplaceOrInsert:
588 llvm_unreachable("Missing entry in covered switch.");
591 static void performReadOperation(ArchiveOperation Operation,
592 object::Archive *OldArchive) {
593 if (Operation == Extract && OldArchive->isThin())
594 fail("extracting from a thin archive is not supported");
596 bool Filter = !Members.empty();
597 StringMap<int> MemberCount;
599 Error Err = Error::success();
600 for (auto &C : OldArchive->children(Err)) {
601 Expected<StringRef> NameOrErr = C.getName();
602 failIfError(NameOrErr.takeError());
603 StringRef Name = NameOrErr.get();
606 auto I = find_if(Members, [Name](StringRef Path) {
607 return comparePaths(Name, Path);
609 if (I == Members.end())
611 if (CountParam && ++MemberCount[Name] != CountParam)
618 llvm_unreachable("Not a read operation");
623 doDisplayTable(Name, C);
630 failIfError(std::move(Err));
635 for (StringRef Name : Members)
636 WithColor::error(errs(), ToolName) << "'" << Name << "' was not found\n";
640 static void addChildMember(std::vector<NewArchiveMember> &Members,
641 const object::Archive::Child &M,
642 bool FlattenArchive = false) {
643 if (Thin && !M.getParent()->isThin())
644 fail("cannot convert a regular archive to a thin one");
645 Expected<NewArchiveMember> NMOrErr =
646 NewArchiveMember::getOldMember(M, Deterministic);
647 failIfError(NMOrErr.takeError());
648 // If the child member we're trying to add is thin, use the path relative to
649 // the archive it's in, so the file resolves correctly.
650 if (Thin && FlattenArchive) {
651 StringSaver Saver(Alloc);
652 Expected<std::string> FileNameOrErr = M.getName();
653 failIfError(FileNameOrErr.takeError());
654 if (sys::path::is_absolute(*FileNameOrErr)) {
655 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(*FileNameOrErr));
657 FileNameOrErr = M.getFullName();
658 failIfError(FileNameOrErr.takeError());
659 Expected<std::string> PathOrErr =
660 computeArchiveRelativePath(ArchiveName, *FileNameOrErr);
661 NMOrErr->MemberName = Saver.save(
662 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(*FileNameOrErr));
665 if (FlattenArchive &&
666 identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
667 Expected<std::string> FileNameOrErr = M.getFullName();
668 failIfError(FileNameOrErr.takeError());
669 object::Archive &Lib = readLibrary(*FileNameOrErr);
670 // When creating thin archives, only flatten if the member is also thin.
671 if (!Thin || Lib.isThin()) {
672 Error Err = Error::success();
673 // Only Thin archives are recursively flattened.
674 for (auto &Child : Lib.children(Err))
675 addChildMember(Members, Child, /*FlattenArchive=*/Thin);
676 failIfError(std::move(Err));
680 Members.push_back(std::move(*NMOrErr));
683 static void addMember(std::vector<NewArchiveMember> &Members,
684 StringRef FileName, bool FlattenArchive = false) {
685 Expected<NewArchiveMember> NMOrErr =
686 NewArchiveMember::getFile(FileName, Deterministic);
687 failIfError(NMOrErr.takeError(), FileName);
688 StringSaver Saver(Alloc);
689 // For regular archives, use the basename of the object path for the member
690 // name. For thin archives, use the full relative paths so the file resolves
693 NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
695 if (sys::path::is_absolute(FileName))
696 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName));
698 Expected<std::string> PathOrErr =
699 computeArchiveRelativePath(ArchiveName, FileName);
700 NMOrErr->MemberName = Saver.save(
701 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName));
705 if (FlattenArchive &&
706 identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
707 object::Archive &Lib = readLibrary(FileName);
708 // When creating thin archives, only flatten if the member is also thin.
709 if (!Thin || Lib.isThin()) {
710 Error Err = Error::success();
711 // Only Thin archives are recursively flattened.
712 for (auto &Child : Lib.children(Err))
713 addChildMember(Members, Child, /*FlattenArchive=*/Thin);
714 failIfError(std::move(Err));
718 Members.push_back(std::move(*NMOrErr));
729 static InsertAction computeInsertAction(ArchiveOperation Operation,
730 const object::Archive::Child &Member,
732 std::vector<StringRef>::iterator &Pos,
733 StringMap<int> &MemberCount) {
734 if (Operation == QuickAppend || Members.empty())
735 return IA_AddOldMember;
737 Members, [Name](StringRef Path) { return comparePaths(Name, Path); });
739 if (MI == Members.end())
740 return IA_AddOldMember;
744 if (Operation == Delete) {
745 if (CountParam && ++MemberCount[Name] != CountParam)
746 return IA_AddOldMember;
750 if (Operation == Move)
751 return IA_MoveOldMember;
753 if (Operation == ReplaceOrInsert) {
756 return IA_AddNewMember;
757 return IA_MoveNewMember;
760 // We could try to optimize this to a fstat, but it is not a common
762 sys::fs::file_status Status;
763 failIfError(sys::fs::status(*MI, Status), *MI);
764 auto ModTimeOrErr = Member.getLastModified();
765 failIfError(ModTimeOrErr.takeError());
766 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
768 return IA_AddOldMember;
769 return IA_MoveOldMember;
773 return IA_AddNewMember;
774 return IA_MoveNewMember;
776 llvm_unreachable("No such operation");
779 // We have to walk this twice and computing it is not trivial, so creating an
780 // explicit std::vector is actually fairly efficient.
781 static std::vector<NewArchiveMember>
782 computeNewArchiveMembers(ArchiveOperation Operation,
783 object::Archive *OldArchive) {
784 std::vector<NewArchiveMember> Ret;
785 std::vector<NewArchiveMember> Moved;
788 Error Err = Error::success();
789 StringMap<int> MemberCount;
790 for (auto &Child : OldArchive->children(Err)) {
791 int Pos = Ret.size();
792 Expected<StringRef> NameOrErr = Child.getName();
793 failIfError(NameOrErr.takeError());
794 std::string Name = NameOrErr.get();
795 if (comparePaths(Name, RelPos)) {
796 assert(AddAfter || AddBefore);
803 std::vector<StringRef>::iterator MemberI = Members.end();
804 InsertAction Action =
805 computeInsertAction(Operation, Child, Name, MemberI, MemberCount);
807 case IA_AddOldMember:
808 addChildMember(Ret, Child, /*FlattenArchive=*/Thin);
810 case IA_AddNewMember:
811 addMember(Ret, *MemberI);
815 case IA_MoveOldMember:
816 addChildMember(Moved, Child, /*FlattenArchive=*/Thin);
818 case IA_MoveNewMember:
819 addMember(Moved, *MemberI);
822 // When processing elements with the count param, we need to preserve the
823 // full members list when iterating over all archive members. For
824 // instance, "llvm-ar dN 2 archive.a member.o" should delete the second
825 // file named member.o it sees; we are not done with member.o the first
826 // time we see it in the archive.
827 if (MemberI != Members.end() && !CountParam)
828 Members.erase(MemberI);
830 failIfError(std::move(Err));
833 if (Operation == Delete)
836 if (!RelPos.empty() && InsertPos == -1)
837 fail("insertion point not found");
840 InsertPos = Ret.size();
842 assert(unsigned(InsertPos) <= Ret.size());
844 for (auto &M : Moved) {
845 Ret.insert(Ret.begin() + Pos, std::move(M));
850 assert(Operation == QuickAppend);
851 for (auto &Member : Members)
852 addMember(Ret, Member, /*FlattenArchive=*/true);
856 std::vector<NewArchiveMember> NewMembers;
857 for (auto &Member : Members)
858 addMember(NewMembers, Member, /*FlattenArchive=*/Thin);
859 Ret.reserve(Ret.size() + NewMembers.size());
860 std::move(NewMembers.begin(), NewMembers.end(),
861 std::inserter(Ret, std::next(Ret.begin(), InsertPos)));
866 static object::Archive::Kind getDefaultForHost() {
867 return Triple(sys::getProcessTriple()).isOSDarwin()
868 ? object::Archive::K_DARWIN
869 : object::Archive::K_GNU;
872 static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
873 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
874 object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
877 return isa<object::MachOObjectFile>(**OptionalObject)
878 ? object::Archive::K_DARWIN
879 : object::Archive::K_GNU;
881 // squelch the error in case we had a non-object file
882 consumeError(OptionalObject.takeError());
883 return getDefaultForHost();
886 static void performWriteOperation(ArchiveOperation Operation,
887 object::Archive *OldArchive,
888 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
889 std::vector<NewArchiveMember> *NewMembersP) {
890 std::vector<NewArchiveMember> NewMembers;
892 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
894 object::Archive::Kind Kind;
895 switch (FormatType) {
898 Kind = object::Archive::K_GNU;
900 Kind = OldArchive->kind();
901 else if (NewMembersP)
902 Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front())
903 : getDefaultForHost();
905 Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front())
906 : getDefaultForHost();
909 Kind = object::Archive::K_GNU;
913 fail("only the gnu format has a thin mode");
914 Kind = object::Archive::K_BSD;
918 fail("only the gnu format has a thin mode");
919 Kind = object::Archive::K_DARWIN;
922 llvm_unreachable("");
926 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
927 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
928 failIfError(std::move(E), ArchiveName);
931 static void createSymbolTable(object::Archive *OldArchive) {
932 // When an archive is created or modified, if the s option is given, the
933 // resulting archive will have a current symbol table. If the S option
934 // is given, it will have no symbol table.
935 // In summary, we only need to update the symbol table if we have none.
936 // This is actually very common because of broken build systems that think
937 // they have to run ranlib.
938 if (OldArchive->hasSymbolTable())
941 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
944 static void performOperation(ArchiveOperation Operation,
945 object::Archive *OldArchive,
946 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
947 std::vector<NewArchiveMember> *NewMembers) {
952 performReadOperation(Operation, OldArchive);
958 case ReplaceOrInsert:
959 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
963 createSymbolTable(OldArchive);
966 llvm_unreachable("Unknown operation.");
969 static int performOperation(ArchiveOperation Operation,
970 std::vector<NewArchiveMember> *NewMembers) {
971 // Create or open the archive object.
972 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
973 MemoryBuffer::getFile(ArchiveName, -1, false);
974 std::error_code EC = Buf.getError();
975 if (EC && EC != errc::no_such_file_or_directory)
976 fail("error opening '" + ArchiveName + "': " + EC.message());
979 Error Err = Error::success();
980 object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
981 failIfError(std::move(Err), "unable to load '" + ArchiveName + "'");
982 if (Archive.isThin())
983 CompareFullPath = true;
984 performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
988 assert(EC == errc::no_such_file_or_directory);
990 if (!shouldCreateArchive(Operation)) {
991 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
994 // Produce a warning if we should and we're creating the archive
995 WithColor::warning(errs(), ToolName)
996 << "creating " << ArchiveName << "\n";
1000 performOperation(Operation, nullptr, nullptr, NewMembers);
1004 static void runMRIScript() {
1005 enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
1007 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
1008 failIfError(Buf.getError());
1009 const MemoryBuffer &Ref = *Buf.get();
1011 std::vector<NewArchiveMember> NewMembers;
1012 ParsingMRIScript = true;
1014 for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
1016 StringRef Line = *I;
1017 Line = Line.split(';').first;
1018 Line = Line.split('*').first;
1022 StringRef CommandStr, Rest;
1023 std::tie(CommandStr, Rest) = Line.split(' ');
1025 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
1026 Rest = Rest.drop_front().drop_back();
1027 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
1028 .Case("addlib", MRICommand::AddLib)
1029 .Case("addmod", MRICommand::AddMod)
1030 .Case("create", MRICommand::Create)
1031 .Case("createthin", MRICommand::CreateThin)
1032 .Case("delete", MRICommand::Delete)
1033 .Case("save", MRICommand::Save)
1034 .Case("end", MRICommand::End)
1035 .Default(MRICommand::Invalid);
1038 case MRICommand::AddLib: {
1039 object::Archive &Lib = readLibrary(Rest);
1041 Error Err = Error::success();
1042 for (auto &Member : Lib.children(Err))
1043 addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
1044 failIfError(std::move(Err));
1048 case MRICommand::AddMod:
1049 addMember(NewMembers, Rest);
1051 case MRICommand::CreateThin:
1054 case MRICommand::Create:
1056 if (!ArchiveName.empty())
1057 fail("editing multiple archives not supported");
1059 fail("file already saved");
1062 case MRICommand::Delete: {
1063 llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
1064 return comparePaths(M.MemberName, Rest);
1068 case MRICommand::Save:
1071 case MRICommand::End:
1073 case MRICommand::Invalid:
1074 fail("unknown command: " + CommandStr);
1078 ParsingMRIScript = false;
1080 // Nothing to do if not saved.
1082 performOperation(ReplaceOrInsert, &NewMembers);
1086 static bool handleGenericOption(StringRef arg) {
1087 if (arg == "-help" || arg == "--help" || arg == "-h") {
1091 if (arg == "-version" || arg == "--version") {
1092 cl::PrintVersionMessage();
1098 static int ar_main(int argc, char **argv) {
1099 SmallVector<const char *, 0> Argv(argv, argv + argc);
1100 StringSaver Saver(Alloc);
1101 cl::ExpandResponseFiles(Saver, cl::TokenizeGNUCommandLine, Argv);
1102 for (size_t i = 1; i < Argv.size(); ++i) {
1103 StringRef Arg = Argv[i];
1104 const char *match = nullptr;
1105 auto MatchFlagWithArg = [&](const char *expected) {
1106 size_t len = strlen(expected);
1107 if (Arg == expected) {
1108 if (++i >= Argv.size())
1109 fail(std::string(expected) + " requires an argument");
1113 if (Arg.startswith(expected) && Arg.size() > len && Arg[len] == '=') {
1114 match = Arg.data() + len + 1;
1119 if (handleGenericOption(Argv[i]))
1122 for (; i < Argv.size(); ++i)
1123 PositionalArgs.push_back(Argv[i]);
1126 if (Arg[0] == '-') {
1127 if (Arg.startswith("--"))
1133 } else if (MatchFlagWithArg("format")) {
1134 FormatType = StringSwitch<Format>(match)
1135 .Case("default", Default)
1137 .Case("darwin", DARWIN)
1140 if (FormatType == Unknown)
1141 fail(std::string("Invalid format ") + match);
1142 } else if (MatchFlagWithArg("plugin")) {
1145 Options += Argv[i] + 1;
1147 } else if (Options.empty()) {
1150 PositionalArgs.push_back(Argv[i]);
1153 ArchiveOperation Operation = parseCommandLine();
1154 return performOperation(Operation, nullptr);
1157 static int ranlib_main(int argc, char **argv) {
1158 bool ArchiveSpecified = false;
1159 for (int i = 1; i < argc; ++i) {
1160 StringRef arg(argv[i]);
1161 if (handleGenericOption(arg)) {
1163 } else if (arg.consume_front("-")) {
1164 // Handle the -D/-U flag
1165 while (!arg.empty()) {
1166 if (arg.front() == 'D') {
1167 Deterministic = true;
1168 } else if (arg.front() == 'U') {
1169 Deterministic = false;
1170 } else if (arg.front() == 'h') {
1173 } else if (arg.front() == 'v') {
1174 cl::PrintVersionMessage();
1177 // TODO: GNU ranlib also supports a -t flag
1178 fail("Invalid option: '-" + arg + "'");
1180 arg = arg.drop_front(1);
1183 if (ArchiveSpecified)
1184 fail("exactly one archive should be specified");
1185 ArchiveSpecified = true;
1186 ArchiveName = arg.str();
1189 if (!ArchiveSpecified) {
1190 badUsage("an archive name must be specified");
1192 return performOperation(CreateSymTab, nullptr);
1195 int main(int argc, char **argv) {
1196 InitLLVM X(argc, argv);
1199 llvm::InitializeAllTargetInfos();
1200 llvm::InitializeAllTargetMCs();
1201 llvm::InitializeAllAsmParsers();
1203 Stem = sys::path::stem(ToolName);
1204 auto Is = [](StringRef Tool) {
1205 // We need to recognize the following filenames.
1207 // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe)
1208 // dlltool.exe -> dlltool
1209 // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar
1210 auto I = Stem.rfind_lower(Tool);
1211 return I != StringRef::npos &&
1212 (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
1216 return dlltoolDriverMain(makeArrayRef(argv, argc));
1218 return ranlib_main(argc, argv);
1220 return libDriverMain(makeArrayRef(argv, argc));
1222 return ar_main(argc, argv);
1224 fail("not ranlib, ar, lib or dlltool");