Use std::error_code instead of llvm::error_code.
[oota-llvm.git] / tools / llvm-ar / llvm-ar.cpp
1 //===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file 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 // llvm-ar/llvm-ranlib remaining positional arguments.
67 static cl::list<std::string>
68 RestOfArgs(cl::Positional, cl::OneOrMore,
69     cl::desc("[relpos] [count] <archive-file> [members]..."));
70
71 std::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.
76 static 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.
101 enum 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
113 static bool AddAfter = false;      ///< 'a' modifier
114 static bool AddBefore = false;     ///< 'b' modifier
115 static bool Create = false;        ///< 'c' modifier
116 static bool OriginalDates = false; ///< 'o' modifier
117 static bool OnlyUpdate = false;    ///< 'u' modifier
118 static bool Verbose = false;       ///< 'v' modifier
119 static 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.
125 static std::string RelPos;
126
127 // This variable holds the name of the archive file as given on the
128 // command line.
129 static std::string ArchiveName;
130
131 // This variable holds the list of member files to proecess, as given
132 // on the command line.
133 static std::vector<std::string> Members;
134
135 // show_help - Show the error message, the help message and exit.
136 LLVM_ATTRIBUTE_NORETURN static void
137 show_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
145 static 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
152 static 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
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   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.
272 static 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.
282 static 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.
301 static 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.
318 static 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_None, 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
348 static 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
366 static void performReadOperation(ArchiveOperation Operation,
367                                  object::Archive *OldArchive) {
368   for (object::Archive::child_iterator I = OldArchive->child_begin(),
369                                        E = OldArchive->child_end();
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
394 namespace {
395 class NewArchiveIterator {
396   bool IsNewMember;
397   StringRef Name;
398
399   object::Archive::child_iterator OldI;
400
401   std::string NewFilename;
402   mutable int NewFD;
403   mutable sys::fs::file_status NewStatus;
404
405 public:
406   NewArchiveIterator(object::Archive::child_iterator I, StringRef Name);
407   NewArchiveIterator(std::string *I, StringRef Name);
408   NewArchiveIterator();
409   bool isNewMember() const;
410   StringRef getName() const;
411
412   object::Archive::child_iterator getOld() const;
413
414   const char *getNew() const;
415   int getFD() const;
416   const sys::fs::file_status &getStatus() const;
417 };
418 }
419
420 NewArchiveIterator::NewArchiveIterator() {}
421
422 NewArchiveIterator::NewArchiveIterator(object::Archive::child_iterator I,
423                                        StringRef Name)
424     : IsNewMember(false), Name(Name), OldI(I) {}
425
426 NewArchiveIterator::NewArchiveIterator(std::string *NewFilename, StringRef Name)
427     : IsNewMember(true), Name(Name), NewFilename(*NewFilename), NewFD(-1) {}
428
429 StringRef NewArchiveIterator::getName() const { return Name; }
430
431 bool NewArchiveIterator::isNewMember() const { return IsNewMember; }
432
433 object::Archive::child_iterator NewArchiveIterator::getOld() const {
434   assert(!IsNewMember);
435   return OldI;
436 }
437
438 const char *NewArchiveIterator::getNew() const {
439   assert(IsNewMember);
440   return NewFilename.c_str();
441 }
442
443 int NewArchiveIterator::getFD() const {
444   assert(IsNewMember);
445   if (NewFD != -1)
446     return NewFD;
447   failIfError(sys::fs::openFileForRead(NewFilename, NewFD), NewFilename);
448   assert(NewFD != -1);
449
450   failIfError(sys::fs::status(NewFD, NewStatus), NewFilename);
451
452   // Opening a directory doesn't make sense. Let it fail.
453   // Linux cannot open directories with open(2), although
454   // cygwin and *bsd can.
455   if (NewStatus.type() == sys::fs::file_type::directory_file)
456     failIfError(make_error_code(std::errc::is_a_directory), NewFilename);
457
458   return NewFD;
459 }
460
461 const sys::fs::file_status &NewArchiveIterator::getStatus() const {
462   assert(IsNewMember);
463   assert(NewFD != -1 && "Must call getFD first");
464   return NewStatus;
465 }
466
467 template <typename T>
468 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
469                int Pos = -1) {
470   NewArchiveIterator NI(I, Name);
471   if (Pos == -1)
472     Members.push_back(NI);
473   else
474     Members[Pos] = NI;
475 }
476
477 enum InsertAction {
478   IA_AddOldMember,
479   IA_AddNewMeber,
480   IA_Delete,
481   IA_MoveOldMember,
482   IA_MoveNewMember
483 };
484
485 static InsertAction
486 computeInsertAction(ArchiveOperation Operation,
487                     object::Archive::child_iterator I, StringRef Name,
488                     std::vector<std::string>::iterator &Pos) {
489   if (Operation == QuickAppend || Members.empty())
490     return IA_AddOldMember;
491
492   std::vector<std::string>::iterator MI = std::find_if(
493       Members.begin(), Members.end(),
494       [Name](StringRef Path) { return Name == sys::path::filename(Path); });
495
496   if (MI == Members.end())
497     return IA_AddOldMember;
498
499   Pos = MI;
500
501   if (Operation == Delete)
502     return IA_Delete;
503
504   if (Operation == Move)
505     return IA_MoveOldMember;
506
507   if (Operation == ReplaceOrInsert) {
508     StringRef PosName = sys::path::filename(RelPos);
509     if (!OnlyUpdate) {
510       if (PosName.empty())
511         return IA_AddNewMeber;
512       return IA_MoveNewMember;
513     }
514
515     // We could try to optimize this to a fstat, but it is not a common
516     // operation.
517     sys::fs::file_status Status;
518     failIfError(sys::fs::status(*MI, Status), *MI);
519     if (Status.getLastModificationTime() < I->getLastModified()) {
520       if (PosName.empty())
521         return IA_AddOldMember;
522       return IA_MoveOldMember;
523     }
524
525     if (PosName.empty())
526       return IA_AddNewMeber;
527     return IA_MoveNewMember;
528   }
529   llvm_unreachable("No such operation");
530 }
531
532 // We have to walk this twice and computing it is not trivial, so creating an
533 // explicit std::vector is actually fairly efficient.
534 static std::vector<NewArchiveIterator>
535 computeNewArchiveMembers(ArchiveOperation Operation,
536                          object::Archive *OldArchive) {
537   std::vector<NewArchiveIterator> Ret;
538   std::vector<NewArchiveIterator> Moved;
539   int InsertPos = -1;
540   StringRef PosName = sys::path::filename(RelPos);
541   if (OldArchive) {
542     for (object::Archive::child_iterator I = OldArchive->child_begin(),
543                                          E = OldArchive->child_end();
544          I != E; ++I) {
545       int Pos = Ret.size();
546       StringRef Name;
547       failIfError(I->getName(Name));
548       if (Name == PosName) {
549         assert(AddAfter || AddBefore);
550         if (AddBefore)
551           InsertPos = Pos;
552         else
553           InsertPos = Pos + 1;
554       }
555
556       std::vector<std::string>::iterator MemberI = Members.end();
557       InsertAction Action = computeInsertAction(Operation, I, Name, MemberI);
558       switch (Action) {
559       case IA_AddOldMember:
560         addMember(Ret, I, Name);
561         break;
562       case IA_AddNewMeber:
563         addMember(Ret, &*MemberI, Name);
564         break;
565       case IA_Delete:
566         break;
567       case IA_MoveOldMember:
568         addMember(Moved, I, Name);
569         break;
570       case IA_MoveNewMember:
571         addMember(Moved, &*MemberI, Name);
572         break;
573       }
574       if (MemberI != Members.end())
575         Members.erase(MemberI);
576     }
577   }
578
579   if (Operation == Delete)
580     return Ret;
581
582   if (!RelPos.empty() && InsertPos == -1)
583     fail("Insertion point not found");
584
585   if (RelPos.empty())
586     InsertPos = Ret.size();
587
588   assert(unsigned(InsertPos) <= Ret.size());
589   Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
590
591   Ret.insert(Ret.begin() + InsertPos, Members.size(), NewArchiveIterator());
592   int Pos = InsertPos;
593   for (std::vector<std::string>::iterator I = Members.begin(),
594          E = Members.end();
595        I != E; ++I, ++Pos) {
596     StringRef Name = sys::path::filename(*I);
597     addMember(Ret, &*I, Name, Pos);
598   }
599
600   return Ret;
601 }
602
603 template <typename T>
604 static void printWithSpacePadding(raw_fd_ostream &OS, T Data, unsigned Size,
605                                   bool MayTruncate = false) {
606   uint64_t OldPos = OS.tell();
607   OS << Data;
608   unsigned SizeSoFar = OS.tell() - OldPos;
609   if (Size > SizeSoFar) {
610     unsigned Remaining = Size - SizeSoFar;
611     for (unsigned I = 0; I < Remaining; ++I)
612       OS << ' ';
613   } else if (Size < SizeSoFar) {
614     assert(MayTruncate && "Data doesn't fit in Size");
615     // Some of the data this is used for (like UID) can be larger than the
616     // space available in the archive format. Truncate in that case.
617     OS.seek(OldPos + Size);
618   }
619 }
620
621 static void print32BE(raw_fd_ostream &Out, unsigned Val) {
622   for (int I = 3; I >= 0; --I) {
623     char V = (Val >> (8 * I)) & 0xff;
624     Out << V;
625   }
626 }
627
628 static void printRestOfMemberHeader(raw_fd_ostream &Out,
629                                     const sys::TimeValue &ModTime, unsigned UID,
630                                     unsigned GID, unsigned Perms,
631                                     unsigned Size) {
632   printWithSpacePadding(Out, ModTime.toEpochTime(), 12);
633   printWithSpacePadding(Out, UID, 6, true);
634   printWithSpacePadding(Out, GID, 6, true);
635   printWithSpacePadding(Out, format("%o", Perms), 8);
636   printWithSpacePadding(Out, Size, 10);
637   Out << "`\n";
638 }
639
640 static void printMemberHeader(raw_fd_ostream &Out, StringRef Name,
641                               const sys::TimeValue &ModTime, unsigned UID,
642                               unsigned GID, unsigned Perms, unsigned Size) {
643   printWithSpacePadding(Out, Twine(Name) + "/", 16);
644   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
645 }
646
647 static void printMemberHeader(raw_fd_ostream &Out, unsigned NameOffset,
648                               const sys::TimeValue &ModTime, unsigned UID,
649                               unsigned GID, unsigned Perms, unsigned Size) {
650   Out << '/';
651   printWithSpacePadding(Out, NameOffset, 15);
652   printRestOfMemberHeader(Out, ModTime, UID, GID, Perms, Size);
653 }
654
655 static void writeStringTable(raw_fd_ostream &Out,
656                              ArrayRef<NewArchiveIterator> Members,
657                              std::vector<unsigned> &StringMapIndexes) {
658   unsigned StartOffset = 0;
659   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
660                                               E = Members.end();
661        I != E; ++I) {
662     StringRef Name = I->getName();
663     if (Name.size() < 16)
664       continue;
665     if (StartOffset == 0) {
666       printWithSpacePadding(Out, "//", 58);
667       Out << "`\n";
668       StartOffset = Out.tell();
669     }
670     StringMapIndexes.push_back(Out.tell() - StartOffset);
671     Out << Name << "/\n";
672   }
673   if (StartOffset == 0)
674     return;
675   if (Out.tell() % 2)
676     Out << '\n';
677   int Pos = Out.tell();
678   Out.seek(StartOffset - 12);
679   printWithSpacePadding(Out, Pos - StartOffset, 10);
680   Out.seek(Pos);
681 }
682
683 static void writeSymbolTable(
684     raw_fd_ostream &Out, ArrayRef<NewArchiveIterator> Members,
685     ArrayRef<MemoryBuffer *> Buffers,
686     std::vector<std::pair<unsigned, unsigned> > &MemberOffsetRefs) {
687   unsigned StartOffset = 0;
688   unsigned MemberNum = 0;
689   std::string NameBuf;
690   raw_string_ostream NameOS(NameBuf);
691   unsigned NumSyms = 0;
692   std::vector<object::SymbolicFile *> DeleteIt;
693   LLVMContext &Context = getGlobalContext();
694   for (ArrayRef<NewArchiveIterator>::iterator I = Members.begin(),
695                                               E = Members.end();
696        I != E; ++I, ++MemberNum) {
697     MemoryBuffer *MemberBuffer = Buffers[MemberNum];
698     ErrorOr<object::SymbolicFile *> ObjOrErr =
699         object::SymbolicFile::createSymbolicFile(
700             MemberBuffer, false, sys::fs::file_magic::unknown, &Context);
701     if (!ObjOrErr)
702       continue;  // FIXME: check only for "not an object file" errors.
703     object::SymbolicFile *Obj = ObjOrErr.get();
704
705     DeleteIt.push_back(Obj);
706     if (!StartOffset) {
707       printMemberHeader(Out, "", sys::TimeValue::now(), 0, 0, 0, 0);
708       StartOffset = Out.tell();
709       print32BE(Out, 0);
710     }
711
712     for (object::basic_symbol_iterator I = Obj->symbol_begin(),
713                                        E = Obj->symbol_end();
714          I != E; ++I) {
715       uint32_t Symflags = I->getFlags();
716       if (Symflags & object::SymbolRef::SF_FormatSpecific)
717         continue;
718       if (!(Symflags & object::SymbolRef::SF_Global))
719         continue;
720       if (Symflags & object::SymbolRef::SF_Undefined)
721         continue;
722       failIfError(I->printName(NameOS));
723       NameOS << '\0';
724       ++NumSyms;
725       MemberOffsetRefs.push_back(std::make_pair(Out.tell(), MemberNum));
726       print32BE(Out, 0);
727     }
728   }
729   Out << NameOS.str();
730
731   for (std::vector<object::SymbolicFile *>::iterator I = DeleteIt.begin(),
732                                                      E = DeleteIt.end();
733        I != E; ++I) {
734     object::SymbolicFile *O = *I;
735     delete O;
736   }
737
738   if (StartOffset == 0)
739     return;
740
741   if (Out.tell() % 2)
742     Out << '\0';
743
744   unsigned Pos = Out.tell();
745   Out.seek(StartOffset - 12);
746   printWithSpacePadding(Out, Pos - StartOffset, 10);
747   Out.seek(StartOffset);
748   print32BE(Out, NumSyms);
749   Out.seek(Pos);
750 }
751
752 static void performWriteOperation(ArchiveOperation Operation,
753                                   object::Archive *OldArchive) {
754   SmallString<128> TmpArchive;
755   failIfError(sys::fs::createUniqueFile(ArchiveName + ".temp-archive-%%%%%%%.a",
756                                         TmpArchiveFD, TmpArchive));
757
758   TemporaryOutput = TmpArchive.c_str();
759   tool_output_file Output(TemporaryOutput, TmpArchiveFD);
760   raw_fd_ostream &Out = Output.os();
761   Out << "!<arch>\n";
762
763   std::vector<NewArchiveIterator> NewMembers =
764       computeNewArchiveMembers(Operation, OldArchive);
765
766   std::vector<std::pair<unsigned, unsigned> > MemberOffsetRefs;
767
768   std::vector<MemoryBuffer *> MemberBuffers;
769   MemberBuffers.resize(NewMembers.size());
770
771   for (unsigned I = 0, N = NewMembers.size(); I < N; ++I) {
772     std::unique_ptr<MemoryBuffer> MemberBuffer;
773     NewArchiveIterator &Member = NewMembers[I];
774
775     if (Member.isNewMember()) {
776       const char *Filename = Member.getNew();
777       int FD = Member.getFD();
778       const sys::fs::file_status &Status = Member.getStatus();
779       failIfError(MemoryBuffer::getOpenFile(FD, Filename, MemberBuffer,
780                                             Status.getSize(), false),
781                   Filename);
782
783     } else {
784       object::Archive::child_iterator OldMember = Member.getOld();
785       failIfError(OldMember->getMemoryBuffer(MemberBuffer));
786     }
787     MemberBuffers[I] = MemberBuffer.release();
788   }
789
790   if (Symtab) {
791     writeSymbolTable(Out, NewMembers, MemberBuffers, MemberOffsetRefs);
792   }
793
794   std::vector<unsigned> StringMapIndexes;
795   writeStringTable(Out, NewMembers, StringMapIndexes);
796
797   std::vector<std::pair<unsigned, unsigned> >::iterator MemberRefsI =
798       MemberOffsetRefs.begin();
799
800   unsigned MemberNum = 0;
801   unsigned LongNameMemberNum = 0;
802   for (std::vector<NewArchiveIterator>::iterator I = NewMembers.begin(),
803                                                  E = NewMembers.end();
804        I != E; ++I, ++MemberNum) {
805
806     unsigned Pos = Out.tell();
807     while (MemberRefsI != MemberOffsetRefs.end() &&
808            MemberRefsI->second == MemberNum) {
809       Out.seek(MemberRefsI->first);
810       print32BE(Out, Pos);
811       ++MemberRefsI;
812     }
813     Out.seek(Pos);
814
815     const MemoryBuffer *File = MemberBuffers[MemberNum];
816     if (I->isNewMember()) {
817       const char *FileName = I->getNew();
818       const sys::fs::file_status &Status = I->getStatus();
819
820       StringRef Name = sys::path::filename(FileName);
821       if (Name.size() < 16)
822         printMemberHeader(Out, Name, Status.getLastModificationTime(),
823                           Status.getUser(), Status.getGroup(),
824                           Status.permissions(), Status.getSize());
825       else
826         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
827                           Status.getLastModificationTime(), Status.getUser(),
828                           Status.getGroup(), Status.permissions(),
829                           Status.getSize());
830     } else {
831       object::Archive::child_iterator OldMember = I->getOld();
832       StringRef Name = I->getName();
833
834       if (Name.size() < 16)
835         printMemberHeader(Out, Name, OldMember->getLastModified(),
836                           OldMember->getUID(), OldMember->getGID(),
837                           OldMember->getAccessMode(), OldMember->getSize());
838       else
839         printMemberHeader(Out, StringMapIndexes[LongNameMemberNum++],
840                           OldMember->getLastModified(), OldMember->getUID(),
841                           OldMember->getGID(), OldMember->getAccessMode(),
842                           OldMember->getSize());
843     }
844
845     Out << File->getBuffer();
846
847     if (Out.tell() % 2)
848       Out << '\n';
849   }
850
851   for (unsigned I = 0, N = MemberBuffers.size(); I < N; ++I) {
852     delete MemberBuffers[I];
853   }
854
855   Output.keep();
856   Out.close();
857   sys::fs::rename(TemporaryOutput, ArchiveName);
858   TemporaryOutput = nullptr;
859 }
860
861 static void createSymbolTable(object::Archive *OldArchive) {
862   // When an archive is created or modified, if the s option is given, the
863   // resulting archive will have a current symbol table. If the S option
864   // is given, it will have no symbol table.
865   // In summary, we only need to update the symbol table if we have none.
866   // This is actually very common because of broken build systems that think
867   // they have to run ranlib.
868   if (OldArchive->hasSymbolTable())
869     return;
870
871   performWriteOperation(CreateSymTab, OldArchive);
872 }
873
874 static void performOperation(ArchiveOperation Operation,
875                              object::Archive *OldArchive) {
876   switch (Operation) {
877   case Print:
878   case DisplayTable:
879   case Extract:
880     performReadOperation(Operation, OldArchive);
881     return;
882
883   case Delete:
884   case Move:
885   case QuickAppend:
886   case ReplaceOrInsert:
887     performWriteOperation(Operation, OldArchive);
888     return;
889   case CreateSymTab:
890     createSymbolTable(OldArchive);
891     return;
892   }
893   llvm_unreachable("Unknown operation.");
894 }
895
896 static int ar_main(char **argv);
897 static int ranlib_main();
898
899 // main - main program for llvm-ar .. see comments in the code
900 int main(int argc, char **argv) {
901   ToolName = argv[0];
902   // Print a stack trace if we signal out.
903   sys::PrintStackTraceOnErrorSignal();
904   PrettyStackTraceProgram X(argc, argv);
905   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
906
907   // Have the command line options parsed and handle things
908   // like --help and --version.
909   cl::ParseCommandLineOptions(argc, argv,
910     "LLVM Archiver (llvm-ar)\n\n"
911     "  This program archives bitcode files into single libraries\n"
912   );
913
914   StringRef Stem = sys::path::stem(ToolName);
915   if (Stem.find("ar") != StringRef::npos)
916     return ar_main(argv);
917   if (Stem.find("ranlib") != StringRef::npos)
918     return ranlib_main();
919   fail("Not ranlib or ar!");
920 }
921
922 static int performOperation(ArchiveOperation Operation);
923
924 int ranlib_main() {
925   if (RestOfArgs.size() != 1)
926     fail(ToolName + "takes just one archive as argument");
927   ArchiveName = RestOfArgs[0];
928   return performOperation(CreateSymTab);
929 }
930
931 int ar_main(char **argv) {
932   // Do our own parsing of the command line because the CommandLine utility
933   // can't handle the grouped positional parameters without a dash.
934   ArchiveOperation Operation = parseCommandLine();
935   return performOperation(Operation);
936 }
937
938 static int performOperation(ArchiveOperation Operation) {
939   // Create or open the archive object.
940   std::unique_ptr<MemoryBuffer> Buf;
941   error_code EC = MemoryBuffer::getFile(ArchiveName, Buf, -1, false);
942   if (EC && EC != std::errc::no_such_file_or_directory) {
943     errs() << ToolName << ": error opening '" << ArchiveName
944            << "': " << EC.message() << "!\n";
945     return 1;
946   }
947
948   if (!EC) {
949     object::Archive Archive(Buf.release(), EC);
950
951     if (EC) {
952       errs() << ToolName << ": error loading '" << ArchiveName
953              << "': " << EC.message() << "!\n";
954       return 1;
955     }
956     performOperation(Operation, &Archive);
957     return 0;
958   }
959
960   assert(EC == std::errc::no_such_file_or_directory);
961
962   if (!shouldCreateArchive(Operation)) {
963     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
964   } else {
965     if (!Create) {
966       // Produce a warning if we should and we're creating the archive
967       errs() << ToolName << ": creating " << ArchiveName << "\n";
968     }
969   }
970
971   performOperation(Operation, nullptr);
972   return 0;
973 }