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/Bitcode/Archive.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"
31 // Option for compatibility with AIX, not used but must allow it to be present.
33 X32Option ("X32_64", cl::Hidden,
34 cl::desc("Ignored option for compatibility with AIX"));
36 // llvm-ar operation code and modifier flags. This must come first.
37 static cl::opt<std::string>
38 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
40 // llvm-ar remaining positional arguments.
41 static cl::list<std::string>
42 RestOfArgs(cl::Positional, cl::OneOrMore,
43 cl::desc("[relpos] [count] <archive-file> [members]..."));
45 // MoreHelp - Provide additional help output explaining the operations and
46 // modifiers of llvm-ar. This object instructs the CommandLine library
47 // to print the text of the constructor when the --help option is given.
48 static cl::extrahelp MoreHelp(
50 " d[NsS] - delete file(s) from the archive\n"
51 " m[abiSs] - move file(s) in the archive\n"
52 " p[kN] - print file(s) found in the archive\n"
53 " q[ufsS] - quick append file(s) to the archive\n"
54 " r[abfiuRsS] - replace or insert file(s) into the archive\n"
55 " t - display contents of archive\n"
56 " x[No] - extract file(s) from the archive\n"
57 "\nMODIFIERS (operation specific):\n"
58 " [a] - put file(s) after [relpos]\n"
59 " [b] - put file(s) before [relpos] (same as [i])\n"
60 " [f] - truncate inserted file names\n"
61 " [i] - put file(s) before [relpos] (same as [b])\n"
62 " [k] - always print bitcode files (default is to skip them)\n"
63 " [N] - use instance [count] of name\n"
64 " [o] - preserve original dates\n"
65 " [P] - use full path names when matching\n"
66 " [R] - recurse through directories when inserting\n"
67 " [s] - create an archive index (cf. ranlib)\n"
68 " [S] - do not build a symbol table\n"
69 " [u] - update only files newer than archive contents\n"
70 "\nMODIFIERS (generic):\n"
71 " [c] - do not warn if the library had to be created\n"
72 " [v] - be verbose about actions taken\n"
73 " [V] - be *really* verbose about actions taken\n"
76 // This enumeration delineates the kinds of operations on an archive
77 // that are permitted.
78 enum ArchiveOperation {
79 NoOperation, ///< An operation hasn't been specified
80 Print, ///< Print the contents of the archive
81 Delete, ///< Delete the specified members
82 Move, ///< Move members to end or as given by {a,b,i} modifiers
83 QuickAppend, ///< Quickly append to end of archive
84 ReplaceOrInsert, ///< Replace or Insert members
85 DisplayTable, ///< Display the table of contents
86 Extract ///< Extract files back to file system
89 // Modifiers to follow operation to vary behavior
90 bool AddAfter = false; ///< 'a' modifier
91 bool AddBefore = false; ///< 'b' modifier
92 bool Create = false; ///< 'c' modifier
93 bool TruncateNames = false; ///< 'f' modifier
94 bool InsertBefore = false; ///< 'i' modifier
95 bool DontSkipBitcode = false; ///< 'k' modifier
96 bool UseCount = false; ///< 'N' modifier
97 bool OriginalDates = false; ///< 'o' modifier
98 bool FullPath = false; ///< 'P' modifier
99 bool RecurseDirectories = false; ///< 'R' modifier
100 bool SymTable = true; ///< 's' & 'S' modifiers
101 bool OnlyUpdate = false; ///< 'u' modifier
102 bool Verbose = false; ///< 'v' modifier
103 bool ReallyVerbose = false; ///< 'V' modifier
105 // Relative Positional Argument (for insert/move). This variable holds
106 // the name of the archive member to which the 'a', 'b' or 'i' modifier
107 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
111 // Select which of multiple entries in the archive with the same name should be
112 // used (specified with -N) for the delete and extract operations.
115 // This variable holds the name of the archive file as given on the
117 std::string ArchiveName;
119 // This variable holds the list of member files to proecess, as given
120 // on the command line.
121 std::vector<std::string> Members;
123 // This variable holds the (possibly expanded) list of path objects that
124 // correspond to files we will
125 std::set<sys::Path> Paths;
127 // The Archive object to which all the editing operations will be sent.
128 Archive* TheArchive = 0;
130 // The name this program was invoked as.
131 static const char *program_name;
133 // show_help - Show the error message, the help message and exit.
134 LLVM_ATTRIBUTE_NORETURN static void
135 show_help(const std::string &msg) {
136 errs() << program_name << ": " << msg << "\n\n";
137 cl::PrintHelpMessage();
143 // fail - Show the error message and exit.
144 LLVM_ATTRIBUTE_NORETURN static void
145 fail(const std::string &msg) {
146 errs() << program_name << ": " << msg << "\n\n";
152 // getRelPos - Extract the member filename from the command line for
153 // the [relpos] argument associated with a, b, and i modifiers
155 if(RestOfArgs.size() == 0)
156 show_help("Expected [relpos] for a, b, or i modifier");
157 RelPos = RestOfArgs[0];
158 RestOfArgs.erase(RestOfArgs.begin());
161 // getCount - Extract the [count] argument associated with the N modifier
162 // from the command line and check its value.
164 if(RestOfArgs.size() == 0)
165 show_help("Expected [count] value with N modifier");
167 Count = atoi(RestOfArgs[0].c_str());
168 RestOfArgs.erase(RestOfArgs.begin());
170 // Non-positive counts are not allowed
172 show_help("Invalid [count] value (not a positive integer)");
175 // getArchive - Get the archive file name from the command line
177 if(RestOfArgs.size() == 0)
178 show_help("An archive name must be specified");
179 ArchiveName = RestOfArgs[0];
180 RestOfArgs.erase(RestOfArgs.begin());
183 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
184 // This is just for clarity.
186 if(RestOfArgs.size() > 0)
187 Members = std::vector<std::string>(RestOfArgs);
190 // parseCommandLine - Parse the command line options as presented and return the
191 // operation specified. Process all modifiers and check to make sure that
192 // constraints on modifier/operation pairs have not been violated.
193 ArchiveOperation parseCommandLine() {
195 // Keep track of number of operations. We can only specify one
197 unsigned NumOperations = 0;
199 // Keep track of the number of positional modifiers (a,b,i). Only
200 // one can be specified.
201 unsigned NumPositional = 0;
203 // Keep track of which operation was requested
204 ArchiveOperation Operation = NoOperation;
206 for(unsigned i=0; i<Options.size(); ++i) {
208 case 'd': ++NumOperations; Operation = Delete; break;
209 case 'm': ++NumOperations; Operation = Move ; break;
210 case 'p': ++NumOperations; Operation = Print; break;
211 case 'q': ++NumOperations; Operation = QuickAppend; break;
212 case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
213 case 't': ++NumOperations; Operation = DisplayTable; break;
214 case 'x': ++NumOperations; Operation = Extract; break;
215 case 'c': Create = true; break;
216 case 'f': TruncateNames = true; break;
217 case 'k': DontSkipBitcode = true; break;
218 case 'l': /* accepted but unused */ break;
219 case 'o': OriginalDates = true; break;
220 case 'P': FullPath = true; break;
221 case 'R': RecurseDirectories = true; break;
222 case 's': SymTable = true; break;
223 case 'S': SymTable = false; break;
224 case 'u': OnlyUpdate = true; break;
225 case 'v': Verbose = true; break;
226 case 'V': Verbose = ReallyVerbose = true; break;
247 cl::PrintHelpMessage();
251 // At this point, the next thing on the command line must be
255 // Everything on the command line at this point is a member.
258 // Perform various checks on the operation/modifier specification
259 // to make sure we are dealing with a legal request.
260 if (NumOperations == 0)
261 show_help("You must specify at least one of the operations");
262 if (NumOperations > 1)
263 show_help("Only one operation may be specified");
264 if (NumPositional > 1)
265 show_help("You may only specify one of a, b, and i modifiers");
266 if (AddAfter || AddBefore || InsertBefore) {
267 if (Operation != Move && Operation != ReplaceOrInsert)
268 show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
269 "the 'm' or 'r' operations");
271 if (RecurseDirectories && Operation != ReplaceOrInsert)
272 show_help("The 'R' modifiers is only applicabe to the 'r' operation");
273 if (OriginalDates && Operation != Extract)
274 show_help("The 'o' modifier is only applicable to the 'x' operation");
275 if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert)
276 show_help("The 'f' modifier is only applicable to the 'q' and 'r' "
278 if (OnlyUpdate && Operation != ReplaceOrInsert)
279 show_help("The 'u' modifier is only applicable to the 'r' operation");
280 if (Count > 1 && Members.size() > 1)
281 show_help("Only one member name may be specified with the 'N' modifier");
283 // Return the parsed operation to the caller
287 // recurseDirectories - Implements the "R" modifier. This function scans through
288 // the Paths vector (built by buildPaths, below) and replaces any directories it
289 // finds with all the files in that directory (recursively). It uses the
290 // sys::Path::getDirectoryContent method to perform the actual directory scans.
292 recurseDirectories(const sys::Path& path,
293 std::set<sys::Path>& result, std::string* ErrMsg) {
295 if (RecurseDirectories) {
296 std::set<sys::Path> content;
297 if (path.getDirectoryContents(content, ErrMsg))
300 for (std::set<sys::Path>::iterator I = content.begin(), E = content.end();
302 // Make sure it exists and is a directory
303 sys::PathWithStatus PwS(*I);
304 const sys::FileStatus *Status = PwS.getFileStatus(false, ErrMsg);
308 std::set<sys::Path> moreResults;
309 if (recurseDirectories(*I, moreResults, ErrMsg))
311 result.insert(moreResults.begin(), moreResults.end());
320 // buildPaths - Convert the strings in the Members vector to sys::Path objects
321 // and make sure they are valid and exist exist. This check is only needed for
322 // the operations that add/replace files to the archive ('q' and 'r')
323 bool buildPaths(bool checkExistence, std::string* ErrMsg) {
324 for (unsigned i = 0; i < Members.size(); i++) {
326 if (!aPath.set(Members[i]))
327 fail(std::string("File member name invalid: ") + Members[i]);
328 if (checkExistence) {
330 if (sys::fs::exists(aPath.str(), Exists) || !Exists)
331 fail(std::string("File does not exist: ") + Members[i]);
333 sys::PathWithStatus PwS(aPath);
334 const sys::FileStatus *si = PwS.getFileStatus(false, &Err);
338 std::set<sys::Path> dirpaths;
339 if (recurseDirectories(aPath, dirpaths, ErrMsg))
341 Paths.insert(dirpaths.begin(),dirpaths.end());
352 // printSymbolTable - print out the archive's symbol table.
353 void printSymbolTable() {
354 outs() << "\nArchive Symbol Table:\n";
355 const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
356 for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
358 unsigned offset = TheArchive->getFirstFileOffset() + I->second;
359 outs() << " " << format("%9u", offset) << "\t" << I->first <<"\n";
363 // doPrint - Implements the 'p' operation. This function traverses the archive
364 // looking for members that match the path list. It is careful to uncompress
365 // things that should be and to skip bitcode files unless the 'k' modifier was
367 bool doPrint(std::string* ErrMsg) {
368 if (buildPaths(false, ErrMsg))
370 unsigned countDown = Count;
371 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
374 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
375 if (countDown == 1) {
376 const char* data = reinterpret_cast<const char*>(I->getData());
378 // Skip things that don't make sense to print
379 if (I->isLLVMSymbolTable() || I->isSVR4SymbolTable() ||
380 I->isBSD4SymbolTable() || (!DontSkipBitcode && I->isBitcode()))
384 outs() << "Printing " << I->getPath().str() << "\n";
386 unsigned len = I->getSize();
387 outs().write(data, len);
396 // putMode - utility function for printing out the file mode when the 't'
397 // operation is in verbose mode.
399 printMode(unsigned mode) {
414 // doDisplayTable - Implement the 't' operation. This function prints out just
415 // the file names of each of the members. However, if verbose mode is requested
416 // ('v' modifier) then the file type, permission mode, user, group, size, and
417 // modification time are also printed.
419 doDisplayTable(std::string* ErrMsg) {
420 if (buildPaths(false, ErrMsg))
422 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
425 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
427 // FIXME: Output should be this format:
428 // Zrw-r--r-- 500/ 500 525 Nov 8 17:42 2004 Makefile
433 unsigned mode = I->getMode();
434 printMode((mode >> 6) & 007);
435 printMode((mode >> 3) & 007);
436 printMode(mode & 007);
437 outs() << " " << format("%4u", I->getUser());
438 outs() << "/" << format("%4u", I->getGroup());
439 outs() << " " << format("%8u", I->getSize());
440 outs() << " " << format("%20s", I->getModTime().str().substr(4).c_str());
441 outs() << " " << I->getPath().str() << "\n";
443 outs() << I->getPath().str() << "\n";
452 // doExtract - Implement the 'x' operation. This function extracts files back to
455 doExtract(std::string* ErrMsg) {
456 if (buildPaths(false, ErrMsg))
458 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
461 (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
463 // Make sure the intervening directories are created
465 sys::Path dirs(I->getPath());
466 dirs.eraseComponent();
467 if (dirs.createDirectoryOnDisk(/*create_parents=*/true, ErrMsg))
471 // Open up a file stream for writing
472 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
474 std::ofstream file(I->getPath().c_str(), io_mode);
476 // Get the data and its length
477 const char* data = reinterpret_cast<const char*>(I->getData());
478 unsigned len = I->getSize();
481 file.write(data,len);
484 // If we're supposed to retain the original modification times, etc. do so
487 I->getPath().setStatusInfoOnDisk(I->getFileStatus());
493 // doDelete - Implement the delete operation. This function deletes zero or more
494 // members from the archive. Note that if the count is specified, there should
495 // be no more than one path in the Paths list or else this algorithm breaks.
496 // That check is enforced in parseCommandLine (above).
498 doDelete(std::string* ErrMsg) {
499 if (buildPaths(false, ErrMsg))
503 unsigned countDown = Count;
504 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
506 if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
507 if (countDown == 1) {
508 Archive::iterator J = I;
510 TheArchive->erase(J);
518 // We're done editting, reconstruct the archive.
519 if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
526 // doMore - Implement the move operation. This function re-arranges just the
527 // order of the archive members so that when the archive is written the move
528 // of the members is accomplished. Note the use of the RelPos variable to
529 // determine where the items should be moved to.
531 doMove(std::string* ErrMsg) {
532 if (buildPaths(false, ErrMsg))
535 // By default and convention the place to move members to is the end of the
537 Archive::iterator moveto_spot = TheArchive->end();
539 // However, if the relative positioning modifiers were used, we need to scan
540 // the archive to find the member in question. If we don't find it, its no
541 // crime, we just move to the end.
542 if (AddBefore || InsertBefore || AddAfter) {
543 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
545 if (RelPos == I->getPath().str()) {
557 // Keep a list of the paths remaining to be moved
558 std::set<sys::Path> remaining(Paths);
560 // Scan the archive again, this time looking for the members to move to the
562 for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
563 I != E && !remaining.empty(); ++I ) {
564 std::set<sys::Path>::iterator found =
565 std::find(remaining.begin(),remaining.end(),I->getPath());
566 if (found != remaining.end()) {
567 if (I != moveto_spot)
568 TheArchive->splice(moveto_spot,*TheArchive,I);
569 remaining.erase(found);
573 // We're done editting, reconstruct the archive.
574 if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
581 // doQuickAppend - Implements the 'q' operation. This function just
582 // indiscriminantly adds the members to the archive and rebuilds it.
584 doQuickAppend(std::string* ErrMsg) {
585 // Get the list of paths to append.
586 if (buildPaths(true, ErrMsg))
591 // Append them quickly.
592 for (std::set<sys::Path>::iterator PI = Paths.begin(), PE = Paths.end();
594 if (TheArchive->addFileBefore(*PI,TheArchive->end(),ErrMsg))
598 // We're done editting, reconstruct the archive.
599 if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
606 // doReplaceOrInsert - Implements the 'r' operation. This function will replace
607 // any existing files or insert new ones into the archive.
609 doReplaceOrInsert(std::string* ErrMsg) {
611 // Build the list of files to be added/replaced.
612 if (buildPaths(true, ErrMsg))
617 // Keep track of the paths that remain to be inserted.
618 std::set<sys::Path> remaining(Paths);
620 // Default the insertion spot to the end of the archive
621 Archive::iterator insert_spot = TheArchive->end();
623 // Iterate over the archive contents
624 for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
625 I != E && !remaining.empty(); ++I ) {
627 // Determine if this archive member matches one of the paths we're trying
630 std::set<sys::Path>::iterator found = remaining.end();
631 for (std::set<sys::Path>::iterator RI = remaining.begin(),
632 RE = remaining.end(); RI != RE; ++RI ) {
633 std::string compare(RI->str());
634 if (TruncateNames && compare.length() > 15) {
635 const char* nm = compare.c_str();
636 unsigned len = compare.length();
637 size_t slashpos = compare.rfind('/');
638 if (slashpos != std::string::npos) {
644 compare.assign(nm,len);
646 if (compare == I->getPath().str()) {
652 if (found != remaining.end()) {
654 sys::PathWithStatus PwS(*found);
655 const sys::FileStatus *si = PwS.getFileStatus(false, &Err);
660 // Replace the item only if it is newer.
661 if (si->modTime > I->getModTime())
662 if (I->replaceWith(*found, ErrMsg))
665 // Replace the item regardless of time stamp
666 if (I->replaceWith(*found, ErrMsg))
670 // We purposefully ignore directories.
673 // Remove it from our "to do" list
674 remaining.erase(found);
677 // Determine if this is the place where we should insert
678 if ((AddBefore || InsertBefore) && RelPos == I->getPath().str())
680 else if (AddAfter && RelPos == I->getPath().str()) {
686 // If we didn't replace all the members, some will remain and need to be
687 // inserted at the previously computed insert-spot.
688 if (!remaining.empty()) {
689 for (std::set<sys::Path>::iterator PI = remaining.begin(),
690 PE = remaining.end(); PI != PE; ++PI) {
691 if (TheArchive->addFileBefore(*PI,insert_spot, ErrMsg))
696 // We're done editting, reconstruct the archive.
697 if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
704 // main - main program for llvm-ar .. see comments in the code
705 int main(int argc, char **argv) {
706 program_name = argv[0];
707 // Print a stack trace if we signal out.
708 sys::PrintStackTraceOnErrorSignal();
709 PrettyStackTraceProgram X(argc, argv);
710 LLVMContext &Context = getGlobalContext();
711 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
713 // Have the command line options parsed and handle things
714 // like --help and --version.
715 cl::ParseCommandLineOptions(argc, argv,
716 "LLVM Archiver (llvm-ar)\n\n"
717 " This program archives bitcode files into single libraries\n"
722 // Do our own parsing of the command line because the CommandLine utility
723 // can't handle the grouped positional parameters without a dash.
724 ArchiveOperation Operation = parseCommandLine();
726 // Check the path name of the archive
727 sys::Path ArchivePath;
728 if (!ArchivePath.set(ArchiveName)) {
729 errs() << argv[0] << ": Archive name invalid: " << ArchiveName << "\n";
733 // Create or open the archive object.
735 if (llvm::sys::fs::exists(ArchivePath.str(), Exists) || !Exists) {
736 // Produce a warning if we should and we're creating the archive
738 errs() << argv[0] << ": creating " << ArchivePath.str() << "\n";
739 TheArchive = Archive::CreateEmpty(ArchivePath, Context);
740 TheArchive->writeToDisk();
743 TheArchive = Archive::OpenAndLoad(ArchivePath, Context, &Error);
744 if (TheArchive == 0) {
745 errs() << argv[0] << ": error loading '" << ArchivePath.str() << "': "
751 // Make sure we're not fooling ourselves.
752 assert(TheArchive && "Unable to instantiate the archive");
754 // Perform the operation
756 bool haveError = false;
758 case Print: haveError = doPrint(&ErrMsg); break;
759 case Delete: haveError = doDelete(&ErrMsg); break;
760 case Move: haveError = doMove(&ErrMsg); break;
761 case QuickAppend: haveError = doQuickAppend(&ErrMsg); break;
762 case ReplaceOrInsert: haveError = doReplaceOrInsert(&ErrMsg); break;
763 case DisplayTable: haveError = doDisplayTable(&ErrMsg); break;
764 case Extract: haveError = doExtract(&ErrMsg); break;
766 errs() << argv[0] << ": No operation was selected.\n";
770 errs() << argv[0] << ": " << ErrMsg << "\n";
777 // Return result code back to operating system.