1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Builds up (relatively) standard unix archive files (.a) containing LLVM
11 // bitcode or other files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/LibDriver/LibDriver.h"
19 #include "llvm/Object/Archive.h"
20 #include "llvm/Object/ArchiveWriter.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Format.h"
26 #include "llvm/Support/LineIterator.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/Path.h"
30 #include "llvm/Support/PrettyStackTrace.h"
31 #include "llvm/Support/Signals.h"
32 #include "llvm/Support/TargetSelect.h"
33 #include "llvm/Support/ToolOutputFile.h"
34 #include "llvm/Support/raw_ostream.h"
39 #if !defined(_MSC_VER) && !defined(__MINGW32__)
47 // The name this program was invoked as.
48 static StringRef ToolName;
50 // Show the error message and exit.
51 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
52 outs() << ToolName << ": " << Error << ".\n";
56 static void failIfError(std::error_code EC, Twine Context = "") {
60 std::string ContextStr = Context.str();
63 fail(Context + ": " + EC.message());
66 // llvm-ar/llvm-ranlib remaining positional arguments.
67 static cl::list<std::string>
68 RestOfArgs(cl::Positional, cl::ZeroOrMore,
69 cl::desc("[relpos] [count] <archive-file> [members]..."));
71 static cl::opt<bool> MRI("M", cl::desc(""));
75 // Provide additional help output explaining the operations and modifiers of
76 // llvm-ar. This object instructs the CommandLine library to print the text of
77 // the constructor when the --help option is given.
78 static cl::extrahelp MoreHelp(
80 " d[NsS] - delete file(s) from the archive\n"
81 " m[abiSs] - move file(s) in the archive\n"
82 " p[kN] - print file(s) found in the archive\n"
83 " q[ufsS] - quick append file(s) to the archive\n"
84 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
85 " t - display contents of archive\n"
86 " x[No] - extract file(s) from the archive\n"
87 "\nMODIFIERS (operation specific):\n"
88 " [a] - put file(s) after [relpos]\n"
89 " [b] - put file(s) before [relpos] (same as [i])\n"
90 " [i] - put file(s) before [relpos] (same as [b])\n"
91 " [o] - preserve original dates\n"
92 " [s] - create an archive index (cf. ranlib)\n"
93 " [S] - do not build a symbol table\n"
94 " [u] - update only files newer than archive contents\n"
95 "\nMODIFIERS (generic):\n"
96 " [c] - do not warn if the library had to be created\n"
97 " [v] - be verbose about actions taken\n"
100 // This enumeration delineates the kinds of operations on an archive
101 // that are permitted.
102 enum ArchiveOperation {
103 Print, ///< Print the contents of the archive
104 Delete, ///< Delete the specified members
105 Move, ///< Move members to end or as given by {a,b,i} modifiers
106 QuickAppend, ///< Quickly append to end of archive
107 ReplaceOrInsert, ///< Replace or Insert members
108 DisplayTable, ///< Display the table of contents
109 Extract, ///< Extract files back to file system
110 CreateSymTab ///< Create a symbol table in an existing archive
113 // Modifiers to follow operation to vary behavior
114 static bool AddAfter = false; ///< 'a' modifier
115 static bool AddBefore = false; ///< 'b' modifier
116 static bool Create = false; ///< 'c' modifier
117 static bool OriginalDates = false; ///< 'o' modifier
118 static bool OnlyUpdate = false; ///< 'u' modifier
119 static bool Verbose = false; ///< 'v' modifier
120 static bool Symtab = true; ///< 's' modifier
122 // Relative Positional Argument (for insert/move). This variable holds
123 // the name of the archive member to which the 'a', 'b' or 'i' modifier
124 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
126 static std::string RelPos;
128 // This variable holds the name of the archive file as given on the
130 static std::string ArchiveName;
132 // This variable holds the list of member files to proecess, as given
133 // on the command line.
134 static std::vector<StringRef> Members;
136 // Show the error message, the help message and exit.
137 LLVM_ATTRIBUTE_NORETURN static void
138 show_help(const std::string &msg) {
139 errs() << ToolName << ": " << msg << "\n\n";
140 cl::PrintHelpMessage();
144 // Extract the member filename from the command line for the [relpos] argument
145 // associated with a, b, and i modifiers
146 static void getRelPos() {
147 if(RestOfArgs.size() == 0)
148 show_help("Expected [relpos] for a, b, or i modifier");
149 RelPos = RestOfArgs[0];
150 RestOfArgs.erase(RestOfArgs.begin());
153 static void getOptions() {
154 if(RestOfArgs.size() == 0)
155 show_help("Expected options");
156 Options = RestOfArgs[0];
157 RestOfArgs.erase(RestOfArgs.begin());
160 // Get the archive file name from the command line
161 static void getArchive() {
162 if(RestOfArgs.size() == 0)
163 show_help("An archive name must be specified");
164 ArchiveName = RestOfArgs[0];
165 RestOfArgs.erase(RestOfArgs.begin());
168 // Copy over remaining items in RestOfArgs to our Members vector
169 static void getMembers() {
170 for (auto &Arg : RestOfArgs)
171 Members.push_back(Arg);
174 static void runMRIScript();
176 // Parse the command line options as presented and return the operation
177 // specified. Process all modifiers and check to make sure that constraints on
178 // modifier/operation pairs have not been violated.
179 static ArchiveOperation parseCommandLine() {
181 if (!RestOfArgs.empty())
182 fail("Cannot mix -M and other options");
188 // Keep track of number of operations. We can only specify one
190 unsigned NumOperations = 0;
192 // Keep track of the number of positional modifiers (a,b,i). Only
193 // one can be specified.
194 unsigned NumPositional = 0;
196 // Keep track of which operation was requested
197 ArchiveOperation Operation;
199 bool MaybeJustCreateSymTab = false;
201 for(unsigned i=0; i<Options.size(); ++i) {
203 case 'd': ++NumOperations; Operation = Delete; break;
204 case 'm': ++NumOperations; Operation = Move ; break;
205 case 'p': ++NumOperations; Operation = Print; break;
206 case 'q': ++NumOperations; Operation = QuickAppend; break;
207 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
208 case 't': ++NumOperations; Operation = DisplayTable; break;
209 case 'x': ++NumOperations; Operation = Extract; break;
210 case 'c': Create = true; break;
211 case 'l': /* accepted but unused */ break;
212 case 'o': OriginalDates = true; break;
215 MaybeJustCreateSymTab = true;
220 case 'u': OnlyUpdate = true; break;
221 case 'v': Verbose = true; break;
238 cl::PrintHelpMessage();
242 // At this point, the next thing on the command line must be
246 // Everything on the command line at this point is a member.
249 if (NumOperations == 0 && MaybeJustCreateSymTab) {
251 Operation = CreateSymTab;
252 if (!Members.empty())
253 show_help("The s operation takes only an archive as argument");
256 // Perform various checks on the operation/modifier specification
257 // to make sure we are dealing with a legal request.
258 if (NumOperations == 0)
259 show_help("You must specify at least one of the operations");
260 if (NumOperations > 1)
261 show_help("Only one operation may be specified");
262 if (NumPositional > 1)
263 show_help("You may only specify one of a, b, and i modifiers");
264 if (AddAfter || AddBefore) {
265 if (Operation != Move && Operation != ReplaceOrInsert)
266 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
267 "the 'm' or 'r' operations");
269 if (OriginalDates && Operation != Extract)
270 show_help("The 'o' modifier is only applicable to the 'x' operation");
271 if (OnlyUpdate && Operation != ReplaceOrInsert)
272 show_help("The 'u' modifier is only applicable to the 'r' operation");
274 // Return the parsed operation to the caller
278 // Implements the 'p' operation. This function traverses the archive
279 // looking for members that match the path list.
280 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
282 outs() << "Printing " << Name << "\n";
284 StringRef Data = I->getBuffer();
285 outs().write(Data.data(), Data.size());
288 // Utility function for printing out the file mode when the 't' operation is in
290 static void printMode(unsigned mode) {
305 // Implement the 't' operation. This function prints out just
306 // the file names of each of the members. However, if verbose mode is requested
307 // ('v' modifier) then the file type, permission mode, user, group, size, and
308 // modification time are also printed.
309 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
311 sys::fs::perms Mode = I->getAccessMode();
312 printMode((Mode >> 6) & 007);
313 printMode((Mode >> 3) & 007);
314 printMode(Mode & 007);
315 outs() << ' ' << I->getUID();
316 outs() << '/' << I->getGID();
317 outs() << ' ' << format("%6llu", I->getSize());
318 outs() << ' ' << I->getLastModified().str();
321 outs() << Name << "\n";
324 // Implement the 'x' operation. This function extracts files back to the file
326 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
327 // Retain the original mode.
328 sys::fs::perms Mode = I->getAccessMode();
329 SmallString<128> Storage = Name;
333 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
337 raw_fd_ostream file(FD, false);
339 // Get the data and its length
340 StringRef Data = I->getBuffer();
343 file.write(Data.data(), Data.size());
346 // If we're supposed to retain the original modification times, etc. do so
350 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
353 fail("Could not close the file");
356 static bool shouldCreateArchive(ArchiveOperation Op) {
367 case ReplaceOrInsert:
371 llvm_unreachable("Missing entry in covered switch.");
374 static void performReadOperation(ArchiveOperation Operation,
375 object::Archive *OldArchive) {
376 for (object::Archive::child_iterator I = OldArchive->child_begin(),
377 E = OldArchive->child_end();
379 ErrorOr<StringRef> NameOrErr = I->getName();
380 failIfError(NameOrErr.getError());
381 StringRef Name = NameOrErr.get();
383 if (!Members.empty() &&
384 std::find(Members.begin(), Members.end(), Name) == Members.end())
389 llvm_unreachable("Not a read operation");
394 doDisplayTable(Name, I);
403 template <typename T>
404 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
406 NewArchiveIterator NI(I, Name);
408 Members.push_back(NI);
421 static InsertAction computeInsertAction(ArchiveOperation Operation,
422 object::Archive::child_iterator I,
424 std::vector<StringRef>::iterator &Pos) {
425 if (Operation == QuickAppend || Members.empty())
426 return IA_AddOldMember;
429 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
430 return Name == sys::path::filename(Path);
433 if (MI == Members.end())
434 return IA_AddOldMember;
438 if (Operation == Delete)
441 if (Operation == Move)
442 return IA_MoveOldMember;
444 if (Operation == ReplaceOrInsert) {
445 StringRef PosName = sys::path::filename(RelPos);
448 return IA_AddNewMeber;
449 return IA_MoveNewMember;
452 // We could try to optimize this to a fstat, but it is not a common
454 sys::fs::file_status Status;
455 failIfError(sys::fs::status(*MI, Status), *MI);
456 if (Status.getLastModificationTime() < I->getLastModified()) {
458 return IA_AddOldMember;
459 return IA_MoveOldMember;
463 return IA_AddNewMeber;
464 return IA_MoveNewMember;
466 llvm_unreachable("No such operation");
469 // We have to walk this twice and computing it is not trivial, so creating an
470 // explicit std::vector is actually fairly efficient.
471 static std::vector<NewArchiveIterator>
472 computeNewArchiveMembers(ArchiveOperation Operation,
473 object::Archive *OldArchive) {
474 std::vector<NewArchiveIterator> Ret;
475 std::vector<NewArchiveIterator> Moved;
477 StringRef PosName = sys::path::filename(RelPos);
479 for (auto &Child : OldArchive->children()) {
480 int Pos = Ret.size();
481 ErrorOr<StringRef> NameOrErr = Child.getName();
482 failIfError(NameOrErr.getError());
483 StringRef Name = NameOrErr.get();
484 if (Name == PosName) {
485 assert(AddAfter || AddBefore);
492 std::vector<StringRef>::iterator MemberI = Members.end();
493 InsertAction Action =
494 computeInsertAction(Operation, Child, Name, MemberI);
496 case IA_AddOldMember:
497 addMember(Ret, Child, Name);
500 addMember(Ret, *MemberI, Name);
504 case IA_MoveOldMember:
505 addMember(Moved, Child, Name);
507 case IA_MoveNewMember:
508 addMember(Moved, *MemberI, Name);
511 if (MemberI != Members.end())
512 Members.erase(MemberI);
516 if (Operation == Delete)
519 if (!RelPos.empty() && InsertPos == -1)
520 fail("Insertion point not found");
523 InsertPos = Ret.size();
525 assert(unsigned(InsertPos) <= Ret.size());
526 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
528 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
530 for (auto &Member : Members) {
531 StringRef Name = sys::path::filename(Member);
532 addMember(Ret, Member, Name, Pos);
540 performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
541 std::vector<NewArchiveIterator> *NewMembersP) {
543 std::pair<StringRef, std::error_code> Result =
544 writeArchive(ArchiveName, *NewMembersP, Symtab);
545 failIfError(Result.second, Result.first);
548 std::vector<NewArchiveIterator> NewMembers =
549 computeNewArchiveMembers(Operation, OldArchive);
550 auto Result = writeArchive(ArchiveName, NewMembers, Symtab);
551 failIfError(Result.second, Result.first);
554 static void createSymbolTable(object::Archive *OldArchive) {
555 // When an archive is created or modified, if the s option is given, the
556 // resulting archive will have a current symbol table. If the S option
557 // is given, it will have no symbol table.
558 // In summary, we only need to update the symbol table if we have none.
559 // This is actually very common because of broken build systems that think
560 // they have to run ranlib.
561 if (OldArchive->hasSymbolTable())
564 performWriteOperation(CreateSymTab, OldArchive, nullptr);
567 static void performOperation(ArchiveOperation Operation,
568 object::Archive *OldArchive,
569 std::vector<NewArchiveIterator> *NewMembers) {
574 performReadOperation(Operation, OldArchive);
580 case ReplaceOrInsert:
581 performWriteOperation(Operation, OldArchive, NewMembers);
584 createSymbolTable(OldArchive);
587 llvm_unreachable("Unknown operation.");
590 static int performOperation(ArchiveOperation Operation,
591 std::vector<NewArchiveIterator> *NewMembers) {
592 // Create or open the archive object.
593 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
594 MemoryBuffer::getFile(ArchiveName, -1, false);
595 std::error_code EC = Buf.getError();
596 if (EC && EC != errc::no_such_file_or_directory) {
597 errs() << ToolName << ": error opening '" << ArchiveName
598 << "': " << EC.message() << "!\n";
603 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
606 errs() << ToolName << ": error loading '" << ArchiveName
607 << "': " << EC.message() << "!\n";
610 performOperation(Operation, &Archive, NewMembers);
614 assert(EC == errc::no_such_file_or_directory);
616 if (!shouldCreateArchive(Operation)) {
617 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
620 // Produce a warning if we should and we're creating the archive
621 errs() << ToolName << ": creating " << ArchiveName << "\n";
625 performOperation(Operation, nullptr, NewMembers);
629 static void runMRIScript() {
630 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
632 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
633 failIfError(Buf.getError());
634 const MemoryBuffer &Ref = *Buf.get();
636 std::vector<NewArchiveIterator> NewMembers;
637 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
638 std::vector<std::unique_ptr<object::Archive>> Archives;
640 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
642 StringRef CommandStr, Rest;
643 std::tie(CommandStr, Rest) = Line.split(' ');
645 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
646 Rest = Rest.drop_front().drop_back();
647 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
648 .Case("addlib", MRICommand::AddLib)
649 .Case("addmod", MRICommand::AddMod)
650 .Case("create", MRICommand::Create)
651 .Case("save", MRICommand::Save)
652 .Case("end", MRICommand::End)
653 .Default(MRICommand::Invalid);
656 case MRICommand::AddLib: {
657 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
658 failIfError(BufOrErr.getError(), "Could not open library");
659 ArchiveBuffers.push_back(std::move(*BufOrErr));
661 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
662 failIfError(LibOrErr.getError(), "Could not parse library");
663 Archives.push_back(std::move(*LibOrErr));
664 object::Archive &Lib = *Archives.back();
665 for (auto &Member : Lib.children()) {
666 ErrorOr<StringRef> NameOrErr = Member.getName();
667 failIfError(NameOrErr.getError());
668 addMember(NewMembers, Member, *NameOrErr);
672 case MRICommand::AddMod:
673 addMember(NewMembers, Rest, sys::path::filename(Rest));
675 case MRICommand::Create:
677 if (!ArchiveName.empty())
678 fail("Editing multiple archives not supported");
680 fail("File already saved");
683 case MRICommand::Save:
686 case MRICommand::End:
688 case MRICommand::Invalid:
689 fail("Unknown command: " + CommandStr);
693 // Nothing to do if not saved.
695 performOperation(ReplaceOrInsert, &NewMembers);
699 static int ar_main() {
700 // Do our own parsing of the command line because the CommandLine utility
701 // can't handle the grouped positional parameters without a dash.
702 ArchiveOperation Operation = parseCommandLine();
703 return performOperation(Operation, nullptr);
706 static int ranlib_main() {
707 if (RestOfArgs.size() != 1)
708 fail(ToolName + "takes just one archive as argument");
709 ArchiveName = RestOfArgs[0];
710 return performOperation(CreateSymTab, nullptr);
713 int main(int argc, char **argv) {
715 // Print a stack trace if we signal out.
716 sys::PrintStackTraceOnErrorSignal();
717 PrettyStackTraceProgram X(argc, argv);
718 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
720 llvm::InitializeAllTargetInfos();
721 llvm::InitializeAllTargetMCs();
722 llvm::InitializeAllAsmParsers();
724 StringRef Stem = sys::path::stem(ToolName);
725 if (Stem.find("ranlib") == StringRef::npos &&
726 Stem.find("lib") != StringRef::npos)
727 return libDriverMain(makeArrayRef(argv, argc));
729 // Have the command line options parsed and handle things
730 // like --help and --version.
731 cl::ParseCommandLineOptions(argc, argv,
732 "LLVM Archiver (llvm-ar)\n\n"
733 " This program archives bitcode files into single libraries\n"
736 if (Stem.find("ar") != StringRef::npos)
738 if (Stem.find("ranlib") != StringRef::npos)
739 return ranlib_main();
740 fail("Not ranlib, ar or lib!");