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(""));
74 enum Format { Default, GNU, BSD };
77 static cl::opt<Format>
78 FormatOpt("format", cl::desc("Archive format to create"),
79 cl::values(clEnumValN(Default, "defalut", "default"),
80 clEnumValN(GNU, "gnu", "gnu"),
81 clEnumValN(BSD, "bsd", "bsd"), clEnumValEnd));
85 // Provide additional help output explaining the operations and modifiers of
86 // llvm-ar. This object instructs the CommandLine library to print the text of
87 // the constructor when the --help option is given.
88 static cl::extrahelp MoreHelp(
90 " d[NsS] - delete file(s) from the archive\n"
91 " m[abiSs] - move file(s) in the archive\n"
92 " p[kN] - print file(s) found in the archive\n"
93 " q[ufsS] - quick append file(s) to the archive\n"
94 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
95 " t - display contents of archive\n"
96 " x[No] - extract file(s) from the archive\n"
97 "\nMODIFIERS (operation specific):\n"
98 " [a] - put file(s) after [relpos]\n"
99 " [b] - put file(s) before [relpos] (same as [i])\n"
100 " [i] - put file(s) before [relpos] (same as [b])\n"
101 " [o] - preserve original dates\n"
102 " [s] - create an archive index (cf. ranlib)\n"
103 " [S] - do not build a symbol table\n"
104 " [u] - update only files newer than archive contents\n"
105 "\nMODIFIERS (generic):\n"
106 " [c] - do not warn if the library had to be created\n"
107 " [v] - be verbose about actions taken\n"
110 // This enumeration delineates the kinds of operations on an archive
111 // that are permitted.
112 enum ArchiveOperation {
113 Print, ///< Print the contents of the archive
114 Delete, ///< Delete the specified members
115 Move, ///< Move members to end or as given by {a,b,i} modifiers
116 QuickAppend, ///< Quickly append to end of archive
117 ReplaceOrInsert, ///< Replace or Insert members
118 DisplayTable, ///< Display the table of contents
119 Extract, ///< Extract files back to file system
120 CreateSymTab ///< Create a symbol table in an existing archive
123 // Modifiers to follow operation to vary behavior
124 static bool AddAfter = false; ///< 'a' modifier
125 static bool AddBefore = false; ///< 'b' modifier
126 static bool Create = false; ///< 'c' modifier
127 static bool OriginalDates = false; ///< 'o' modifier
128 static bool OnlyUpdate = false; ///< 'u' modifier
129 static bool Verbose = false; ///< 'v' modifier
130 static bool Symtab = true; ///< 's' modifier
132 // Relative Positional Argument (for insert/move). This variable holds
133 // the name of the archive member to which the 'a', 'b' or 'i' modifier
134 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
136 static std::string RelPos;
138 // This variable holds the name of the archive file as given on the
140 static std::string ArchiveName;
142 // This variable holds the list of member files to proecess, as given
143 // on the command line.
144 static std::vector<StringRef> Members;
146 // Show the error message, the help message and exit.
147 LLVM_ATTRIBUTE_NORETURN static void
148 show_help(const std::string &msg) {
149 errs() << ToolName << ": " << msg << "\n\n";
150 cl::PrintHelpMessage();
154 // Extract the member filename from the command line for the [relpos] argument
155 // associated with a, b, and i modifiers
156 static void getRelPos() {
157 if(RestOfArgs.size() == 0)
158 show_help("Expected [relpos] for a, b, or i modifier");
159 RelPos = RestOfArgs[0];
160 RestOfArgs.erase(RestOfArgs.begin());
163 static void getOptions() {
164 if(RestOfArgs.size() == 0)
165 show_help("Expected options");
166 Options = RestOfArgs[0];
167 RestOfArgs.erase(RestOfArgs.begin());
170 // Get the archive file name from the command line
171 static void getArchive() {
172 if(RestOfArgs.size() == 0)
173 show_help("An archive name must be specified");
174 ArchiveName = RestOfArgs[0];
175 RestOfArgs.erase(RestOfArgs.begin());
178 // Copy over remaining items in RestOfArgs to our Members vector
179 static void getMembers() {
180 for (auto &Arg : RestOfArgs)
181 Members.push_back(Arg);
184 static void runMRIScript();
186 // Parse the command line options as presented and return the operation
187 // specified. Process all modifiers and check to make sure that constraints on
188 // modifier/operation pairs have not been violated.
189 static ArchiveOperation parseCommandLine() {
191 if (!RestOfArgs.empty())
192 fail("Cannot mix -M and other options");
198 // Keep track of number of operations. We can only specify one
200 unsigned NumOperations = 0;
202 // Keep track of the number of positional modifiers (a,b,i). Only
203 // one can be specified.
204 unsigned NumPositional = 0;
206 // Keep track of which operation was requested
207 ArchiveOperation Operation;
209 bool MaybeJustCreateSymTab = false;
211 for(unsigned i=0; i<Options.size(); ++i) {
213 case 'd': ++NumOperations; Operation = Delete; break;
214 case 'm': ++NumOperations; Operation = Move ; break;
215 case 'p': ++NumOperations; Operation = Print; break;
216 case 'q': ++NumOperations; Operation = QuickAppend; break;
217 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
218 case 't': ++NumOperations; Operation = DisplayTable; break;
219 case 'x': ++NumOperations; Operation = Extract; break;
220 case 'c': Create = true; break;
221 case 'l': /* accepted but unused */ break;
222 case 'o': OriginalDates = true; break;
225 MaybeJustCreateSymTab = true;
230 case 'u': OnlyUpdate = true; break;
231 case 'v': Verbose = true; break;
248 cl::PrintHelpMessage();
252 // At this point, the next thing on the command line must be
256 // Everything on the command line at this point is a member.
259 if (NumOperations == 0 && MaybeJustCreateSymTab) {
261 Operation = CreateSymTab;
262 if (!Members.empty())
263 show_help("The s operation takes only an archive as argument");
266 // Perform various checks on the operation/modifier specification
267 // to make sure we are dealing with a legal request.
268 if (NumOperations == 0)
269 show_help("You must specify at least one of the operations");
270 if (NumOperations > 1)
271 show_help("Only one operation may be specified");
272 if (NumPositional > 1)
273 show_help("You may only specify one of a, b, and i modifiers");
274 if (AddAfter || AddBefore) {
275 if (Operation != Move && Operation != ReplaceOrInsert)
276 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
277 "the 'm' or 'r' operations");
279 if (OriginalDates && Operation != Extract)
280 show_help("The 'o' modifier is only applicable to the 'x' operation");
281 if (OnlyUpdate && Operation != ReplaceOrInsert)
282 show_help("The 'u' modifier is only applicable to the 'r' operation");
284 // Return the parsed operation to the caller
288 // Implements the 'p' operation. This function traverses the archive
289 // looking for members that match the path list.
290 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
292 outs() << "Printing " << Name << "\n";
294 StringRef Data = I->getBuffer();
295 outs().write(Data.data(), Data.size());
298 // Utility function for printing out the file mode when the 't' operation is in
300 static void printMode(unsigned mode) {
315 // Implement the 't' operation. This function prints out just
316 // the file names of each of the members. However, if verbose mode is requested
317 // ('v' modifier) then the file type, permission mode, user, group, size, and
318 // modification time are also printed.
319 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
321 sys::fs::perms Mode = I->getAccessMode();
322 printMode((Mode >> 6) & 007);
323 printMode((Mode >> 3) & 007);
324 printMode(Mode & 007);
325 outs() << ' ' << I->getUID();
326 outs() << '/' << I->getGID();
327 outs() << ' ' << format("%6llu", I->getSize());
328 outs() << ' ' << I->getLastModified().str();
331 outs() << Name << "\n";
334 // Implement the 'x' operation. This function extracts files back to the file
336 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
337 // Retain the original mode.
338 sys::fs::perms Mode = I->getAccessMode();
339 SmallString<128> Storage = Name;
343 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
347 raw_fd_ostream file(FD, false);
349 // Get the data and its length
350 StringRef Data = I->getBuffer();
353 file.write(Data.data(), Data.size());
356 // If we're supposed to retain the original modification times, etc. do so
360 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
363 fail("Could not close the file");
366 static bool shouldCreateArchive(ArchiveOperation Op) {
377 case ReplaceOrInsert:
381 llvm_unreachable("Missing entry in covered switch.");
384 static void performReadOperation(ArchiveOperation Operation,
385 object::Archive *OldArchive) {
386 for (object::Archive::child_iterator I = OldArchive->child_begin(),
387 E = OldArchive->child_end();
389 ErrorOr<StringRef> NameOrErr = I->getName();
390 failIfError(NameOrErr.getError());
391 StringRef Name = NameOrErr.get();
393 if (!Members.empty() &&
394 std::find(Members.begin(), Members.end(), Name) == Members.end())
399 llvm_unreachable("Not a read operation");
404 doDisplayTable(Name, I);
413 template <typename T>
414 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
416 NewArchiveIterator NI(I, Name);
418 Members.push_back(NI);
431 static InsertAction computeInsertAction(ArchiveOperation Operation,
432 object::Archive::child_iterator I,
434 std::vector<StringRef>::iterator &Pos) {
435 if (Operation == QuickAppend || Members.empty())
436 return IA_AddOldMember;
439 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
440 return Name == sys::path::filename(Path);
443 if (MI == Members.end())
444 return IA_AddOldMember;
448 if (Operation == Delete)
451 if (Operation == Move)
452 return IA_MoveOldMember;
454 if (Operation == ReplaceOrInsert) {
455 StringRef PosName = sys::path::filename(RelPos);
458 return IA_AddNewMeber;
459 return IA_MoveNewMember;
462 // We could try to optimize this to a fstat, but it is not a common
464 sys::fs::file_status Status;
465 failIfError(sys::fs::status(*MI, Status), *MI);
466 if (Status.getLastModificationTime() < I->getLastModified()) {
468 return IA_AddOldMember;
469 return IA_MoveOldMember;
473 return IA_AddNewMeber;
474 return IA_MoveNewMember;
476 llvm_unreachable("No such operation");
479 // We have to walk this twice and computing it is not trivial, so creating an
480 // explicit std::vector is actually fairly efficient.
481 static std::vector<NewArchiveIterator>
482 computeNewArchiveMembers(ArchiveOperation Operation,
483 object::Archive *OldArchive) {
484 std::vector<NewArchiveIterator> Ret;
485 std::vector<NewArchiveIterator> Moved;
487 StringRef PosName = sys::path::filename(RelPos);
489 for (auto &Child : OldArchive->children()) {
490 int Pos = Ret.size();
491 ErrorOr<StringRef> NameOrErr = Child.getName();
492 failIfError(NameOrErr.getError());
493 StringRef Name = NameOrErr.get();
494 if (Name == PosName) {
495 assert(AddAfter || AddBefore);
502 std::vector<StringRef>::iterator MemberI = Members.end();
503 InsertAction Action =
504 computeInsertAction(Operation, Child, Name, MemberI);
506 case IA_AddOldMember:
507 addMember(Ret, Child, Name);
510 addMember(Ret, *MemberI, Name);
514 case IA_MoveOldMember:
515 addMember(Moved, Child, Name);
517 case IA_MoveNewMember:
518 addMember(Moved, *MemberI, Name);
521 if (MemberI != Members.end())
522 Members.erase(MemberI);
526 if (Operation == Delete)
529 if (!RelPos.empty() && InsertPos == -1)
530 fail("Insertion point not found");
533 InsertPos = Ret.size();
535 assert(unsigned(InsertPos) <= Ret.size());
536 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
538 Ret.insert(Ret.begin() + InsertPos, Members.size(),
539 NewArchiveIterator("", ""));
541 for (auto &Member : Members) {
542 StringRef Name = sys::path::filename(Member);
543 addMember(Ret, Member, Name, Pos);
551 performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
552 std::vector<NewArchiveIterator> *NewMembersP) {
553 object::Archive::Kind Kind;
556 // FIXME: change as the support for other formats improve.
557 Kind = object::Archive::K_GNU;
559 Kind = object::Archive::K_GNU;
562 Kind = object::Archive::K_BSD;
566 std::pair<StringRef, std::error_code> Result =
567 writeArchive(ArchiveName, *NewMembersP, Symtab, Kind);
568 failIfError(Result.second, Result.first);
571 std::vector<NewArchiveIterator> NewMembers =
572 computeNewArchiveMembers(Operation, OldArchive);
573 auto Result = writeArchive(ArchiveName, NewMembers, Symtab, Kind);
574 failIfError(Result.second, Result.first);
577 static void createSymbolTable(object::Archive *OldArchive) {
578 // When an archive is created or modified, if the s option is given, the
579 // resulting archive will have a current symbol table. If the S option
580 // is given, it will have no symbol table.
581 // In summary, we only need to update the symbol table if we have none.
582 // This is actually very common because of broken build systems that think
583 // they have to run ranlib.
584 if (OldArchive->hasSymbolTable())
587 performWriteOperation(CreateSymTab, OldArchive, nullptr);
590 static void performOperation(ArchiveOperation Operation,
591 object::Archive *OldArchive,
592 std::vector<NewArchiveIterator> *NewMembers) {
597 performReadOperation(Operation, OldArchive);
603 case ReplaceOrInsert:
604 performWriteOperation(Operation, OldArchive, NewMembers);
607 createSymbolTable(OldArchive);
610 llvm_unreachable("Unknown operation.");
613 static int performOperation(ArchiveOperation Operation,
614 std::vector<NewArchiveIterator> *NewMembers) {
615 // Create or open the archive object.
616 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
617 MemoryBuffer::getFile(ArchiveName, -1, false);
618 std::error_code EC = Buf.getError();
619 if (EC && EC != errc::no_such_file_or_directory) {
620 errs() << ToolName << ": error opening '" << ArchiveName
621 << "': " << EC.message() << "!\n";
626 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
629 errs() << ToolName << ": error loading '" << ArchiveName
630 << "': " << EC.message() << "!\n";
633 performOperation(Operation, &Archive, NewMembers);
637 assert(EC == errc::no_such_file_or_directory);
639 if (!shouldCreateArchive(Operation)) {
640 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
643 // Produce a warning if we should and we're creating the archive
644 errs() << ToolName << ": creating " << ArchiveName << "\n";
648 performOperation(Operation, nullptr, NewMembers);
652 static void runMRIScript() {
653 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
655 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
656 failIfError(Buf.getError());
657 const MemoryBuffer &Ref = *Buf.get();
659 std::vector<NewArchiveIterator> NewMembers;
660 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
661 std::vector<std::unique_ptr<object::Archive>> Archives;
663 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
665 StringRef CommandStr, Rest;
666 std::tie(CommandStr, Rest) = Line.split(' ');
668 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
669 Rest = Rest.drop_front().drop_back();
670 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
671 .Case("addlib", MRICommand::AddLib)
672 .Case("addmod", MRICommand::AddMod)
673 .Case("create", MRICommand::Create)
674 .Case("save", MRICommand::Save)
675 .Case("end", MRICommand::End)
676 .Default(MRICommand::Invalid);
679 case MRICommand::AddLib: {
680 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
681 failIfError(BufOrErr.getError(), "Could not open library");
682 ArchiveBuffers.push_back(std::move(*BufOrErr));
684 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
685 failIfError(LibOrErr.getError(), "Could not parse library");
686 Archives.push_back(std::move(*LibOrErr));
687 object::Archive &Lib = *Archives.back();
688 for (auto &Member : Lib.children()) {
689 ErrorOr<StringRef> NameOrErr = Member.getName();
690 failIfError(NameOrErr.getError());
691 addMember(NewMembers, Member, *NameOrErr);
695 case MRICommand::AddMod:
696 addMember(NewMembers, Rest, sys::path::filename(Rest));
698 case MRICommand::Create:
700 if (!ArchiveName.empty())
701 fail("Editing multiple archives not supported");
703 fail("File already saved");
706 case MRICommand::Save:
709 case MRICommand::End:
711 case MRICommand::Invalid:
712 fail("Unknown command: " + CommandStr);
716 // Nothing to do if not saved.
718 performOperation(ReplaceOrInsert, &NewMembers);
722 static int ar_main() {
723 // Do our own parsing of the command line because the CommandLine utility
724 // can't handle the grouped positional parameters without a dash.
725 ArchiveOperation Operation = parseCommandLine();
726 return performOperation(Operation, nullptr);
729 static int ranlib_main() {
730 if (RestOfArgs.size() != 1)
731 fail(ToolName + "takes just one archive as argument");
732 ArchiveName = RestOfArgs[0];
733 return performOperation(CreateSymTab, nullptr);
736 int main(int argc, char **argv) {
738 // Print a stack trace if we signal out.
739 sys::PrintStackTraceOnErrorSignal();
740 PrettyStackTraceProgram X(argc, argv);
741 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
743 llvm::InitializeAllTargetInfos();
744 llvm::InitializeAllTargetMCs();
745 llvm::InitializeAllAsmParsers();
747 StringRef Stem = sys::path::stem(ToolName);
748 if (Stem.find("ranlib") == StringRef::npos &&
749 Stem.find("lib") != StringRef::npos)
750 return libDriverMain(makeArrayRef(argv, argc));
752 // Have the command line options parsed and handle things
753 // like --help and --version.
754 cl::ParseCommandLineOptions(argc, argv,
755 "LLVM Archiver (llvm-ar)\n\n"
756 " This program archives bitcode files into single libraries\n"
759 if (Stem.find("ar") != StringRef::npos)
761 if (Stem.find("ranlib") != StringRef::npos)
762 return ranlib_main();
763 fail("Not ranlib, ar or lib!");