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