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