Remove the 'R' modifier.
[oota-llvm.git] / tools / llvm-ar / llvm-ar.cpp
1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Builds up (relatively) standard unix archive files (.a) containing LLVM
11 // bitcode or other files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Archive.h"
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"
25 #include <algorithm>
26 #include <cstdlib>
27 #include <fstream>
28 #include <memory>
29 using namespace llvm;
30
31 // Option for compatibility with AIX, not used but must allow it to be present.
32 static cl::opt<bool>
33 X32Option ("X32_64", cl::Hidden,
34             cl::desc("Ignored option for compatibility with AIX"));
35
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]..."));
39
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]..."));
44
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(
49   "\nOPERATIONS:\n"
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"
74 );
75
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
87 };
88
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 SymTable = true;            ///< 's' & 'S' modifiers
100 bool OnlyUpdate = false;         ///< 'u' modifier
101 bool Verbose = false;            ///< 'v' modifier
102 bool ReallyVerbose = false;      ///< 'V' modifier
103
104 // Relative Positional Argument (for insert/move). This variable holds
105 // the name of the archive member to which the 'a', 'b' or 'i' modifier
106 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
107 // one variable.
108 std::string RelPos;
109
110 // Select which of multiple entries in the archive with the same name should be
111 // used (specified with -N) for the delete and extract operations.
112 int Count = 1;
113
114 // This variable holds the name of the archive file as given on the
115 // command line.
116 std::string ArchiveName;
117
118 // This variable holds the list of member files to proecess, as given
119 // on the command line.
120 std::vector<std::string> Members;
121
122 // This variable holds the (possibly expanded) list of path objects that
123 // correspond to files we will
124 std::set<sys::Path> Paths;
125
126 // The Archive object to which all the editing operations will be sent.
127 Archive* TheArchive = 0;
128
129 // The name this program was invoked as.
130 static const char *program_name;
131
132 // show_help - Show the error message, the help message and exit.
133 LLVM_ATTRIBUTE_NORETURN static void
134 show_help(const std::string &msg) {
135   errs() << program_name << ": " << msg << "\n\n";
136   cl::PrintHelpMessage();
137   if (TheArchive)
138     delete TheArchive;
139   std::exit(1);
140 }
141
142 // fail - Show the error message and exit.
143 LLVM_ATTRIBUTE_NORETURN static void
144 fail(const std::string &msg) {
145   errs() << program_name << ": " << msg << "\n\n";
146   if (TheArchive)
147     delete TheArchive;
148   std::exit(1);
149 }
150
151 // getRelPos - Extract the member filename from the command line for
152 // the [relpos] argument associated with a, b, and i modifiers
153 void getRelPos() {
154   if(RestOfArgs.size() == 0)
155     show_help("Expected [relpos] for a, b, or i modifier");
156   RelPos = RestOfArgs[0];
157   RestOfArgs.erase(RestOfArgs.begin());
158 }
159
160 // getCount - Extract the [count] argument associated with the N modifier
161 // from the command line and check its value.
162 void getCount() {
163   if(RestOfArgs.size() == 0)
164     show_help("Expected [count] value with N modifier");
165
166   Count = atoi(RestOfArgs[0].c_str());
167   RestOfArgs.erase(RestOfArgs.begin());
168
169   // Non-positive counts are not allowed
170   if (Count < 1)
171     show_help("Invalid [count] value (not a positive integer)");
172 }
173
174 // getArchive - Get the archive file name from the command line
175 void getArchive() {
176   if(RestOfArgs.size() == 0)
177     show_help("An archive name must be specified");
178   ArchiveName = RestOfArgs[0];
179   RestOfArgs.erase(RestOfArgs.begin());
180 }
181
182 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
183 // This is just for clarity.
184 void getMembers() {
185   if(RestOfArgs.size() > 0)
186     Members = std::vector<std::string>(RestOfArgs);
187 }
188
189 // parseCommandLine - Parse the command line options as presented and return the
190 // operation specified. Process all modifiers and check to make sure that
191 // constraints on modifier/operation pairs have not been violated.
192 ArchiveOperation parseCommandLine() {
193
194   // Keep track of number of operations. We can only specify one
195   // per execution.
196   unsigned NumOperations = 0;
197
198   // Keep track of the number of positional modifiers (a,b,i). Only
199   // one can be specified.
200   unsigned NumPositional = 0;
201
202   // Keep track of which operation was requested
203   ArchiveOperation Operation = NoOperation;
204
205   for(unsigned i=0; i<Options.size(); ++i) {
206     switch(Options[i]) {
207     case 'd': ++NumOperations; Operation = Delete; break;
208     case 'm': ++NumOperations; Operation = Move ; break;
209     case 'p': ++NumOperations; Operation = Print; break;
210     case 'q': ++NumOperations; Operation = QuickAppend; break;
211     case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
212     case 't': ++NumOperations; Operation = DisplayTable; break;
213     case 'x': ++NumOperations; Operation = Extract; break;
214     case 'c': Create = true; break;
215     case 'f': TruncateNames = true; break;
216     case 'k': DontSkipBitcode = true; break;
217     case 'l': /* accepted but unused */ break;
218     case 'o': OriginalDates = true; break;
219     case 'P': FullPath = true; break;
220     case 's': SymTable = true; break;
221     case 'S': SymTable = false; break;
222     case 'u': OnlyUpdate = true; break;
223     case 'v': Verbose = true; break;
224     case 'V': Verbose = ReallyVerbose = true; break;
225     case 'a':
226       getRelPos();
227       AddAfter = true;
228       NumPositional++;
229       break;
230     case 'b':
231       getRelPos();
232       AddBefore = true;
233       NumPositional++;
234       break;
235     case 'i':
236       getRelPos();
237       InsertBefore = true;
238       NumPositional++;
239       break;
240     case 'N':
241       getCount();
242       UseCount = true;
243       break;
244     default:
245       cl::PrintHelpMessage();
246     }
247   }
248
249   // At this point, the next thing on the command line must be
250   // the archive name.
251   getArchive();
252
253   // Everything on the command line at this point is a member.
254   getMembers();
255
256   // Perform various checks on the operation/modifier specification
257   // to make sure we are dealing with a legal request.
258   if (NumOperations == 0)
259     show_help("You must specify at least one of the operations");
260   if (NumOperations > 1)
261     show_help("Only one operation may be specified");
262   if (NumPositional > 1)
263     show_help("You may only specify one of a, b, and i modifiers");
264   if (AddAfter || AddBefore || InsertBefore) {
265     if (Operation != Move && Operation != ReplaceOrInsert)
266       show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
267             "the 'm' or 'r' operations");
268   }
269   if (OriginalDates && Operation != Extract)
270     show_help("The 'o' modifier is only applicable to the 'x' operation");
271   if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert)
272     show_help("The 'f' modifier is only applicable to the 'q' and 'r' "
273               "operations");
274   if (OnlyUpdate && Operation != ReplaceOrInsert)
275     show_help("The 'u' modifier is only applicable to the 'r' operation");
276   if (Count > 1 && Members.size() > 1)
277     show_help("Only one member name may be specified with the 'N' modifier");
278
279   // Return the parsed operation to the caller
280   return Operation;
281 }
282
283 // buildPaths - Convert the strings in the Members vector to sys::Path objects
284 // and make sure they are valid and exist exist. This check is only needed for
285 // the operations that add/replace files to the archive ('q' and 'r')
286 bool buildPaths(bool checkExistence, std::string* ErrMsg) {
287   for (unsigned i = 0; i < Members.size(); i++) {
288     sys::Path aPath;
289     if (!aPath.set(Members[i]))
290       fail(std::string("File member name invalid: ") + Members[i]);
291     if (checkExistence) {
292       bool Exists;
293       if (sys::fs::exists(aPath.str(), Exists) || !Exists)
294         fail(std::string("File does not exist: ") + Members[i]);
295       std::string Err;
296       sys::PathWithStatus PwS(aPath);
297       const sys::FileStatus *si = PwS.getFileStatus(false, &Err);
298       if (!si)
299         fail(Err);
300       if (si->isDir)
301         fail(aPath.str() + " Is a directory");
302
303       Paths.insert(aPath);
304     } else {
305       Paths.insert(aPath);
306     }
307   }
308   return false;
309 }
310
311 // printSymbolTable - print out the archive's symbol table.
312 void printSymbolTable() {
313   outs() << "\nArchive Symbol Table:\n";
314   const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
315   for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end();
316        I != E; ++I ) {
317     unsigned offset = TheArchive->getFirstFileOffset() + I->second;
318     outs() << " " << format("%9u", offset) << "\t" << I->first <<"\n";
319   }
320 }
321
322 // doPrint - Implements the 'p' operation. This function traverses the archive
323 // looking for members that match the path list. It is careful to uncompress
324 // things that should be and to skip bitcode files unless the 'k' modifier was
325 // given.
326 bool doPrint(std::string* ErrMsg) {
327   if (buildPaths(false, ErrMsg))
328     return true;
329   unsigned countDown = Count;
330   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
331        I != E; ++I ) {
332     if (Paths.empty() ||
333         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
334       if (countDown == 1) {
335         const char* data = reinterpret_cast<const char*>(I->getData());
336
337         // Skip things that don't make sense to print
338         if (I->isSVR4SymbolTable() ||
339             I->isBSD4SymbolTable() || (!DontSkipBitcode && I->isBitcode()))
340           continue;
341
342         if (Verbose)
343           outs() << "Printing " << I->getPath().str() << "\n";
344
345         unsigned len = I->getSize();
346         outs().write(data, len);
347       } else {
348         countDown--;
349       }
350     }
351   }
352   return false;
353 }
354
355 // putMode - utility function for printing out the file mode when the 't'
356 // operation is in verbose mode.
357 void
358 printMode(unsigned mode) {
359   if (mode & 004)
360     outs() << "r";
361   else
362     outs() << "-";
363   if (mode & 002)
364     outs() << "w";
365   else
366     outs() << "-";
367   if (mode & 001)
368     outs() << "x";
369   else
370     outs() << "-";
371 }
372
373 // doDisplayTable - Implement the 't' operation. This function prints out just
374 // the file names of each of the members. However, if verbose mode is requested
375 // ('v' modifier) then the file type, permission mode, user, group, size, and
376 // modification time are also printed.
377 bool
378 doDisplayTable(std::string* ErrMsg) {
379   if (buildPaths(false, ErrMsg))
380     return true;
381   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
382        I != E; ++I ) {
383     if (Paths.empty() ||
384         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
385       if (Verbose) {
386         // FIXME: Output should be this format:
387         // Zrw-r--r--  500/ 500    525 Nov  8 17:42 2004 Makefile
388         if (I->isBitcode())
389           outs() << "b";
390         else
391           outs() << " ";
392         unsigned mode = I->getMode();
393         printMode((mode >> 6) & 007);
394         printMode((mode >> 3) & 007);
395         printMode(mode & 007);
396         outs() << " " << format("%4u", I->getUser());
397         outs() << "/" << format("%4u", I->getGroup());
398         outs() << " " << format("%8u", I->getSize());
399         outs() << " " << format("%20s", I->getModTime().str().substr(4).c_str());
400         outs() << " " << I->getPath().str() << "\n";
401       } else {
402         outs() << I->getPath().str() << "\n";
403       }
404     }
405   }
406   if (ReallyVerbose)
407     printSymbolTable();
408   return false;
409 }
410
411 // doExtract - Implement the 'x' operation. This function extracts files back to
412 // the file system.
413 bool
414 doExtract(std::string* ErrMsg) {
415   if (buildPaths(false, ErrMsg))
416     return true;
417   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
418        I != E; ++I ) {
419     if (Paths.empty() ||
420         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
421
422       // Make sure the intervening directories are created
423       if (I->hasPath()) {
424         sys::Path dirs(I->getPath());
425         dirs.eraseComponent();
426         if (dirs.createDirectoryOnDisk(/*create_parents=*/true, ErrMsg))
427           return true;
428       }
429
430       // Open up a file stream for writing
431       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
432                                    std::ios::binary;
433       std::ofstream file(I->getPath().c_str(), io_mode);
434
435       // Get the data and its length
436       const char* data = reinterpret_cast<const char*>(I->getData());
437       unsigned len = I->getSize();
438
439       // Write the data.
440       file.write(data,len);
441       file.close();
442
443       // If we're supposed to retain the original modification times, etc. do so
444       // now.
445       if (OriginalDates)
446         I->getPath().setStatusInfoOnDisk(I->getFileStatus());
447     }
448   }
449   return false;
450 }
451
452 // doDelete - Implement the delete operation. This function deletes zero or more
453 // members from the archive. Note that if the count is specified, there should
454 // be no more than one path in the Paths list or else this algorithm breaks.
455 // That check is enforced in parseCommandLine (above).
456 bool
457 doDelete(std::string* ErrMsg) {
458   if (buildPaths(false, ErrMsg))
459     return true;
460   if (Paths.empty())
461     return false;
462   unsigned countDown = Count;
463   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
464        I != E; ) {
465     if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
466       if (countDown == 1) {
467         Archive::iterator J = I;
468         ++I;
469         TheArchive->erase(J);
470       } else
471         countDown--;
472     } else {
473       ++I;
474     }
475   }
476
477   // We're done editting, reconstruct the archive.
478   if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
479     return true;
480   if (ReallyVerbose)
481     printSymbolTable();
482   return false;
483 }
484
485 // doMore - Implement the move operation. This function re-arranges just the
486 // order of the archive members so that when the archive is written the move
487 // of the members is accomplished. Note the use of the RelPos variable to
488 // determine where the items should be moved to.
489 bool
490 doMove(std::string* ErrMsg) {
491   if (buildPaths(false, ErrMsg))
492     return true;
493
494   // By default and convention the place to move members to is the end of the
495   // archive.
496   Archive::iterator moveto_spot = TheArchive->end();
497
498   // However, if the relative positioning modifiers were used, we need to scan
499   // the archive to find the member in question. If we don't find it, its no
500   // crime, we just move to the end.
501   if (AddBefore || InsertBefore || AddAfter) {
502     for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
503          I != E; ++I ) {
504       if (RelPos == I->getPath().str()) {
505         if (AddAfter) {
506           moveto_spot = I;
507           moveto_spot++;
508         } else {
509           moveto_spot = I;
510         }
511         break;
512       }
513     }
514   }
515
516   // Keep a list of the paths remaining to be moved
517   std::set<sys::Path> remaining(Paths);
518
519   // Scan the archive again, this time looking for the members to move to the
520   // moveto_spot.
521   for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end();
522        I != E && !remaining.empty(); ++I ) {
523     std::set<sys::Path>::iterator found =
524       std::find(remaining.begin(),remaining.end(),I->getPath());
525     if (found != remaining.end()) {
526       if (I != moveto_spot)
527         TheArchive->splice(moveto_spot,*TheArchive,I);
528       remaining.erase(found);
529     }
530   }
531
532   // We're done editting, reconstruct the archive.
533   if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
534     return true;
535   if (ReallyVerbose)
536     printSymbolTable();
537   return false;
538 }
539
540 // doQuickAppend - Implements the 'q' operation. This function just
541 // indiscriminantly adds the members to the archive and rebuilds it.
542 bool
543 doQuickAppend(std::string* ErrMsg) {
544   // Get the list of paths to append.
545   if (buildPaths(true, ErrMsg))
546     return true;
547   if (Paths.empty())
548     return false;
549
550   // Append them quickly.
551   for (std::set<sys::Path>::iterator PI = Paths.begin(), PE = Paths.end();
552        PI != PE; ++PI) {
553     if (TheArchive->addFileBefore(*PI,TheArchive->end(),ErrMsg))
554       return true;
555   }
556
557   // We're done editting, reconstruct the archive.
558   if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
559     return true;
560   if (ReallyVerbose)
561     printSymbolTable();
562   return false;
563 }
564
565 // doReplaceOrInsert - Implements the 'r' operation. This function will replace
566 // any existing files or insert new ones into the archive.
567 bool
568 doReplaceOrInsert(std::string* ErrMsg) {
569
570   // Build the list of files to be added/replaced.
571   if (buildPaths(true, ErrMsg))
572     return true;
573   if (Paths.empty())
574     return false;
575
576   // Keep track of the paths that remain to be inserted.
577   std::set<sys::Path> remaining(Paths);
578
579   // Default the insertion spot to the end of the archive
580   Archive::iterator insert_spot = TheArchive->end();
581
582   // Iterate over the archive contents
583   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
584        I != E && !remaining.empty(); ++I ) {
585
586     // Determine if this archive member matches one of the paths we're trying
587     // to replace.
588
589     std::set<sys::Path>::iterator found = remaining.end();
590     for (std::set<sys::Path>::iterator RI = remaining.begin(),
591          RE = remaining.end(); RI != RE; ++RI ) {
592       std::string compare(RI->str());
593       if (TruncateNames && compare.length() > 15) {
594         const char* nm = compare.c_str();
595         unsigned len = compare.length();
596         size_t slashpos = compare.rfind('/');
597         if (slashpos != std::string::npos) {
598           nm += slashpos + 1;
599           len -= slashpos +1;
600         }
601         if (len > 15)
602           len = 15;
603         compare.assign(nm,len);
604       }
605       if (compare == I->getPath().str()) {
606         found = RI;
607         break;
608       }
609     }
610
611     if (found != remaining.end()) {
612       std::string Err;
613       sys::PathWithStatus PwS(*found);
614       const sys::FileStatus *si = PwS.getFileStatus(false, &Err);
615       if (!si)
616         return true;
617       if (!si->isDir) {
618         if (OnlyUpdate) {
619           // Replace the item only if it is newer.
620           if (si->modTime > I->getModTime())
621             if (I->replaceWith(*found, ErrMsg))
622               return true;
623         } else {
624           // Replace the item regardless of time stamp
625           if (I->replaceWith(*found, ErrMsg))
626             return true;
627         }
628       } else {
629         // We purposefully ignore directories.
630       }
631
632       // Remove it from our "to do" list
633       remaining.erase(found);
634     }
635
636     // Determine if this is the place where we should insert
637     if ((AddBefore || InsertBefore) && RelPos == I->getPath().str())
638       insert_spot = I;
639     else if (AddAfter && RelPos == I->getPath().str()) {
640       insert_spot = I;
641       insert_spot++;
642     }
643   }
644
645   // If we didn't replace all the members, some will remain and need to be
646   // inserted at the previously computed insert-spot.
647   if (!remaining.empty()) {
648     for (std::set<sys::Path>::iterator PI = remaining.begin(),
649          PE = remaining.end(); PI != PE; ++PI) {
650       if (TheArchive->addFileBefore(*PI,insert_spot, ErrMsg))
651         return true;
652     }
653   }
654
655   // We're done editting, reconstruct the archive.
656   if (TheArchive->writeToDisk(SymTable,TruncateNames,ErrMsg))
657     return true;
658   if (ReallyVerbose)
659     printSymbolTable();
660   return false;
661 }
662
663 // main - main program for llvm-ar .. see comments in the code
664 int main(int argc, char **argv) {
665   program_name = argv[0];
666   // Print a stack trace if we signal out.
667   sys::PrintStackTraceOnErrorSignal();
668   PrettyStackTraceProgram X(argc, argv);
669   LLVMContext &Context = getGlobalContext();
670   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
671
672   // Have the command line options parsed and handle things
673   // like --help and --version.
674   cl::ParseCommandLineOptions(argc, argv,
675     "LLVM Archiver (llvm-ar)\n\n"
676     "  This program archives bitcode files into single libraries\n"
677   );
678
679   int exitCode = 0;
680
681   // Do our own parsing of the command line because the CommandLine utility
682   // can't handle the grouped positional parameters without a dash.
683   ArchiveOperation Operation = parseCommandLine();
684
685   // Check the path name of the archive
686   sys::Path ArchivePath;
687   if (!ArchivePath.set(ArchiveName)) {
688     errs() << argv[0] << ": Archive name invalid: " << ArchiveName << "\n";
689     return 1;
690   }
691
692   // Create or open the archive object.
693   bool Exists;
694   if (llvm::sys::fs::exists(ArchivePath.str(), Exists) || !Exists) {
695     // Produce a warning if we should and we're creating the archive
696     if (!Create)
697       errs() << argv[0] << ": creating " << ArchivePath.str() << "\n";
698     TheArchive = Archive::CreateEmpty(ArchivePath, Context);
699     TheArchive->writeToDisk();
700   } else {
701     std::string Error;
702     TheArchive = Archive::OpenAndLoad(ArchivePath, Context, &Error);
703     if (TheArchive == 0) {
704       errs() << argv[0] << ": error loading '" << ArchivePath.str() << "': "
705              << Error << "!\n";
706       return 1;
707     }
708   }
709
710   // Make sure we're not fooling ourselves.
711   assert(TheArchive && "Unable to instantiate the archive");
712
713   // Perform the operation
714   std::string ErrMsg;
715   bool haveError = false;
716   switch (Operation) {
717     case Print:           haveError = doPrint(&ErrMsg); break;
718     case Delete:          haveError = doDelete(&ErrMsg); break;
719     case Move:            haveError = doMove(&ErrMsg); break;
720     case QuickAppend:     haveError = doQuickAppend(&ErrMsg); break;
721     case ReplaceOrInsert: haveError = doReplaceOrInsert(&ErrMsg); break;
722     case DisplayTable:    haveError = doDisplayTable(&ErrMsg); break;
723     case Extract:         haveError = doExtract(&ErrMsg); break;
724     case NoOperation:
725       errs() << argv[0] << ": No operation was selected.\n";
726       break;
727   }
728   if (haveError) {
729     errs() << argv[0] << ": " << ErrMsg << "\n";
730     return 1;
731   }
732
733   delete TheArchive;
734   TheArchive = 0;
735
736   // Return result code back to operating system.
737   return exitCode;
738 }