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/Object/Archive.h"
19 #include "llvm/Object/ArchiveWriter.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Support/CommandLine.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/LineIterator.h"
26 #include "llvm/Support/ManagedStatic.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/Path.h"
29 #include "llvm/Support/PrettyStackTrace.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/TargetSelect.h"
32 #include "llvm/Support/ToolOutputFile.h"
33 #include "llvm/Support/raw_ostream.h"
38 #if !defined(_MSC_VER) && !defined(__MINGW32__)
46 // The name this program was invoked as.
47 static StringRef ToolName;
49 // Show the error message and exit.
50 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
51 outs() << ToolName << ": " << Error << ".\n";
55 static void failIfError(std::error_code EC, Twine Context = "") {
59 std::string ContextStr = Context.str();
62 fail(Context + ": " + EC.message());
65 // llvm-ar/llvm-ranlib remaining positional arguments.
66 static cl::list<std::string>
67 RestOfArgs(cl::Positional, cl::ZeroOrMore,
68 cl::desc("[relpos] [count] <archive-file> [members]..."));
70 static cl::opt<bool> MRI("M", cl::desc(""));
74 // Provide additional help output explaining the operations and modifiers of
75 // llvm-ar. This object instructs the CommandLine library to print the text of
76 // the constructor when the --help option is given.
77 static cl::extrahelp MoreHelp(
79 " d[NsS] - delete file(s) from the archive\n"
80 " m[abiSs] - move file(s) in the archive\n"
81 " p[kN] - print file(s) found in the archive\n"
82 " q[ufsS] - quick append file(s) to the archive\n"
83 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
84 " t - display contents of archive\n"
85 " x[No] - extract file(s) from the archive\n"
86 "\nMODIFIERS (operation specific):\n"
87 " [a] - put file(s) after [relpos]\n"
88 " [b] - put file(s) before [relpos] (same as [i])\n"
89 " [i] - put file(s) before [relpos] (same as [b])\n"
90 " [o] - preserve original dates\n"
91 " [s] - create an archive index (cf. ranlib)\n"
92 " [S] - do not build a symbol table\n"
93 " [u] - update only files newer than archive contents\n"
94 "\nMODIFIERS (generic):\n"
95 " [c] - do not warn if the library had to be created\n"
96 " [v] - be verbose about actions taken\n"
99 // This enumeration delineates the kinds of operations on an archive
100 // that are permitted.
101 enum ArchiveOperation {
102 Print, ///< Print the contents of the archive
103 Delete, ///< Delete the specified members
104 Move, ///< Move members to end or as given by {a,b,i} modifiers
105 QuickAppend, ///< Quickly append to end of archive
106 ReplaceOrInsert, ///< Replace or Insert members
107 DisplayTable, ///< Display the table of contents
108 Extract, ///< Extract files back to file system
109 CreateSymTab ///< Create a symbol table in an existing archive
112 // Modifiers to follow operation to vary behavior
113 static bool AddAfter = false; ///< 'a' modifier
114 static bool AddBefore = false; ///< 'b' modifier
115 static bool Create = false; ///< 'c' modifier
116 static bool OriginalDates = false; ///< 'o' modifier
117 static bool OnlyUpdate = false; ///< 'u' modifier
118 static bool Verbose = false; ///< 'v' modifier
119 static bool Symtab = true; ///< 's' modifier
121 // Relative Positional Argument (for insert/move). This variable holds
122 // the name of the archive member to which the 'a', 'b' or 'i' modifier
123 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
125 static std::string RelPos;
127 // This variable holds the name of the archive file as given on the
129 static std::string ArchiveName;
131 // This variable holds the list of member files to proecess, as given
132 // on the command line.
133 static std::vector<StringRef> Members;
135 // Show the error message, the help message and exit.
136 LLVM_ATTRIBUTE_NORETURN static void
137 show_help(const std::string &msg) {
138 errs() << ToolName << ": " << msg << "\n\n";
139 cl::PrintHelpMessage();
143 // Extract the member filename from the command line for the [relpos] argument
144 // associated with a, b, and i modifiers
145 static void getRelPos() {
146 if(RestOfArgs.size() == 0)
147 show_help("Expected [relpos] for a, b, or i modifier");
148 RelPos = RestOfArgs[0];
149 RestOfArgs.erase(RestOfArgs.begin());
152 static void getOptions() {
153 if(RestOfArgs.size() == 0)
154 show_help("Expected options");
155 Options = RestOfArgs[0];
156 RestOfArgs.erase(RestOfArgs.begin());
159 // Get the archive file name from the command line
160 static void getArchive() {
161 if(RestOfArgs.size() == 0)
162 show_help("An archive name must be specified");
163 ArchiveName = RestOfArgs[0];
164 RestOfArgs.erase(RestOfArgs.begin());
167 // Copy over remaining items in RestOfArgs to our Members vector
168 static void getMembers() {
169 for (auto &Arg : RestOfArgs)
170 Members.push_back(Arg);
173 static void runMRIScript();
175 // Parse the command line options as presented and return the operation
176 // specified. Process all modifiers and check to make sure that constraints on
177 // modifier/operation pairs have not been violated.
178 static ArchiveOperation parseCommandLine() {
180 if (!RestOfArgs.empty())
181 fail("Cannot mix -M and other options");
187 // Keep track of number of operations. We can only specify one
189 unsigned NumOperations = 0;
191 // Keep track of the number of positional modifiers (a,b,i). Only
192 // one can be specified.
193 unsigned NumPositional = 0;
195 // Keep track of which operation was requested
196 ArchiveOperation Operation;
198 bool MaybeJustCreateSymTab = false;
200 for(unsigned i=0; i<Options.size(); ++i) {
202 case 'd': ++NumOperations; Operation = Delete; break;
203 case 'm': ++NumOperations; Operation = Move ; break;
204 case 'p': ++NumOperations; Operation = Print; break;
205 case 'q': ++NumOperations; Operation = QuickAppend; break;
206 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
207 case 't': ++NumOperations; Operation = DisplayTable; break;
208 case 'x': ++NumOperations; Operation = Extract; break;
209 case 'c': Create = true; break;
210 case 'l': /* accepted but unused */ break;
211 case 'o': OriginalDates = true; break;
214 MaybeJustCreateSymTab = true;
219 case 'u': OnlyUpdate = true; break;
220 case 'v': Verbose = true; break;
237 cl::PrintHelpMessage();
241 // At this point, the next thing on the command line must be
245 // Everything on the command line at this point is a member.
248 if (NumOperations == 0 && MaybeJustCreateSymTab) {
250 Operation = CreateSymTab;
251 if (!Members.empty())
252 show_help("The s operation takes only an archive as argument");
255 // Perform various checks on the operation/modifier specification
256 // to make sure we are dealing with a legal request.
257 if (NumOperations == 0)
258 show_help("You must specify at least one of the operations");
259 if (NumOperations > 1)
260 show_help("Only one operation may be specified");
261 if (NumPositional > 1)
262 show_help("You may only specify one of a, b, and i modifiers");
263 if (AddAfter || AddBefore) {
264 if (Operation != Move && Operation != ReplaceOrInsert)
265 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
266 "the 'm' or 'r' operations");
268 if (OriginalDates && Operation != Extract)
269 show_help("The 'o' modifier is only applicable to the 'x' operation");
270 if (OnlyUpdate && Operation != ReplaceOrInsert)
271 show_help("The 'u' modifier is only applicable to the 'r' operation");
273 // Return the parsed operation to the caller
277 // Implements the 'p' operation. This function traverses the archive
278 // looking for members that match the path list.
279 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
281 outs() << "Printing " << Name << "\n";
283 StringRef Data = I->getBuffer();
284 outs().write(Data.data(), Data.size());
287 // Utility function for printing out the file mode when the 't' operation is in
289 static void printMode(unsigned mode) {
304 // Implement the 't' operation. This function prints out just
305 // the file names of each of the members. However, if verbose mode is requested
306 // ('v' modifier) then the file type, permission mode, user, group, size, and
307 // modification time are also printed.
308 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
310 sys::fs::perms Mode = I->getAccessMode();
311 printMode((Mode >> 6) & 007);
312 printMode((Mode >> 3) & 007);
313 printMode(Mode & 007);
314 outs() << ' ' << I->getUID();
315 outs() << '/' << I->getGID();
316 outs() << ' ' << format("%6llu", I->getSize());
317 outs() << ' ' << I->getLastModified().str();
320 outs() << Name << "\n";
323 // Implement the 'x' operation. This function extracts files back to the file
325 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
326 // Retain the original mode.
327 sys::fs::perms Mode = I->getAccessMode();
328 SmallString<128> Storage = Name;
332 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
336 raw_fd_ostream file(FD, false);
338 // Get the data and its length
339 StringRef Data = I->getBuffer();
342 file.write(Data.data(), Data.size());
345 // If we're supposed to retain the original modification times, etc. do so
349 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
352 fail("Could not close the file");
355 static bool shouldCreateArchive(ArchiveOperation Op) {
366 case ReplaceOrInsert:
370 llvm_unreachable("Missing entry in covered switch.");
373 static void performReadOperation(ArchiveOperation Operation,
374 object::Archive *OldArchive) {
375 for (object::Archive::child_iterator I = OldArchive->child_begin(),
376 E = OldArchive->child_end();
378 ErrorOr<StringRef> NameOrErr = I->getName();
379 failIfError(NameOrErr.getError());
380 StringRef Name = NameOrErr.get();
382 if (!Members.empty() &&
383 std::find(Members.begin(), Members.end(), Name) == Members.end())
388 llvm_unreachable("Not a read operation");
393 doDisplayTable(Name, I);
402 template <typename T>
403 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
405 NewArchiveIterator NI(I, Name);
407 Members.push_back(NI);
420 static InsertAction computeInsertAction(ArchiveOperation Operation,
421 object::Archive::child_iterator I,
423 std::vector<StringRef>::iterator &Pos) {
424 if (Operation == QuickAppend || Members.empty())
425 return IA_AddOldMember;
428 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
429 return Name == sys::path::filename(Path);
432 if (MI == Members.end())
433 return IA_AddOldMember;
437 if (Operation == Delete)
440 if (Operation == Move)
441 return IA_MoveOldMember;
443 if (Operation == ReplaceOrInsert) {
444 StringRef PosName = sys::path::filename(RelPos);
447 return IA_AddNewMeber;
448 return IA_MoveNewMember;
451 // We could try to optimize this to a fstat, but it is not a common
453 sys::fs::file_status Status;
454 failIfError(sys::fs::status(*MI, Status), *MI);
455 if (Status.getLastModificationTime() < I->getLastModified()) {
457 return IA_AddOldMember;
458 return IA_MoveOldMember;
462 return IA_AddNewMeber;
463 return IA_MoveNewMember;
465 llvm_unreachable("No such operation");
468 // We have to walk this twice and computing it is not trivial, so creating an
469 // explicit std::vector is actually fairly efficient.
470 static std::vector<NewArchiveIterator>
471 computeNewArchiveMembers(ArchiveOperation Operation,
472 object::Archive *OldArchive) {
473 std::vector<NewArchiveIterator> Ret;
474 std::vector<NewArchiveIterator> Moved;
476 StringRef PosName = sys::path::filename(RelPos);
478 for (auto &Child : OldArchive->children()) {
479 int Pos = Ret.size();
480 ErrorOr<StringRef> NameOrErr = Child.getName();
481 failIfError(NameOrErr.getError());
482 StringRef Name = NameOrErr.get();
483 if (Name == PosName) {
484 assert(AddAfter || AddBefore);
491 std::vector<StringRef>::iterator MemberI = Members.end();
492 InsertAction Action =
493 computeInsertAction(Operation, Child, Name, MemberI);
495 case IA_AddOldMember:
496 addMember(Ret, Child, Name);
499 addMember(Ret, *MemberI, Name);
503 case IA_MoveOldMember:
504 addMember(Moved, Child, Name);
506 case IA_MoveNewMember:
507 addMember(Moved, *MemberI, Name);
510 if (MemberI != Members.end())
511 Members.erase(MemberI);
515 if (Operation == Delete)
518 if (!RelPos.empty() && InsertPos == -1)
519 fail("Insertion point not found");
522 InsertPos = Ret.size();
524 assert(unsigned(InsertPos) <= Ret.size());
525 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
527 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
529 for (auto &Member : Members) {
530 StringRef Name = sys::path::filename(Member);
531 addMember(Ret, Member, Name, Pos);
539 performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
540 std::vector<NewArchiveIterator> *NewMembersP) {
542 std::pair<StringRef, std::error_code> Result =
543 writeArchive(ArchiveName, *NewMembersP, Symtab);
544 failIfError(Result.second, Result.first);
547 std::vector<NewArchiveIterator> NewMembers =
548 computeNewArchiveMembers(Operation, OldArchive);
549 auto Result = writeArchive(ArchiveName, NewMembers, Symtab);
550 failIfError(Result.second, Result.first);
553 static void createSymbolTable(object::Archive *OldArchive) {
554 // When an archive is created or modified, if the s option is given, the
555 // resulting archive will have a current symbol table. If the S option
556 // is given, it will have no symbol table.
557 // In summary, we only need to update the symbol table if we have none.
558 // This is actually very common because of broken build systems that think
559 // they have to run ranlib.
560 if (OldArchive->hasSymbolTable())
563 performWriteOperation(CreateSymTab, OldArchive, nullptr);
566 static void performOperation(ArchiveOperation Operation,
567 object::Archive *OldArchive,
568 std::vector<NewArchiveIterator> *NewMembers) {
573 performReadOperation(Operation, OldArchive);
579 case ReplaceOrInsert:
580 performWriteOperation(Operation, OldArchive, NewMembers);
583 createSymbolTable(OldArchive);
586 llvm_unreachable("Unknown operation.");
589 static int performOperation(ArchiveOperation Operation,
590 std::vector<NewArchiveIterator> *NewMembers) {
591 // Create or open the archive object.
592 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
593 MemoryBuffer::getFile(ArchiveName, -1, false);
594 std::error_code EC = Buf.getError();
595 if (EC && EC != errc::no_such_file_or_directory) {
596 errs() << ToolName << ": error opening '" << ArchiveName
597 << "': " << EC.message() << "!\n";
602 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
605 errs() << ToolName << ": error loading '" << ArchiveName
606 << "': " << EC.message() << "!\n";
609 performOperation(Operation, &Archive, NewMembers);
613 assert(EC == errc::no_such_file_or_directory);
615 if (!shouldCreateArchive(Operation)) {
616 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
619 // Produce a warning if we should and we're creating the archive
620 errs() << ToolName << ": creating " << ArchiveName << "\n";
624 performOperation(Operation, nullptr, NewMembers);
628 static void runMRIScript() {
629 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
631 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
632 failIfError(Buf.getError());
633 const MemoryBuffer &Ref = *Buf.get();
635 std::vector<NewArchiveIterator> NewMembers;
636 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
637 std::vector<std::unique_ptr<object::Archive>> Archives;
639 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
641 StringRef CommandStr, Rest;
642 std::tie(CommandStr, Rest) = Line.split(' ');
644 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
645 Rest = Rest.drop_front().drop_back();
646 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
647 .Case("addlib", MRICommand::AddLib)
648 .Case("addmod", MRICommand::AddMod)
649 .Case("create", MRICommand::Create)
650 .Case("save", MRICommand::Save)
651 .Case("end", MRICommand::End)
652 .Default(MRICommand::Invalid);
655 case MRICommand::AddLib: {
656 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
657 failIfError(BufOrErr.getError(), "Could not open library");
658 ArchiveBuffers.push_back(std::move(*BufOrErr));
660 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
661 failIfError(LibOrErr.getError(), "Could not parse library");
662 Archives.push_back(std::move(*LibOrErr));
663 object::Archive &Lib = *Archives.back();
664 for (auto &Member : Lib.children()) {
665 ErrorOr<StringRef> NameOrErr = Member.getName();
666 failIfError(NameOrErr.getError());
667 addMember(NewMembers, Member, *NameOrErr);
671 case MRICommand::AddMod:
672 addMember(NewMembers, Rest, sys::path::filename(Rest));
674 case MRICommand::Create:
676 if (!ArchiveName.empty())
677 fail("Editing multiple archives not supported");
679 fail("File already saved");
682 case MRICommand::Save:
685 case MRICommand::End:
687 case MRICommand::Invalid:
688 fail("Unknown command: " + CommandStr);
692 // Nothing to do if not saved.
694 performOperation(ReplaceOrInsert, &NewMembers);
698 static int ar_main() {
699 // Do our own parsing of the command line because the CommandLine utility
700 // can't handle the grouped positional parameters without a dash.
701 ArchiveOperation Operation = parseCommandLine();
702 return performOperation(Operation, nullptr);
705 static int ranlib_main() {
706 if (RestOfArgs.size() != 1)
707 fail(ToolName + "takes just one archive as argument");
708 ArchiveName = RestOfArgs[0];
709 return performOperation(CreateSymTab, nullptr);
712 int main(int argc, char **argv) {
714 // Print a stack trace if we signal out.
715 sys::PrintStackTraceOnErrorSignal();
716 PrettyStackTraceProgram X(argc, argv);
717 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
719 // Have the command line options parsed and handle things
720 // like --help and --version.
721 cl::ParseCommandLineOptions(argc, argv,
722 "LLVM Archiver (llvm-ar)\n\n"
723 " This program archives bitcode files into single libraries\n"
726 llvm::InitializeAllTargetInfos();
727 llvm::InitializeAllTargetMCs();
728 llvm::InitializeAllAsmParsers();
730 StringRef Stem = sys::path::stem(ToolName);
731 if (Stem.find("ar") != StringRef::npos)
733 if (Stem.find("ranlib") != StringRef::npos)
734 return ranlib_main();
735 fail("Not ranlib or ar!");