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