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