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