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));
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
134 // Relative Positional Argument (for insert/move). This variable holds
135 // the name of the archive member to which the 'a', 'b' or 'i' modifier
136 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
138 static std::string RelPos;
140 // This variable holds the name of the archive file as given on the
142 static std::string ArchiveName;
144 // This variable holds the list of member files to proecess, as given
145 // on the command line.
146 static std::vector<StringRef> Members;
148 // Show the error message, the help message and exit.
149 LLVM_ATTRIBUTE_NORETURN static void
150 show_help(const std::string &msg) {
151 errs() << ToolName << ": " << msg << "\n\n";
152 cl::PrintHelpMessage();
156 // Extract the member filename from the command line for the [relpos] argument
157 // associated with a, b, and i modifiers
158 static void getRelPos() {
159 if(RestOfArgs.size() == 0)
160 show_help("Expected [relpos] for a, b, or i modifier");
161 RelPos = RestOfArgs[0];
162 RestOfArgs.erase(RestOfArgs.begin());
165 static void getOptions() {
166 if(RestOfArgs.size() == 0)
167 show_help("Expected options");
168 Options = RestOfArgs[0];
169 RestOfArgs.erase(RestOfArgs.begin());
172 // Get the archive file name from the command line
173 static void getArchive() {
174 if(RestOfArgs.size() == 0)
175 show_help("An archive name must be specified");
176 ArchiveName = RestOfArgs[0];
177 RestOfArgs.erase(RestOfArgs.begin());
180 // Copy over remaining items in RestOfArgs to our Members vector
181 static void getMembers() {
182 for (auto &Arg : RestOfArgs)
183 Members.push_back(Arg);
186 static void runMRIScript();
188 // Parse the command line options as presented and return the operation
189 // specified. Process all modifiers and check to make sure that constraints on
190 // modifier/operation pairs have not been violated.
191 static ArchiveOperation parseCommandLine() {
193 if (!RestOfArgs.empty())
194 fail("Cannot mix -M and other options");
200 // Keep track of number of operations. We can only specify one
202 unsigned NumOperations = 0;
204 // Keep track of the number of positional modifiers (a,b,i). Only
205 // one can be specified.
206 unsigned NumPositional = 0;
208 // Keep track of which operation was requested
209 ArchiveOperation Operation;
211 bool MaybeJustCreateSymTab = false;
213 for(unsigned i=0; i<Options.size(); ++i) {
215 case 'd': ++NumOperations; Operation = Delete; break;
216 case 'm': ++NumOperations; Operation = Move ; break;
217 case 'p': ++NumOperations; Operation = Print; break;
218 case 'q': ++NumOperations; Operation = QuickAppend; break;
219 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
220 case 't': ++NumOperations; Operation = DisplayTable; break;
221 case 'x': ++NumOperations; Operation = Extract; break;
222 case 'c': Create = true; break;
223 case 'l': /* accepted but unused */ break;
224 case 'o': OriginalDates = true; break;
227 MaybeJustCreateSymTab = true;
232 case 'u': OnlyUpdate = true; break;
233 case 'v': Verbose = true; break;
250 Deterministic = true;
253 Deterministic = false;
256 cl::PrintHelpMessage();
260 // At this point, the next thing on the command line must be
264 // Everything on the command line at this point is a member.
267 if (NumOperations == 0 && MaybeJustCreateSymTab) {
269 Operation = CreateSymTab;
270 if (!Members.empty())
271 show_help("The s operation takes only an archive as argument");
274 // Perform various checks on the operation/modifier specification
275 // to make sure we are dealing with a legal request.
276 if (NumOperations == 0)
277 show_help("You must specify at least one of the operations");
278 if (NumOperations > 1)
279 show_help("Only one operation may be specified");
280 if (NumPositional > 1)
281 show_help("You may only specify one of a, b, and i modifiers");
282 if (AddAfter || AddBefore) {
283 if (Operation != Move && Operation != ReplaceOrInsert)
284 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
285 "the 'm' or 'r' operations");
287 if (OriginalDates && Operation != Extract)
288 show_help("The 'o' modifier is only applicable to the 'x' operation");
289 if (OnlyUpdate && Operation != ReplaceOrInsert)
290 show_help("The 'u' modifier is only applicable to the 'r' operation");
292 // Return the parsed operation to the caller
296 // Implements the 'p' operation. This function traverses the archive
297 // looking for members that match the path list.
298 static void doPrint(StringRef Name, const object::Archive::Child &C) {
300 outs() << "Printing " << Name << "\n";
302 StringRef Data = C.getBuffer();
303 outs().write(Data.data(), Data.size());
306 // Utility function for printing out the file mode when the 't' operation is in
308 static void printMode(unsigned mode) {
323 // Implement the 't' operation. This function prints out just
324 // the file names of each of the members. However, if verbose mode is requested
325 // ('v' modifier) then the file type, permission mode, user, group, size, and
326 // modification time are also printed.
327 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
329 sys::fs::perms Mode = C.getAccessMode();
330 printMode((Mode >> 6) & 007);
331 printMode((Mode >> 3) & 007);
332 printMode(Mode & 007);
333 outs() << ' ' << C.getUID();
334 outs() << '/' << C.getGID();
335 outs() << ' ' << format("%6llu", C.getSize());
336 outs() << ' ' << C.getLastModified().str();
339 outs() << Name << "\n";
342 // Implement the 'x' operation. This function extracts files back to the file
344 static void doExtract(StringRef Name, const object::Archive::Child &C) {
345 // Retain the original mode.
346 sys::fs::perms Mode = C.getAccessMode();
347 SmallString<128> Storage = Name;
351 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_None, Mode),
355 raw_fd_ostream file(FD, false);
357 // Get the data and its length
358 StringRef Data = C.getBuffer();
361 file.write(Data.data(), Data.size());
364 // If we're supposed to retain the original modification times, etc. do so
368 sys::fs::setLastModificationAndAccessTime(FD, C.getLastModified()));
371 fail("Could not close the file");
374 static bool shouldCreateArchive(ArchiveOperation Op) {
385 case ReplaceOrInsert:
389 llvm_unreachable("Missing entry in covered switch.");
392 static void performReadOperation(ArchiveOperation Operation,
393 object::Archive *OldArchive) {
394 if (Operation == Extract && OldArchive->isThin()) {
395 errs() << "extracting from a thin archive is not supported\n";
399 bool Filter = !Members.empty();
400 for (const object::Archive::Child &C : OldArchive->children()) {
401 ErrorOr<StringRef> NameOrErr = C.getName();
402 failIfError(NameOrErr.getError());
403 StringRef Name = NameOrErr.get();
406 auto I = std::find(Members.begin(), Members.end(), Name);
407 if (I == Members.end())
414 llvm_unreachable("Not a read operation");
419 doDisplayTable(Name, C);
428 for (StringRef Name : Members)
429 errs() << Name << " was not found\n";
433 template <typename T>
434 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
436 NewArchiveIterator NI(I, Name);
438 Members.push_back(NI);
451 static InsertAction computeInsertAction(ArchiveOperation Operation,
452 object::Archive::child_iterator I,
454 std::vector<StringRef>::iterator &Pos) {
455 if (Operation == QuickAppend || Members.empty())
456 return IA_AddOldMember;
459 std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
460 return Name == sys::path::filename(Path);
463 if (MI == Members.end())
464 return IA_AddOldMember;
468 if (Operation == Delete)
471 if (Operation == Move)
472 return IA_MoveOldMember;
474 if (Operation == ReplaceOrInsert) {
475 StringRef PosName = sys::path::filename(RelPos);
478 return IA_AddNewMeber;
479 return IA_MoveNewMember;
482 // We could try to optimize this to a fstat, but it is not a common
484 sys::fs::file_status Status;
485 failIfError(sys::fs::status(*MI, Status), *MI);
486 if (Status.getLastModificationTime() < I->getLastModified()) {
488 return IA_AddOldMember;
489 return IA_MoveOldMember;
493 return IA_AddNewMeber;
494 return IA_MoveNewMember;
496 llvm_unreachable("No such operation");
499 // We have to walk this twice and computing it is not trivial, so creating an
500 // explicit std::vector is actually fairly efficient.
501 static std::vector<NewArchiveIterator>
502 computeNewArchiveMembers(ArchiveOperation Operation,
503 object::Archive *OldArchive) {
504 std::vector<NewArchiveIterator> Ret;
505 std::vector<NewArchiveIterator> Moved;
507 StringRef PosName = sys::path::filename(RelPos);
509 for (auto &Child : OldArchive->children()) {
510 int Pos = Ret.size();
511 ErrorOr<StringRef> NameOrErr = Child.getName();
512 failIfError(NameOrErr.getError());
513 StringRef Name = NameOrErr.get();
514 if (Name == PosName) {
515 assert(AddAfter || AddBefore);
522 std::vector<StringRef>::iterator MemberI = Members.end();
523 InsertAction Action =
524 computeInsertAction(Operation, Child, Name, MemberI);
526 case IA_AddOldMember:
527 addMember(Ret, Child, Name);
530 addMember(Ret, *MemberI, Name);
534 case IA_MoveOldMember:
535 addMember(Moved, Child, Name);
537 case IA_MoveNewMember:
538 addMember(Moved, *MemberI, Name);
541 if (MemberI != Members.end())
542 Members.erase(MemberI);
546 if (Operation == Delete)
549 if (!RelPos.empty() && InsertPos == -1)
550 fail("Insertion point not found");
553 InsertPos = Ret.size();
555 assert(unsigned(InsertPos) <= Ret.size());
556 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
558 Ret.insert(Ret.begin() + InsertPos, Members.size(),
559 NewArchiveIterator("", ""));
561 for (auto &Member : Members) {
562 StringRef Name = sys::path::filename(Member);
563 addMember(Ret, Member, Name, Pos);
571 performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
572 std::vector<NewArchiveIterator> *NewMembersP) {
573 object::Archive::Kind Kind;
576 Triple T(sys::getProcessTriple());
578 Kind = object::Archive::K_BSD;
580 Kind = object::Archive::K_GNU;
584 Kind = object::Archive::K_GNU;
587 Kind = object::Archive::K_BSD;
591 std::pair<StringRef, std::error_code> Result =
592 writeArchive(ArchiveName, *NewMembersP, Symtab, Kind, Deterministic);
593 failIfError(Result.second, Result.first);
596 std::vector<NewArchiveIterator> NewMembers =
597 computeNewArchiveMembers(Operation, OldArchive);
599 writeArchive(ArchiveName, NewMembers, Symtab, Kind, Deterministic);
600 failIfError(Result.second, Result.first);
603 static void createSymbolTable(object::Archive *OldArchive) {
604 // When an archive is created or modified, if the s option is given, the
605 // resulting archive will have a current symbol table. If the S option
606 // is given, it will have no symbol table.
607 // In summary, we only need to update the symbol table if we have none.
608 // This is actually very common because of broken build systems that think
609 // they have to run ranlib.
610 if (OldArchive->hasSymbolTable())
613 performWriteOperation(CreateSymTab, OldArchive, nullptr);
616 static void performOperation(ArchiveOperation Operation,
617 object::Archive *OldArchive,
618 std::vector<NewArchiveIterator> *NewMembers) {
623 performReadOperation(Operation, OldArchive);
629 case ReplaceOrInsert:
630 performWriteOperation(Operation, OldArchive, NewMembers);
633 createSymbolTable(OldArchive);
636 llvm_unreachable("Unknown operation.");
639 static int performOperation(ArchiveOperation Operation,
640 std::vector<NewArchiveIterator> *NewMembers) {
641 // Create or open the archive object.
642 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
643 MemoryBuffer::getFile(ArchiveName, -1, false);
644 std::error_code EC = Buf.getError();
645 if (EC && EC != errc::no_such_file_or_directory) {
646 errs() << ToolName << ": error opening '" << ArchiveName
647 << "': " << EC.message() << "!\n";
652 object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
655 errs() << ToolName << ": error loading '" << ArchiveName
656 << "': " << EC.message() << "!\n";
659 performOperation(Operation, &Archive, NewMembers);
663 assert(EC == errc::no_such_file_or_directory);
665 if (!shouldCreateArchive(Operation)) {
666 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
669 // Produce a warning if we should and we're creating the archive
670 errs() << ToolName << ": creating " << ArchiveName << "\n";
674 performOperation(Operation, nullptr, NewMembers);
678 static void runMRIScript() {
679 enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
681 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
682 failIfError(Buf.getError());
683 const MemoryBuffer &Ref = *Buf.get();
685 std::vector<NewArchiveIterator> NewMembers;
686 std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
687 std::vector<std::unique_ptr<object::Archive>> Archives;
689 for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
691 StringRef CommandStr, Rest;
692 std::tie(CommandStr, Rest) = Line.split(' ');
694 if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
695 Rest = Rest.drop_front().drop_back();
696 auto Command = StringSwitch<MRICommand>(CommandStr.lower())
697 .Case("addlib", MRICommand::AddLib)
698 .Case("addmod", MRICommand::AddMod)
699 .Case("create", MRICommand::Create)
700 .Case("save", MRICommand::Save)
701 .Case("end", MRICommand::End)
702 .Default(MRICommand::Invalid);
705 case MRICommand::AddLib: {
706 auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
707 failIfError(BufOrErr.getError(), "Could not open library");
708 ArchiveBuffers.push_back(std::move(*BufOrErr));
710 object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
711 failIfError(LibOrErr.getError(), "Could not parse library");
712 Archives.push_back(std::move(*LibOrErr));
713 object::Archive &Lib = *Archives.back();
714 for (auto &Member : Lib.children()) {
715 ErrorOr<StringRef> NameOrErr = Member.getName();
716 failIfError(NameOrErr.getError());
717 addMember(NewMembers, Member, *NameOrErr);
721 case MRICommand::AddMod:
722 addMember(NewMembers, Rest, sys::path::filename(Rest));
724 case MRICommand::Create:
726 if (!ArchiveName.empty())
727 fail("Editing multiple archives not supported");
729 fail("File already saved");
732 case MRICommand::Save:
735 case MRICommand::End:
737 case MRICommand::Invalid:
738 fail("Unknown command: " + CommandStr);
742 // Nothing to do if not saved.
744 performOperation(ReplaceOrInsert, &NewMembers);
748 static int ar_main() {
749 // Do our own parsing of the command line because the CommandLine utility
750 // can't handle the grouped positional parameters without a dash.
751 ArchiveOperation Operation = parseCommandLine();
752 return performOperation(Operation, nullptr);
755 static int ranlib_main() {
756 if (RestOfArgs.size() != 1)
757 fail(ToolName + "takes just one archive as argument");
758 ArchiveName = RestOfArgs[0];
759 return performOperation(CreateSymTab, nullptr);
762 int main(int argc, char **argv) {
764 // Print a stack trace if we signal out.
765 sys::PrintStackTraceOnErrorSignal();
766 PrettyStackTraceProgram X(argc, argv);
767 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
769 llvm::InitializeAllTargetInfos();
770 llvm::InitializeAllTargetMCs();
771 llvm::InitializeAllAsmParsers();
773 StringRef Stem = sys::path::stem(ToolName);
774 if (Stem.find("ranlib") == StringRef::npos &&
775 Stem.find("lib") != StringRef::npos)
776 return libDriverMain(makeArrayRef(argv, argc));
778 // Have the command line options parsed and handle things
779 // like --help and --version.
780 cl::ParseCommandLineOptions(argc, argv,
781 "LLVM Archiver (llvm-ar)\n\n"
782 " This program archives bitcode files into single libraries\n"
785 if (Stem.find("ar") != StringRef::npos)
787 if (Stem.find("ranlib") != StringRef::npos)
788 return ranlib_main();
789 fail("Not ranlib, ar or lib!");