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/IR/LLVMContext.h"
16 #include "llvm/IR/Module.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/Support/Signals.h"
25 #include "llvm/Support/ToolOutputFile.h"
26 #include "llvm/Support/raw_ostream.h"
31 #if !defined(_MSC_VER) && !defined(__MINGW32__)
39 // The name this program was invoked as.
40 static StringRef ToolName;
42 static const char *TemporaryOutput;
43 static int TmpArchiveFD = -1;
45 // fail - Show the error message and exit.
46 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
47 outs() << ToolName << ": " << Error << ".\n";
48 if (TmpArchiveFD != -1)
51 sys::fs::remove(TemporaryOutput);
55 static void failIfError(error_code EC, Twine Context = "") {
59 std::string ContextStr = Context.str();
62 fail(Context + ": " + EC.message());
65 // Option for compatibility with AIX, not used but must allow it to be present.
67 X32Option ("X32_64", cl::Hidden,
68 cl::desc("Ignored option for compatibility with AIX"));
70 // llvm-ar operation code and modifier flags. This must come first.
71 static cl::opt<std::string>
72 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
74 // llvm-ar remaining positional arguments.
75 static cl::list<std::string>
76 RestOfArgs(cl::Positional, cl::OneOrMore,
77 cl::desc("[relpos] [count] <archive-file> [members]..."));
79 // MoreHelp - Provide additional help output explaining the operations and
80 // modifiers of llvm-ar. This object instructs the CommandLine library
81 // to print the text of the constructor when the --help option is given.
82 static cl::extrahelp MoreHelp(
84 " d[NsS] - delete file(s) from the archive\n"
85 " m[abiSs] - move file(s) in the archive\n"
86 " p[kN] - print file(s) found in the archive\n"
87 " q[ufsS] - quick append file(s) to the archive\n"
88 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
89 " t - display contents of archive\n"
90 " x[No] - extract file(s) from the archive\n"
91 "\nMODIFIERS (operation specific):\n"
92 " [a] - put file(s) after [relpos]\n"
93 " [b] - put file(s) before [relpos] (same as [i])\n"
94 " [i] - put file(s) before [relpos] (same as [b])\n"
95 " [N] - use instance [count] of name\n"
96 " [o] - preserve original dates\n"
97 " [s] - create an archive index (cf. ranlib)\n"
98 " [S] - do not build a symbol table\n"
99 " [u] - update only files newer than archive contents\n"
100 "\nMODIFIERS (generic):\n"
101 " [c] - do not warn if the library had to be created\n"
102 " [v] - be verbose about actions taken\n"
105 // This enumeration delineates the kinds of operations on an archive
106 // that are permitted.
107 enum ArchiveOperation {
108 Print, ///< Print the contents of the archive
109 Delete, ///< Delete the specified members
110 Move, ///< Move members to end or as given by {a,b,i} modifiers
111 QuickAppend, ///< Quickly append to end of archive
112 ReplaceOrInsert, ///< Replace or Insert members
113 DisplayTable, ///< Display the table of contents
114 Extract ///< Extract files back to file system
117 // Modifiers to follow operation to vary behavior
118 static bool AddAfter = false; ///< 'a' modifier
119 static bool AddBefore = false; ///< 'b' modifier
120 static bool Create = false; ///< 'c' modifier
121 static bool OriginalDates = false; ///< 'o' modifier
122 static bool OnlyUpdate = false; ///< 'u' modifier
123 static bool Verbose = false; ///< 'v' modifier
125 // Relative Positional Argument (for insert/move). This variable holds
126 // the name of the archive member to which the 'a', 'b' or 'i' modifier
127 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
129 static std::string RelPos;
131 // This variable holds the name of the archive file as given on the
133 static std::string ArchiveName;
135 // This variable holds the list of member files to proecess, as given
136 // on the command line.
137 static std::vector<std::string> Members;
139 // show_help - Show the error message, the help message and exit.
140 LLVM_ATTRIBUTE_NORETURN static void
141 show_help(const std::string &msg) {
142 errs() << ToolName << ": " << msg << "\n\n";
143 cl::PrintHelpMessage();
147 // getRelPos - Extract the member filename from the command line for
148 // the [relpos] argument associated with a, b, and i modifiers
149 static void getRelPos() {
150 if(RestOfArgs.size() == 0)
151 show_help("Expected [relpos] for a, b, or i modifier");
152 RelPos = RestOfArgs[0];
153 RestOfArgs.erase(RestOfArgs.begin());
156 // getArchive - Get the archive file name from the command line
157 static void getArchive() {
158 if(RestOfArgs.size() == 0)
159 show_help("An archive name must be specified");
160 ArchiveName = RestOfArgs[0];
161 RestOfArgs.erase(RestOfArgs.begin());
164 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
165 // This is just for clarity.
166 static void getMembers() {
167 if(RestOfArgs.size() > 0)
168 Members = std::vector<std::string>(RestOfArgs);
171 // parseCommandLine - Parse the command line options as presented and return the
172 // operation specified. Process all modifiers and check to make sure that
173 // constraints on modifier/operation pairs have not been violated.
174 static ArchiveOperation parseCommandLine() {
176 // Keep track of number of operations. We can only specify one
178 unsigned NumOperations = 0;
180 // Keep track of the number of positional modifiers (a,b,i). Only
181 // one can be specified.
182 unsigned NumPositional = 0;
184 // Keep track of which operation was requested
185 ArchiveOperation Operation;
187 for(unsigned i=0; i<Options.size(); ++i) {
189 case 'd': ++NumOperations; Operation = Delete; break;
190 case 'm': ++NumOperations; Operation = Move ; break;
191 case 'p': ++NumOperations; Operation = Print; break;
192 case 'q': ++NumOperations; Operation = QuickAppend; break;
193 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
194 case 't': ++NumOperations; Operation = DisplayTable; break;
195 case 'x': ++NumOperations; Operation = Extract; break;
196 case 'c': Create = true; break;
197 case 'l': /* accepted but unused */ break;
198 case 'o': OriginalDates = true; break;
199 case 's': break; // Ignore for now.
200 case 'S': break; // Ignore for now.
201 case 'u': OnlyUpdate = true; break;
202 case 'v': Verbose = true; break;
219 cl::PrintHelpMessage();
223 // At this point, the next thing on the command line must be
227 // Everything on the command line at this point is a member.
230 // Perform various checks on the operation/modifier specification
231 // to make sure we are dealing with a legal request.
232 if (NumOperations == 0)
233 show_help("You must specify at least one of the operations");
234 if (NumOperations > 1)
235 show_help("Only one operation may be specified");
236 if (NumPositional > 1)
237 show_help("You may only specify one of a, b, and i modifiers");
238 if (AddAfter || AddBefore) {
239 if (Operation != Move && Operation != ReplaceOrInsert)
240 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
241 "the 'm' or 'r' operations");
243 if (OriginalDates && Operation != Extract)
244 show_help("The 'o' modifier is only applicable to the 'x' operation");
245 if (OnlyUpdate && Operation != ReplaceOrInsert)
246 show_help("The 'u' modifier is only applicable to the 'r' operation");
248 // Return the parsed operation to the caller
252 // Implements the 'p' operation. This function traverses the archive
253 // looking for members that match the path list.
254 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
256 outs() << "Printing " << Name << "\n";
258 StringRef Data = I->getBuffer();
259 outs().write(Data.data(), Data.size());
262 // putMode - utility function for printing out the file mode when the 't'
263 // operation is in verbose mode.
264 static void printMode(unsigned mode) {
279 // Implement the 't' operation. This function prints out just
280 // the file names of each of the members. However, if verbose mode is requested
281 // ('v' modifier) then the file type, permission mode, user, group, size, and
282 // modification time are also printed.
283 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
285 sys::fs::perms Mode = I->getAccessMode();
286 printMode((Mode >> 6) & 007);
287 printMode((Mode >> 3) & 007);
288 printMode(Mode & 007);
289 outs() << ' ' << I->getUID();
290 outs() << '/' << I->getGID();
291 outs() << ' ' << format("%6llu", I->getSize());
292 outs() << ' ' << I->getLastModified().str();
295 outs() << Name << "\n";
298 // Implement the 'x' operation. This function extracts files back to the file
300 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
301 // Retain the original mode.
302 sys::fs::perms Mode = I->getAccessMode();
303 SmallString<128> Storage = Name;
307 sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_Binary, Mode),
311 raw_fd_ostream file(FD, false);
313 // Get the data and its length
314 StringRef Data = I->getBuffer();
317 file.write(Data.data(), Data.size());
320 // If we're supposed to retain the original modification times, etc. do so
324 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
327 fail("Could not close the file");
330 static bool shouldCreateArchive(ArchiveOperation Op) {
340 case ReplaceOrInsert:
344 llvm_unreachable("Missing entry in covered switch.");
347 static void performReadOperation(ArchiveOperation Operation,
348 object::Archive *OldArchive) {
349 for (object::Archive::child_iterator I = OldArchive->begin_children(),
350 E = OldArchive->end_children();
353 failIfError(I->getName(Name));
355 if (!Members.empty() &&
356 std::find(Members.begin(), Members.end(), Name) == Members.end())
361 llvm_unreachable("Not a read operation");
366 doDisplayTable(Name, I);
376 class NewArchiveIterator {
378 SmallString<16> MemberName;
379 object::Archive::child_iterator OldI;
380 std::string NewFilename;
383 NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
384 NewArchiveIterator(std::string *I, Twine Name);
385 NewArchiveIterator();
386 bool isNewMember() const;
387 object::Archive::child_iterator getOld() const;
388 const char *getNew() const;
389 StringRef getMemberName() const { return MemberName; }
393 NewArchiveIterator::NewArchiveIterator() {}
395 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
397 : IsNewMember(false), OldI(I) {
398 Name.toVector(MemberName);
401 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, Twine Name)
402 : IsNewMember(true), NewFilename(*NewFilename) {
403 Name.toVector(MemberName);
406 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
408 object::Archive::child_iterator NewArchiveIterator::getOld() const {
409 assert(!IsNewMember);
413 const char *NewArchiveIterator::getNew() const {
415 return NewFilename.c_str();
418 template <typename T>
419 void addMember(std::vector<NewArchiveIterator> &Members,
420 std::string &StringTable, T I, StringRef Name, int Pos = -1) {
422 Pos = Members.size();
423 Members.resize(Pos + 1);
426 if (Name.size() < 16) {
427 NewArchiveIterator NI(I, Twine(Name) + "/");
430 int MapIndex = StringTable.size();
431 NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
434 StringTable += "/\n";
443 HasName(StringRef Name) : Name(Name) {}
444 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
457 computeInsertAction(ArchiveOperation Operation,
458 object::Archive::child_iterator I, StringRef Name,
459 std::vector<std::string>::iterator &Pos) {
460 if (Operation == QuickAppend || Members.empty())
461 return IA_AddOldMember;
463 std::vector<std::string>::iterator MI =
464 std::find_if(Members.begin(), Members.end(), HasName(Name));
466 if (MI == Members.end())
467 return IA_AddOldMember;
471 if (Operation == Delete)
474 if (Operation == Move)
475 return IA_MoveOldMember;
477 if (Operation == ReplaceOrInsert) {
478 StringRef PosName = sys::path::filename(RelPos);
481 return IA_AddNewMeber;
482 return IA_MoveNewMember;
485 // We could try to optimize this to a fstat, but it is not a common
487 sys::fs::file_status Status;
488 failIfError(sys::fs::status(*MI, Status));
489 if (Status.getLastModificationTime() < I->getLastModified()) {
491 return IA_AddOldMember;
492 return IA_MoveOldMember;
496 return IA_AddNewMeber;
497 return IA_MoveNewMember;
499 llvm_unreachable("No such operation");
502 // We have to walk this twice and computing it is not trivial, so creating an
503 // explicit std::vector is actually fairly efficient.
504 static std::vector<NewArchiveIterator>
505 computeNewArchiveMembers(ArchiveOperation Operation,
506 object::Archive *OldArchive,
507 std::string &StringTable) {
508 std::vector<NewArchiveIterator> Ret;
509 std::vector<NewArchiveIterator> Moved;
511 StringRef PosName = sys::path::filename(RelPos);
513 for (object::Archive::child_iterator I = OldArchive->begin_children(),
514 E = OldArchive->end_children();
516 int Pos = Ret.size();
518 failIfError(I->getName(Name));
519 if (Name == PosName) {
520 assert(AddAfter || AddBefore);
527 std::vector<std::string>::iterator MemberI = Members.end();
528 InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
530 case IA_AddOldMember:
531 addMember(Ret, StringTable, I, Name);
534 addMember(Ret, StringTable, &*MemberI, Name);
538 case IA_MoveOldMember:
539 addMember(Moved, StringTable, I, Name);
541 case IA_MoveNewMember:
542 addMember(Moved, StringTable, &*MemberI, Name);
545 if (MemberI != Members.end())
546 Members.erase(MemberI);
550 if (Operation == Delete)
553 if (!RelPos.empty() && InsertPos == -1)
554 fail("Insertion point not found");
557 InsertPos = Ret.size();
559 assert(unsigned(InsertPos) <= Ret.size());
560 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
562 Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
564 for (std::vector<std::string>::iterator I = Members.begin(),
566 I != E; ++I, ++Pos) {
567 StringRef Name = sys::path::filename(*I);
568 addMember(Ret, StringTable, &*I, Name, Pos);
574 template <typename T>
575 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
576 uint64_t OldPos = OS.tell();
578 unsigned SizeSoFar = OS.tell() - OldPos;
579 assert(Size >= SizeSoFar && "Data doesn't fit in Size");
580 unsigned Remaining = Size - SizeSoFar;
581 for (unsigned I = 0; I < Remaining; ++I)
585 static void performWriteOperation(ArchiveOperation Operation,
586 object::Archive *OldArchive) {
587 SmallString<128> TmpArchive;
588 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
589 TmpArchiveFD, TmpArchive));
591 TemporaryOutput = TmpArchive.c_str();
592 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
593 raw_fd_ostream &Out = Output.os();
596 std::string StringTable;
597 std::vector<NewArchiveIterator> NewMembers =
598 computeNewArchiveMembers(Operation, OldArchive, StringTable);
599 if (!StringTable.empty()) {
600 if (StringTable.size() % 2)
602 printWithSpacePadding(Out, "//", 48);
603 printWithSpacePadding(Out, StringTable.size(), 10);
608 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
609 E = NewMembers.end();
611 StringRef Name = I->getMemberName();
612 printWithSpacePadding(Out, Name, 16);
614 if (I->isNewMember()) {
615 const char *FileName = I->getNew();
618 failIfError(sys::fs::openFileForRead(FileName, FD), FileName);
620 sys::fs::file_status Status;
621 failIfError(sys::fs::status(FD, Status), FileName);
623 OwningPtr<MemoryBuffer> File;
625 MemoryBuffer::getOpenFile(FD, FileName, File, Status.getSize()),
628 uint64_t secondsSinceEpoch =
629 Status.getLastModificationTime().toEpochTime();
630 printWithSpacePadding(Out, secondsSinceEpoch, 12);
632 printWithSpacePadding(Out, Status.getUser(), 6);
633 printWithSpacePadding(Out, Status.getGroup(), 6);
634 printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
635 printWithSpacePadding(Out, Status.getSize(), 10);
638 Out << File->getBuffer();
640 object::Archive::child_iterator OldMember = I->getOld();
642 uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
643 printWithSpacePadding(Out, secondsSinceEpoch, 12);
645 printWithSpacePadding(Out, OldMember->getUID(), 6);
646 printWithSpacePadding(Out, OldMember->getGID(), 6);
647 printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
648 printWithSpacePadding(Out, OldMember->getSize(), 10);
651 Out << OldMember->getBuffer();
659 sys::fs::rename(TemporaryOutput, ArchiveName);
660 TemporaryOutput = NULL;
663 static void performOperation(ArchiveOperation Operation,
664 object::Archive *OldArchive) {
669 performReadOperation(Operation, OldArchive);
675 case ReplaceOrInsert:
676 performWriteOperation(Operation, OldArchive);
679 llvm_unreachable("Unknown operation.");
682 // main - main program for llvm-ar .. see comments in the code
683 int main(int argc, char **argv) {
685 // Print a stack trace if we signal out.
686 sys::PrintStackTraceOnErrorSignal();
687 PrettyStackTraceProgram X(argc, argv);
688 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
690 // Have the command line options parsed and handle things
691 // like --help and --version.
692 cl::ParseCommandLineOptions(argc, argv,
693 "LLVM Archiver (llvm-ar)\n\n"
694 " This program archives bitcode files into single libraries\n"
697 // Do our own parsing of the command line because the CommandLine utility
698 // can't handle the grouped positional parameters without a dash.
699 ArchiveOperation Operation = parseCommandLine();
701 // Create or open the archive object.
702 OwningPtr<MemoryBuffer> Buf;
703 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
704 if (EC && EC != llvm::errc::no_such_file_or_directory) {
705 errs() << argv[0] << ": error opening '" << ArchiveName
706 << "': " << EC.message() << "!\n";
711 object::Archive Archive(Buf.take(), EC);
714 errs() << argv[0] << ": error loading '" << ArchiveName
715 << "': " << EC.message() << "!\n";
718 performOperation(Operation, &Archive);
722 assert(EC == llvm::errc::no_such_file_or_directory);
724 if (!shouldCreateArchive(Operation)) {
725 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
728 // Produce a warning if we should and we're creating the archive
729 errs() << argv[0] << ": creating " << ArchiveName << "\n";
733 performOperation(Operation, NULL);