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