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