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