Correct call of methods whose names have changed.
[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 was developed by the Reid Spencer based on the original design by
6 // Tanya Lattner and is distributed by the University of Illinois Open Source 
7 // License. See LICENSE.TXT for details.
8 // 
9 //===----------------------------------------------------------------------===//
10 //
11 // Builds up (relatively) standard unix archive files (.a) containing LLVM 
12 // bytecode or other files.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Module.h"
17 #include "llvm/Bytecode/Archive.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Compressor.h"
20 #include "llvm/Support/FileUtilities.h"
21 #include "llvm/System/Signals.h"
22 #include <iostream>
23 #include <algorithm>
24 #include <iomanip>
25
26 using namespace llvm;
27
28 // Option for compatibility with ASIX, not used but must allow it to be present.
29 cl::opt<bool> 
30 X32Option ("X32_64", cl::desc("Ignored option for compatibility with AIX"));
31
32 // llvm-ar operation code and modifier flags. This must come first
33 cl::opt<std::string> 
34 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
35
36 // llvm-ar remaining positional arguments 
37 cl::list<std::string> 
38 RestOfArgs(cl::Positional, cl::OneOrMore, 
39     cl::desc("[relpos] [count] <archive-file> [members]..."));
40
41 // This enumeration delineates the kinds of operations on an archive
42 // that are permitted.
43 enum ArchiveOperation {
44   NoOperation,      ///< An operation hasn't been specified
45   Print,            ///< Print the contents of the archive
46   Delete,           ///< Delete the specified members
47   Move,             ///< Move members to end or as given by {a,b,i} modifiers
48   QuickAppend,      ///< Quickly append to end of archive
49   ReplaceOrInsert,  ///< Replace or Insert members
50   DisplayTable,     ///< Display the table of contents
51   Extract,          ///< Extract files back to file system
52 };
53
54 // Modifiers to follow operation to vary behavior
55 bool AddAfter = false;           ///< 'a' modifier
56 bool AddBefore = false;          ///< 'b' modifier
57 bool Create = false;             ///< 'c' modifier 
58 bool TruncateNames = false;      ///< 'f' modifier
59 bool InsertBefore = false;       ///< 'i' modifier
60 bool DontSkipBytecode = false;   ///< 'k' modifier
61 bool UseCount = false;           ///< 'N' modifier
62 bool OriginalDates = false;      ///< 'o' modifier
63 bool FullPath = false;           ///< 'P' modifier
64 bool RecurseDirectories = false; ///< 'R' modifier
65 bool SymTable = true;            ///< 's' & 'S' modifiers
66 bool OnlyUpdate = false;         ///< 'u' modifier
67 bool Verbose = false;            ///< 'v' modifier
68 bool ReallyVerbose = false;      ///< 'V' modifier
69 bool Compression = false;        ///< 'z' modifier
70
71 // Relative Positional Argument (for insert/move). This variable holds
72 // the name of the archive member to which the 'a', 'b' or 'i' modifier
73 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
74 // one variable.
75 std::string RelPos;
76
77 // Select which of multiple entries in the archive with the same name should be
78 // used (specified with -N) for the delete and extract operations.
79 int Count = 1;
80
81 // This variable holds the name of the archive file as given on the
82 // command line.
83 std::string ArchiveName;
84
85 // This variable holds the list of member files to proecess, as given
86 // on the command line.
87 std::vector<std::string> Members;
88
89 // This variable holds the (possibly expanded) list of path objects that
90 // correspond to files we will
91 sys::Path::Vector Paths;
92
93 // The Archive object to which all the editing operations will be sent.
94 Archive* TheArchive = 0;
95
96 // printMoreHelp - Provide additional help output explaining the operations and
97 // modifiers of llvm-ar. This function is called by the CommandLine library
98 // when the --help option is given because we set the global cl::MoreHelp
99 // variable to the address of this function.
100 void printMoreHelp() {
101   std::cout 
102     << "\nOPERATIONS:\n" 
103     << "  d[NsS]       - delete file(s) from the archive\n"
104     << "  m[abiSs]     - move file(s) in the archive\n"
105     << "  p[kN]        - print file(s) found in the archive\n"
106     << "  q[ufsS]      - quick append file(s) to the archive\n"
107     << "  r[abfiuzRsS] - replace or insert file(s) into the archive\n"
108     << "  t            - display contents of archive\n"
109     << "  x[No]        - extract file(s) from the archive\n";
110
111   std::cout 
112     << "\nMODIFIERS (operation specific):\n"
113     << "  [a] - put file(s) after [relpos]\n"
114     << "  [b] - put file(s) before [relpos] (same as [i])\n"
115     << "  [f] - truncate inserted file names\n"
116     << "  [i] - put file(s) before [relpos] (same as [b])\n"
117     << "  [k] - always print bytecode files (default is to skip them)\n"
118     << "  [N] - use instance [count] of name\n"
119     << "  [o] - preserve original dates\n"
120     << "  [P] - use full path names when matching\n"
121     << "  [R] - recurse through directories when inserting\n"
122     << "  [s] - create an archive index (cf. ranlib)\n"
123     << "  [S] - do not build a symbol table\n"
124     << "  [u] - update only files newer than archive contents\n"
125     << "  [z] - compress files before inserting/extracting\n";
126
127   std::cout 
128     << "\nMODIFIERS (generic):\n"
129     << "  [c] - do not warn if the library had to be created\n"
130     << "  [v] - be verbose about actions taken\n"
131     << "  [V] - be *really* verbose about actions taken\n";
132 }
133
134 // printUse - Print out our usage information. This is used in cases where the 
135 // user has made a mistake on the command line syntax. 
136 void printUse() {
137   std::cout 
138     << "OVERVIEW: LLVM Archiver (llvm-ar)\n\n"
139     << "  This program archives bytecode files into single libraries\n\n"
140     << "USAGE: llvm-ar [-X32_64] [-]{operation}[modifiers]... "
141     << "[relpos] [count] archive-file [files..]\n";
142
143   printMoreHelp();
144   exit(1);
145 }
146
147 // getRelPos - Extract the member filename from the command line for
148 // the [relpos] argument associated with a, b, and i modifiers
149 void getRelPos() {
150   if(RestOfArgs.size() > 0) {
151     RelPos = RestOfArgs[0];
152     RestOfArgs.erase(RestOfArgs.begin());
153   }
154   else
155     throw "Expected [relpos] for a, b, or i modifier";
156 }
157
158 // getCount - Extract the [count] argument associated with the N modifier 
159 // from the command line and check its value.
160 void getCount() {
161   if(RestOfArgs.size() > 0) {
162     Count = atoi(RestOfArgs[0].c_str());
163     RestOfArgs.erase(RestOfArgs.begin());
164   }
165   else
166     throw "Expected [count] value with N modifier";
167
168   // Non-positive counts are not allowed
169   if (Count < 1)
170     throw "Invalid [count] value (not a positive integer)";
171 }
172
173 // getArchive - Get the archive file name from the command line
174 void getArchive() {
175   if(RestOfArgs.size() > 0) {
176     ArchiveName = RestOfArgs[0];
177     RestOfArgs.erase(RestOfArgs.begin());
178   }
179   else
180     throw "An archive name must be specified.";
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 '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': DontSkipBytecode = true; break;
217     case 'l': /* accepted but unused */ break;
218     case 'o': OriginalDates = true; break;
219     case 'P': FullPath = true; break;
220     case 'R': RecurseDirectories = 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 'z': Compression = 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       printUse();
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     throw "You must specify at least one of the operations";
262   if (NumOperations > 1)
263     throw "Only one operation may be specified";
264   if (NumPositional > 1)
265     throw "You may only specify one of a, b, and i modifiers";
266   if (AddAfter || AddBefore || InsertBefore)
267     if (Operation != Move && Operation != ReplaceOrInsert)
268       throw "The 'a', 'b' and 'i' modifiers can only be specified with "
269             "the 'm' or 'r' operations";
270   if (RecurseDirectories && Operation != ReplaceOrInsert)
271     throw "The 'R' modifiers is only applicabe to the 'r' operation";
272   if (OriginalDates && Operation != Extract)
273     throw "The 'o' modifier is only applicable to the 'x' operation";
274   if (TruncateNames && Operation!=QuickAppend && Operation!=ReplaceOrInsert)
275     throw "The 'f' modifier is only applicable to the 'q' and 'r' operations";
276   if (OnlyUpdate && Operation != ReplaceOrInsert)
277     throw "The 'u' modifier is only applicable to the 'r' operation";
278   if (Compression && Operation!=ReplaceOrInsert && Operation!=Extract)
279     throw "The 'z' modifier is only applicable to the 'r' and 'x' operations";
280   if (Count > 1 && Members.size() > 1)
281     throw "Only one member name may be specified with the 'N' modifier";
282
283   // Return the parsed operation to the caller
284   return Operation;
285 }
286
287 // recurseDirectories - Implements the "R" modifier. This function scans through
288 // the Paths vector (built by buildPaths, below) and replaces any directories it
289 // finds with all the files in that directory (recursively). It uses the
290 // sys::Path::getDirectoryContent method to perform the actual directory scans.
291 sys::Path::Vector recurseDirectories(const sys::Path& path) {
292   assert(path.isDirectory() && "Oops, can't recurse a file");
293   sys::Path::Vector result;
294   if (RecurseDirectories) {
295     sys::Path::Vector content;
296     path.getDirectoryContents(content);
297     for (sys::Path::Vector::iterator I = content.begin(), E = content.end(); 
298          I != E; ++I) {
299       if (I->isDirectory()) {
300         sys::Path::Vector moreResults = recurseDirectories(*I);
301         result.insert(result.begin(), moreResults.begin(), moreResults.end());
302       } else {
303         result.push_back(*I);
304       }
305     }
306   }
307   return result;
308 }
309
310 // buildPaths - Convert the strings in the Members vector to sys::Path objects
311 // and make sure they are valid and exist exist. This check is only needed for 
312 // the operations that add/replace files to the archive ('q' and 'r')
313 void buildPaths(bool checkExistence = true) {
314   for (unsigned i = 0; i < Members.size(); i++) {
315     sys::Path aPath;
316     if (!aPath.setFile(Members[i]))
317       throw std::string("File member name invalid: ") + Members[i];
318     if (checkExistence) {
319       if (!aPath.exists())
320         throw std::string("File does not exist: ") + Members[i];
321       sys::Path::StatusInfo si;
322       aPath.getStatusInfo(si);
323       if (si.isDir) {
324         sys::Path::Vector dirpaths = recurseDirectories(aPath);
325         Paths.insert(Paths.end(),dirpaths.begin(),dirpaths.end());
326       } else {
327         Paths.push_back(aPath);
328       }
329     } else {
330       Paths.push_back(aPath);
331     }
332   }
333 }
334
335 // doPrint - Implements the 'p' operation. This function traverses the archive
336 // looking for members that match the path list. It is careful to uncompress
337 // things that should be and to skip bytecode files unless the 'k' modifier was
338 // given.
339 void doPrint() {
340   buildPaths(false);
341   unsigned countDown = Count;
342   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 
343        I != E; ++I ) {
344     if (Paths.empty() || 
345         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
346       if (countDown == 1) {
347         const char* data = reinterpret_cast<const char*>(I->getData());
348
349         // Skip things that don't make sense to print
350         if (I->isLLVMSymbolTable() || I->isForeignSymbolTable() ||
351             (!DontSkipBytecode && 
352              (I->isBytecode() || I->isCompressedBytecode())))
353           continue;
354
355         if (Verbose)
356           std::cout << "Printing " << I->getPath().get() << "\n";
357
358         if (I->isCompressedBytecode())
359           Compressor::decompressToStream(data+4,I->getSize()-4,std::cout);
360         else if (I->isCompressed()) {
361           Compressor::decompressToStream(data,I->getSize(),std::cout);
362         } else {
363           unsigned len = I->getSize();
364           std::cout.write(data, len);
365         }
366       } else {
367         countDown--;
368       }
369     }
370   }
371 }
372
373 // putMode - utility function for printing out the file mode when the 't'
374 // operation is in verbose mode.
375 void putMode(unsigned mode) {
376   if (mode & 004) 
377     std::cout << "r";
378   else
379     std::cout << "-";
380   if (mode & 002)
381     std::cout << "w";
382   else
383     std::cout << "-";
384   if (mode & 001)
385     std::cout << "x";
386   else
387     std::cout << "-";
388 }
389
390 // doDisplayTable - Implement the 't' operation. This function prints out just
391 // the file names of each of the members. However, if verbose mode is requested
392 // ('v' modifier) then the file type, permission mode, user, group, size, and
393 // modification time are also printed.
394 void doDisplayTable() {
395   buildPaths(false);
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       if (Verbose) {
401         // FIXME: Output should be this format:
402         // Zrw-r--r--  500/ 500    525 Nov  8 17:42 2004 Makefile
403         if (I->isBytecode())
404           std::cout << "b";
405         else if (I->isCompressedBytecode())
406           std::cout << "B";
407         else if (I->isForeignSymbolTable())
408           std::cout << "s";
409         else if (I->isLLVMSymbolTable())
410           std::cout << "S";
411         else if (I->isCompressed())
412           std::cout << "Z";
413         else
414           std::cout << " ";
415         unsigned mode = I->getMode();
416         putMode((mode >> 6) & 007);
417         putMode((mode >> 3) & 007);
418         putMode(mode & 007);
419         std::cout << " " << std::setw(4) << I->getUser();
420         std::cout << "/" << std::setw(4) << I->getGroup();
421         std::cout << " " << std::setw(8) << I->getSize();
422         std::cout << " " << std::setw(20) << 
423           I->getModTime().toString().substr(4);
424         std::cout << " " << I->getPath().get() << "\n";
425       } else {
426         std::cout << I->getPath().get() << "\n";
427       }
428     }
429   }
430   if (ReallyVerbose) {
431     std::cout << "\nArchive Symbol Table:\n";
432     const Archive::SymTabType& symtab = TheArchive->getSymbolTable();
433     for (Archive::SymTabType::const_iterator I=symtab.begin(), E=symtab.end(); 
434          I != E; ++I ) {
435       unsigned offset = TheArchive->getFirstFileOffset() + I->second;
436       std::cout << " " << std::setw(9) << offset << "\t" << I->first <<"\n";
437     }
438   }
439 }
440
441 // doExtract - Implement the 'x' operation. This function extracts files back to
442 // the file system, making sure to uncompress any that were compressed.
443 void doExtract() {
444   buildPaths(false);
445   unsigned countDown = Count;
446   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 
447        I != E; ++I ) {
448     if (Paths.empty() ||
449         (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end())) {
450
451       // Make sure the intervening directories are created
452       if (I->hasPath()) {
453         sys::Path dirs(I->getPath());
454         dirs.elideFile();
455         dirs.createDirectory(/*create_parents=*/true);
456       }
457
458       // Open up a file stream for writing
459       std::ofstream file(I->getPath().c_str());
460
461       // Get the data and its length
462       const char* data = reinterpret_cast<const char*>(I->getData());
463       unsigned len = I->getSize();
464
465       // Write the data, making sure to uncompress things first
466       if (I->isCompressed()) {
467         Compressor::decompressToStream(data,len,file);
468       } else {
469         file.write(data,len);
470       }
471       file.close();
472
473       // If we're supposed to retain the original modification times, etc. do so
474       // now.
475       if (OriginalDates)
476         I->getPath().setStatusInfo(I->getStatusInfo());
477     }
478   }
479 }
480
481 // doDelete - Implement the delete operation. This function deletes zero or more
482 // members from the archive. Note that if the count is specified, there should
483 // be no more than one path in the Paths list or else this algorithm breaks.
484 // That check is enforced in parseCommandLine (above).
485 void doDelete() {
486   buildPaths(false);
487   if (Paths.empty()) return;
488   unsigned countDown = Count;
489   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end(); 
490        I != E; ) {
491     if (std::find(Paths.begin(), Paths.end(), I->getPath()) != Paths.end()) {
492       if (countDown == 1) {
493         Archive::iterator J = I;
494         ++I;
495         TheArchive->remove(J);
496       } else
497         countDown--;
498     } else {
499       ++I;
500     }
501   }
502
503   // We're done editting, reconstruct the archive.
504   TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
505 }
506
507 // doMore - Implement the move operation. This function re-arranges just the
508 // order of the archive members so that when the archive is written the move
509 // of the members is accomplished. Note the use of the RelPos variable to
510 // determine where the items should be moved to.
511 void doMove() {
512
513   buildPaths(false);
514
515   // By default and convention the place to move members to is the end of the
516   // archive.
517   Archive::iterator moveto_spot = TheArchive->end();
518
519   // However, if the relative positioning modifiers were used, we need to scan
520   // the archive to find the member in question. If we don't find it, its no
521   // crime, we just move to the end.
522   if (AddBefore || InsertBefore || AddAfter) {
523     for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end(); 
524          I != E; ++I ) {
525       if (RelPos == I->getPath().get()) {
526         if (AddAfter) {
527           moveto_spot = I;
528           moveto_spot++;
529         } else {
530           moveto_spot = I;
531         }
532         break;
533       }
534     }
535   }
536
537   // Keep a list of the paths remaining to be moved
538   sys::Path::Vector remaining(Paths);
539
540   // Scan the archive again, this time looking for the members to move to the
541   // moveto_spot.
542   for (Archive::iterator I = TheArchive->begin(), E= TheArchive->end(); 
543        I != E && !remaining.empty(); ++I ) {
544     sys::Path::Vector::iterator found = 
545       std::find(remaining.begin(),remaining.end(),I->getPath());
546     if (found != remaining.end()) {
547       if (I != moveto_spot) 
548         TheArchive->moveMemberBefore(I,moveto_spot);
549       remaining.erase(found);
550     }
551   }
552
553   // We're done editting, reconstruct the archive.
554   TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
555 }
556
557 // doQuickAppend - Implements the 'q' operation. This function just
558 // indiscriminantly adds the members to the archive and rebuilds it.
559 void doQuickAppend() {
560   // Get the list of paths to append.
561   buildPaths(true);
562   if (Paths.empty()) return;
563
564   // Append them quickly.
565   for (sys::Path::Vector::iterator PI = Paths.begin(), PE = Paths.end();
566        PI != PE; ++PI) {
567     TheArchive->addFileBefore(*PI,TheArchive->end());
568   }
569
570   // We're done editting, reconstruct the archive.
571   TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
572 }
573
574 // doReplaceOrInsert - Implements the 'r' operation. This function will replace
575 // any existing files or insert new ones into the archive. 
576 void doReplaceOrInsert() {
577
578   // Build the list of files to be added/replaced.
579   buildPaths(true);
580   if (Paths.empty()) return;
581
582   // Keep track of the paths that remain to be inserted.
583   sys::Path::Vector remaining(Paths);
584
585   // Default the insertion spot to the end of the archive
586   Archive::iterator insert_spot = TheArchive->end();
587
588   // Iterate over the archive contents
589   for (Archive::iterator I = TheArchive->begin(), E = TheArchive->end();
590        I != E && !remaining.empty(); ++I ) {
591
592     // Determine if this archive member matches one of the paths we're trying
593     // to replace.
594     sys::Path::Vector::iterator found = 
595       std::find(remaining.begin(),remaining.end(), I->getPath());
596     if (found != remaining.end()) {
597       if (OnlyUpdate) {
598         // Replace the item only if it is newer.
599         sys::Path::StatusInfo si;
600         found->getStatusInfo(si);
601         if (si.modTime > I->getModTime())
602           I->replaceWith(*found);
603       } else {
604         // Replace the item regardless of time stamp
605         I->replaceWith(*found);
606       }
607
608       // Remove it from our "to do" list
609       remaining.erase(found);
610     }
611
612     // Determine if this is the place where we should insert
613     if ((AddBefore || InsertBefore) && (RelPos == I->getPath().get()))
614       insert_spot = I;
615     else if (AddAfter && (RelPos == I->getPath().get())) {
616       insert_spot = I;
617       insert_spot++;
618     }
619   }
620
621   // If we didn't replace all the members, some will remain and need to be
622   // inserted at the previously computed insert-spot.
623   if (!remaining.empty()) {
624     for (sys::Path::Vector::iterator PI = remaining.begin(), 
625          PE = remaining.end(); PI != PE; ++PI) {
626       TheArchive->addFileBefore(*PI,insert_spot);
627     }
628   }
629
630   // We're done editting, reconstruct the archive.
631   TheArchive->writeToDisk(SymTable,TruncateNames,Compression,ReallyVerbose);
632 }
633
634 // main - main program for llvm-ar .. see comments in the code
635 int main(int argc, char **argv) {
636
637   // Ensure we initialize the global MoreHelp to tell the command line utility
638   // that we have a MoreHelp function. This function is called to print more
639   // help if the --help option is given on the command line
640   cl::MoreHelp = printMoreHelp;
641
642   // Have the command line options parsed and handle things
643   // like --help and --version.
644   cl::ParseCommandLineOptions(argc, argv,
645     " LLVM Archiver (llvm-ar)\n\n"
646     "  This program archives bytecode files into single libraries\n"
647   );
648
649   // Print a stack trace if we signal out.
650   sys::PrintStackTraceOnErrorSignal();
651
652   int exitCode = 0;
653
654   // Make sure we don't exit with "unhandled exception".
655   try {
656     // Do our own parsing of the command line because the CommandLine utility
657     // can't handle the grouped positional parameters without a dash.
658     ArchiveOperation Operation = parseCommandLine();
659
660     // Check the path name of the archive
661     sys::Path ArchivePath;
662     if (!ArchivePath.setFile(ArchiveName))
663       throw std::string("Archive name invalid: ") + ArchiveName;
664
665     // Create or open the archive object.
666     if (!ArchivePath.exists()) {
667       // Produce a warning if we should and we're creating the archive
668       if (!Create)
669         std::cerr << argv[0] << ": creating " << ArchivePath.get() << "\n";
670       TheArchive = Archive::CreateEmpty(ArchivePath);
671     } else {
672       TheArchive = Archive::OpenAndLoad(ArchivePath);
673     }
674
675     // Make sure we're not fooling ourselves.
676     assert(TheArchive && "Unable to instantiate the archive");
677
678     // Perform the operation
679     switch (Operation) {
680       case Print:           doPrint(); break;
681       case Delete:          doDelete(); break;
682       case Move:            doMove(); break;
683       case QuickAppend:      /* FALL THROUGH */
684       case ReplaceOrInsert: doReplaceOrInsert(); break;
685       case DisplayTable:    doDisplayTable(); break;
686       case Extract:         doExtract(); break;
687       case NoOperation:
688         std::cerr << argv[0] << ": No operation was selected.\n";
689         break;
690     }
691
692     // Close up shop
693     delete TheArchive;
694
695   } catch (const char*msg) {
696     // These errors are usage errors, thrown only by the various checks in the
697     // code above.
698     std::cerr << argv[0] << ": " << msg << "\n\n";
699     printUse();
700     exitCode = 1;
701   } catch (const std::string& msg) {
702     // These errors are thrown by LLVM libraries (e.g. lib System) and represent
703     // a more serious error so we bump the exitCode and don't print the usage.
704     std::cerr << argv[0] << ": " << msg << "\n";
705     exitCode = 2;
706   } catch (...) {
707     // This really shouldn't happen, but just in case ....
708     std::cerr << argv[0] << ": An nexpected unknown exception occurred.\n";
709     exitCode = 3;
710   }
711
712   // Return result code back to operating system.
713   return exitCode;
714 }