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"
32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
40 // The name this program was invoked as.
41 static StringRef ToolName;
43 static const char *TemporaryOutput;
45 // fail - Show the error message and exit.
46 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
47 outs() << ToolName << ": " << Error << ".\n";
49 sys::fs::remove(TemporaryOutput);
53 static void failIfError(error_code EC, Twine Context = "") {
57 std::string ContextStr = Context.str();
60 fail(Context + ": " + EC.message());
63 // Option for compatibility with AIX, not used but must allow it to be present.
65 X32Option ("X32_64", cl::Hidden,
66 cl::desc("Ignored option for compatibility with AIX"));
68 // llvm-ar operation code and modifier flags. This must come first.
69 static cl::opt<std::string>
70 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
72 // llvm-ar remaining positional arguments.
73 static cl::list<std::string>
74 RestOfArgs(cl::Positional, cl::OneOrMore,
75 cl::desc("[relpos] [count] <archive-file> [members]..."));
77 // MoreHelp - Provide additional help output explaining the operations and
78 // modifiers of llvm-ar. This object instructs the CommandLine library
79 // to print the text of the constructor when the --help option is given.
80 static cl::extrahelp MoreHelp(
82 " d[NsS] - delete file(s) from the archive\n"
83 " m[abiSs] - move file(s) in the archive\n"
84 " p[kN] - print file(s) found in the archive\n"
85 " q[ufsS] - quick append file(s) to the archive\n"
86 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
87 " t - display contents of archive\n"
88 " x[No] - extract file(s) from the archive\n"
89 "\nMODIFIERS (operation specific):\n"
90 " [a] - put file(s) after [relpos]\n"
91 " [b] - put file(s) before [relpos] (same as [i])\n"
92 " [i] - put file(s) before [relpos] (same as [b])\n"
93 " [N] - use instance [count] of name\n"
94 " [o] - preserve original dates\n"
95 " [s] - create an archive index (cf. ranlib)\n"
96 " [S] - do not build a symbol table\n"
97 " [u] - update only files newer than archive contents\n"
98 "\nMODIFIERS (generic):\n"
99 " [c] - do not warn if the library had to be created\n"
100 " [v] - be verbose about actions taken\n"
103 // This enumeration delineates the kinds of operations on an archive
104 // that are permitted.
105 enum ArchiveOperation {
106 Print, ///< Print the contents of the archive
107 Delete, ///< Delete the specified members
108 Move, ///< Move members to end or as given by {a,b,i} modifiers
109 QuickAppend, ///< Quickly append to end of archive
110 ReplaceOrInsert, ///< Replace or Insert members
111 DisplayTable, ///< Display the table of contents
112 Extract ///< Extract files back to file system
115 // Modifiers to follow operation to vary behavior
116 static bool AddAfter = false; ///< 'a' modifier
117 static bool AddBefore = false; ///< 'b' modifier
118 static bool Create = false; ///< 'c' modifier
119 static bool OriginalDates = false; ///< 'o' modifier
120 static bool OnlyUpdate = false; ///< 'u' modifier
121 static bool Verbose = false; ///< 'v' modifier
123 // Relative Positional Argument (for insert/move). This variable holds
124 // the name of the archive member to which the 'a', 'b' or 'i' modifier
125 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
127 static std::string RelPos;
129 // This variable holds the name of the archive file as given on the
131 static std::string ArchiveName;
133 // This variable holds the list of member files to proecess, as given
134 // on the command line.
135 static std::vector<std::string> Members;
137 // show_help - Show the error message, the help message and exit.
138 LLVM_ATTRIBUTE_NORETURN static void
139 show_help(const std::string &msg) {
140 errs() << ToolName << ": " << msg << "\n\n";
141 cl::PrintHelpMessage();
145 // getRelPos - Extract the member filename from the command line for
146 // the [relpos] argument associated with a, b, and i modifiers
147 static void getRelPos() {
148 if(RestOfArgs.size() == 0)
149 show_help("Expected [relpos] for a, b, or i modifier");
150 RelPos = RestOfArgs[0];
151 RestOfArgs.erase(RestOfArgs.begin());
154 // getArchive - Get the archive file name from the command line
155 static void getArchive() {
156 if(RestOfArgs.size() == 0)
157 show_help("An archive name must be specified");
158 ArchiveName = RestOfArgs[0];
159 RestOfArgs.erase(RestOfArgs.begin());
162 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
163 // This is just for clarity.
164 static void getMembers() {
165 if(RestOfArgs.size() > 0)
166 Members = std::vector<std::string>(RestOfArgs);
169 // parseCommandLine - Parse the command line options as presented and return the
170 // operation specified. Process all modifiers and check to make sure that
171 // constraints on modifier/operation pairs have not been violated.
172 static ArchiveOperation parseCommandLine() {
174 // Keep track of number of operations. We can only specify one
176 unsigned NumOperations = 0;
178 // Keep track of the number of positional modifiers (a,b,i). Only
179 // one can be specified.
180 unsigned NumPositional = 0;
182 // Keep track of which operation was requested
183 ArchiveOperation Operation;
185 for(unsigned i=0; i<Options.size(); ++i) {
187 case 'd': ++NumOperations; Operation = Delete; break;
188 case 'm': ++NumOperations; Operation = Move ; break;
189 case 'p': ++NumOperations; Operation = Print; break;
190 case 'q': ++NumOperations; Operation = QuickAppend; break;
191 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
192 case 't': ++NumOperations; Operation = DisplayTable; break;
193 case 'x': ++NumOperations; Operation = Extract; break;
194 case 'c': Create = true; break;
195 case 'l': /* accepted but unused */ break;
196 case 'o': OriginalDates = true; break;
197 case 's': break; // Ignore for now.
198 case 'S': break; // Ignore for now.
199 case 'u': OnlyUpdate = true; break;
200 case 'v': Verbose = true; break;
217 cl::PrintHelpMessage();
221 // At this point, the next thing on the command line must be
225 // Everything on the command line at this point is a member.
228 // Perform various checks on the operation/modifier specification
229 // to make sure we are dealing with a legal request.
230 if (NumOperations == 0)
231 show_help("You must specify at least one of the operations");
232 if (NumOperations > 1)
233 show_help("Only one operation may be specified");
234 if (NumPositional > 1)
235 show_help("You may only specify one of a, b, and i modifiers");
236 if (AddAfter || AddBefore) {
237 if (Operation != Move && Operation != ReplaceOrInsert)
238 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
239 "the 'm' or 'r' operations");
241 if (OriginalDates && Operation != Extract)
242 show_help("The 'o' modifier is only applicable to the 'x' operation");
243 if (OnlyUpdate && Operation != ReplaceOrInsert)
244 show_help("The 'u' modifier is only applicable to the 'r' operation");
246 // Return the parsed operation to the caller
250 // Implements the 'p' operation. This function traverses the archive
251 // looking for members that match the path list.
252 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
254 outs() << "Printing " << Name << "\n";
256 StringRef Data = I->getBuffer();
257 outs().write(Data.data(), Data.size());
260 // putMode - utility function for printing out the file mode when the 't'
261 // operation is in verbose mode.
262 static void printMode(unsigned mode) {
277 // Implement the 't' operation. This function prints out just
278 // the file names of each of the members. However, if verbose mode is requested
279 // ('v' modifier) then the file type, permission mode, user, group, size, and
280 // modification time are also printed.
281 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
283 sys::fs::perms Mode = I->getAccessMode();
284 printMode((Mode >> 6) & 007);
285 printMode((Mode >> 3) & 007);
286 printMode(Mode & 007);
287 outs() << ' ' << I->getUID();
288 outs() << '/' << I->getGID();
289 outs() << ' ' << format("%6llu", I->getSize());
290 outs() << ' ' << I->getLastModified().str();
293 outs() << Name << "\n";
296 // Implement the 'x' operation. This function extracts files back to the file
298 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
299 // Open up a file stream for writing
300 // FIXME: we should abstract this, O_BINARY in particular.
301 int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
303 OpenFlags |= O_BINARY;
306 // Retain the original mode.
307 sys::fs::perms Mode = I->getAccessMode();
309 int FD = open(Name.str().c_str(), OpenFlags, Mode);
311 fail("Could not open output file");
314 raw_fd_ostream file(FD, false);
316 // Get the data and its length
317 StringRef Data = I->getBuffer();
320 file.write(Data.data(), Data.size());
323 // If we're supposed to retain the original modification times, etc. do so
327 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
330 fail("Could not close the file");
333 static bool shouldCreateArchive(ArchiveOperation Op) {
343 case ReplaceOrInsert:
347 llvm_unreachable("Missing entry in covered switch.");
350 static void performReadOperation(ArchiveOperation Operation,
351 object::Archive *OldArchive) {
352 for (object::Archive::child_iterator I = OldArchive->begin_children(),
353 E = OldArchive->end_children();
356 failIfError(I->getName(Name));
358 if (!Members.empty() &&
359 std::find(Members.begin(), Members.end(), Name) == Members.end())
364 llvm_unreachable("Not a read operation");
369 doDisplayTable(Name, I);
379 class NewArchiveIterator {
381 SmallString<16> MemberName;
382 object::Archive::child_iterator OldI;
383 std::vector<std::string>::const_iterator NewI;
386 NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
387 NewArchiveIterator(std::vector<std::string>::const_iterator I, Twine Name);
388 bool isNewMember() const;
389 object::Archive::child_iterator getOld() const;
390 const char *getNew() const;
391 StringRef getMemberName() const { return MemberName; }
395 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
397 : IsNewMember(false), OldI(I) {
398 Name.toVector(MemberName);
401 NewArchiveIterator::NewArchiveIterator(
402 std::vector<std::string>::const_iterator I, Twine Name)
403 : IsNewMember(true), NewI(I) {
404 Name.toVector(MemberName);
407 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
409 object::Archive::child_iterator NewArchiveIterator::getOld() const {
410 assert(!IsNewMember);
414 const char *NewArchiveIterator::getNew() const {
416 return NewI->c_str();
419 template <typename T>
420 void addMember(std::vector<NewArchiveIterator> &Members,
421 std::string &StringTable, T I, StringRef Name) {
422 if (Name.size() < 16) {
423 NewArchiveIterator NI(I, Twine(Name) + "/");
424 Members.push_back(NI);
426 int MapIndex = StringTable.size();
427 NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
428 Members.push_back(NI);
430 StringTable += "/\n";
439 HasName(StringRef Name) : Name(Name) {}
440 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
444 // We have to walk this twice and computing it is not trivial, so creating an
445 // explicit std::vector is actually fairly efficient.
446 static std::vector<NewArchiveIterator>
447 computeNewArchiveMembers(ArchiveOperation Operation,
448 object::Archive *OldArchive,
449 std::string &StringTable) {
450 std::vector<NewArchiveIterator> Ret;
451 std::vector<NewArchiveIterator> Moved;
453 StringRef PosName = sys::path::filename(RelPos);
456 for (object::Archive::child_iterator I = OldArchive->begin_children(),
457 E = OldArchive->end_children();
458 I != E; ++I, ++Pos) {
460 failIfError(I->getName(Name));
461 if (Name == PosName) {
462 assert(AddAfter || AddBefore);
468 if (Operation != QuickAppend && !Members.empty()) {
469 std::vector<std::string>::iterator MI =
470 std::find_if(Members.begin(), Members.end(), HasName(Name));
471 if (MI != Members.end()) {
472 if (Operation == Move) {
473 addMember(Moved, StringTable, I, Name);
476 if (Operation != ReplaceOrInsert || !OnlyUpdate)
478 // Ignore if the file if it is older than the member.
479 sys::fs::file_status Status;
480 failIfError(sys::fs::status(*MI, Status));
481 if (Status.getLastModificationTime() < I->getLastModified())
487 addMember(Ret, StringTable, I, Name);
491 if (Operation == Delete)
494 if (Operation == Move) {
495 if (RelPos.empty()) {
496 Ret.insert(Ret.end(), Moved.begin(), Moved.end());
500 fail("Insertion point not found");
501 assert(unsigned(InsertPos) <= Ret.size());
502 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
506 for (std::vector<std::string>::iterator I = Members.begin(),
509 StringRef Name = sys::path::filename(*I);
510 addMember(Ret, StringTable, I, Name);
516 template <typename T>
517 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
518 uint64_t OldPos = OS.tell();
520 unsigned SizeSoFar = OS.tell() - OldPos;
521 assert(Size >= SizeSoFar && "Data doesn't fit in Size");
522 unsigned Remaining = Size - SizeSoFar;
523 for (unsigned I = 0; I < Remaining; ++I)
527 static void performWriteOperation(ArchiveOperation Operation,
528 object::Archive *OldArchive) {
530 SmallString<128> TmpArchive;
531 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
532 TmpArchiveFD, TmpArchive));
534 TemporaryOutput = TmpArchive.c_str();
535 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
536 raw_fd_ostream &Out = Output.os();
539 std::string StringTable;
540 std::vector<NewArchiveIterator> NewMembers =
541 computeNewArchiveMembers(Operation, OldArchive, StringTable);
542 if (!StringTable.empty()) {
543 if (StringTable.size() % 2)
545 printWithSpacePadding(Out, "//", 48);
546 printWithSpacePadding(Out, StringTable.size(), 10);
551 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
552 E = NewMembers.end();
554 StringRef Name = I->getMemberName();
555 printWithSpacePadding(Out, Name, 16);
557 if (I->isNewMember()) {
558 // FIXME: we do a stat + open. We should do a open + fstat.
559 const char *FileName = I->getNew();
560 sys::fs::file_status Status;
561 failIfError(sys::fs::status(FileName, Status), FileName);
563 OwningPtr<MemoryBuffer> File;
564 failIfError(MemoryBuffer::getFile(FileName, File), FileName);
566 uint64_t secondsSinceEpoch =
567 Status.getLastModificationTime().toEpochTime();
568 printWithSpacePadding(Out, secondsSinceEpoch, 12);
570 printWithSpacePadding(Out, Status.getUser(), 6);
571 printWithSpacePadding(Out, Status.getGroup(), 6);
572 printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
573 printWithSpacePadding(Out, Status.getSize(), 10);
576 Out << File->getBuffer();
578 object::Archive::child_iterator OldMember = I->getOld();
580 uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
581 printWithSpacePadding(Out, secondsSinceEpoch, 12);
583 printWithSpacePadding(Out, OldMember->getUID(), 6);
584 printWithSpacePadding(Out, OldMember->getGID(), 6);
585 printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
586 printWithSpacePadding(Out, OldMember->getSize(), 10);
589 Out << OldMember->getBuffer();
597 sys::fs::rename(TemporaryOutput, ArchiveName);
598 TemporaryOutput = NULL;
601 static void performOperation(ArchiveOperation Operation,
602 object::Archive *OldArchive) {
607 performReadOperation(Operation, OldArchive);
613 case ReplaceOrInsert:
614 performWriteOperation(Operation, OldArchive);
617 llvm_unreachable("Unknown operation.");
620 // main - main program for llvm-ar .. see comments in the code
621 int main(int argc, char **argv) {
623 // Print a stack trace if we signal out.
624 sys::PrintStackTraceOnErrorSignal();
625 PrettyStackTraceProgram X(argc, argv);
626 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
628 // Have the command line options parsed and handle things
629 // like --help and --version.
630 cl::ParseCommandLineOptions(argc, argv,
631 "LLVM Archiver (llvm-ar)\n\n"
632 " This program archives bitcode files into single libraries\n"
635 // Do our own parsing of the command line because the CommandLine utility
636 // can't handle the grouped positional parameters without a dash.
637 ArchiveOperation Operation = parseCommandLine();
639 // Create or open the archive object.
640 OwningPtr<MemoryBuffer> Buf;
641 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
642 if (EC && EC != llvm::errc::no_such_file_or_directory) {
643 errs() << argv[0] << ": error opening '" << ArchiveName
644 << "': " << EC.message() << "!\n";
649 object::Archive Archive(Buf.take(), EC);
652 errs() << argv[0] << ": error loading '" << ArchiveName
653 << "': " << EC.message() << "!\n";
656 performOperation(Operation, &Archive);
660 assert(EC == llvm::errc::no_such_file_or_directory);
662 if (!shouldCreateArchive(Operation)) {
663 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
666 // Produce a warning if we should and we're creating the archive
667 errs() << argv[0] << ": creating " << ArchiveName << "\n";
671 performOperation(Operation, NULL);