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 --thin - create a thin archive
94 --version - print the version and exit
95 @<file> - read options from <file>
98 d - delete [files] from the archive
99 m - move [files] in the archive
100 p - print contents of [files] found in the archive
101 q - quick append [files] to the archive
102 r - replace or insert [files] into the archive
104 t - display list of files in archive
105 x - extract [files] from the archive
108 [a] - put [files] after [relpos]
109 [b] - put [files] before [relpos] (same as [i])
110 [c] - do not warn if archive had to be created
111 [D] - use zero for timestamps and uids/gids (default)
112 [h] - display this help and exit
113 [i] - put [files] before [relpos] (same as [b])
114 [l] - ignored for compatibility
115 [L] - add archive's contents
116 [N] - use instance [count] of name
117 [o] - preserve original dates
118 [O] - display member offsets
119 [P] - use full names when matching (implied for thin archives)
120 [s] - create an archive index (cf. ranlib)
121 [S] - do not build a symbol table
122 [T] - deprecated, use --thin instead
123 [u] - update only [files] newer than archive contents
124 [U] - use actual timestamps and uids/gids
125 [v] - be verbose about actions taken
126 [V] - display the version and exit
129 static void printHelpMessage() {
130 if (Stem.contains_insensitive("ranlib"))
131 outs() << RanlibHelp;
132 else if (Stem.contains_insensitive("ar"))
136 static unsigned MRILineNumber;
137 static bool ParsingMRIScript;
139 // Show the error plus the usage message, and exit.
140 [[noreturn]] static void badUsage(Twine Error) {
141 WithColor::error(errs(), ToolName) << Error << "\n";
146 // Show the error message and exit.
147 [[noreturn]] static void fail(Twine Error) {
148 if (ParsingMRIScript) {
149 WithColor::error(errs(), ToolName)
150 << "script line " << MRILineNumber << ": " << Error << "\n";
152 WithColor::error(errs(), ToolName) << Error << "\n";
157 static void failIfError(std::error_code EC, Twine Context = "") {
161 std::string ContextStr = Context.str();
162 if (ContextStr.empty())
164 fail(Context + ": " + EC.message());
167 static void failIfError(Error E, Twine Context = "") {
171 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
172 std::string ContextStr = Context.str();
173 if (ContextStr.empty())
175 fail(Context + ": " + EIB.message());
179 static SmallVector<const char *, 256> PositionalArgs;
184 enum Format { Default, GNU, BSD, DARWIN, Unknown };
187 static Format FormatType = Default;
189 static std::string Options;
191 // This enumeration delineates the kinds of operations on an archive
192 // that are permitted.
193 enum ArchiveOperation {
194 Print, ///< Print the contents of the archive
195 Delete, ///< Delete the specified members
196 Move, ///< Move members to end or as given by {a,b,i} modifiers
197 QuickAppend, ///< Quickly append to end of archive
198 ReplaceOrInsert, ///< Replace or Insert members
199 DisplayTable, ///< Display the table of contents
200 Extract, ///< Extract files back to file system
201 CreateSymTab ///< Create a symbol table in an existing archive
204 // Modifiers to follow operation to vary behavior
205 static bool AddAfter = false; ///< 'a' modifier
206 static bool AddBefore = false; ///< 'b' modifier
207 static bool Create = false; ///< 'c' modifier
208 static bool OriginalDates = false; ///< 'o' modifier
209 static bool DisplayMemberOffsets = false; ///< 'O' modifier
210 static bool CompareFullPath = false; ///< 'P' modifier
211 static bool OnlyUpdate = false; ///< 'u' modifier
212 static bool Verbose = false; ///< 'v' modifier
213 static bool Symtab = true; ///< 's' modifier
214 static bool Deterministic = true; ///< 'D' and 'U' modifiers
215 static bool Thin = false; ///< 'T' modifier
216 static bool AddLibrary = false; ///< 'L' modifier
218 // Relative Positional Argument (for insert/move). This variable holds
219 // the name of the archive member to which the 'a', 'b' or 'i' modifier
220 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
222 static std::string RelPos;
224 // Count parameter for 'N' modifier. This variable specifies which file should
225 // match for extract/delete operations when there are multiple matches. This is
226 // 1-indexed. A value of 0 is invalid, and implies 'N' is not used.
227 static int CountParam = 0;
229 // This variable holds the name of the archive file as given on the
231 static std::string ArchiveName;
233 static std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
234 static std::vector<std::unique_ptr<object::Archive>> Archives;
236 // This variable holds the list of member files to proecess, as given
237 // on the command line.
238 static std::vector<StringRef> Members;
240 // Static buffer to hold StringRefs.
241 static BumpPtrAllocator Alloc;
243 // Extract the member filename from the command line for the [relpos] argument
244 // associated with a, b, and i modifiers
245 static void getRelPos() {
246 if (PositionalArgs.empty())
247 fail("expected [relpos] for 'a', 'b', or 'i' modifier");
248 RelPos = PositionalArgs[0];
249 PositionalArgs.erase(PositionalArgs.begin());
252 // Extract the parameter from the command line for the [count] argument
253 // associated with the N modifier
254 static void getCountParam() {
255 if (PositionalArgs.empty())
256 badUsage("expected [count] for 'N' modifier");
257 auto CountParamArg = StringRef(PositionalArgs[0]);
258 if (CountParamArg.getAsInteger(10, CountParam))
259 badUsage("value for [count] must be numeric, got: " + CountParamArg);
261 badUsage("value for [count] must be positive, got: " + CountParamArg);
262 PositionalArgs.erase(PositionalArgs.begin());
265 // Get the archive file name from the command line
266 static void getArchive() {
267 if (PositionalArgs.empty())
268 badUsage("an archive name must be specified");
269 ArchiveName = PositionalArgs[0];
270 PositionalArgs.erase(PositionalArgs.begin());
273 static object::Archive &readLibrary(const Twine &Library) {
274 auto BufOrErr = MemoryBuffer::getFile(Library, /*IsText=*/false,
275 /*RequiresNullTerminator=*/false);
276 failIfError(BufOrErr.getError(), "could not open library " + Library);
277 ArchiveBuffers.push_back(std::move(*BufOrErr));
279 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
280 failIfError(errorToErrorCode(LibOrErr.takeError()),
281 "could not parse library");
282 Archives.push_back(std::move(*LibOrErr));
283 return *Archives.back();
286 static void runMRIScript();
288 // Parse the command line options as presented and return the operation
289 // specified. Process all modifiers and check to make sure that constraints on
290 // modifier/operation pairs have not been violated.
291 static ArchiveOperation parseCommandLine() {
293 if (!PositionalArgs.empty() || !Options.empty())
294 badUsage("cannot mix -M and other options");
298 // Keep track of number of operations. We can only specify one
300 unsigned NumOperations = 0;
302 // Keep track of the number of positional modifiers (a,b,i). Only
303 // one can be specified.
304 unsigned NumPositional = 0;
306 // Keep track of which operation was requested
307 ArchiveOperation Operation;
309 bool MaybeJustCreateSymTab = false;
311 for (unsigned i = 0; i < Options.size(); ++i) {
312 switch (Options[i]) {
327 Operation = QuickAppend;
331 Operation = ReplaceOrInsert;
335 Operation = DisplayTable;
344 case 'l': /* accepted but unused */
347 OriginalDates = true;
350 DisplayMemberOffsets = true;
353 CompareFullPath = true;
357 MaybeJustCreateSymTab = true;
384 Deterministic = true;
387 Deterministic = false;
399 cl::PrintVersionMessage();
405 badUsage(std::string("unknown option ") + Options[i]);
409 // Thin archives store path names, so P should be forced.
411 CompareFullPath = true;
413 // At this point, the next thing on the command line must be
417 // Everything on the command line at this point is a member.
418 Members.assign(PositionalArgs.begin(), PositionalArgs.end());
420 if (NumOperations == 0 && MaybeJustCreateSymTab) {
422 Operation = CreateSymTab;
423 if (!Members.empty())
424 badUsage("the 's' operation takes only an archive as argument");
427 // Perform various checks on the operation/modifier specification
428 // to make sure we are dealing with a legal request.
429 if (NumOperations == 0)
430 badUsage("you must specify at least one of the operations");
431 if (NumOperations > 1)
432 badUsage("only one operation may be specified");
433 if (NumPositional > 1)
434 badUsage("you may only specify one of 'a', 'b', and 'i' modifiers");
435 if (AddAfter || AddBefore)
436 if (Operation != Move && Operation != ReplaceOrInsert)
437 badUsage("the 'a', 'b' and 'i' modifiers can only be specified with "
438 "the 'm' or 'r' operations");
440 if (Operation != Extract && Operation != Delete)
441 badUsage("the 'N' modifier can only be specified with the 'x' or 'd' "
443 if (OriginalDates && Operation != Extract)
444 badUsage("the 'o' modifier is only applicable to the 'x' operation");
445 if (OnlyUpdate && Operation != ReplaceOrInsert)
446 badUsage("the 'u' modifier is only applicable to the 'r' operation");
447 if (AddLibrary && Operation != QuickAppend)
448 badUsage("the 'L' modifier is only applicable to the 'q' operation");
450 // Return the parsed operation to the caller
454 // Implements the 'p' operation. This function traverses the archive
455 // looking for members that match the path list.
456 static void doPrint(StringRef Name, const object::Archive::Child &C) {
458 outs() << "Printing " << Name << "\n";
460 Expected<StringRef> DataOrErr = C.getBuffer();
461 failIfError(DataOrErr.takeError());
462 StringRef Data = *DataOrErr;
463 outs().write(Data.data(), Data.size());
466 // Utility function for printing out the file mode when the 't' operation is in
468 static void printMode(unsigned mode) {
469 outs() << ((mode & 004) ? "r" : "-");
470 outs() << ((mode & 002) ? "w" : "-");
471 outs() << ((mode & 001) ? "x" : "-");
474 // Implement the 't' operation. This function prints out just
475 // the file names of each of the members. However, if verbose mode is requested
476 // ('v' modifier) then the file type, permission mode, user, group, size, and
477 // modification time are also printed.
478 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
480 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
481 failIfError(ModeOrErr.takeError());
482 sys::fs::perms Mode = ModeOrErr.get();
483 printMode((Mode >> 6) & 007);
484 printMode((Mode >> 3) & 007);
485 printMode(Mode & 007);
486 Expected<unsigned> UIDOrErr = C.getUID();
487 failIfError(UIDOrErr.takeError());
488 outs() << ' ' << UIDOrErr.get();
489 Expected<unsigned> GIDOrErr = C.getGID();
490 failIfError(GIDOrErr.takeError());
491 outs() << '/' << GIDOrErr.get();
492 Expected<uint64_t> Size = C.getSize();
493 failIfError(Size.takeError());
494 outs() << ' ' << format("%6llu", Size.get());
495 auto ModTimeOrErr = C.getLastModified();
496 failIfError(ModTimeOrErr.takeError());
497 // Note: formatv() only handles the default TimePoint<>, which is in
499 // TODO: fix format_provider<TimePoint<>> to allow other units.
500 sys::TimePoint<> ModTimeInNs = ModTimeOrErr.get();
501 outs() << ' ' << formatv("{0:%b %e %H:%M %Y}", ModTimeInNs);
505 if (C.getParent()->isThin()) {
506 if (!sys::path::is_absolute(Name)) {
507 StringRef ParentDir = sys::path::parent_path(ArchiveName);
508 if (!ParentDir.empty())
509 outs() << sys::path::convert_to_slash(ParentDir) << '/';
514 if (DisplayMemberOffsets)
515 outs() << " 0x" << utohexstr(C.getDataOffset(), true);
520 static std::string normalizePath(StringRef Path) {
521 return CompareFullPath ? sys::path::convert_to_slash(Path)
522 : std::string(sys::path::filename(Path));
525 static bool comparePaths(StringRef Path1, StringRef Path2) {
526 // When on Windows this function calls CompareStringOrdinal
527 // as Windows file paths are case-insensitive.
528 // CompareStringOrdinal compares two Unicode strings for
529 // binary equivalence and allows for case insensitivity.
531 SmallVector<wchar_t, 128> WPath1, WPath2;
532 failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path1), WPath1));
533 failIfError(sys::windows::UTF8ToUTF16(normalizePath(Path2), WPath2));
535 return CompareStringOrdinal(WPath1.data(), WPath1.size(), WPath2.data(),
536 WPath2.size(), true) == CSTR_EQUAL;
538 return normalizePath(Path1) == normalizePath(Path2);
542 // Implement the 'x' operation. This function extracts files back to the file
544 static void doExtract(StringRef Name, const object::Archive::Child &C) {
545 // Retain the original mode.
546 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
547 failIfError(ModeOrErr.takeError());
548 sys::fs::perms Mode = ModeOrErr.get();
550 llvm::StringRef outputFilePath = sys::path::filename(Name);
552 outs() << "x - " << outputFilePath << '\n';
555 failIfError(sys::fs::openFileForWrite(outputFilePath, FD,
556 sys::fs::CD_CreateAlways,
557 sys::fs::OF_None, Mode),
561 raw_fd_ostream file(FD, false);
563 // Get the data and its length
564 Expected<StringRef> BufOrErr = C.getBuffer();
565 failIfError(BufOrErr.takeError());
566 StringRef Data = BufOrErr.get();
569 file.write(Data.data(), Data.size());
572 // If we're supposed to retain the original modification times, etc. do so
575 auto ModTimeOrErr = C.getLastModified();
576 failIfError(ModTimeOrErr.takeError());
578 sys::fs::setLastAccessAndModificationTime(FD, ModTimeOrErr.get()));
582 fail("Could not close the file");
585 static bool shouldCreateArchive(ArchiveOperation Op) {
596 case ReplaceOrInsert:
600 llvm_unreachable("Missing entry in covered switch.");
603 static void performReadOperation(ArchiveOperation Operation,
604 object::Archive *OldArchive) {
605 if (Operation == Extract && OldArchive->isThin())
606 fail("extracting from a thin archive is not supported");
608 bool Filter = !Members.empty();
609 StringMap<int> MemberCount;
611 Error Err = Error::success();
612 for (auto &C : OldArchive->children(Err)) {
613 Expected<StringRef> NameOrErr = C.getName();
614 failIfError(NameOrErr.takeError());
615 StringRef Name = NameOrErr.get();
618 auto I = find_if(Members, [Name](StringRef Path) {
619 return comparePaths(Name, Path);
621 if (I == Members.end())
623 if (CountParam && ++MemberCount[Name] != CountParam)
630 llvm_unreachable("Not a read operation");
635 doDisplayTable(Name, C);
642 failIfError(std::move(Err));
647 for (StringRef Name : Members)
648 WithColor::error(errs(), ToolName) << "'" << Name << "' was not found\n";
652 static void addChildMember(std::vector<NewArchiveMember> &Members,
653 const object::Archive::Child &M,
654 bool FlattenArchive = false) {
655 if (Thin && !M.getParent()->isThin())
656 fail("cannot convert a regular archive to a thin one");
657 Expected<NewArchiveMember> NMOrErr =
658 NewArchiveMember::getOldMember(M, Deterministic);
659 failIfError(NMOrErr.takeError());
660 // If the child member we're trying to add is thin, use the path relative to
661 // the archive it's in, so the file resolves correctly.
662 if (Thin && FlattenArchive) {
663 StringSaver Saver(Alloc);
664 Expected<std::string> FileNameOrErr(M.getName());
665 failIfError(FileNameOrErr.takeError());
666 if (sys::path::is_absolute(*FileNameOrErr)) {
667 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(*FileNameOrErr));
669 FileNameOrErr = M.getFullName();
670 failIfError(FileNameOrErr.takeError());
671 Expected<std::string> PathOrErr =
672 computeArchiveRelativePath(ArchiveName, *FileNameOrErr);
673 NMOrErr->MemberName = Saver.save(
674 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(*FileNameOrErr));
677 if (FlattenArchive &&
678 identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
679 Expected<std::string> FileNameOrErr = M.getFullName();
680 failIfError(FileNameOrErr.takeError());
681 object::Archive &Lib = readLibrary(*FileNameOrErr);
682 // When creating thin archives, only flatten if the member is also thin.
683 if (!Thin || Lib.isThin()) {
684 Error Err = Error::success();
685 // Only Thin archives are recursively flattened.
686 for (auto &Child : Lib.children(Err))
687 addChildMember(Members, Child, /*FlattenArchive=*/Thin);
688 failIfError(std::move(Err));
692 Members.push_back(std::move(*NMOrErr));
695 static void addMember(std::vector<NewArchiveMember> &Members,
696 StringRef FileName, bool FlattenArchive = false) {
697 Expected<NewArchiveMember> NMOrErr =
698 NewArchiveMember::getFile(FileName, Deterministic);
699 failIfError(NMOrErr.takeError(), FileName);
700 StringSaver Saver(Alloc);
701 // For regular archives, use the basename of the object path for the member
702 // name. For thin archives, use the full relative paths so the file resolves
705 NMOrErr->MemberName = sys::path::filename(NMOrErr->MemberName);
707 if (sys::path::is_absolute(FileName))
708 NMOrErr->MemberName = Saver.save(sys::path::convert_to_slash(FileName));
710 Expected<std::string> PathOrErr =
711 computeArchiveRelativePath(ArchiveName, FileName);
712 NMOrErr->MemberName = Saver.save(
713 PathOrErr ? *PathOrErr : sys::path::convert_to_slash(FileName));
717 if (FlattenArchive &&
718 identify_magic(NMOrErr->Buf->getBuffer()) == file_magic::archive) {
719 object::Archive &Lib = readLibrary(FileName);
720 // When creating thin archives, only flatten if the member is also thin.
721 if (!Thin || Lib.isThin()) {
722 Error Err = Error::success();
723 // Only Thin archives are recursively flattened.
724 for (auto &Child : Lib.children(Err))
725 addChildMember(Members, Child, /*FlattenArchive=*/Thin);
726 failIfError(std::move(Err));
730 Members.push_back(std::move(*NMOrErr));
741 static InsertAction computeInsertAction(ArchiveOperation Operation,
742 const object::Archive::Child &Member,
744 std::vector<StringRef>::iterator &Pos,
745 StringMap<int> &MemberCount) {
746 if (Operation == QuickAppend || Members.empty())
747 return IA_AddOldMember;
749 Members, [Name](StringRef Path) { return comparePaths(Name, Path); });
751 if (MI == Members.end())
752 return IA_AddOldMember;
756 if (Operation == Delete) {
757 if (CountParam && ++MemberCount[Name] != CountParam)
758 return IA_AddOldMember;
762 if (Operation == Move)
763 return IA_MoveOldMember;
765 if (Operation == ReplaceOrInsert) {
768 return IA_AddNewMember;
769 return IA_MoveNewMember;
772 // We could try to optimize this to a fstat, but it is not a common
774 sys::fs::file_status Status;
775 failIfError(sys::fs::status(*MI, Status), *MI);
776 auto ModTimeOrErr = Member.getLastModified();
777 failIfError(ModTimeOrErr.takeError());
778 if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
780 return IA_AddOldMember;
781 return IA_MoveOldMember;
785 return IA_AddNewMember;
786 return IA_MoveNewMember;
788 llvm_unreachable("No such operation");
791 // We have to walk this twice and computing it is not trivial, so creating an
792 // explicit std::vector is actually fairly efficient.
793 static std::vector<NewArchiveMember>
794 computeNewArchiveMembers(ArchiveOperation Operation,
795 object::Archive *OldArchive) {
796 std::vector<NewArchiveMember> Ret;
797 std::vector<NewArchiveMember> Moved;
800 Error Err = Error::success();
801 StringMap<int> MemberCount;
802 for (auto &Child : OldArchive->children(Err)) {
803 int Pos = Ret.size();
804 Expected<StringRef> NameOrErr = Child.getName();
805 failIfError(NameOrErr.takeError());
806 std::string Name = std::string(NameOrErr.get());
807 if (comparePaths(Name, RelPos)) {
808 assert(AddAfter || AddBefore);
815 std::vector<StringRef>::iterator MemberI = Members.end();
816 InsertAction Action =
817 computeInsertAction(Operation, Child, Name, MemberI, MemberCount);
819 case IA_AddOldMember:
820 addChildMember(Ret, Child, /*FlattenArchive=*/Thin);
822 case IA_AddNewMember:
823 addMember(Ret, *MemberI);
827 case IA_MoveOldMember:
828 addChildMember(Moved, Child, /*FlattenArchive=*/Thin);
830 case IA_MoveNewMember:
831 addMember(Moved, *MemberI);
834 // When processing elements with the count param, we need to preserve the
835 // full members list when iterating over all archive members. For
836 // instance, "llvm-ar dN 2 archive.a member.o" should delete the second
837 // file named member.o it sees; we are not done with member.o the first
838 // time we see it in the archive.
839 if (MemberI != Members.end() && !CountParam)
840 Members.erase(MemberI);
842 failIfError(std::move(Err));
845 if (Operation == Delete)
848 if (!RelPos.empty() && InsertPos == -1)
849 fail("insertion point not found");
852 InsertPos = Ret.size();
854 assert(unsigned(InsertPos) <= Ret.size());
856 for (auto &M : Moved) {
857 Ret.insert(Ret.begin() + Pos, std::move(M));
862 assert(Operation == QuickAppend);
863 for (auto &Member : Members)
864 addMember(Ret, Member, /*FlattenArchive=*/true);
868 std::vector<NewArchiveMember> NewMembers;
869 for (auto &Member : Members)
870 addMember(NewMembers, Member, /*FlattenArchive=*/Thin);
871 Ret.reserve(Ret.size() + NewMembers.size());
872 std::move(NewMembers.begin(), NewMembers.end(),
873 std::inserter(Ret, std::next(Ret.begin(), InsertPos)));
878 static object::Archive::Kind getDefaultForHost() {
879 return Triple(sys::getProcessTriple()).isOSDarwin()
880 ? object::Archive::K_DARWIN
881 : object::Archive::K_GNU;
884 static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
885 auto MemBufferRef = Member.Buf->getMemBufferRef();
886 Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
887 object::ObjectFile::createObjectFile(MemBufferRef);
890 return isa<object::MachOObjectFile>(**OptionalObject)
891 ? object::Archive::K_DARWIN
892 : object::Archive::K_GNU;
894 // squelch the error in case we had a non-object file
895 consumeError(OptionalObject.takeError());
897 // If we're adding a bitcode file to the archive, detect the Archive kind
898 // based on the target triple.
900 if (identify_magic(MemBufferRef.getBuffer()) == file_magic::bitcode) {
901 if (auto ObjOrErr = object::SymbolicFile::createSymbolicFile(
902 MemBufferRef, file_magic::bitcode, &Context)) {
903 auto &IRObject = cast<object::IRObjectFile>(**ObjOrErr);
904 return Triple(IRObject.getTargetTriple()).isOSDarwin()
905 ? object::Archive::K_DARWIN
906 : object::Archive::K_GNU;
908 // Squelch the error in case this was not a SymbolicFile.
909 consumeError(ObjOrErr.takeError());
913 return getDefaultForHost();
916 static void performWriteOperation(ArchiveOperation Operation,
917 object::Archive *OldArchive,
918 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
919 std::vector<NewArchiveMember> *NewMembersP) {
920 std::vector<NewArchiveMember> NewMembers;
922 NewMembers = computeNewArchiveMembers(Operation, OldArchive);
924 object::Archive::Kind Kind;
925 switch (FormatType) {
928 Kind = object::Archive::K_GNU;
930 Kind = OldArchive->kind();
931 else if (NewMembersP)
932 Kind = !NewMembersP->empty() ? getKindFromMember(NewMembersP->front())
933 : getDefaultForHost();
935 Kind = !NewMembers.empty() ? getKindFromMember(NewMembers.front())
936 : getDefaultForHost();
939 Kind = object::Archive::K_GNU;
943 fail("only the gnu format has a thin mode");
944 Kind = object::Archive::K_BSD;
948 fail("only the gnu format has a thin mode");
949 Kind = object::Archive::K_DARWIN;
952 llvm_unreachable("");
956 writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
957 Kind, Deterministic, Thin, std::move(OldArchiveBuf));
958 failIfError(std::move(E), ArchiveName);
961 static void createSymbolTable(object::Archive *OldArchive) {
962 // When an archive is created or modified, if the s option is given, the
963 // resulting archive will have a current symbol table. If the S option
964 // is given, it will have no symbol table.
965 // In summary, we only need to update the symbol table if we have none.
966 // This is actually very common because of broken build systems that think
967 // they have to run ranlib.
968 if (OldArchive->hasSymbolTable())
971 if (OldArchive->isThin())
973 performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
976 static void performOperation(ArchiveOperation Operation,
977 object::Archive *OldArchive,
978 std::unique_ptr<MemoryBuffer> OldArchiveBuf,
979 std::vector<NewArchiveMember> *NewMembers) {
984 performReadOperation(Operation, OldArchive);
990 case ReplaceOrInsert:
991 performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
995 createSymbolTable(OldArchive);
998 llvm_unreachable("Unknown operation.");
1001 static int performOperation(ArchiveOperation Operation,
1002 std::vector<NewArchiveMember> *NewMembers) {
1003 // Create or open the archive object.
1004 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getFile(
1005 ArchiveName, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1006 std::error_code EC = Buf.getError();
1007 if (EC && EC != errc::no_such_file_or_directory)
1008 fail("unable to open '" + ArchiveName + "': " + EC.message());
1011 Expected<std::unique_ptr<object::Archive>> ArchiveOrError =
1012 object::Archive::create(Buf.get()->getMemBufferRef());
1013 if (!ArchiveOrError)
1014 failIfError(ArchiveOrError.takeError(),
1015 "unable to load '" + ArchiveName + "'");
1017 std::unique_ptr<object::Archive> Archive = std::move(ArchiveOrError.get());
1018 if (Archive->isThin())
1019 CompareFullPath = true;
1020 performOperation(Operation, Archive.get(), std::move(Buf.get()),
1025 assert(EC == errc::no_such_file_or_directory);
1027 if (!shouldCreateArchive(Operation)) {
1028 failIfError(EC, Twine("unable to load '") + ArchiveName + "'");
1031 // Produce a warning if we should and we're creating the archive
1032 WithColor::warning(errs(), ToolName)
1033 << "creating " << ArchiveName << "\n";
1037 performOperation(Operation, nullptr, nullptr, NewMembers);
1041 static void runMRIScript() {
1042 enum class MRICommand { AddLib, AddMod, Create, CreateThin, Delete, Save, End, Invalid };
1044 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
1045 failIfError(Buf.getError());
1046 const MemoryBuffer &Ref = *Buf.get();
1048 std::vector<NewArchiveMember> NewMembers;
1049 ParsingMRIScript = true;
1051 for (line_iterator I(Ref, /*SkipBlanks*/ false), E; I != E; ++I) {
1053 StringRef Line = *I;
1054 Line = Line.split(';').first;
1055 Line = Line.split('*').first;
1059 StringRef CommandStr, Rest;
1060 std::tie(CommandStr, Rest) = Line.split(' ');
1062 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
1063 Rest = Rest.drop_front().drop_back();
1064 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
1065 .Case("addlib", MRICommand::AddLib)
1066 .Case("addmod", MRICommand::AddMod)
1067 .Case("create", MRICommand::Create)
1068 .Case("createthin", MRICommand::CreateThin)
1069 .Case("delete", MRICommand::Delete)
1070 .Case("save", MRICommand::Save)
1071 .Case("end", MRICommand::End)
1072 .Default(MRICommand::Invalid);
1075 case MRICommand::AddLib: {
1076 object::Archive &Lib = readLibrary(Rest);
1078 Error Err = Error::success();
1079 for (auto &Member : Lib.children(Err))
1080 addChildMember(NewMembers, Member, /*FlattenArchive=*/Thin);
1081 failIfError(std::move(Err));
1085 case MRICommand::AddMod:
1086 addMember(NewMembers, Rest);
1088 case MRICommand::CreateThin:
1091 case MRICommand::Create:
1093 if (!ArchiveName.empty())
1094 fail("editing multiple archives not supported");
1096 fail("file already saved");
1097 ArchiveName = std::string(Rest);
1099 case MRICommand::Delete: {
1100 llvm::erase_if(NewMembers, [=](NewArchiveMember &M) {
1101 return comparePaths(M.MemberName, Rest);
1105 case MRICommand::Save:
1108 case MRICommand::End:
1110 case MRICommand::Invalid:
1111 fail("unknown command: " + CommandStr);
1115 ParsingMRIScript = false;
1117 // Nothing to do if not saved.
1119 performOperation(ReplaceOrInsert, &NewMembers);
1123 static bool handleGenericOption(StringRef arg) {
1124 if (arg == "--help" || arg == "-h") {
1128 if (arg == "--version") {
1129 cl::PrintVersionMessage();
1135 static const char *matchFlagWithArg(StringRef Expected,
1136 ArrayRef<const char *>::iterator &ArgIt,
1137 ArrayRef<const char *> Args) {
1138 StringRef Arg = *ArgIt;
1140 if (Arg.startswith("--"))
1141 Arg = Arg.substr(2);
1143 size_t len = Expected.size();
1144 if (Arg == Expected) {
1145 if (++ArgIt == Args.end())
1146 fail(std::string(Expected) + " requires an argument");
1150 if (Arg.startswith(Expected) && Arg.size() > len && Arg[len] == '=')
1151 return Arg.data() + len + 1;
1156 static cl::TokenizerCallback getRspQuoting(ArrayRef<const char *> ArgsArr) {
1157 cl::TokenizerCallback Ret =
1158 Triple(sys::getProcessTriple()).getOS() == Triple::Win32
1159 ? cl::TokenizeWindowsCommandLine
1160 : cl::TokenizeGNUCommandLine;
1162 for (ArrayRef<const char *>::iterator ArgIt = ArgsArr.begin();
1163 ArgIt != ArgsArr.end(); ++ArgIt) {
1164 if (const char *Match = matchFlagWithArg("rsp-quoting", ArgIt, ArgsArr)) {
1165 StringRef MatchRef = Match;
1166 if (MatchRef == "posix")
1167 Ret = cl::TokenizeGNUCommandLine;
1168 else if (MatchRef == "windows")
1169 Ret = cl::TokenizeWindowsCommandLine;
1171 fail(std::string("Invalid response file quoting style ") + Match);
1178 static int ar_main(int argc, char **argv) {
1179 SmallVector<const char *, 0> Argv(argv + 1, argv + argc);
1180 StringSaver Saver(Alloc);
1182 cl::ExpandResponseFiles(Saver, getRspQuoting(makeArrayRef(argv, argc)), Argv);
1184 for (ArrayRef<const char *>::iterator ArgIt = Argv.begin();
1185 ArgIt != Argv.end(); ++ArgIt) {
1186 const char *Match = nullptr;
1188 if (handleGenericOption(*ArgIt))
1190 if (strcmp(*ArgIt, "--") == 0) {
1192 for (; ArgIt != Argv.end(); ++ArgIt)
1193 PositionalArgs.push_back(*ArgIt);
1197 if (*ArgIt[0] != '-') {
1198 if (Options.empty())
1201 PositionalArgs.push_back(*ArgIt);
1205 if (strcmp(*ArgIt, "-M") == 0) {
1210 if (strcmp(*ArgIt, "--thin") == 0) {
1215 Match = matchFlagWithArg("format", ArgIt, Argv);
1217 FormatType = StringSwitch<Format>(Match)
1218 .Case("default", Default)
1220 .Case("darwin", DARWIN)
1223 if (FormatType == Unknown)
1224 fail(std::string("Invalid format ") + Match);
1228 if (matchFlagWithArg("plugin", ArgIt, Argv) ||
1229 matchFlagWithArg("rsp-quoting", ArgIt, Argv))
1232 Options += *ArgIt + 1;
1235 ArchiveOperation Operation = parseCommandLine();
1236 return performOperation(Operation, nullptr);
1239 static int ranlib_main(int argc, char **argv) {
1240 bool ArchiveSpecified = false;
1241 for (int i = 1; i < argc; ++i) {
1242 StringRef arg(argv[i]);
1243 if (handleGenericOption(arg)) {
1245 } else if (arg.consume_front("-")) {
1246 // Handle the -D/-U flag
1247 while (!arg.empty()) {
1248 if (arg.front() == 'D') {
1249 Deterministic = true;
1250 } else if (arg.front() == 'U') {
1251 Deterministic = false;
1252 } else if (arg.front() == 'h') {
1255 } else if (arg.front() == 'v') {
1256 cl::PrintVersionMessage();
1259 // TODO: GNU ranlib also supports a -t flag
1260 fail("Invalid option: '-" + arg + "'");
1262 arg = arg.drop_front(1);
1265 if (ArchiveSpecified)
1266 fail("exactly one archive should be specified");
1267 ArchiveSpecified = true;
1268 ArchiveName = arg.str();
1271 if (!ArchiveSpecified) {
1272 badUsage("an archive name must be specified");
1274 return performOperation(CreateSymTab, nullptr);
1277 int main(int argc, char **argv) {
1278 InitLLVM X(argc, argv);
1281 llvm::InitializeAllTargetInfos();
1282 llvm::InitializeAllTargetMCs();
1283 llvm::InitializeAllAsmParsers();
1285 Stem = sys::path::stem(ToolName);
1286 auto Is = [](StringRef Tool) {
1287 // We need to recognize the following filenames.
1289 // Lib.exe -> lib (see D44808, MSBuild runs Lib.exe)
1290 // dlltool.exe -> dlltool
1291 // arm-pokymllib32-linux-gnueabi-llvm-ar-10 -> ar
1292 auto I = Stem.rfind_insensitive(Tool);
1293 return I != StringRef::npos &&
1294 (I + Tool.size() == Stem.size() || !isAlnum(Stem[I + Tool.size()]));
1298 return dlltoolDriverMain(makeArrayRef(argv, argc));
1300 return ranlib_main(argc, argv);
1302 return libDriverMain(makeArrayRef(argv, argc));
1304 return ar_main(argc, argv);
1306 fail("not ranlib, ar, lib or dlltool");