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