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/IR/LLVMContext.h"
     16 #include "llvm/IR/Module.h"
     17 #include "llvm/Object/Archive.h"
     18 #include "llvm/Object/ObjectFile.h"
     19 #include "llvm/Support/CommandLine.h"
     20 #include "llvm/Support/FileSystem.h"
     21 #include "llvm/Support/Format.h"
     22 #include "llvm/Support/ManagedStatic.h"
     23 #include "llvm/Support/MemoryBuffer.h"
     24 #include "llvm/Support/PrettyStackTrace.h"
     25 #include "llvm/Support/Signals.h"
     26 #include "llvm/Support/ToolOutputFile.h"
     27 #include "llvm/Support/raw_ostream.h"
     28 #include <algorithm>
     29 #include <cstdlib>
     30 #include <memory>
     31 
     32 #if !defined(_MSC_VER) && !defined(__MINGW32__)
     33 #include <unistd.h>
     34 #else
     35 #include <io.h>
     36 #endif
     37 
     38 using namespace llvm;
     39 
     40 // The name this program was invoked as.
     41 static StringRef ToolName;
     42 
     43 static const char *TemporaryOutput;
     44 static int TmpArchiveFD = -1;
     45 
     46 // fail - Show the error message and exit.
     47 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
     48   outs() << ToolName << ": " << Error << ".\n";
     49   if (TmpArchiveFD != -1)
     50     close(TmpArchiveFD);
     51   if (TemporaryOutput)
     52     sys::fs::remove(TemporaryOutput);
     53   exit(1);
     54 }
     55 
     56 static void failIfError(error_code EC, Twine Context = "") {
     57   if (!EC)
     58     return;
     59 
     60   std::string ContextStr = Context.str();
     61   if (ContextStr == "")
     62     fail(EC.message());
     63   fail(Context + ": " + EC.message());
     64 }
     65 
     66 // Option for compatibility with AIX, not used but must allow it to be present.
     67 static cl::opt<bool>
     68 X32Option ("X32_64", cl::Hidden,
     69             cl::desc("Ignored option for compatibility with AIX"));
     70 
     71 // llvm-ar operation code and modifier flags. This must come first.
     72 static cl::opt<std::string>
     73 Options(cl::Positional, cl::Required, cl::desc("{operation}[modifiers]..."));
     74 
     75 // llvm-ar remaining positional arguments.
     76 static cl::list<std::string>
     77 RestOfArgs(cl::Positional, cl::OneOrMore,
     78     cl::desc("[relpos] [count] <archive-file> [members]..."));
     79 
     80 // MoreHelp - Provide additional help output explaining the operations and
     81 // modifiers of llvm-ar. This object instructs the CommandLine library
     82 // to print the text of the constructor when the --help option is given.
     83 static cl::extrahelp MoreHelp(
     84   "\nOPERATIONS:\n"
     85   "  d[NsS]       - delete file(s) from the archive\n"
     86   "  m[abiSs]     - move file(s) in the archive\n"
     87   "  p[kN]        - print file(s) found in the archive\n"
     88   "  q[ufsS]      - quick append file(s) to the archive\n"
     89   "  r[abfiuRsS]  - replace or insert file(s) into the archive\n"
     90   "  t            - display contents of archive\n"
     91   "  x[No]        - extract file(s) from the archive\n"
     92   "\nMODIFIERS (operation specific):\n"
     93   "  [a] - put file(s) after [relpos]\n"
     94   "  [b] - put file(s) before [relpos] (same as [i])\n"
     95   "  [i] - put file(s) before [relpos] (same as [b])\n"
     96   "  [N] - use instance [count] of name\n"
     97   "  [o] - preserve original dates\n"
     98   "  [s] - create an archive index (cf. ranlib)\n"
     99   "  [S] - do not build a symbol table\n"
    100   "  [u] - update only files newer than archive contents\n"
    101   "\nMODIFIERS (generic):\n"
    102   "  [c] - do not warn if the library had to be created\n"
    103   "  [v] - be verbose about actions taken\n"
    104 );
    105 
    106 // This enumeration delineates the kinds of operations on an archive
    107 // that are permitted.
    108 enum ArchiveOperation {
    109   Print,            ///< Print the contents of the archive
    110   Delete,           ///< Delete the specified members
    111   Move,             ///< Move members to end or as given by {a,b,i} modifiers
    112   QuickAppend,      ///< Quickly append to end of archive
    113   ReplaceOrInsert,  ///< Replace or Insert members
    114   DisplayTable,     ///< Display the table of contents
    115   Extract,          ///< Extract files back to file system
    116   CreateSymTab      ///< Create a symbol table in an existing archive
    117 };
    118 
    119 // Modifiers to follow operation to vary behavior
    120 static bool AddAfter = false;      ///< 'a' modifier
    121 static bool AddBefore = false;     ///< 'b' modifier
    122 static bool Create = false;        ///< 'c' modifier
    123 static bool OriginalDates = false; ///< 'o' modifier
    124 static bool OnlyUpdate = false;    ///< 'u' modifier
    125 static bool Verbose = false;       ///< 'v' modifier
    126 static bool Symtab = true;         ///< 's' modifier
    127 
    128 // Relative Positional Argument (for insert/move). This variable holds
    129 // the name of the archive member to which the 'a', 'b' or 'i' modifier
    130 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
    131 // one variable.
    132 static std::string RelPos;
    133 
    134 // This variable holds the name of the archive file as given on the
    135 // command line.
    136 static std::string ArchiveName;
    137 
    138 // This variable holds the list of member files to proecess, as given
    139 // on the command line.
    140 static std::vector<std::string> Members;
    141 
    142 // show_help - Show the error message, the help message and exit.
    143 LLVM_ATTRIBUTE_NORETURN static void
    144 show_help(const std::string &msg) {
    145   errs() << ToolName << ": " << msg << "\n\n";
    146   cl::PrintHelpMessage();
    147   std::exit(1);
    148 }
    149 
    150 // getRelPos - Extract the member filename from the command line for
    151 // the [relpos] argument associated with a, b, and i modifiers
    152 static void getRelPos() {
    153   if(RestOfArgs.size() == 0)
    154     show_help("Expected [relpos] for a, b, or i modifier");
    155   RelPos = RestOfArgs[0];
    156   RestOfArgs.erase(RestOfArgs.begin());
    157 }
    158 
    159 // getArchive - Get the archive file name from the command line
    160 static void getArchive() {
    161   if(RestOfArgs.size() == 0)
    162     show_help("An archive name must be specified");
    163   ArchiveName = RestOfArgs[0];
    164   RestOfArgs.erase(RestOfArgs.begin());
    165 }
    166 
    167 // getMembers - Copy over remaining items in RestOfArgs to our Members vector
    168 // This is just for clarity.
    169 static void getMembers() {
    170   if(RestOfArgs.size() > 0)
    171     Members = std::vector<std::string>(RestOfArgs);
    172 }
    173 
    174 // parseCommandLine - Parse the command line options as presented and return the
    175 // operation specified. Process all modifiers and check to make sure that
    176 // constraints on modifier/operation pairs have not been violated.
    177 static ArchiveOperation parseCommandLine() {
    178 
    179   // Keep track of number of operations. We can only specify one
    180   // per execution.
    181   unsigned NumOperations = 0;
    182 
    183   // Keep track of the number of positional modifiers (a,b,i). Only
    184   // one can be specified.
    185   unsigned NumPositional = 0;
    186 
    187   // Keep track of which operation was requested
    188   ArchiveOperation Operation;
    189 
    190   bool MaybeJustCreateSymTab = false;
    191 
    192   for(unsigned i=0; i<Options.size(); ++i) {
    193     switch(Options[i]) {
    194     case 'd': ++NumOperations; Operation = Delete; break;
    195     case 'm': ++NumOperations; Operation = Move ; break;
    196     case 'p': ++NumOperations; Operation = Print; break;
    197     case 'q': ++NumOperations; Operation = QuickAppend; break;
    198     case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
    199     case 't': ++NumOperations; Operation = DisplayTable; break;
    200     case 'x': ++NumOperations; Operation = Extract; break;
    201     case 'c': Create = true; break;
    202     case 'l': /* accepted but unused */ break;
    203     case 'o': OriginalDates = true; break;
    204     case 's':
    205       Symtab = true;
    206       MaybeJustCreateSymTab = true;
    207       break;
    208     case 'S':
    209       Symtab = false;
    210       break;
    211     case 'u': OnlyUpdate = true; break;
    212     case 'v': Verbose = true; break;
    213     case 'a':
    214       getRelPos();
    215       AddAfter = true;
    216       NumPositional++;
    217       break;
    218     case 'b':
    219       getRelPos();
    220       AddBefore = true;
    221       NumPositional++;
    222       break;
    223     case 'i':
    224       getRelPos();
    225       AddBefore = true;
    226       NumPositional++;
    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  if (NumOperations == 0 && MaybeJustCreateSymTab) {
    241     NumOperations = 1;
    242     Operation = CreateSymTab;
    243     if (!Members.empty())
    244       show_help("The s operation takes only an archive as argument");
    245   }
    246 
    247   // Perform various checks on the operation/modifier specification
    248   // to make sure we are dealing with a legal request.
    249   if (NumOperations == 0)
    250     show_help("You must specify at least one of the operations");
    251   if (NumOperations > 1)
    252     show_help("Only one operation may be specified");
    253   if (NumPositional > 1)
    254     show_help("You may only specify one of a, b, and i modifiers");
    255   if (AddAfter || AddBefore) {
    256     if (Operation != Move && Operation != ReplaceOrInsert)
    257       show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
    258             "the 'm' or 'r' operations");
    259   }
    260   if (OriginalDates && Operation != Extract)
    261     show_help("The 'o' modifier is only applicable to the 'x' operation");
    262   if (OnlyUpdate && Operation != ReplaceOrInsert)
    263     show_help("The 'u' modifier is only applicable to the 'r' operation");
    264 
    265   // Return the parsed operation to the caller
    266   return Operation;
    267 }
    268 
    269 // Implements the 'p' operation. This function traverses the archive
    270 // looking for members that match the path list.
    271 static void doPrint(StringRef Name, object::Archive::child_iterator I) {
    272   if (Verbose)
    273     outs() << "Printing " << Name << "\n";
    274 
    275   StringRef Data = I->getBuffer();
    276   outs().write(Data.data(), Data.size());
    277 }
    278 
    279 // putMode - utility function for printing out the file mode when the 't'
    280 // operation is in verbose mode.
    281 static void printMode(unsigned mode) {
    282   if (mode & 004)
    283     outs() << "r";
    284   else
    285     outs() << "-";
    286   if (mode & 002)
    287     outs() << "w";
    288   else
    289     outs() << "-";
    290   if (mode & 001)
    291     outs() << "x";
    292   else
    293     outs() << "-";
    294 }
    295 
    296 // Implement the 't' operation. This function prints out just
    297 // the file names of each of the members. However, if verbose mode is requested
    298 // ('v' modifier) then the file type, permission mode, user, group, size, and
    299 // modification time are also printed.
    300 static void doDisplayTable(StringRef Name, object::Archive::child_iterator I) {
    301   if (Verbose) {
    302     sys::fs::perms Mode = I->getAccessMode();
    303     printMode((Mode >> 6) & 007);
    304     printMode((Mode >> 3) & 007);
    305     printMode(Mode & 007);
    306     outs() << ' ' << I->getUID();
    307     outs() << '/' << I->getGID();
    308     outs() << ' ' << format("%6llu", I->getSize());
    309     outs() << ' ' << I->getLastModified().str();
    310     outs() << ' ';
    311   }
    312   outs() << Name << "\n";
    313 }
    314 
    315 // Implement the 'x' operation. This function extracts files back to the file
    316 // system.
    317 static void doExtract(StringRef Name, object::Archive::child_iterator I) {
    318   // Retain the original mode.
    319   sys::fs::perms Mode = I->getAccessMode();
    320   SmallString<128> Storage = Name;
    321 
    322   int FD;
    323   failIfError(
    324       sys::fs::openFileForWrite(Storage.c_str(), FD, sys::fs::F_Binary, Mode),
    325       Storage.c_str());
    326 
    327   {
    328     raw_fd_ostream file(FD, false);
    329 
    330     // Get the data and its length
    331     StringRef Data = I->getBuffer();
    332 
    333     // Write the data.
    334     file.write(Data.data(), Data.size());
    335   }
    336 
    337   // If we're supposed to retain the original modification times, etc. do so
    338   // now.
    339   if (OriginalDates)
    340     failIfError(
    341         sys::fs::setLastModificationAndAccessTime(FD, I->getLastModified()));
    342 
    343   if (close(FD))
    344     fail("Could not close the file");
    345 }
    346 
    347 static bool shouldCreateArchive(ArchiveOperation Op) {
    348   switch (Op) {
    349   case Print:
    350   case Delete:
    351   case Move:
    352   case DisplayTable:
    353   case Extract:
    354   case CreateSymTab:
    355     return false;
    356 
    357   case QuickAppend:
    358   case ReplaceOrInsert:
    359     return true;
    360   }
    361 
    362   llvm_unreachable("Missing entry in covered switch.");
    363 }
    364 
    365 static void performReadOperation(ArchiveOperation Operation,
    366                                  object::Archive *OldArchive) {
    367   for (object::Archive::child_iterator I = OldArchive->begin_children(),
    368                                        E = OldArchive->end_children();
    369        I != E; ++I) {
    370     StringRef Name;
    371     failIfError(I->getName(Name));
    372 
    373     if (!Members.empty() &&
    374         std::find(Members.begin(), Members.end(), Name) == Members.end())
    375       continue;
    376 
    377     switch (Operation) {
    378     default:
    379       llvm_unreachable("Not a read operation");
    380     case Print:
    381       doPrint(Name, I);
    382       break;
    383     case DisplayTable:
    384       doDisplayTable(Name, I);
    385       break;
    386     case Extract:
    387       doExtract(Name, I);
    388       break;
    389     }
    390   }
    391 }
    392 
    393 namespace {
    394 class NewArchiveIterator {
    395   bool IsNewMember;
    396   StringRef Name;
    397   object::Archive::child_iterator OldI;
    398   std::string NewFilename;
    399 
    400 public:
    401   NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
    402   NewArchiveIterator(std::string *I, StringRef Name);
    403   NewArchiveIterator();
    404   bool isNewMember() const;
    405   object::Archive::child_iterator getOld() const;
    406   const char *getNew() const;
    407   StringRef getName() const;
    408 };
    409 }
    410 
    411 NewArchiveIterator::NewArchiveIterator() {}
    412 
    413 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
    414                                        StringRef Name)
    415     : IsNewMember(false), Name(Name), OldI(I) {}
    416 
    417 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
    418     : IsNewMember(true), Name(Name), NewFilename(*NewFilename) {}
    419 
    420 StringRef NewArchiveIterator::getName() const { return Name; }
    421 
    422 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
    423 
    424 object::Archive::child_iterator NewArchiveIterator::getOld() const {
    425   assert(!IsNewMember);
    426   return OldI;
    427 }
    428 
    429 const char *NewArchiveIterator::getNew() const {
    430   assert(IsNewMember);
    431   return NewFilename.c_str();
    432 }
    433 
    434 template <typename T>
    435 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
    436                int Pos = -1) {
    437   NewArchiveIterator NI(I, Name);
    438   if (Pos == -1)
    439     Members.push_back(NI);
    440   else
    441     Members[Pos] = NI;
    442 }
    443 
    444 namespace {
    445 class HasName {
    446   StringRef Name;
    447 
    448 public:
    449   HasName(StringRef Name) : Name(Name) {}
    450   bool operator()(StringRef Path) { return Name == sys::path::filename(Path); }
    451 };
    452 }
    453 
    454 enum InsertAction {
    455   IA_AddOldMember,
    456   IA_AddNewMeber,
    457   IA_Delete,
    458   IA_MoveOldMember,
    459   IA_MoveNewMember
    460 };
    461 
    462 static InsertAction
    463 computeInsertAction(ArchiveOperation Operation,
    464                     object::Archive::child_iterator I, StringRef Name,
    465                     std::vector<std::string>::iterator &Pos) {
    466   if (Operation == QuickAppend || Members.empty())
    467     return IA_AddOldMember;
    468 
    469   std::vector<std::string>::iterator MI =
    470       std::find_if(Members.begin(), Members.end(), HasName(Name));
    471 
    472   if (MI == Members.end())
    473     return IA_AddOldMember;
    474 
    475   Pos = MI;
    476 
    477   if (Operation == Delete)
    478     return IA_Delete;
    479 
    480   if (Operation == Move)
    481     return IA_MoveOldMember;
    482 
    483   if (Operation == ReplaceOrInsert) {
    484     StringRef PosName = sys::path::filename(RelPos);
    485     if (!OnlyUpdate) {
    486       if (PosName.empty())
    487         return IA_AddNewMeber;
    488       return IA_MoveNewMember;
    489     }
    490 
    491     // We could try to optimize this to a fstat, but it is not a common
    492     // operation.
    493     sys::fs::file_status Status;
    494     failIfError(sys::fs::status(*MI, Status));
    495     if (Status.getLastModificationTime() < I->getLastModified()) {
    496       if (PosName.empty())
    497         return IA_AddOldMember;
    498       return IA_MoveOldMember;
    499     }
    500 
    501     if (PosName.empty())
    502       return IA_AddNewMeber;
    503     return IA_MoveNewMember;
    504   }
    505   llvm_unreachable("No such operation");
    506 }
    507 
    508 // We have to walk this twice and computing it is not trivial, so creating an
    509 // explicit std::vector is actually fairly efficient.
    510 static std::vector<NewArchiveIterator>
    511 computeNewArchiveMembers(ArchiveOperation Operation,
    512                          object::Archive *OldArchive) {
    513   std::vector<NewArchiveIterator> Ret;
    514   std::vector<NewArchiveIterator> Moved;
    515   int InsertPos = -1;
    516   StringRef PosName = sys::path::filename(RelPos);
    517   if (OldArchive) {
    518     for (object::Archive::child_iterator I = OldArchive->begin_children(),
    519                                          E = OldArchive->end_children();
    520          I != E; ++I) {
    521       int Pos = Ret.size();
    522       StringRef Name;
    523       failIfError(I->getName(Name));
    524       if (Name == PosName) {
    525         assert(AddAfter || AddBefore);
    526         if (AddBefore)
    527           InsertPos = Pos;
    528         else
    529           InsertPos = Pos + 1;
    530       }
    531 
    532       std::vector<std::string>::iterator MemberI = Members.end();
    533       InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
    534       switch (Action) {
    535       case IA_AddOldMember:
    536         addMember(Ret, I, Name);
    537         break;
    538       case IA_AddNewMeber:
    539         addMember(Ret, &*MemberI, Name);
    540         break;
    541       case IA_Delete:
    542         break;
    543       case IA_MoveOldMember:
    544         addMember(Moved, I, Name);
    545         break;
    546       case IA_MoveNewMember:
    547         addMember(Moved, &*MemberI, Name);
    548         break;
    549       }
    550       if (MemberI != Members.end())
    551         Members.erase(MemberI);
    552     }
    553   }
    554 
    555   if (Operation == Delete)
    556     return Ret;
    557 
    558   if (!RelPos.empty() && InsertPos == -1)
    559     fail("Insertion point not found");
    560 
    561   if (RelPos.empty())
    562     InsertPos = Ret.size();
    563 
    564   assert(unsigned(InsertPos) <= Ret.size());
    565   Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
    566 
    567   Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
    568   int Pos = InsertPos;
    569   for (std::vector<std::string>::iterator I = Members.begin(),
    570          E = Members.end();
    571        I != E; ++I, ++Pos) {
    572     StringRef Name = sys::path::filename(*I);
    573     addMember(Ret, &*I, Name, Pos);
    574   }
    575 
    576   return Ret;
    577 }
    578 
    579 template <typename T>
    580 static void printWithSpacePadding(raw_ostream &OS, T Data, unsigned Size) {
    581   uint64_t OldPos = OS.tell();
    582   OS << Data;
    583   unsigned SizeSoFar = OS.tell() - OldPos;
    584   assert(Size >= SizeSoFar && "Data doesn't fit in Size");
    585   unsigned Remaining = Size - SizeSoFar;
    586   for (unsigned I = 0; I < Remaining; ++I)
    587     OS << ' ';
    588 }
    589 
    590 static void print32BE(raw_fd_ostream &Out, unsigned Val) {
    591   for (int I = 3; I >= 0; --I) {
    592     char V = (Val >> (8 * I)) & 0xff;
    593     Out << V;
    594   }
    595 }
    596 
    597 static void printRestOfMemberHeader(raw_fd_ostream &Out,
    598                                     const sys::TimeValue &ModTime, unsigned UID,
    599                                     unsigned GID, unsigned Perms,
    600                                     unsigned Size) {
    601   printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
    602   printWithSpacePadding(Out, UID, 6);
    603   printWithSpacePadding(Out, GID, 6);
    604   printWithSpacePadding(Out, format("%o", Perms), 8);
    605   printWithSpacePadding(Out, Size, 10);
    606   Out << "`\n";
    607 }
    608 
    609 static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
    610                               const sys::TimeValue &ModTime, unsigned UID,
    611                               unsigned GID, unsigned Perms, unsigned Size) {
    612   printWithSpacePadding(Out, Twine(Name) + "/", 16);
    613   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
    614 }
    615 
    616 static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
    617                               const sys::TimeValue &ModTime, unsigned UID,
    618                               unsigned GID, unsigned Perms, unsigned Size) {
    619   Out << '/';
    620   printWithSpacePadding(Out, NameOffset, 15);
    621   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
    622 }
    623 
    624 static void writeStringTable(raw_fd_ostream &Out,
    625                              ArrayRef<NewArchiveIterator> Members,
    626                              std::vector<unsigned> &StringMapIndexes) {
    627   unsigned StartOffset = 0;
    628   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
    629                                               E = Members.end();
    630        I != E; ++I) {
    631     StringRef Name = I->getName();
    632     if (Name.size() < 16)
    633       continue;
    634     if (StartOffset == 0) {
    635       printWithSpacePadding(Out, "//", 58);
    636       Out << "`\n";
    637       StartOffset = Out.tell();
    638     }
    639     StringMapIndexes.push_back(Out.tell() - StartOffset);
    640     Out << Name << "/\n";
    641   }
    642   if (StartOffset == 0)
    643     return;
    644   if (Out.tell() % 2)
    645     Out << '\n';
    646   int Pos = Out.tell();
    647   Out.seek(StartOffset - 12);
    648   printWithSpacePadding(Out, Pos - StartOffset, 10);
    649   Out.seek(Pos);
    650 }
    651 
    652 static void writeSymbolTable(
    653     raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
    654     std::vector<std::pair<unsigned, unsigned> > &MemberOffsetRefs) {
    655   unsigned StartOffset = 0;
    656   unsigned MemberNum = 0;
    657   std::vector<StringRef> SymNames;
    658   std::vector<object::ObjectFile *> DeleteIt;
    659   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
    660                                               E = Members.end();
    661        I != E; ++I, ++MemberNum) {
    662     object::ObjectFile *Obj;
    663     if (I->isNewMember()) {
    664       const char *Filename = I->getNew();
    665       Obj = object::ObjectFile::createObjectFile(Filename);
    666     } else {
    667       object::Archive::child_iterator OldMember = I->getOld();
    668       OwningPtr<object::Binary> Binary;
    669       error_code EC = OldMember->getAsBinary(Binary);
    670       if (EC) { // FIXME: check only for "not an object file" errors.
    671         Obj = NULL;
    672       } else {
    673         Obj = dyn_cast<object::ObjectFile>(Binary.get());
    674         if (Obj)
    675           Binary.take();
    676       }
    677     }
    678     if (!Obj)
    679       continue;
    680     DeleteIt.push_back(Obj);
    681     if (!StartOffset) {
    682       printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
    683       StartOffset = Out.tell();
    684       print32BE(Out, 0);
    685     }
    686 
    687     error_code Err;
    688     for (object::symbol_iterator I = Obj->begin_symbols(),
    689                                  E = Obj->end_symbols();
    690          I != E; I.increment(Err), failIfError(Err)) {
    691       uint32_t Symflags;
    692       failIfError(I->getFlags(Symflags));
    693       if (Symflags & object::SymbolRef::SF_FormatSpecific)
    694         continue;
    695       if (!(Symflags & object::SymbolRef::SF_Global))
    696         continue;
    697       if (Symflags & object::SymbolRef::SF_Undefined)
    698         continue;
    699       StringRef Name;
    700       failIfError(I->getName(Name));
    701       SymNames.push_back(Name);
    702       MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
    703       print32BE(Out, 0);
    704     }
    705   }
    706   for (std::vector<StringRef>::iterator I = SymNames.begin(),
    707                                         E = SymNames.end();
    708        I != E; ++I) {
    709     Out << *I;
    710     Out << '\0';
    711   }
    712 
    713   for (std::vector<object::ObjectFile *>::iterator I = DeleteIt.begin(),
    714                                                    E = DeleteIt.end();
    715        I != E; ++I) {
    716     object::ObjectFile *O = *I;
    717     delete O;
    718   }
    719 
    720   if (StartOffset == 0)
    721     return;
    722 
    723   if (Out.tell() % 2)
    724     Out << '\0';
    725 
    726   unsigned Pos = Out.tell();
    727   Out.seek(StartOffset - 12);
    728   printWithSpacePadding(Out, Pos - StartOffset, 10);
    729   Out.seek(StartOffset);
    730   print32BE(Out, SymNames.size());
    731   Out.seek(Pos);
    732 }
    733 
    734 static void performWriteOperation(ArchiveOperation Operation,
    735                                   object::Archive *OldArchive) {
    736   SmallString<128> TmpArchive;
    737   failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
    738                                         TmpArchiveFD, TmpArchive));
    739 
    740   TemporaryOutput = TmpArchive.c_str();
    741   tool_output_file Output(TemporaryOutput, TmpArchiveFD);
    742   raw_fd_ostream &Out = Output.os();
    743   Out << "!<arch>\n";
    744 
    745   std::vector<NewArchiveIterator> NewMembers =
    746       computeNewArchiveMembers(Operation, OldArchive);
    747 
    748   std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
    749 
    750   if (Symtab) {
    751     writeSymbolTable(Out, NewMembers, MemberOffsetRefs);
    752   }
    753 
    754   std::vector<unsigned> StringMapIndexes;
    755   writeStringTable(Out, NewMembers, StringMapIndexes);
    756 
    757   std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
    758       MemberOffsetRefs.begin();
    759 
    760   unsigned MemberNum = 0;
    761   unsigned LongNameMemberNum = 0;
    762   for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
    763                                                  E = NewMembers.end();
    764        I != E; ++I, ++MemberNum) {
    765 
    766     unsigned Pos = Out.tell();
    767     while (MemberRefsI != MemberOffsetRefs.end() &&
    768            MemberRefsI->second == MemberNum) {
    769       Out.seek(MemberRefsI->first);
    770       print32BE(Out, Pos);
    771       ++MemberRefsI;
    772     }
    773     Out.seek(Pos);
    774 
    775     if (I->isNewMember()) {
    776       const char *FileName = I->getNew();
    777 
    778       int FD;
    779       failIfError(sys::fs::openFileForRead(FileName, FD), FileName);
    780 
    781       sys::fs::file_status Status;
    782       failIfError(sys::fs::status(FD, Status), FileName);
    783 
    784       OwningPtr<MemoryBuffer> File;
    785       failIfError(MemoryBuffer::getOpenFile(FD, FileName, File,
    786                                             Status.getSize(), false),
    787                   FileName);
    788 
    789       StringRef Name = sys::path::filename(FileName);
    790       if (Name.size() < 16)
    791         printMemberHeader(Out, Name, Status.getLastModificationTime(),
    792                           Status.getUser(), Status.getGroup(),
    793                           Status.permissions(), Status.getSize());
    794       else
    795         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
    796                           Status.getLastModificationTime(), Status.getUser(),
    797                           Status.getGroup(), Status.permissions(),
    798                           Status.getSize());
    799       Out << File->getBuffer();
    800     } else {
    801       object::Archive::child_iterator OldMember = I->getOld();
    802       StringRef Name = I->getName();
    803 
    804       if (Name.size() < 16)
    805         printMemberHeader(Out, Name, OldMember->getLastModified(),
    806                           OldMember->getUID(), OldMember->getGID(),
    807                           OldMember->getAccessMode(), OldMember->getSize());
    808       else
    809         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
    810                           OldMember->getLastModified(), OldMember->getUID(),
    811                           OldMember->getGID(), OldMember->getAccessMode(),
    812                           OldMember->getSize());
    813       Out << OldMember->getBuffer();
    814     }
    815 
    816     if (Out.tell() % 2)
    817       Out << '\n';
    818   }
    819   Output.keep();
    820   Out.close();
    821   sys::fs::rename(TemporaryOutput, ArchiveName);
    822   TemporaryOutput = NULL;
    823 }
    824 
    825 static void createSymbolTable(object::Archive *OldArchive) {
    826   // When an archive is created or modified, if the s option is given, the
    827   // resulting archive will have a current symbol table. If the S option
    828   // is given, it will have no symbol table.
    829   // In summary, we only need to update the symbol table if we have none.
    830   // This is actually very common because of broken build systems that think
    831   // they have to run ranlib.
    832   if (OldArchive->hasSymbolTable())
    833     return;
    834 
    835   performWriteOperation(CreateSymTab, OldArchive);
    836 }
    837 
    838 static void performOperation(ArchiveOperation Operation,
    839                              object::Archive *OldArchive) {
    840   switch (Operation) {
    841   case Print:
    842   case DisplayTable:
    843   case Extract:
    844     performReadOperation(Operation, OldArchive);
    845     return;
    846 
    847   case Delete:
    848   case Move:
    849   case QuickAppend:
    850   case ReplaceOrInsert:
    851     performWriteOperation(Operation, OldArchive);
    852     return;
    853   case CreateSymTab:
    854     createSymbolTable(OldArchive);
    855     return;
    856   }
    857   llvm_unreachable("Unknown operation.");
    858 }
    859 
    860 // main - main program for llvm-ar .. see comments in the code
    861 int main(int argc, char **argv) {
    862   ToolName = argv[0];
    863   // Print a stack trace if we signal out.
    864   sys::PrintStackTraceOnErrorSignal();
    865   PrettyStackTraceProgram X(argc, argv);
    866   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
    867 
    868   // Have the command line options parsed and handle things
    869   // like --help and --version.
    870   cl::ParseCommandLineOptions(argc, argv,
    871     "LLVM Archiver (llvm-ar)\n\n"
    872     "  This program archives bitcode files into single libraries\n"
    873   );
    874 
    875   // Do our own parsing of the command line because the CommandLine utility
    876   // can't handle the grouped positional parameters without a dash.
    877   ArchiveOperation Operation = parseCommandLine();
    878 
    879   // Create or open the archive object.
    880   OwningPtr<MemoryBuffer> Buf;
    881   error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
    882   if (EC && EC != llvm::errc::no_such_file_or_directory) {
    883     errs() << argv[0] << ": error opening '" << ArchiveName
    884            << "': " << EC.message() << "!\n";
    885     return 1;
    886   }
    887 
    888   if (!EC) {
    889     object::Archive Archive(Buf.take(), EC);
    890 
    891     if (EC) {
    892       errs() << argv[0] << ": error loading '" << ArchiveName
    893              << "': " << EC.message() << "!\n";
    894       return 1;
    895     }
    896     performOperation(Operation, &Archive);
    897     return 0;
    898   }
    899 
    900   assert(EC == llvm::errc::no_such_file_or_directory);
    901 
    902   if (!shouldCreateArchive(Operation)) {
    903     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
    904   } else {
    905     if (!Create) {
    906       // Produce a warning if we should and we're creating the archive
    907       errs() << argv[0] << ": creating " << ArchiveName << "\n";
    908     }
    909   }
    910 
    911   performOperation(Operation, NULL);
    912   return 0;
    913 }
    914