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/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"
46 #if !defined(_MSC_VER) && !defined(__MINGW32__)
53 #include "llvm/Support/Windows/WindowsSupport.h"
58 // The name this program was invoked as.
59 static StringRef ToolName;
61 // The basename of this program.
62 static StringRef Stem;
64 const char RanlibHelp[] = R"(OVERVIEW: LLVM Ranlib (llvm-ranlib)
66 This program generates an index to speed access to archives
68 USAGE: llvm-ranlib <archive-file>
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
77 const char ArHelp[] = R"(OVERVIEW: LLVM Archiver
79 USAGE: llvm-ar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files]
80 llvm-ar -M [<mri-script]
83 --format - archive format to create
88 --plugin=<string> - ignored for compatibility
89 -h --help - display this help and exit
90 --rsp-quoting - quoting style for response files
93 --version - print the version and exit
94 @<file> - read options from <file>
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
103 t - display contents of archive
104 x - extract [files] from the archive
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
128 static void printHelpMessage() {
129 if (Stem.contains_insensitive("ranlib"))
130 outs() << RanlibHelp;
131 else if (Stem.contains_insensitive("ar"))
135 static unsigned MRILineNumber;
136 static bool ParsingMRIScript;
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";
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";
151 WithColor::error(errs(), ToolName) << Error << "\n";
156 static void failIfError(std::error_code EC, Twine Context = "") {
160 std::string ContextStr = Context.str();
161 if (ContextStr.empty())
163 fail(Context + ": " + EC.message());
166 static void failIfError(Error E, Twine Context = "") {
170 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
171 std::string ContextStr = Context.str();
172 if (ContextStr.empty())
174 fail(Context + ": " + EIB.message());
178 static SmallVector<const char *, 256> PositionalArgs;
183 enum Format { Default, GNU, BSD, DARWIN, Unknown };
186 static Format FormatType = Default;
188 static std::string Options;
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
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
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
221 static std::string RelPos;
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;
228 // This variable holds the name of the archive file as given on the
230 static std::string ArchiveName;
232 static std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
233 static std::vector<std::unique_ptr<object::Archive>> Archives;
235 // This variable holds the list of member files to proecess, as given
236 // on the command line.
237 static std::vector<StringRef> Members;
239 // Static buffer to hold StringRefs.
240 static BumpPtrAllocator Alloc;
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());
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);
260 badUsage("value for [count] must be positive, got: " + CountParamArg);
261 PositionalArgs.erase(PositionalArgs.begin());
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());
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));
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();
285 static void runMRIScript();
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() {
292 if (!PositionalArgs.empty() || !Options.empty())
293 badUsage("cannot mix -M and other options");
297 // Keep track of number of operations. We can only specify one
299 unsigned NumOperations = 0;
301 // Keep track of the number of positional modifiers (a,b,i). Only
302 // one can be specified.
303 unsigned NumPositional = 0;
305 // Keep track of which operation was requested
306 ArchiveOperation Operation;
308 bool MaybeJustCreateSymTab = false;
310 for (unsigned i = 0; i < Options.size(); ++i) {
311 switch (Options[i]) {
326 Operation = QuickAppend;
330 Operation = ReplaceOrInsert;
334 Operation = DisplayTable;
343 case 'l': /* accepted but unused */
346 OriginalDates = true;
349 DisplayMemberOffsets = true;
352 CompareFullPath = true;
356 MaybeJustCreateSymTab = true;
383 Deterministic = true;
386 Deterministic = false;
393 // Thin archives store path names, so P should be forced.
394 CompareFullPath = true;
400 cl::PrintVersionMessage();
406 badUsage(std::string("unknown option ") + Options[i]);
410 // At this point, the next thing on the command line must be
414 // Everything on the command line at this point is a member.
415 Members.assign(PositionalArgs.begin(), PositionalArgs.end());
417 if (NumOperations == 0 && MaybeJustCreateSymTab) {
419 Operation = CreateSymTab;
420 if (!Members.empty())
421 badUsage("the 's' operation takes only an archive as argument");
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");
437 if (Operation != Extract && Operation != Delete)
438 badUsage("the 'N' modifier can only be specified with the 'x' or 'd' "
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");
447 // Return the parsed operation to the caller
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) {
455 outs() << "Printing " << Name << "\n";
457 Expected<StringRef> DataOrErr = C.getBuffer();
458 failIfError(DataOrErr.takeError());
459 StringRef Data = *DataOrErr;
460 outs().write(Data.data(), Data.size());
463 // Utility function for printing out the file mode when the 't' operation is in
465 static void printMode(unsigned mode) {
466 outs() << ((mode & 004) ? "r" : "-");
467 outs() << ((mode & 002) ? "w" : "-");
468 outs() << ((mode & 001) ? "x" : "-");
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) {
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
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);
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) << '/';
511 if (DisplayMemberOffsets)
512 outs() << " 0x" << utohexstr(C.getDataOffset(), true);
517 static std::string normalizePath(StringRef Path) {
518 return CompareFullPath ? sys::path::convert_to_slash(Path)
519 : std::string(sys::path::filename(Path));
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.
528 SmallVector<wchar_t, 128> WPath1, WPath2;
529 failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path1), WPath1));
530 failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path2), WPath2));
532 return CompareStringOrdinal(WPath1.data(), WPath1.size(), WPath2.data(),
533 WPath2.size(), true) == CSTR_EQUAL;
535 return normalizePath(Path1) == normalizePath(Path2);
539 // Implement the 'x' operation. This function extracts files back to the file
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();
547 llvm::StringRef outputFilePath = sys::path::filename(Name);
549 outs() << "x - " << outputFilePath << '\n';
552 failIfError(sys::fs::openFileForWrite(outputFilePath, FD,
553 sys::fs::CD_CreateAlways,
554 sys::fs::OF_None, Mode),
558 raw_fd_ostream file(FD, false);
560 // Get the data and its length
561 Expected<StringRef> BufOrErr = C.getBuffer();
562 failIfError(BufOrErr.takeError());
563 StringRef Data = BufOrErr.get();
566 file.write(Data.data(), Data.size());
569 // If we're supposed to retain the original modification times, etc. do so
572 auto ModTimeOrErr = C.getLastModified();
573 failIfError(ModTimeOrErr.takeError());
575 sys::fs::setLastAccessAndModificationTime(FD, ModTimeOrErr.get()));
579 fail("Could not close the file");
582 static bool shouldCreateArchive(ArchiveOperation Op) {
593 case ReplaceOrInsert:
597 llvm_unreachable("Missing entry in covered switch.");
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");
605 bool Filter = !Members.empty();
606 StringMap<int> MemberCount;
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();
615 auto I = find_if(Members, [Name](StringRef Path) {
616 return comparePaths(Name, Path);
618 if (I == Members.end())
620 if (CountParam && ++MemberCount[Name] != CountParam)
627 llvm_unreachable("Not a read operation");
632 doDisplayTable(Name, C);
639 failIfError(std::move(Err));
644 for (StringRef Name : Members)
645 WithColor::error(errs(), ToolName) << "'" << Name << "' was not found\n";
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));
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));
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));
689 Members.push_back(std::move(*NMOrErr));
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
702 NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
704 if (sys::path::is_absolute(FileName))
705 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName));
707 Expected<std::string> PathOrErr =
708 computeArchiveRelativePath(ArchiveName, FileName);
709 NMOrErr->MemberName = Saver.save(
710 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName));
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));
727 Members.push_back(std::move(*NMOrErr));
738 static InsertAction computeInsertAction(ArchiveOperation Operation,
739 const object::Archive::Child &Member,
741 std::vector<StringRef>::iterator &Pos,
742 StringMap<int> &MemberCount) {
743 if (Operation == QuickAppend || Members.empty())
744 return IA_AddOldMember;
746 Members, [Name](StringRef Path) { return comparePaths(Name, Path); });
748 if (MI == Members.end())
749 return IA_AddOldMember;
753 if (Operation == Delete) {
754 if (CountParam && ++MemberCount[Name] != CountParam)
755 return IA_AddOldMember;
759 if (Operation == Move)
760 return IA_MoveOldMember;
762 if (Operation == ReplaceOrInsert) {
765 return IA_AddNewMember;
766 return IA_MoveNewMember;
769 // We could try to optimize this to a fstat, but it is not a common
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()) {
777 return IA_AddOldMember;
778 return IA_MoveOldMember;
782 return IA_AddNewMember;
783 return IA_MoveNewMember;
785 llvm_unreachable("No such operation");
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;
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);
812 std::vector<StringRef>::iterator MemberI = Members.end();
813 InsertAction Action =
814 computeInsertAction(Operation, Child, Name, MemberI, MemberCount);
816 case IA_AddOldMember:
817 addChildMember(Ret, Child, /*FlattenArchive=*/Thin);
819 case IA_AddNewMember:
820 addMember(Ret, *MemberI);
824 case IA_MoveOldMember:
825 addChildMember(Moved, Child, /*FlattenArchive=*/Thin);
827 case IA_MoveNewMember:
828 addMember(Moved, *MemberI);
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);
839 failIfError(std::move(Err));
842 if (Operation == Delete)
845 if (!RelPos.empty() && InsertPos == -1)
846 fail("insertion point not found");
849 InsertPos = Ret.size();
851 assert(unsigned(InsertPos) <= Ret.size());
853 for (auto &M : Moved) {
854 Ret.insert(Ret.begin() + Pos, std::move(M));
859 assert(Operation == QuickAppend);
860 for (auto &Member : Members)
861 addMember(Ret, Member, /*FlattenArchive=*/true);
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)));
875 static object::Archive::Kind getDefaultForHost() {
876 return Triple(sys::getProcessTriple()).isOSDarwin()
877 ? object::Archive::K_DARWIN
878 : object::Archive::K_GNU;
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);
887 return isa<object::MachOObjectFile>(**OptionalObject)
888 ? object::Archive::K_DARWIN
889 : object::Archive::K_GNU;
891 // squelch the error in case we had a non-object file
892 consumeError(OptionalObject.takeError());
894 // If we're adding a bitcode file to the archive, detect the Archive kind
895 // based on the target triple.
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;
905 // Squelch the error in case this was not a SymbolicFile.
906 consumeError(ObjOrErr.takeError());
910 return getDefaultForHost();
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;
919 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
921 object::Archive::Kind Kind;
922 switch (FormatType) {
925 Kind = object::Archive::K_GNU;
927 Kind = OldArchive->kind();
928 else if (NewMembersP)
929 Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front())
930 : getDefaultForHost();
932 Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front())
933 : getDefaultForHost();
936 Kind = object::Archive::K_GNU;
940 fail("only the gnu format has a thin mode");
941 Kind = object::Archive::K_BSD;
945 fail("only the gnu format has a thin mode");
946 Kind = object::Archive::K_DARWIN;
949 llvm_unreachable("");
953 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
954 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
955 failIfError(std::move(E), ArchiveName);
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())
968 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
971 static void performOperation(ArchiveOperation Operation,
972 object::Archive *OldArchive,
973 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
974 std::vector<NewArchiveMember> *NewMembers) {
979 performReadOperation(Operation, OldArchive);
985 case ReplaceOrInsert:
986 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
990 createSymbolTable(OldArchive);
993 llvm_unreachable("Unknown operation.");
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());
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);
1015 assert(EC == errc::no_such_file_or_directory);
1017 if (!shouldCreateArchive(Operation)) {
1018 failIfError(EC, Twine("unable to load '") + ArchiveName + "'");
1021 // Produce a warning if we should and we're creating the archive
1022 WithColor::warning(errs(), ToolName)
1023 << "creating " << ArchiveName << "\n";
1027 performOperation(Operation, nullptr, nullptr, NewMembers);
1031 static void runMRIScript() {
1032 enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
1034 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
1035 failIfError(Buf.getError());
1036 const MemoryBuffer &Ref = *Buf.get();
1038 std::vector<NewArchiveMember> NewMembers;
1039 ParsingMRIScript = true;
1041 for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
1043 StringRef Line = *I;
1044 Line = Line.split(';').first;
1045 Line = Line.split('*').first;
1049 StringRef CommandStr, Rest;
1050 std::tie(CommandStr, Rest) = Line.split(' ');
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);
1065 case MRICommand::AddLib: {
1066 object::Archive &Lib = readLibrary(Rest);
1068 Error Err = Error::success();
1069 for (auto &Member : Lib.children(Err))
1070 addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
1071 failIfError(std::move(Err));
1075 case MRICommand::AddMod:
1076 addMember(NewMembers, Rest);
1078 case MRICommand::CreateThin:
1081 case MRICommand::Create:
1083 if (!ArchiveName.empty())
1084 fail("editing multiple archives not supported");
1086 fail("file already saved");
1087 ArchiveName = std::string(Rest);
1089 case MRICommand::Delete: {
1090 llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
1091 return comparePaths(M.MemberName, Rest);
1095 case MRICommand::Save:
1098 case MRICommand::End:
1100 case MRICommand::Invalid:
1101 fail("unknown command: " + CommandStr);
1105 ParsingMRIScript = false;
1107 // Nothing to do if not saved.
1109 performOperation(ReplaceOrInsert, &NewMembers);
1113 static bool handleGenericOption(StringRef arg) {
1114 if (arg == "-help" || arg == "--help" || arg == "-h") {
1118 if (arg == "-version" || arg == "--version") {
1119 cl::PrintVersionMessage();
1125 static const char *matchFlagWithArg(StringRef Expected,
1126 ArrayRef<const char *>::iterator &ArgIt,
1127 ArrayRef<const char *> Args) {
1128 StringRef Arg = *ArgIt;
1130 if (Arg.startswith("--"))
1131 Arg = Arg.substr(2);
1132 else if (Arg.startswith("-"))
1133 Arg = Arg.substr(1);
1135 size_t len = Expected.size();
1136 if (Arg == Expected) {
1137 if (++ArgIt == Args.end())
1138 fail(std::string(Expected) + " requires an argument");
1142 if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=')
1143 return Arg.data() + len + 1;
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;
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;
1163 fail(std::string("Invalid response file quoting style ") + Match);
1170 static int ar_main(int argc, char **argv) {
1171 SmallVector<const char *, 0> Argv(argv + 1, argv + argc);
1172 StringSaver Saver(Alloc);
1174 cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv);
1176 for (ArrayRef<const char *>::iterator ArgIt = Argv.begin();
1177 ArgIt != Argv.end(); ++ArgIt) {
1178 const char *Match = nullptr;
1180 if (handleGenericOption(*ArgIt))
1182 if (strcmp(*ArgIt, "--") == 0) {
1184 for (; ArgIt != Argv.end(); ++ArgIt)
1185 PositionalArgs.push_back(*ArgIt);
1189 if (*ArgIt[0] != '-') {
1190 if (Options.empty())
1193 PositionalArgs.push_back(*ArgIt);
1197 if (strcmp(*ArgIt, "-M") == 0) {
1202 Match = matchFlagWithArg("format", ArgIt, Argv);
1204 FormatType = StringSwitch<Format>(Match)
1205 .Case("default", Default)
1207 .Case("darwin", DARWIN)
1210 if (FormatType == Unknown)
1211 fail(std::string("Invalid format ") + Match);
1215 if (matchFlagWithArg("plugin", ArgIt, Argv) ||
1216 matchFlagWithArg("rsp-quoting", ArgIt, Argv))
1219 Options += *ArgIt + 1;
1222 ArchiveOperation Operation = parseCommandLine();
1223 return performOperation(Operation, nullptr);
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)) {
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') {
1242 } else if (arg.front() == 'v') {
1243 cl::PrintVersionMessage();
1246 // TODO: GNU ranlib also supports a -t flag
1247 fail("Invalid option: '-" + arg + "'");
1249 arg = arg.drop_front(1);
1252 if (ArchiveSpecified)
1253 fail("exactly one archive should be specified");
1254 ArchiveSpecified = true;
1255 ArchiveName = arg.str();
1258 if (!ArchiveSpecified) {
1259 badUsage("an archive name must be specified");
1261 return performOperation(CreateSymTab, nullptr);
1264 int main(int argc, char **argv) {
1265 InitLLVM X(argc, argv);
1268 llvm::InitializeAllTargetInfos();
1269 llvm::InitializeAllTargetMCs();
1270 llvm::InitializeAllAsmParsers();
1272 Stem = sys::path::stem(ToolName);
1273 auto Is = [](StringRef Tool) {
1274 // We need to recognize the following filenames.
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()]));
1285 return dlltoolDriverMain(makeArrayRef(argv, argc));
1287 return ranlib_main(argc, argv);
1289 return libDriverMain(makeArrayRef(argv, argc));
1291 return ar_main(argc, argv);
1293 fail("not ranlib, ar, lib or dlltool");