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/ADT/Triple.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/LibDriver/LibDriver.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ArchiveWriter.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Errc.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/LineIterator.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/Path.h"
31 #include "llvm/Support/PrettyStackTrace.h"
32 #include "llvm/Support/Signals.h"
33 #include "llvm/Support/TargetSelect.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Support/raw_ostream.h"
40 #if !defined(_MSC_VER) && !defined(__MINGW32__)
48 // The name this program was invoked as.
49 static StringRef ToolName;
51 // Show the error message and exit.
52 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
53 outs() << ToolName << ": " << Error << ".\n";
57 static void failIfError(std::error_code EC, Twine Context = "") {
61 std::string ContextStr = Context.str();
64 fail(Context + ": " + EC.message());
67 // llvm-ar/llvm-ranlib remaining positional arguments.
68 static cl::list<std::string>
69 RestOfArgs(cl::Positional, cl::ZeroOrMore,
70 cl::desc("[relpos] [count] <archive-file> [members]..."));
72 static cl::opt<bool> MRI("M", cl::desc(""));
75 enum Format { Default, GNU, BSD };
78 static cl::opt<Format>
79 FormatOpt("format", cl::desc("Archive format to create"),
80 cl::values(clEnumValN(Default, "defalut", "default"),
81 clEnumValN(GNU, "gnu", "gnu"),
82 clEnumValN(BSD, "bsd", "bsd"), clEnumValEnd));
84 static std::string Options;
86 // Provide additional help output explaining the operations and modifiers of
87 // llvm-ar. This object instructs the CommandLine library to print the text of
88 // the constructor when the --help option is given.
89 static cl::extrahelp MoreHelp(
91 " d[NsS] - delete file(s) from the archive\n"
92 " m[abiSs] - move file(s) in the archive\n"
93 " p[kN] - print file(s) found in the archive\n"
94 " q[ufsS] - quick append file(s) to the archive\n"
95 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
96 " t - display contents of archive\n"
97 " x[No] - extract file(s) from the archive\n"
98 "\nMODIFIERS (operation specific):\n"
99 " [a] - put file(s) after [relpos]\n"
100 " [b] - put file(s) before [relpos] (same as [i])\n"
101 " [i] - put file(s) before [relpos] (same as [b])\n"
102 " [o] - preserve original dates\n"
103 " [s] - create an archive index (cf. ranlib)\n"
104 " [S] - do not build a symbol table\n"
105 " [u] - update only files newer than archive contents\n"
106 "\nMODIFIERS (generic):\n"
107 " [c] - do not warn if the library had to be created\n"
108 " [v] - be verbose about actions taken\n"
111 // This enumeration delineates the kinds of operations on an archive
112 // that are permitted.
113 enum ArchiveOperation {
114 Print, ///< Print the contents of the archive
115 Delete, ///< Delete the specified members
116 Move, ///< Move members to end or as given by {a,b,i} modifiers
117 QuickAppend, ///< Quickly append to end of archive
118 ReplaceOrInsert, ///< Replace or Insert members
119 DisplayTable, ///< Display the table of contents
120 Extract, ///< Extract files back to file system
121 CreateSymTab ///< Create a symbol table in an existing archive
124 // Modifiers to follow operation to vary behavior
125 static bool AddAfter = false; ///< 'a' modifier
126 static bool AddBefore = false; ///< 'b' modifier
127 static bool Create = false; ///< 'c' modifier
128 static bool OriginalDates = false; ///< 'o' modifier
129 static bool OnlyUpdate = false; ///< 'u' modifier
130 static bool Verbose = false; ///< 'v' modifier
131 static bool Symtab = true; ///< 's' modifier
132 static bool Deterministic = true; ///< 'D' and 'U' modifiers
133 static bool Thin = false; ///< 'T' modifier
135 // Relative Positional Argument (for insert/move). This variable holds
136 // the name of the archive member to which the 'a', 'b' or 'i' modifier
137 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
139 static std::string RelPos;
141 // This variable holds the name of the archive file as given on the
143 static std::string ArchiveName;
145 // This variable holds the list of member files to proecess, as given
146 // on the command line.
147 static std::vector<StringRef> Members;
149 // Show the error message, the help message and exit.
150 LLVM_ATTRIBUTE_NORETURN static void
151 show_help(const std::string &msg) {
152 errs() << ToolName << ": " << msg << "\n\n";
153 cl::PrintHelpMessage();
157 // Extract the member filename from the command line for the [relpos] argument
158 // associated with a, b, and i modifiers
159 static void getRelPos() {
160 if(RestOfArgs.size() == 0)
161 show_help("Expected [relpos] for a, b, or i modifier");
162 RelPos = RestOfArgs[0];
163 RestOfArgs.erase(RestOfArgs.begin());
166 static void getOptions() {
167 if(RestOfArgs.size() == 0)
168 show_help("Expected options");
169 Options = RestOfArgs[0];
170 RestOfArgs.erase(RestOfArgs.begin());
173 // Get the archive file name from the command line
174 static void getArchive() {
175 if(RestOfArgs.size() == 0)
176 show_help("An archive name must be specified");
177 ArchiveName = RestOfArgs[0];
178 RestOfArgs.erase(RestOfArgs.begin());
181 // Copy over remaining items in RestOfArgs to our Members vector
182 static void getMembers() {
183 for (auto &Arg : RestOfArgs)
184 Members.push_back(Arg);
187 static void runMRIScript();
189 // Parse the command line options as presented and return the operation
190 // specified. Process all modifiers and check to make sure that constraints on
191 // modifier/operation pairs have not been violated.
192 static ArchiveOperation parseCommandLine() {
194 if (!RestOfArgs.empty())
195 fail("Cannot mix -M and other options");
201 // Keep track of number of operations. We can only specify one
203 unsigned NumOperations = 0;
205 // Keep track of the number of positional modifiers (a,b,i). Only
206 // one can be specified.
207 unsigned NumPositional = 0;
209 // Keep track of which operation was requested
210 ArchiveOperation Operation;
212 bool MaybeJustCreateSymTab = false;
214 for(unsigned i=0; i<Options.size(); ++i) {
216 case 'd': ++NumOperations; Operation = Delete; break;
217 case 'm': ++NumOperations; Operation = Move ; break;
218 case 'p': ++NumOperations; Operation = Print; break;
219 case 'q': ++NumOperations; Operation = QuickAppend; break;
220 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
221 case 't': ++NumOperations; Operation = DisplayTable; break;
222 case 'x': ++NumOperations; Operation = Extract; break;
223 case 'c': Create = true; break;
224 case 'l': /* accepted but unused */ break;
225 case 'o': OriginalDates = true; break;
228 MaybeJustCreateSymTab = true;
233 case 'u': OnlyUpdate = true; break;
234 case 'v': Verbose = true; break;
251 Deterministic = true;
254 Deterministic = false;
260 cl::PrintHelpMessage();
264 // At this point, the next thing on the command line must be
268 // Everything on the command line at this point is a member.
271 if (NumOperations == 0 && MaybeJustCreateSymTab) {
273 Operation = CreateSymTab;
274 if (!Members.empty())
275 show_help("The s operation takes only an archive as argument");
278 // Perform various checks on the operation/modifier specification
279 // to make sure we are dealing with a legal request.
280 if (NumOperations == 0)
281 show_help("You must specify at least one of the operations");
282 if (NumOperations > 1)
283 show_help("Only one operation may be specified");
284 if (NumPositional > 1)
285 show_help("You may only specify one of a, b, and i modifiers");
286 if (AddAfter || AddBefore) {
287 if (Operation != Move && Operation != ReplaceOrInsert)
288 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
289 "the 'm' or 'r' operations");
291 if (OriginalDates && Operation != Extract)
292 show_help("The 'o' modifier is only applicable to the 'x' operation");
293 if (OnlyUpdate && Operation != ReplaceOrInsert)
294 show_help("The 'u' modifier is only applicable to the 'r' operation");
296 // Return the parsed operation to the caller
300 // Implements the 'p' operation. This function traverses the archive
301 // looking for members that match the path list.
302 static void doPrint(StringRef Name, const object::Archive::Child &C) {
304 outs() << "Printing " << Name << "\n";
306 ErrorOr<StringRef> DataOrErr = C.getBuffer();
307 failIfError(DataOrErr.getError());
308 StringRef Data = *DataOrErr;
309 outs().write(Data.data(), Data.size());
312 // Utility function for printing out the file mode when the 't' operation is in
314 static void printMode(unsigned mode) {
329 // Implement the 't' operation. This function prints out just
330 // the file names of each of the members. However, if verbose mode is requested
331 // ('v' modifier) then the file type, permission mode, user, group, size, and
332 // modification time are also printed.
333 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
335 sys::fs::perms Mode = C.getAccessMode();
336 printMode((Mode >> 6) & 007);
337 printMode((Mode >> 3) & 007);
338 printMode(Mode & 007);
339 outs() << ' ' << C.getUID();
340 outs() << '/' << C.getGID();
341 ErrorOr<uint64_t> Size = C.getSize();
342 failIfError(Size.getError());
343 outs() << ' ' << format("%6llu", Size.get());
344 outs() << ' ' << C.getLastModified().str();
347 outs() << Name << "\n";
350 // Implement the 'x' operation. This function extracts files back to the file
352 static void doExtract(StringRef Name, const object::Archive::Child &C) {
353 // Retain the original mode.
354 sys::fs::perms Mode = C.getAccessMode();
355 SmallString<128> Storage = Name;
359 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
363 raw_fd_ostream file(FD, false);
365 // Get the data and its length
366 StringRef Data = *C.getBuffer();
369 file.write(Data.data(), Data.size());
372 // If we're supposed to retain the original modification times, etc. do so
376 sys::fs::setLastModificationAndAccessTime(FD, C.getLastModified()));
379 fail("Could not close the file");
382 static bool shouldCreateArchive(ArchiveOperation Op) {
393 case ReplaceOrInsert:
397 llvm_unreachable("Missing entry in covered switch.");
400 static void performReadOperation(ArchiveOperation Operation,
401 object::Archive *OldArchive) {
402 if (Operation == Extract && OldArchive->isThin()) {
403 errs() << "extracting from a thin archive is not supported\n";
407 bool Filter = !Members.empty();
408 for (auto &ChildOrErr : OldArchive->children()) {
409 failIfError(ChildOrErr.getError());
410 const object::Archive::Child &C = *ChildOrErr;
412 ErrorOr<StringRef> NameOrErr = C.getName();
413 failIfError(NameOrErr.getError());
414 StringRef Name = NameOrErr.get();
417 auto I = std::find(Members.begin(), Members.end(), Name);
418 if (I == Members.end())
425 llvm_unreachable("Not a read operation");
430 doDisplayTable(Name, C);
439 for (StringRef Name : Members)
440 errs() << Name << " was not found\n";
444 static void addMember(std::vector<NewArchiveIterator> &Members,
445 StringRef FileName, int Pos = -1) {
446 NewArchiveIterator NI(FileName);
448 Members.push_back(NI);
453 static void addMember(std::vector<NewArchiveIterator> &Members,
454 const object::Archive::Child &M, StringRef Name,
456 if (Thin && !M.getParent()->isThin())
457 fail("Cannot convert a regular archive to a thin one");
458 NewArchiveIterator NI(M, Name);
460 Members.push_back(NI);
473 static InsertAction computeInsertAction(ArchiveOperation Operation,
474 const object::Archive::Child &Member,
476 std::vector<StringRef>::iterator &Pos) {
477 if (Operation == QuickAppend || Members.empty())
478 return IA_AddOldMember;
481 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
482 return Name == sys::path::filename(Path);
485 if (MI == Members.end())
486 return IA_AddOldMember;
490 if (Operation == Delete)
493 if (Operation == Move)
494 return IA_MoveOldMember;
496 if (Operation == ReplaceOrInsert) {
497 StringRef PosName = sys::path::filename(RelPos);
500 return IA_AddNewMeber;
501 return IA_MoveNewMember;
504 // We could try to optimize this to a fstat, but it is not a common
506 sys::fs::file_status Status;
507 failIfError(sys::fs::status(*MI, Status), *MI);
508 if (Status.getLastModificationTime() < Member.getLastModified()) {
510 return IA_AddOldMember;
511 return IA_MoveOldMember;
515 return IA_AddNewMeber;
516 return IA_MoveNewMember;
518 llvm_unreachable("No such operation");
521 // We have to walk this twice and computing it is not trivial, so creating an
522 // explicit std::vector is actually fairly efficient.
523 static std::vector<NewArchiveIterator>
524 computeNewArchiveMembers(ArchiveOperation Operation,
525 object::Archive *OldArchive) {
526 std::vector<NewArchiveIterator> Ret;
527 std::vector<NewArchiveIterator> Moved;
529 StringRef PosName = sys::path::filename(RelPos);
531 for (auto &ChildOrErr : OldArchive->children()) {
532 failIfError(ChildOrErr.getError());
533 auto &Child = ChildOrErr.get();
534 int Pos = Ret.size();
535 ErrorOr<StringRef> NameOrErr = Child.getName();
536 failIfError(NameOrErr.getError());
537 StringRef Name = NameOrErr.get();
538 if (Name == PosName) {
539 assert(AddAfter || AddBefore);
546 std::vector<StringRef>::iterator MemberI = Members.end();
547 InsertAction Action =
548 computeInsertAction(Operation, Child, Name, MemberI);
550 case IA_AddOldMember:
551 addMember(Ret, Child, Name);
554 addMember(Ret, *MemberI);
558 case IA_MoveOldMember:
559 addMember(Moved, Child, Name);
561 case IA_MoveNewMember:
562 addMember(Moved, *MemberI);
565 if (MemberI != Members.end())
566 Members.erase(MemberI);
570 if (Operation == Delete)
573 if (!RelPos.empty() && InsertPos == -1)
574 fail("Insertion point not found");
577 InsertPos = Ret.size();
579 assert(unsigned(InsertPos) <= Ret.size());
580 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
582 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator(""));
584 for (auto &Member : Members) {
585 addMember(Ret, Member, Pos);
593 performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
594 std::vector<NewArchiveIterator> *NewMembersP) {
595 object::Archive::Kind Kind;
598 Triple T(sys::getProcessTriple());
600 Kind = object::Archive::K_BSD;
602 Kind = object::Archive::K_GNU;
606 Kind = object::Archive::K_GNU;
609 Kind = object::Archive::K_BSD;
613 std::pair<StringRef, std::error_code> Result = writeArchive(
614 ArchiveName, *NewMembersP, Symtab, Kind, Deterministic, Thin);
615 failIfError(Result.second, Result.first);
618 std::vector<NewArchiveIterator> NewMembers =
619 computeNewArchiveMembers(Operation, OldArchive);
621 writeArchive(ArchiveName, NewMembers, Symtab, Kind, Deterministic, Thin);
622 failIfError(Result.second, Result.first);
625 static void createSymbolTable(object::Archive *OldArchive) {
626 // When an archive is created or modified, if the s option is given, the
627 // resulting archive will have a current symbol table. If the S option
628 // is given, it will have no symbol table.
629 // In summary, we only need to update the symbol table if we have none.
630 // This is actually very common because of broken build systems that think
631 // they have to run ranlib.
632 if (OldArchive->hasSymbolTable())
635 performWriteOperation(CreateSymTab, OldArchive, nullptr);
638 static void performOperation(ArchiveOperation Operation,
639 object::Archive *OldArchive,
640 std::vector<NewArchiveIterator> *NewMembers) {
645 performReadOperation(Operation, OldArchive);
651 case ReplaceOrInsert:
652 performWriteOperation(Operation, OldArchive, NewMembers);
655 createSymbolTable(OldArchive);
658 llvm_unreachable("Unknown operation.");
661 static int performOperation(ArchiveOperation Operation,
662 std::vector<NewArchiveIterator> *NewMembers) {
663 // Create or open the archive object.
664 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
665 MemoryBuffer::getFile(ArchiveName, -1, false);
666 std::error_code EC = Buf.getError();
667 if (EC && EC != errc::no_such_file_or_directory) {
668 errs() << ToolName << ": error opening '" << ArchiveName
669 << "': " << EC.message() << "!\n";
674 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
677 errs() << ToolName << ": error loading '" << ArchiveName
678 << "': " << EC.message() << "!\n";
681 performOperation(Operation, &Archive, NewMembers);
685 assert(EC == errc::no_such_file_or_directory);
687 if (!shouldCreateArchive(Operation)) {
688 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
691 // Produce a warning if we should and we're creating the archive
692 errs() << ToolName << ": creating " << ArchiveName << "\n";
696 performOperation(Operation, nullptr, NewMembers);
700 static void runMRIScript() {
701 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
703 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
704 failIfError(Buf.getError());
705 const MemoryBuffer &Ref = *Buf.get();
707 std::vector<NewArchiveIterator> NewMembers;
708 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
709 std::vector<std::unique_ptr<object::Archive>> Archives;
711 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
713 StringRef CommandStr, Rest;
714 std::tie(CommandStr, Rest) = Line.split(' ');
716 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
717 Rest = Rest.drop_front().drop_back();
718 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
719 .Case("addlib", MRICommand::AddLib)
720 .Case("addmod", MRICommand::AddMod)
721 .Case("create", MRICommand::Create)
722 .Case("save", MRICommand::Save)
723 .Case("end", MRICommand::End)
724 .Default(MRICommand::Invalid);
727 case MRICommand::AddLib: {
728 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
729 failIfError(BufOrErr.getError(), "Could not open library");
730 ArchiveBuffers.push_back(std::move(*BufOrErr));
732 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
733 failIfError(LibOrErr.getError(), "Could not parse library");
734 Archives.push_back(std::move(*LibOrErr));
735 object::Archive &Lib = *Archives.back();
736 for (auto &MemberOrErr : Lib.children()) {
737 failIfError(MemberOrErr.getError());
738 auto &Member = MemberOrErr.get();
739 ErrorOr<StringRef> NameOrErr = Member.getName();
740 failIfError(NameOrErr.getError());
741 addMember(NewMembers, Member, *NameOrErr);
745 case MRICommand::AddMod:
746 addMember(NewMembers, Rest);
748 case MRICommand::Create:
750 if (!ArchiveName.empty())
751 fail("Editing multiple archives not supported");
753 fail("File already saved");
756 case MRICommand::Save:
759 case MRICommand::End:
761 case MRICommand::Invalid:
762 fail("Unknown command: " + CommandStr);
766 // Nothing to do if not saved.
768 performOperation(ReplaceOrInsert, &NewMembers);
772 static int ar_main() {
773 // Do our own parsing of the command line because the CommandLine utility
774 // can't handle the grouped positional parameters without a dash.
775 ArchiveOperation Operation = parseCommandLine();
776 return performOperation(Operation, nullptr);
779 static int ranlib_main() {
780 if (RestOfArgs.size() != 1)
781 fail(ToolName + "takes just one archive as argument");
782 ArchiveName = RestOfArgs[0];
783 return performOperation(CreateSymTab, nullptr);
786 int main(int argc, char **argv) {
788 // Print a stack trace if we signal out.
789 sys::PrintStackTraceOnErrorSignal();
790 PrettyStackTraceProgram X(argc, argv);
791 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
793 llvm::InitializeAllTargetInfos();
794 llvm::InitializeAllTargetMCs();
795 llvm::InitializeAllAsmParsers();
797 StringRef Stem = sys::path::stem(ToolName);
798 if (Stem.find("ranlib") == StringRef::npos &&
799 Stem.find("lib") != StringRef::npos)
800 return libDriverMain(makeArrayRef(argv, argc));
802 // Have the command line options parsed and handle things
803 // like --help and --version.
804 cl::ParseCommandLineOptions(argc, argv,
805 "LLVM Archiver (llvm-ar)\n\n"
806 " This program archives bitcode files into single libraries\n"
809 if (Stem.find("ranlib") != StringRef::npos)
810 return ranlib_main();
811 if (Stem.find("ar") != StringRef::npos)
813 fail("Not ranlib, ar or lib!");