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