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;
44 static int TmpArchiveFD = -1;
46 // fail - Show the error message and exit.
47 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
48 outs() << ToolName << ": " << Error << ".\n";
49 if (TmpArchiveFD != -1)
52 sys::fs::remove(TemporaryOutput);
56 static void failIfError(error_code EC, Twine Context = "") {
60 std::string ContextStr = Context.str();
63 fail(Context + ": " + EC.message());
66 // Option for compatibility with AIX, not used but must allow it to be present.
68 X32Option ("X32_64", cl::Hidden,
69 cl::desc("Ignored option for compatibility with AIX"));
71 // llvm-ar operation code and modifier flags. This must come first.
72 static cl::opt<std::string>
73 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
75 // llvm-ar remaining positional arguments.
76 static cl::list<std::string>
77 RestOfArgs(cl::Positional, cl::OneOrMore,
78 cl::desc("[relpos] [count] <archive-file> [members]..."));
80 // MoreHelp - Provide additional help output explaining the operations and
81 // modifiers of llvm-ar. This object instructs the CommandLine library
82 // to print the text of the constructor when the --help option is given.
83 static cl::extrahelp MoreHelp(
85 " d[NsS] - delete file(s) from the archive\n"
86 " m[abiSs] - move file(s) in the archive\n"
87 " p[kN] - print file(s) found in the archive\n"
88 " q[ufsS] - quick append file(s) to the archive\n"
89 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
90 " t - display contents of archive\n"
91 " x[No] - extract file(s) from the archive\n"
92 "\nMODIFIERS (operation specific):\n"
93 " [a] - put file(s) after [relpos]\n"
94 " [b] - put file(s) before [relpos] (same as [i])\n"
95 " [i] - put file(s) before [relpos] (same as [b])\n"
96 " [N] - use instance [count] of name\n"
97 " [o] - preserve original dates\n"
98 " [s] - create an archive index (cf. ranlib)\n"
99 " [S] - do not build a symbol table\n"
100 " [u] - update only files newer than archive contents\n"
101 "\nMODIFIERS (generic):\n"
102 " [c] - do not warn if the library had to be created\n"
103 " [v] - be verbose about actions taken\n"
106 // This enumeration delineates the kinds of operations on an archive
107 // that are permitted.
108 enum ArchiveOperation {
109 Print, ///< Print the contents of the archive
110 Delete, ///< Delete the specified members
111 Move, ///< Move members to end or as given by {a,b,i} modifiers
112 QuickAppend, ///< Quickly append to end of archive
113 ReplaceOrInsert, ///< Replace or Insert members
114 DisplayTable, ///< Display the table of contents
115 Extract ///< Extract files back to file system
118 // Modifiers to follow operation to vary behavior
119 static bool AddAfter = false; ///< 'a' modifier
120 static bool AddBefore = false; ///< 'b' modifier
121 static bool Create = false; ///< 'c' modifier
122 static bool OriginalDates = false; ///< 'o' modifier
123 static bool OnlyUpdate = false; ///< 'u' modifier
124 static bool Verbose = false; ///< 'v' modifier
126 // Relative Positional Argument (for insert/move). This variable holds
127 // the name of the archive member to which the 'a', 'b' or 'i' modifier
128 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
130 static std::string RelPos;
132 // This variable holds the name of the archive file as given on the
134 static std::string ArchiveName;
136 // This variable holds the list of member files to proecess, as given
137 // on the command line.
138 static std::vector<std::string> Members;
140 // show_help - Show the error message, the help message and exit.
141 LLVM_ATTRIBUTE_NORETURN static void
142 show_help(const std::string &msg) {
143 errs() << ToolName << ": " << msg << "\n\n";
144 cl::PrintHelpMessage();
148 // getRelPos - Extract the member filename from the command line for
149 // the [relpos] argument associated with a, b, and i modifiers
150 static void getRelPos() {
151 if(RestOfArgs.size() == 0)
152 show_help("Expected [relpos] for a, b, or i modifier");
153 RelPos = RestOfArgs[0];
154 RestOfArgs.erase(RestOfArgs.begin());
157 // getArchive - Get the archive file name from the command line
158 static void getArchive() {
159 if(RestOfArgs.size() == 0)
160 show_help("An archive name must be specified");
161 ArchiveName = RestOfArgs[0];
162 RestOfArgs.erase(RestOfArgs.begin());
165 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
166 // This is just for clarity.
167 static void getMembers() {
168 if(RestOfArgs.size() > 0)
169 Members = std::vector<std::string>(RestOfArgs);
172 // parseCommandLine - Parse the command line options as presented and return the
173 // operation specified. Process all modifiers and check to make sure that
174 // constraints on modifier/operation pairs have not been violated.
175 static ArchiveOperation parseCommandLine() {
177 // Keep track of number of operations. We can only specify one
179 unsigned NumOperations = 0;
181 // Keep track of the number of positional modifiers (a,b,i). Only
182 // one can be specified.
183 unsigned NumPositional = 0;
185 // Keep track of which operation was requested
186 ArchiveOperation Operation;
188 for(unsigned i=0; i<Options.size(); ++i) {
190 case 'd': ++NumOperations; Operation = Delete; break;
191 case 'm': ++NumOperations; Operation = Move ; break;
192 case 'p': ++NumOperations; Operation = Print; break;
193 case 'q': ++NumOperations; Operation = QuickAppend; break;
194 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
195 case 't': ++NumOperations; Operation = DisplayTable; break;
196 case 'x': ++NumOperations; Operation = Extract; break;
197 case 'c': Create = true; break;
198 case 'l': /* accepted but unused */ break;
199 case 'o': OriginalDates = true; break;
200 case 's': break; // Ignore for now.
201 case 'S': break; // Ignore for now.
202 case 'u': OnlyUpdate = true; break;
203 case 'v': Verbose = true; break;
220 cl::PrintHelpMessage();
224 // At this point, the next thing on the command line must be
228 // Everything on the command line at this point is a member.
231 // Perform various checks on the operation/modifier specification
232 // to make sure we are dealing with a legal request.
233 if (NumOperations == 0)
234 show_help("You must specify at least one of the operations");
235 if (NumOperations > 1)
236 show_help("Only one operation may be specified");
237 if (NumPositional > 1)
238 show_help("You may only specify one of a, b, and i modifiers");
239 if (AddAfter || AddBefore) {
240 if (Operation != Move && Operation != ReplaceOrInsert)
241 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
242 "the 'm' or 'r' operations");
244 if (OriginalDates && Operation != Extract)
245 show_help("The 'o' modifier is only applicable to the 'x' operation");
246 if (OnlyUpdate && Operation != ReplaceOrInsert)
247 show_help("The 'u' modifier is only applicable to the 'r' operation");
249 // Return the parsed operation to the caller
253 // Implements the 'p' operation. This function traverses the archive
254 // looking for members that match the path list.
255 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
257 outs() << "Printing " << Name << "\n";
259 StringRef Data = I->getBuffer();
260 outs().write(Data.data(), Data.size());
263 // putMode - utility function for printing out the file mode when the 't'
264 // operation is in verbose mode.
265 static void printMode(unsigned mode) {
280 // Implement the 't' operation. This function prints out just
281 // the file names of each of the members. However, if verbose mode is requested
282 // ('v' modifier) then the file type, permission mode, user, group, size, and
283 // modification time are also printed.
284 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
286 sys::fs::perms Mode = I->getAccessMode();
287 printMode((Mode >> 6) & 007);
288 printMode((Mode >> 3) & 007);
289 printMode(Mode & 007);
290 outs() << ' ' << I->getUID();
291 outs() << '/' << I->getGID();
292 outs() << ' ' << format("%6llu", I->getSize());
293 outs() << ' ' << I->getLastModified().str();
296 outs() << Name << "\n";
299 // Implement the 'x' operation. This function extracts files back to the file
301 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
302 // Open up a file stream for writing
303 // FIXME: we should abstract this, O_BINARY in particular.
304 int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
306 OpenFlags |= O_BINARY;
309 // Retain the original mode.
310 sys::fs::perms Mode = I->getAccessMode();
312 int FD = open(Name.str().c_str(), OpenFlags, Mode);
314 fail("Could not open output file");
317 raw_fd_ostream file(FD, false);
319 // Get the data and its length
320 StringRef Data = I->getBuffer();
323 file.write(Data.data(), Data.size());
326 // If we're supposed to retain the original modification times, etc. do so
330 sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
333 fail("Could not close the file");
336 static bool shouldCreateArchive(ArchiveOperation Op) {
346 case ReplaceOrInsert:
350 llvm_unreachable("Missing entry in covered switch.");
353 static void performReadOperation(ArchiveOperation Operation,
354 object::Archive *OldArchive) {
355 for (object::Archive::child_iterator I = OldArchive->begin_children(),
356 E = OldArchive->end_children();
359 failIfError(I->getName(Name));
361 if (!Members.empty() &&
362 std::find(Members.begin(), Members.end(), Name) == Members.end())
367 llvm_unreachable("Not a read operation");
372 doDisplayTable(Name, I);
382 class NewArchiveIterator {
384 SmallString<16> MemberName;
385 object::Archive::child_iterator OldI;
386 std::vector<std::string>::const_iterator NewI;
389 NewArchiveIterator(object::Archive::child_iterator I, Twine Name);
390 NewArchiveIterator(std::vector<std::string>::const_iterator I, Twine Name);
391 bool isNewMember() const;
392 object::Archive::child_iterator getOld() const;
393 const char *getNew() const;
394 StringRef getMemberName() const { return MemberName; }
398 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
400 : IsNewMember(false), OldI(I) {
401 Name.toVector(MemberName);
404 NewArchiveIterator::NewArchiveIterator(
405 std::vector<std::string>::const_iterator I, Twine Name)
406 : IsNewMember(true), NewI(I) {
407 Name.toVector(MemberName);
410 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
412 object::Archive::child_iterator NewArchiveIterator::getOld() const {
413 assert(!IsNewMember);
417 const char *NewArchiveIterator::getNew() const {
419 return NewI->c_str();
422 template <typename T>
423 void addMember(std::vector<NewArchiveIterator> &Members,
424 std::string &StringTable, T I, StringRef Name) {
425 if (Name.size() < 16) {
426 NewArchiveIterator NI(I, Twine(Name) + "/");
427 Members.push_back(NI);
429 int MapIndex = StringTable.size();
430 NewArchiveIterator NI(I, Twine("/") + Twine(MapIndex));
431 Members.push_back(NI);
433 StringTable += "/\n";
442 HasName(StringRef Name) : Name(Name) {}
443 bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
447 // We have to walk this twice and computing it is not trivial, so creating an
448 // explicit std::vector is actually fairly efficient.
449 static std::vector<NewArchiveIterator>
450 computeNewArchiveMembers(ArchiveOperation Operation,
451 object::Archive *OldArchive,
452 std::string &StringTable) {
453 std::vector<NewArchiveIterator> Ret;
454 std::vector<NewArchiveIterator> Moved;
456 StringRef PosName = sys::path::filename(RelPos);
459 for (object::Archive::child_iterator I = OldArchive->begin_children(),
460 E = OldArchive->end_children();
461 I != E; ++I, ++Pos) {
463 failIfError(I->getName(Name));
464 if (Name == PosName) {
465 assert(AddAfter || AddBefore);
471 if (Operation != QuickAppend && !Members.empty()) {
472 std::vector<std::string>::iterator MI =
473 std::find_if(Members.begin(), Members.end(), HasName(Name));
474 if (MI != Members.end()) {
475 if (Operation == Move) {
476 addMember(Moved, StringTable, I, Name);
479 if (Operation != ReplaceOrInsert || !OnlyUpdate)
481 // Ignore if the file if it is older than the member.
482 sys::fs::file_status Status;
483 failIfError(sys::fs::status(*MI, Status));
484 if (Status.getLastModificationTime() < I->getLastModified())
490 addMember(Ret, StringTable, I, Name);
494 if (Operation == Delete)
497 if (Operation == Move) {
498 if (RelPos.empty()) {
499 Ret.insert(Ret.end(), Moved.begin(), Moved.end());
503 fail("Insertion point not found");
504 assert(unsigned(InsertPos) <= Ret.size());
505 Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
509 for (std::vector<std::string>::iterator I = Members.begin(),
512 StringRef Name = sys::path::filename(*I);
513 addMember(Ret, StringTable, I, Name);
519 template <typename T>
520 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
521 uint64_t OldPos = OS.tell();
523 unsigned SizeSoFar = OS.tell() - OldPos;
524 assert(Size >= SizeSoFar && "Data doesn't fit in Size");
525 unsigned Remaining = Size - SizeSoFar;
526 for (unsigned I = 0; I < Remaining; ++I)
530 static void performWriteOperation(ArchiveOperation Operation,
531 object::Archive *OldArchive) {
532 SmallString<128> TmpArchive;
533 failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
534 TmpArchiveFD, TmpArchive));
536 TemporaryOutput = TmpArchive.c_str();
537 tool_output_file Output(TemporaryOutput, TmpArchiveFD);
538 raw_fd_ostream &Out = Output.os();
541 std::string StringTable;
542 std::vector<NewArchiveIterator> NewMembers =
543 computeNewArchiveMembers(Operation, OldArchive, StringTable);
544 if (!StringTable.empty()) {
545 if (StringTable.size() % 2)
547 printWithSpacePadding(Out, "//", 48);
548 printWithSpacePadding(Out, StringTable.size(), 10);
553 for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
554 E = NewMembers.end();
556 StringRef Name = I->getMemberName();
557 printWithSpacePadding(Out, Name, 16);
559 if (I->isNewMember()) {
560 const char *FileName = I->getNew();
562 int OpenFlags = O_RDONLY;
564 OpenFlags |= O_BINARY;
566 int FD = ::open(FileName, OpenFlags);
568 return failIfError(error_code(errno, posix_category()), FileName);
570 sys::fs::file_status Status;
571 failIfError(sys::fs::status(FD, Status), FileName);
573 OwningPtr<MemoryBuffer> File;
575 MemoryBuffer::getOpenFile(FD, FileName, File, Status.getSize()),
578 uint64_t secondsSinceEpoch =
579 Status.getLastModificationTime().toEpochTime();
580 printWithSpacePadding(Out, secondsSinceEpoch, 12);
582 printWithSpacePadding(Out, Status.getUser(), 6);
583 printWithSpacePadding(Out, Status.getGroup(), 6);
584 printWithSpacePadding(Out, format("%o", Status.permissions()), 8);
585 printWithSpacePadding(Out, Status.getSize(), 10);
588 Out << File->getBuffer();
590 object::Archive::child_iterator OldMember = I->getOld();
592 uint64_t secondsSinceEpoch = OldMember->getLastModified().toEpochTime();
593 printWithSpacePadding(Out, secondsSinceEpoch, 12);
595 printWithSpacePadding(Out, OldMember->getUID(), 6);
596 printWithSpacePadding(Out, OldMember->getGID(), 6);
597 printWithSpacePadding(Out, format("%o", OldMember->getAccessMode()), 8);
598 printWithSpacePadding(Out, OldMember->getSize(), 10);
601 Out << OldMember->getBuffer();
609 sys::fs::rename(TemporaryOutput, ArchiveName);
610 TemporaryOutput = NULL;
613 static void performOperation(ArchiveOperation Operation,
614 object::Archive *OldArchive) {
619 performReadOperation(Operation, OldArchive);
625 case ReplaceOrInsert:
626 performWriteOperation(Operation, OldArchive);
629 llvm_unreachable("Unknown operation.");
632 // main - main program for llvm-ar .. see comments in the code
633 int main(int argc, char **argv) {
635 // Print a stack trace if we signal out.
636 sys::PrintStackTraceOnErrorSignal();
637 PrettyStackTraceProgram X(argc, argv);
638 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
640 // Have the command line options parsed and handle things
641 // like --help and --version.
642 cl::ParseCommandLineOptions(argc, argv,
643 "LLVM Archiver (llvm-ar)\n\n"
644 " This program archives bitcode files into single libraries\n"
647 // Do our own parsing of the command line because the CommandLine utility
648 // can't handle the grouped positional parameters without a dash.
649 ArchiveOperation Operation = parseCommandLine();
651 // Create or open the archive object.
652 OwningPtr<MemoryBuffer> Buf;
653 error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
654 if (EC && EC != llvm::errc::no_such_file_or_directory) {
655 errs() << argv[0] << ": error opening '" << ArchiveName
656 << "': " << EC.message() << "!\n";
661 object::Archive Archive(Buf.take(), EC);
664 errs() << argv[0] << ": error loading '" << ArchiveName
665 << "': " << EC.message() << "!\n";
668 performOperation(Operation, &Archive);
672 assert(EC == llvm::errc::no_such_file_or_directory);
674 if (!shouldCreateArchive(Operation)) {
675 failIfError(EC, Twine("error loading '") + ArchiveName + "'");
678 // Produce a warning if we should and we're creating the archive
679 errs() << argv[0] << ": creating " << ArchiveName << "\n";
683 performOperation(Operation, NULL);