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 //===----------------------------------------------------------------------===//
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Module.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/PrettyStackTrace.h"
23 #include "llvm/Support/Signals.h"
24 #include "llvm/Support/raw_ostream.h"
30 #if !defined(_MSC_VER) && !defined(__MINGW32__)
38 // Option for compatibility with AIX, not used but must allow it to be present.
40 X32Option ("X32_64", cl::Hidden,
41 cl::desc("Ignored option for compatibility with AIX"));
43 // llvm-ar operation code and modifier flags. This must come first.
44 static cl::opt<std::string>
45 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
47 // llvm-ar remaining positional arguments.
48 static cl::list<std::string>
49 RestOfArgs(cl::Positional, cl::OneOrMore,
50 cl::desc("[relpos] [count] <archive-file> [members]..."));
52 // MoreHelp - Provide additional help output explaining the operations and
53 // modifiers of llvm-ar. This object instructs the CommandLine library
54 // to print the text of the constructor when the --help option is given.
55 static cl::extrahelp MoreHelp(
57 " d[NsS] - delete file(s) from the archive\n"
58 " m[abiSs] - move file(s) in the archive\n"
59 " p[kN] - print file(s) found in the archive\n"
60 " q[ufsS] - quick append file(s) to the archive\n"
61 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
62 " t - display contents of archive\n"
63 " x[No] - extract file(s) from the archive\n"
64 "\nMODIFIERS (operation specific):\n"
65 " [a] - put file(s) after [relpos]\n"
66 " [b] - put file(s) before [relpos] (same as [i])\n"
67 " [f] - truncate inserted file names\n"
68 " [i] - put file(s) before [relpos] (same as [b])\n"
69 " [k] - always print bitcode files (default is to skip them)\n"
70 " [N] - use instance [count] of name\n"
71 " [o] - preserve original dates\n"
72 " [P] - use full path names when matching\n"
73 " [R] - recurse through directories when inserting\n"
74 " [s] - create an archive index (cf. ranlib)\n"
75 " [S] - do not build a symbol table\n"
76 " [u] - update only files newer than archive contents\n"
77 "\nMODIFIERS (generic):\n"
78 " [c] - do not warn if the library had to be created\n"
79 " [v] - be verbose about actions taken\n"
80 " [V] - be *really* verbose about actions taken\n"
83 // This enumeration delineates the kinds of operations on an archive
84 // that are permitted.
85 enum ArchiveOperation {
86 NoOperation, ///< An operation hasn't been specified
87 Print, ///< Print the contents of the archive
88 Delete, ///< Delete the specified members
89 Move, ///< Move members to end or as given by {a,b,i} modifiers
90 QuickAppend, ///< Quickly append to end of archive
91 ReplaceOrInsert, ///< Replace or Insert members
92 DisplayTable, ///< Display the table of contents
93 Extract ///< Extract files back to file system
96 // Modifiers to follow operation to vary behavior
97 bool AddAfter = false; ///< 'a' modifier
98 bool AddBefore = false; ///< 'b' modifier
99 bool Create = false; ///< 'c' modifier
100 bool TruncateNames = false; ///< 'f' modifier
101 bool InsertBefore = false; ///< 'i' modifier
102 bool UseCount = false; ///< 'N' modifier
103 bool OriginalDates = false; ///< 'o' modifier
104 bool FullPath = false; ///< 'P' modifier
105 bool SymTable = true; ///< 's' & 'S' modifiers
106 bool OnlyUpdate = false; ///< 'u' modifier
107 bool Verbose = false; ///< 'v' modifier
109 // Relative Positional Argument (for insert/move). This variable holds
110 // the name of the archive member to which the 'a', 'b' or 'i' modifier
111 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
115 // Select which of multiple entries in the archive with the same name should be
116 // used (specified with -N) for the delete and extract operations.
119 // This variable holds the name of the archive file as given on the
121 std::string ArchiveName;
123 // This variable holds the list of member files to proecess, as given
124 // on the command line.
125 std::vector<std::string> Members;
127 // This variable holds the (possibly expanded) list of path objects that
128 // correspond to files we will
129 std::set<std::string> Paths;
131 // The Archive object to which all the editing operations will be sent.
132 Archive* TheArchive = 0;
134 // The name this program was invoked as.
135 static const char *program_name;
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() << program_name << ": " << msg << "\n\n";
141 cl::PrintHelpMessage();
147 // fail - Show the error message and exit.
148 LLVM_ATTRIBUTE_NORETURN static void
149 fail(const std::string &msg) {
150 errs() << program_name << ": " << msg << "\n\n";
156 // getRelPos - Extract the member filename from the command line for
157 // the [relpos] argument associated with a, b, and i modifiers
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 // getCount - Extract the [count] argument associated with the N modifier
166 // from the command line and check its value.
168 if(RestOfArgs.size() == 0)
169 show_help("Expected [count] value with N modifier");
171 Count = atoi(RestOfArgs[0].c_str());
172 RestOfArgs.erase(RestOfArgs.begin());
174 // Non-positive counts are not allowed
176 show_help("Invalid [count] value (not a positive integer)");
179 // getArchive - Get the archive file name from the command line
181 if(RestOfArgs.size() == 0)
182 show_help("An archive name must be specified");
183 ArchiveName = RestOfArgs[0];
184 RestOfArgs.erase(RestOfArgs.begin());
187 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
188 // This is just for clarity.
190 if(RestOfArgs.size() > 0)
191 Members = std::vector<std::string>(RestOfArgs);
194 // parseCommandLine - Parse the command line options as presented and return the
195 // operation specified. Process all modifiers and check to make sure that
196 // constraints on modifier/operation pairs have not been violated.
197 ArchiveOperation parseCommandLine() {
199 // Keep track of number of operations. We can only specify one
201 unsigned NumOperations = 0;
203 // Keep track of the number of positional modifiers (a,b,i). Only
204 // one can be specified.
205 unsigned NumPositional = 0;
207 // Keep track of which operation was requested
208 ArchiveOperation Operation = NoOperation;
210 for(unsigned i=0; i<Options.size(); ++i) {
212 case 'd': ++NumOperations; Operation = Delete; break;
213 case 'm': ++NumOperations; Operation = Move ; break;
214 case 'p': ++NumOperations; Operation = Print; break;
215 case 'q': ++NumOperations; Operation = QuickAppend; break;
216 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
217 case 't': ++NumOperations; Operation = DisplayTable; break;
218 case 'x': ++NumOperations; Operation = Extract; break;
219 case 'c': Create = true; break;
220 case 'f': TruncateNames = true; break;
221 case 'l': /* accepted but unused */ break;
222 case 'o': OriginalDates = true; break;
223 case 's': break; // Ignore for now.
224 case 'S': break; // Ignore for now.
225 case 'P': FullPath = true; break;
226 case 'u': OnlyUpdate = true; break;
227 case 'v': Verbose = true; break;
248 cl::PrintHelpMessage();
252 // At this point, the next thing on the command line must be
256 // Everything on the command line at this point is a member.
259 // Perform various checks on the operation/modifier specification
260 // to make sure we are dealing with a legal request.
261 if (NumOperations == 0)
262 show_help("You must specify at least one of the operations");
263 if (NumOperations > 1)
264 show_help("Only one operation may be specified");
265 if (NumPositional > 1)
266 show_help("You may only specify one of a, b, and i modifiers");
267 if (AddAfter || AddBefore || InsertBefore) {
268 if (Operation != Move && Operation != ReplaceOrInsert)
269 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
270 "the 'm' or 'r' operations");
272 if (OriginalDates && Operation != Extract)
273 show_help("The 'o' modifier is only applicable to the 'x' operation");
274 if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert)
275 show_help("The 'f' modifier is only applicable to the 'q' and 'r' "
277 if (OnlyUpdate && Operation != ReplaceOrInsert)
278 show_help("The 'u' modifier is only applicable to the 'r' operation");
279 if (Count > 1 && Members.size() > 1)
280 show_help("Only one member name may be specified with the 'N' modifier");
282 // Return the parsed operation to the caller
286 // buildPaths - Convert the strings in the Members vector to sys::Path objects
287 // and make sure they are valid and exist exist. This check is only needed for
288 // the operations that add/replace files to the archive ('q' and 'r')
289 bool buildPaths(bool checkExistence, std::string* ErrMsg) {
290 for (unsigned i = 0; i < Members.size(); i++) {
291 std::string aPath = Members[i];
292 if (checkExistence) {
294 error_code EC = sys::fs::is_directory(aPath, IsDirectory);
296 fail(aPath + ": " + EC.message());
298 fail(aPath + " Is a directory");
308 // doPrint - Implements the 'p' operation. This function traverses the archive
309 // looking for members that match the path list. It is careful to uncompress
310 // things that should be and to skip bitcode files unless the 'k' modifier was
312 bool doPrint(std::string* ErrMsg) {
313 if (buildPaths(false, ErrMsg))
315 unsigned countDown = Count;
316 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
319 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
320 if (countDown == 1) {
321 const char* data = reinterpret_cast<const char*>(I->getData());
323 // Skip things that don't make sense to print
324 if (I->isSVR4SymbolTable() || I->isBSD4SymbolTable())
328 outs() << "Printing " << I->getPath().str() << "\n";
330 unsigned len = I->getSize();
331 outs().write(data, len);
340 // putMode - utility function for printing out the file mode when the 't'
341 // operation is in verbose mode.
343 printMode(unsigned mode) {
358 // doDisplayTable - Implement the 't' operation. This function prints out just
359 // the file names of each of the members. However, if verbose mode is requested
360 // ('v' modifier) then the file type, permission mode, user, group, size, and
361 // modification time are also printed.
363 doDisplayTable(std::string* ErrMsg) {
364 if (buildPaths(false, ErrMsg))
366 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
369 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
371 // FIXME: Output should be this format:
372 // Zrw-r--r-- 500/ 500 525 Nov 8 17:42 2004 Makefile
374 unsigned mode = I->getMode();
375 printMode((mode >> 6) & 007);
376 printMode((mode >> 3) & 007);
377 printMode(mode & 007);
378 outs() << " " << format("%4u", I->getUser());
379 outs() << "/" << format("%4u", I->getGroup());
380 outs() << " " << format("%8u", I->getSize());
381 outs() << " " << format("%20s", I->getModTime().str().substr(4).c_str());
382 outs() << " " << I->getPath().str() << "\n";
384 outs() << I->getPath().str() << "\n";
391 // doExtract - Implement the 'x' operation. This function extracts files back to
394 doExtract(std::string* ErrMsg) {
395 if (buildPaths(false, ErrMsg))
397 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
400 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
402 // Open up a file stream for writing
403 int OpenFlags = O_TRUNC | O_WRONLY | O_CREAT;
405 OpenFlags |= O_BINARY;
408 int FD = open(I->getPath().str().c_str(), OpenFlags, 0664);
413 raw_fd_ostream file(FD, false);
415 // Get the data and its length
416 const char* data = reinterpret_cast<const char*>(I->getData());
417 unsigned len = I->getSize();
420 file.write(data, len);
423 // Retain the original mode.
424 sys::fs::perms Mode = sys::fs::perms(I->getMode());
425 // FIXME: at least on posix we should be able to reuse FD (fchmod).
426 error_code EC = sys::fs::permissions(I->getPath(), Mode);
430 // If we're supposed to retain the original modification times, etc. do so
433 EC = sys::fs::setLastModificationAndAccessTime(FD, I->getModTime());
444 // doDelete - Implement the delete operation. This function deletes zero or more
445 // members from the archive. Note that if the count is specified, there should
446 // be no more than one path in the Paths list or else this algorithm breaks.
447 // That check is enforced in parseCommandLine (above).
449 doDelete(std::string* ErrMsg) {
450 if (buildPaths(false, ErrMsg))
454 unsigned countDown = Count;
455 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
457 if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
458 if (countDown == 1) {
459 Archive::iterator J = I;
461 TheArchive->erase(J);
469 // We're done editting, reconstruct the archive.
470 if (TheArchive->writeToDisk(TruncateNames,ErrMsg))
475 // doMore - Implement the move operation. This function re-arranges just the
476 // order of the archive members so that when the archive is written the move
477 // of the members is accomplished. Note the use of the RelPos variable to
478 // determine where the items should be moved to.
480 doMove(std::string* ErrMsg) {
481 if (buildPaths(false, ErrMsg))
484 // By default and convention the place to move members to is the end of the
486 Archive::iterator moveto_spot = TheArchive->end();
488 // However, if the relative positioning modifiers were used, we need to scan
489 // the archive to find the member in question. If we don't find it, its no
490 // crime, we just move to the end.
491 if (AddBefore || InsertBefore || AddAfter) {
492 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
494 if (RelPos == I->getPath().str()) {
506 // Keep a list of the paths remaining to be moved
507 std::set<std::string> remaining(Paths);
509 // Scan the archive again, this time looking for the members to move to the
511 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
512 I != E && !remaining.empty(); ++I ) {
513 std::set<std::string>::iterator found =
514 std::find(remaining.begin(),remaining.end(), I->getPath());
515 if (found != remaining.end()) {
516 if (I != moveto_spot)
517 TheArchive->splice(moveto_spot,*TheArchive,I);
518 remaining.erase(found);
522 // We're done editting, reconstruct the archive.
523 if (TheArchive->writeToDisk(TruncateNames,ErrMsg))
528 // doQuickAppend - Implements the 'q' operation. This function just
529 // indiscriminantly adds the members to the archive and rebuilds it.
531 doQuickAppend(std::string* ErrMsg) {
532 // Get the list of paths to append.
533 if (buildPaths(true, ErrMsg))
538 // Append them quickly.
539 for (std::set<std::string>::iterator PI = Paths.begin(), PE = Paths.end();
541 if (TheArchive->addFileBefore(*PI, TheArchive->end(), ErrMsg))
545 // We're done editting, reconstruct the archive.
546 if (TheArchive->writeToDisk(TruncateNames,ErrMsg))
551 // doReplaceOrInsert - Implements the 'r' operation. This function will replace
552 // any existing files or insert new ones into the archive.
554 doReplaceOrInsert(std::string* ErrMsg) {
556 // Build the list of files to be added/replaced.
557 if (buildPaths(true, ErrMsg))
562 // Keep track of the paths that remain to be inserted.
563 std::set<std::string> remaining(Paths);
565 // Default the insertion spot to the end of the archive
566 Archive::iterator insert_spot = TheArchive->end();
568 // Iterate over the archive contents
569 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
570 I != E && !remaining.empty(); ++I ) {
572 // Determine if this archive member matches one of the paths we're trying
575 std::set<std::string>::iterator found = remaining.end();
576 for (std::set<std::string>::iterator RI = remaining.begin(),
577 RE = remaining.end(); RI != RE; ++RI ) {
578 std::string compare(sys::path::filename(*RI));
579 if (TruncateNames && compare.length() > 15) {
580 const char* nm = compare.c_str();
581 unsigned len = compare.length();
582 size_t slashpos = compare.rfind('/');
583 if (slashpos != std::string::npos) {
589 compare.assign(nm,len);
591 if (compare == I->getPath().str()) {
597 if (found != remaining.end()) {
598 sys::fs::file_status Status;
599 error_code EC = sys::fs::status(*found, Status);
602 if (!sys::fs::is_directory(Status)) {
604 // Replace the item only if it is newer.
605 if (Status.getLastModificationTime() > I->getModTime())
606 if (I->replaceWith(*found, ErrMsg))
609 // Replace the item regardless of time stamp
610 if (I->replaceWith(*found, ErrMsg))
614 // We purposefully ignore directories.
617 // Remove it from our "to do" list
618 remaining.erase(found);
621 // Determine if this is the place where we should insert
622 if ((AddBefore || InsertBefore) && RelPos == I->getPath().str())
624 else if (AddAfter && RelPos == I->getPath().str()) {
630 // If we didn't replace all the members, some will remain and need to be
631 // inserted at the previously computed insert-spot.
632 if (!remaining.empty()) {
633 for (std::set<std::string>::iterator PI = remaining.begin(),
634 PE = remaining.end(); PI != PE; ++PI) {
635 if (TheArchive->addFileBefore(*PI, insert_spot, ErrMsg))
640 // We're done editting, reconstruct the archive.
641 if (TheArchive->writeToDisk(TruncateNames,ErrMsg))
646 // main - main program for llvm-ar .. see comments in the code
647 int main(int argc, char **argv) {
648 program_name = argv[0];
649 // Print a stack trace if we signal out.
650 sys::PrintStackTraceOnErrorSignal();
651 PrettyStackTraceProgram X(argc, argv);
652 LLVMContext &Context = getGlobalContext();
653 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
655 // Have the command line options parsed and handle things
656 // like --help and --version.
657 cl::ParseCommandLineOptions(argc, argv,
658 "LLVM Archiver (llvm-ar)\n\n"
659 " This program archives bitcode files into single libraries\n"
664 // Do our own parsing of the command line because the CommandLine utility
665 // can't handle the grouped positional parameters without a dash.
666 ArchiveOperation Operation = parseCommandLine();
668 // Create or open the archive object.
670 if (llvm::sys::fs::exists(ArchiveName, Exists) || !Exists) {
671 // Produce a warning if we should and we're creating the archive
673 errs() << argv[0] << ": creating " << ArchiveName << "\n";
674 TheArchive = Archive::CreateEmpty(ArchiveName, Context);
675 TheArchive->writeToDisk();
678 TheArchive = Archive::OpenAndLoad(ArchiveName, Context, &Error);
679 if (TheArchive == 0) {
680 errs() << argv[0] << ": error loading '" << ArchiveName << "': "
686 // Make sure we're not fooling ourselves.
687 assert(TheArchive && "Unable to instantiate the archive");
689 // Perform the operation
691 bool haveError = false;
693 case Print: haveError = doPrint(&ErrMsg); break;
694 case Delete: haveError = doDelete(&ErrMsg); break;
695 case Move: haveError = doMove(&ErrMsg); break;
696 case QuickAppend: haveError = doQuickAppend(&ErrMsg); break;
697 case ReplaceOrInsert: haveError = doReplaceOrInsert(&ErrMsg); break;
698 case DisplayTable: haveError = doDisplayTable(&ErrMsg); break;
699 case Extract: haveError = doExtract(&ErrMsg); break;
701 errs() << argv[0] << ": No operation was selected.\n";
705 errs() << argv[0] << ": " << ErrMsg << "\n";
712 // Return result code back to operating system.