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