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/ADT/Triple.h"
17 #include "llvm/IR/LLVMContext.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/LibDriver/LibDriver.h"
20 #include "llvm/Object/Archive.h"
21 #include "llvm/Object/ArchiveWriter.h"
22 #include "llvm/Object/MachO.h"
23 #include "llvm/Object/ObjectFile.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Format.h"
28 #include "llvm/Support/LineIterator.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/Signals.h"
34 #include "llvm/Support/TargetSelect.h"
35 #include "llvm/Support/ToolOutputFile.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cstdlib>
39 #include <memory>
40 
41 #if !defined(_MSC_VER) && !defined(__MINGW32__)
42 #include <unistd.h>
43 #else
44 #include <io.h>
45 #endif
46 
47 using namespace llvm;
48 
49 // The name this program was invoked as.
50 static StringRef ToolName;
51 
52 // Show the error message and exit.
53 LLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
54   outs() << ToolName << ": " << Error << ".\n";
55   exit(1);
56 }
57 
58 static void failIfError(std::error_code EC, Twine Context = "") {
59   if (!EC)
60     return;
61 
62   std::string ContextStr = Context.str();
63   if (ContextStr == "")
64     fail(EC.message());
65   fail(Context + ": " + EC.message());
66 }
67 
68 static void failIfError(Error E, Twine Context = "") {
69   if (!E)
70     return;
71 
72   handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
73     std::string ContextStr = Context.str();
74     if (ContextStr == "")
75       fail(EIB.message());
76     fail(Context + ": " + EIB.message());
77   });
78 }
79 
80 // llvm-ar/llvm-ranlib remaining positional arguments.
81 static cl::list<std::string>
82     RestOfArgs(cl::Positional, cl::ZeroOrMore,
83                cl::desc("[relpos] [count] <archive-file> [members]..."));
84 
85 static cl::opt<bool> MRI("M", cl::desc(""));
86 static cl::opt<std::string> Plugin("plugin", cl::desc("plugin (ignored for compatibility"));
87 
88 namespace {
89 enum Format { Default, GNU, BSD };
90 }
91 
92 static cl::opt<Format>
93     FormatOpt("format", cl::desc("Archive format to create"),
94               cl::values(clEnumValN(Default, "default", "default"),
95                          clEnumValN(GNU, "gnu", "gnu"),
96                          clEnumValN(BSD, "bsd", "bsd")));
97 
98 static std::string Options;
99 
100 // Provide additional help output explaining the operations and modifiers of
101 // llvm-ar. This object instructs the CommandLine library to print the text of
102 // the constructor when the --help option is given.
103 static cl::extrahelp MoreHelp(
104   "\nOPERATIONS:\n"
105   "  d[NsS]       - delete file(s) from the archive\n"
106   "  m[abiSs]     - move file(s) in the archive\n"
107   "  p[kN]        - print file(s) found in the archive\n"
108   "  q[ufsS]      - quick append file(s) to the archive\n"
109   "  r[abfiuRsS]  - replace or insert file(s) into the archive\n"
110   "  t            - display contents of archive\n"
111   "  x[No]        - extract file(s) from the archive\n"
112   "\nMODIFIERS (operation specific):\n"
113   "  [a] - put file(s) after [relpos]\n"
114   "  [b] - put file(s) before [relpos] (same as [i])\n"
115   "  [i] - put file(s) before [relpos] (same as [b])\n"
116   "  [o] - preserve original dates\n"
117   "  [s] - create an archive index (cf. ranlib)\n"
118   "  [S] - do not build a symbol table\n"
119   "  [T] - create a thin archive\n"
120   "  [u] - update only files newer than archive contents\n"
121   "\nMODIFIERS (generic):\n"
122   "  [c] - do not warn if the library had to be created\n"
123   "  [v] - be verbose about actions taken\n"
124 );
125 
126 // This enumeration delineates the kinds of operations on an archive
127 // that are permitted.
128 enum ArchiveOperation {
129   Print,            ///< Print the contents of the archive
130   Delete,           ///< Delete the specified members
131   Move,             ///< Move members to end or as given by {a,b,i} modifiers
132   QuickAppend,      ///< Quickly append to end of archive
133   ReplaceOrInsert,  ///< Replace or Insert members
134   DisplayTable,     ///< Display the table of contents
135   Extract,          ///< Extract files back to file system
136   CreateSymTab      ///< Create a symbol table in an existing archive
137 };
138 
139 // Modifiers to follow operation to vary behavior
140 static bool AddAfter = false;      ///< 'a' modifier
141 static bool AddBefore = false;     ///< 'b' modifier
142 static bool Create = false;        ///< 'c' modifier
143 static bool OriginalDates = false; ///< 'o' modifier
144 static bool OnlyUpdate = false;    ///< 'u' modifier
145 static bool Verbose = false;       ///< 'v' modifier
146 static bool Symtab = true;         ///< 's' modifier
147 static bool Deterministic = true;  ///< 'D' and 'U' modifiers
148 static bool Thin = false;          ///< 'T' modifier
149 
150 // Relative Positional Argument (for insert/move). This variable holds
151 // the name of the archive member to which the 'a', 'b' or 'i' modifier
152 // refers. Only one of 'a', 'b' or 'i' can be specified so we only need
153 // one variable.
154 static std::string RelPos;
155 
156 // This variable holds the name of the archive file as given on the
157 // command line.
158 static std::string ArchiveName;
159 
160 // This variable holds the list of member files to proecess, as given
161 // on the command line.
162 static std::vector<StringRef> Members;
163 
164 // Show the error message, the help message and exit.
165 LLVM_ATTRIBUTE_NORETURN static void
166 show_help(const std::string &msg) {
167   errs() << ToolName << ": " << msg << "\n\n";
168   cl::PrintHelpMessage();
169   std::exit(1);
170 }
171 
172 // Extract the member filename from the command line for the [relpos] argument
173 // associated with a, b, and i modifiers
174 static void getRelPos() {
175   if(RestOfArgs.size() == 0)
176     show_help("Expected [relpos] for a, b, or i modifier");
177   RelPos = RestOfArgs[0];
178   RestOfArgs.erase(RestOfArgs.begin());
179 }
180 
181 static void getOptions() {
182   if(RestOfArgs.size() == 0)
183     show_help("Expected options");
184   Options = RestOfArgs[0];
185   RestOfArgs.erase(RestOfArgs.begin());
186 }
187 
188 // Get the archive file name from the command line
189 static void getArchive() {
190   if(RestOfArgs.size() == 0)
191     show_help("An archive name must be specified");
192   ArchiveName = RestOfArgs[0];
193   RestOfArgs.erase(RestOfArgs.begin());
194 }
195 
196 // Copy over remaining items in RestOfArgs to our Members vector
197 static void getMembers() {
198   for (auto &Arg : RestOfArgs)
199     Members.push_back(Arg);
200 }
201 
202 static void runMRIScript();
203 
204 // Parse the command line options as presented and return the operation
205 // specified. Process all modifiers and check to make sure that constraints on
206 // modifier/operation pairs have not been violated.
207 static ArchiveOperation parseCommandLine() {
208   if (MRI) {
209     if (!RestOfArgs.empty())
210       fail("Cannot mix -M and other options");
211     runMRIScript();
212   }
213 
214   getOptions();
215 
216   // Keep track of number of operations. We can only specify one
217   // per execution.
218   unsigned NumOperations = 0;
219 
220   // Keep track of the number of positional modifiers (a,b,i). Only
221   // one can be specified.
222   unsigned NumPositional = 0;
223 
224   // Keep track of which operation was requested
225   ArchiveOperation Operation;
226 
227   bool MaybeJustCreateSymTab = false;
228 
229   for(unsigned i=0; i<Options.size(); ++i) {
230     switch(Options[i]) {
231     case 'd': ++NumOperations; Operation = Delete; break;
232     case 'm': ++NumOperations; Operation = Move ; break;
233     case 'p': ++NumOperations; Operation = Print; break;
234     case 'q': ++NumOperations; Operation = QuickAppend; break;
235     case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
236     case 't': ++NumOperations; Operation = DisplayTable; break;
237     case 'x': ++NumOperations; Operation = Extract; break;
238     case 'c': Create = true; break;
239     case 'l': /* accepted but unused */ break;
240     case 'o': OriginalDates = true; break;
241     case 's':
242       Symtab = true;
243       MaybeJustCreateSymTab = true;
244       break;
245     case 'S':
246       Symtab = false;
247       break;
248     case 'u': OnlyUpdate = true; break;
249     case 'v': Verbose = true; break;
250     case 'a':
251       getRelPos();
252       AddAfter = true;
253       NumPositional++;
254       break;
255     case 'b':
256       getRelPos();
257       AddBefore = true;
258       NumPositional++;
259       break;
260     case 'i':
261       getRelPos();
262       AddBefore = true;
263       NumPositional++;
264       break;
265     case 'D':
266       Deterministic = true;
267       break;
268     case 'U':
269       Deterministic = false;
270       break;
271     case 'T':
272       Thin = true;
273       break;
274     default:
275       cl::PrintHelpMessage();
276     }
277   }
278 
279   // At this point, the next thing on the command line must be
280   // the archive name.
281   getArchive();
282 
283   // Everything on the command line at this point is a member.
284   getMembers();
285 
286  if (NumOperations == 0 && MaybeJustCreateSymTab) {
287     NumOperations = 1;
288     Operation = CreateSymTab;
289     if (!Members.empty())
290       show_help("The s operation takes only an archive as argument");
291   }
292 
293   // Perform various checks on the operation/modifier specification
294   // to make sure we are dealing with a legal request.
295   if (NumOperations == 0)
296     show_help("You must specify at least one of the operations");
297   if (NumOperations > 1)
298     show_help("Only one operation may be specified");
299   if (NumPositional > 1)
300     show_help("You may only specify one of a, b, and i modifiers");
301   if (AddAfter || AddBefore) {
302     if (Operation != Move && Operation != ReplaceOrInsert)
303       show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
304             "the 'm' or 'r' operations");
305   }
306   if (OriginalDates && Operation != Extract)
307     show_help("The 'o' modifier is only applicable to the 'x' operation");
308   if (OnlyUpdate && Operation != ReplaceOrInsert)
309     show_help("The 'u' modifier is only applicable to the 'r' operation");
310 
311   // Return the parsed operation to the caller
312   return Operation;
313 }
314 
315 // Implements the 'p' operation. This function traverses the archive
316 // looking for members that match the path list.
317 static void doPrint(StringRef Name, const object::Archive::Child &C) {
318   if (Verbose)
319     outs() << "Printing " << Name << "\n";
320 
321   Expected<StringRef> DataOrErr = C.getBuffer();
322   failIfError(DataOrErr.takeError());
323   StringRef Data = *DataOrErr;
324   outs().write(Data.data(), Data.size());
325 }
326 
327 // Utility function for printing out the file mode when the 't' operation is in
328 // verbose mode.
329 static void printMode(unsigned mode) {
330   outs() << ((mode & 004) ? "r" : "-");
331   outs() << ((mode & 002) ? "w" : "-");
332   outs() << ((mode & 001) ? "x" : "-");
333 }
334 
335 // Implement the 't' operation. This function prints out just
336 // the file names of each of the members. However, if verbose mode is requested
337 // ('v' modifier) then the file type, permission mode, user, group, size, and
338 // modification time are also printed.
339 static void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
340   if (Verbose) {
341     Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
342     failIfError(ModeOrErr.takeError());
343     sys::fs::perms Mode = ModeOrErr.get();
344     printMode((Mode >> 6) & 007);
345     printMode((Mode >> 3) & 007);
346     printMode(Mode & 007);
347     Expected<unsigned> UIDOrErr = C.getUID();
348     failIfError(UIDOrErr.takeError());
349     outs() << ' ' << UIDOrErr.get();
350     Expected<unsigned> GIDOrErr = C.getGID();
351     failIfError(GIDOrErr.takeError());
352     outs() << '/' << GIDOrErr.get();
353     Expected<uint64_t> Size = C.getSize();
354     failIfError(Size.takeError());
355     outs() << ' ' << format("%6llu", Size.get());
356     Expected<sys::TimeValue> ModTimeOrErr = C.getLastModified();
357     failIfError(ModTimeOrErr.takeError());
358     outs() << ' ' << ModTimeOrErr.get().str();
359     outs() << ' ';
360   }
361   outs() << Name << "\n";
362 }
363 
364 // Implement the 'x' operation. This function extracts files back to the file
365 // system.
366 static void doExtract(StringRef Name, const object::Archive::Child &C) {
367   // Retain the original mode.
368   Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
369   failIfError(ModeOrErr.takeError());
370   sys::fs::perms Mode = ModeOrErr.get();
371 
372   int FD;
373   failIfError(sys::fs::openFileForWrite(Name, FD, sys::fs::F_None, Mode), Name);
374 
375   {
376     raw_fd_ostream file(FD, false);
377 
378     // Get the data and its length
379     Expected<StringRef> BufOrErr = C.getBuffer();
380     failIfError(BufOrErr.takeError());
381     StringRef Data = BufOrErr.get();
382 
383     // Write the data.
384     file.write(Data.data(), Data.size());
385   }
386 
387   // If we're supposed to retain the original modification times, etc. do so
388   // now.
389   if (OriginalDates) {
390     Expected<sys::TimeValue> ModTimeOrErr = C.getLastModified();
391     failIfError(ModTimeOrErr.takeError());
392     failIfError(
393         sys::fs::setLastModificationAndAccessTime(FD, ModTimeOrErr.get()));
394   }
395 
396   if (close(FD))
397     fail("Could not close the file");
398 }
399 
400 static bool shouldCreateArchive(ArchiveOperation Op) {
401   switch (Op) {
402   case Print:
403   case Delete:
404   case Move:
405   case DisplayTable:
406   case Extract:
407   case CreateSymTab:
408     return false;
409 
410   case QuickAppend:
411   case ReplaceOrInsert:
412     return true;
413   }
414 
415   llvm_unreachable("Missing entry in covered switch.");
416 }
417 
418 static void performReadOperation(ArchiveOperation Operation,
419                                  object::Archive *OldArchive) {
420   if (Operation == Extract && OldArchive->isThin())
421     fail("extracting from a thin archive is not supported");
422 
423   bool Filter = !Members.empty();
424   {
425     Error Err;
426     for (auto &C : OldArchive->children(Err)) {
427       Expected<StringRef> NameOrErr = C.getName();
428       failIfError(NameOrErr.takeError());
429       StringRef Name = NameOrErr.get();
430 
431       if (Filter) {
432         auto I = find(Members, Name);
433         if (I == Members.end())
434           continue;
435         Members.erase(I);
436       }
437 
438       switch (Operation) {
439       default:
440         llvm_unreachable("Not a read operation");
441       case Print:
442         doPrint(Name, C);
443         break;
444       case DisplayTable:
445         doDisplayTable(Name, C);
446         break;
447       case Extract:
448         doExtract(Name, C);
449         break;
450       }
451     }
452     failIfError(std::move(Err));
453   }
454 
455   if (Members.empty())
456     return;
457   for (StringRef Name : Members)
458     errs() << Name << " was not found\n";
459   std::exit(1);
460 }
461 
462 static void addMember(std::vector<NewArchiveMember> &Members,
463                       StringRef FileName, int Pos = -1) {
464   Expected<NewArchiveMember> NMOrErr =
465       NewArchiveMember::getFile(FileName, Deterministic);
466   failIfError(NMOrErr.takeError(), FileName);
467   if (Pos == -1)
468     Members.push_back(std::move(*NMOrErr));
469   else
470     Members[Pos] = std::move(*NMOrErr);
471 }
472 
473 static void addMember(std::vector<NewArchiveMember> &Members,
474                       const object::Archive::Child &M, int Pos = -1) {
475   if (Thin && !M.getParent()->isThin())
476     fail("Cannot convert a regular archive to a thin one");
477   Expected<NewArchiveMember> NMOrErr =
478       NewArchiveMember::getOldMember(M, Deterministic);
479   failIfError(NMOrErr.takeError());
480   if (Pos == -1)
481     Members.push_back(std::move(*NMOrErr));
482   else
483     Members[Pos] = std::move(*NMOrErr);
484 }
485 
486 enum InsertAction {
487   IA_AddOldMember,
488   IA_AddNewMeber,
489   IA_Delete,
490   IA_MoveOldMember,
491   IA_MoveNewMember
492 };
493 
494 static InsertAction computeInsertAction(ArchiveOperation Operation,
495                                         const object::Archive::Child &Member,
496                                         StringRef Name,
497                                         std::vector<StringRef>::iterator &Pos) {
498   if (Operation == QuickAppend || Members.empty())
499     return IA_AddOldMember;
500 
501   auto MI = find_if(Members, [Name](StringRef Path) {
502     return Name == sys::path::filename(Path);
503   });
504 
505   if (MI == Members.end())
506     return IA_AddOldMember;
507 
508   Pos = MI;
509 
510   if (Operation == Delete)
511     return IA_Delete;
512 
513   if (Operation == Move)
514     return IA_MoveOldMember;
515 
516   if (Operation == ReplaceOrInsert) {
517     StringRef PosName = sys::path::filename(RelPos);
518     if (!OnlyUpdate) {
519       if (PosName.empty())
520         return IA_AddNewMeber;
521       return IA_MoveNewMember;
522     }
523 
524     // We could try to optimize this to a fstat, but it is not a common
525     // operation.
526     sys::fs::file_status Status;
527     failIfError(sys::fs::status(*MI, Status), *MI);
528     Expected<sys::TimeValue> ModTimeOrErr = Member.getLastModified();
529     failIfError(ModTimeOrErr.takeError());
530     if (Status.getLastModificationTime() < ModTimeOrErr.get()) {
531       if (PosName.empty())
532         return IA_AddOldMember;
533       return IA_MoveOldMember;
534     }
535 
536     if (PosName.empty())
537       return IA_AddNewMeber;
538     return IA_MoveNewMember;
539   }
540   llvm_unreachable("No such operation");
541 }
542 
543 // We have to walk this twice and computing it is not trivial, so creating an
544 // explicit std::vector is actually fairly efficient.
545 static std::vector<NewArchiveMember>
546 computeNewArchiveMembers(ArchiveOperation Operation,
547                          object::Archive *OldArchive) {
548   std::vector<NewArchiveMember> Ret;
549   std::vector<NewArchiveMember> Moved;
550   int InsertPos = -1;
551   StringRef PosName = sys::path::filename(RelPos);
552   if (OldArchive) {
553     Error Err;
554     for (auto &Child : OldArchive->children(Err)) {
555       int Pos = Ret.size();
556       Expected<StringRef> NameOrErr = Child.getName();
557       failIfError(NameOrErr.takeError());
558       StringRef Name = NameOrErr.get();
559       if (Name == PosName) {
560         assert(AddAfter || AddBefore);
561         if (AddBefore)
562           InsertPos = Pos;
563         else
564           InsertPos = Pos + 1;
565       }
566 
567       std::vector<StringRef>::iterator MemberI = Members.end();
568       InsertAction Action =
569           computeInsertAction(Operation, Child, Name, MemberI);
570       switch (Action) {
571       case IA_AddOldMember:
572         addMember(Ret, Child);
573         break;
574       case IA_AddNewMeber:
575         addMember(Ret, *MemberI);
576         break;
577       case IA_Delete:
578         break;
579       case IA_MoveOldMember:
580         addMember(Moved, Child);
581         break;
582       case IA_MoveNewMember:
583         addMember(Moved, *MemberI);
584         break;
585       }
586       if (MemberI != Members.end())
587         Members.erase(MemberI);
588     }
589     failIfError(std::move(Err));
590   }
591 
592   if (Operation == Delete)
593     return Ret;
594 
595   if (!RelPos.empty() && InsertPos == -1)
596     fail("Insertion point not found");
597 
598   if (RelPos.empty())
599     InsertPos = Ret.size();
600 
601   assert(unsigned(InsertPos) <= Ret.size());
602   int Pos = InsertPos;
603   for (auto &M : Moved) {
604     Ret.insert(Ret.begin() + Pos, std::move(M));
605     ++Pos;
606   }
607 
608   for (unsigned I = 0; I != Members.size(); ++I)
609     Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
610   Pos = InsertPos;
611   for (auto &Member : Members) {
612     addMember(Ret, Member, Pos);
613     ++Pos;
614   }
615 
616   return Ret;
617 }
618 
619 static object::Archive::Kind getDefaultForHost() {
620   return Triple(sys::getProcessTriple()).isOSDarwin() ? object::Archive::K_BSD
621                                                       : object::Archive::K_GNU;
622 }
623 
624 static object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
625   Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
626       object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
627 
628   if (OptionalObject)
629     return isa<object::MachOObjectFile>(**OptionalObject)
630                ? object::Archive::K_BSD
631                : object::Archive::K_GNU;
632 
633   // squelch the error in case we had a non-object file
634   consumeError(OptionalObject.takeError());
635   return getDefaultForHost();
636 }
637 
638 static void
639 performWriteOperation(ArchiveOperation Operation,
640                       object::Archive *OldArchive,
641                       std::unique_ptr<MemoryBuffer> OldArchiveBuf,
642                       std::vector<NewArchiveMember> *NewMembersP) {
643   std::vector<NewArchiveMember> NewMembers;
644   if (!NewMembersP)
645     NewMembers = computeNewArchiveMembers(Operation, OldArchive);
646 
647   object::Archive::Kind Kind;
648   switch (FormatOpt) {
649   case Default:
650     if (Thin)
651       Kind = object::Archive::K_GNU;
652     else if (OldArchive)
653       Kind = OldArchive->kind();
654     else if (NewMembersP)
655       Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
656                                  : getDefaultForHost();
657     else
658       Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
659                                : getDefaultForHost();
660     break;
661   case GNU:
662     Kind = object::Archive::K_GNU;
663     break;
664   case BSD:
665     if (Thin)
666       fail("Only the gnu format has a thin mode");
667     Kind = object::Archive::K_BSD;
668     break;
669   }
670 
671   std::pair<StringRef, std::error_code> Result =
672       writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
673                    Kind, Deterministic, Thin, std::move(OldArchiveBuf));
674   failIfError(Result.second, Result.first);
675 }
676 
677 static void createSymbolTable(object::Archive *OldArchive) {
678   // When an archive is created or modified, if the s option is given, the
679   // resulting archive will have a current symbol table. If the S option
680   // is given, it will have no symbol table.
681   // In summary, we only need to update the symbol table if we have none.
682   // This is actually very common because of broken build systems that think
683   // they have to run ranlib.
684   if (OldArchive->hasSymbolTable())
685     return;
686 
687   performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
688 }
689 
690 static void performOperation(ArchiveOperation Operation,
691                              object::Archive *OldArchive,
692                              std::unique_ptr<MemoryBuffer> OldArchiveBuf,
693                              std::vector<NewArchiveMember> *NewMembers) {
694   switch (Operation) {
695   case Print:
696   case DisplayTable:
697   case Extract:
698     performReadOperation(Operation, OldArchive);
699     return;
700 
701   case Delete:
702   case Move:
703   case QuickAppend:
704   case ReplaceOrInsert:
705     performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
706                           NewMembers);
707     return;
708   case CreateSymTab:
709     createSymbolTable(OldArchive);
710     return;
711   }
712   llvm_unreachable("Unknown operation.");
713 }
714 
715 static int performOperation(ArchiveOperation Operation,
716                             std::vector<NewArchiveMember> *NewMembers) {
717   // Create or open the archive object.
718   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
719       MemoryBuffer::getFile(ArchiveName, -1, false);
720   std::error_code EC = Buf.getError();
721   if (EC && EC != errc::no_such_file_or_directory)
722     fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
723 
724   if (!EC) {
725     Error Err;
726     object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
727     EC = errorToErrorCode(std::move(Err));
728     failIfError(EC,
729                 "error loading '" + ArchiveName + "': " + EC.message() + "!");
730     performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
731     return 0;
732   }
733 
734   assert(EC == errc::no_such_file_or_directory);
735 
736   if (!shouldCreateArchive(Operation)) {
737     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
738   } else {
739     if (!Create) {
740       // Produce a warning if we should and we're creating the archive
741       errs() << ToolName << ": creating " << ArchiveName << "\n";
742     }
743   }
744 
745   performOperation(Operation, nullptr, nullptr, NewMembers);
746   return 0;
747 }
748 
749 static void runMRIScript() {
750   enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
751 
752   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
753   failIfError(Buf.getError());
754   const MemoryBuffer &Ref = *Buf.get();
755   bool Saved = false;
756   std::vector<NewArchiveMember> NewMembers;
757   std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
758   std::vector<std::unique_ptr<object::Archive>> Archives;
759 
760   for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
761     StringRef Line = *I;
762     StringRef CommandStr, Rest;
763     std::tie(CommandStr, Rest) = Line.split(' ');
764     Rest = Rest.trim();
765     if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
766       Rest = Rest.drop_front().drop_back();
767     auto Command = StringSwitch<MRICommand>(CommandStr.lower())
768                        .Case("addlib", MRICommand::AddLib)
769                        .Case("addmod", MRICommand::AddMod)
770                        .Case("create", MRICommand::Create)
771                        .Case("save", MRICommand::Save)
772                        .Case("end", MRICommand::End)
773                        .Default(MRICommand::Invalid);
774 
775     switch (Command) {
776     case MRICommand::AddLib: {
777       auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
778       failIfError(BufOrErr.getError(), "Could not open library");
779       ArchiveBuffers.push_back(std::move(*BufOrErr));
780       auto LibOrErr =
781           object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
782       failIfError(errorToErrorCode(LibOrErr.takeError()),
783                   "Could not parse library");
784       Archives.push_back(std::move(*LibOrErr));
785       object::Archive &Lib = *Archives.back();
786       {
787         Error Err;
788         for (auto &Member : Lib.children(Err))
789           addMember(NewMembers, Member);
790         failIfError(std::move(Err));
791       }
792       break;
793     }
794     case MRICommand::AddMod:
795       addMember(NewMembers, Rest);
796       break;
797     case MRICommand::Create:
798       Create = true;
799       if (!ArchiveName.empty())
800         fail("Editing multiple archives not supported");
801       if (Saved)
802         fail("File already saved");
803       ArchiveName = Rest;
804       break;
805     case MRICommand::Save:
806       Saved = true;
807       break;
808     case MRICommand::End:
809       break;
810     case MRICommand::Invalid:
811       fail("Unknown command: " + CommandStr);
812     }
813   }
814 
815   // Nothing to do if not saved.
816   if (Saved)
817     performOperation(ReplaceOrInsert, &NewMembers);
818   exit(0);
819 }
820 
821 static int ar_main() {
822   // Do our own parsing of the command line because the CommandLine utility
823   // can't handle the grouped positional parameters without a dash.
824   ArchiveOperation Operation = parseCommandLine();
825   return performOperation(Operation, nullptr);
826 }
827 
828 static int ranlib_main() {
829   if (RestOfArgs.size() != 1)
830     fail(ToolName + " takes just one archive as an argument");
831   ArchiveName = RestOfArgs[0];
832   return performOperation(CreateSymTab, nullptr);
833 }
834 
835 int main(int argc, char **argv) {
836   ToolName = argv[0];
837   // Print a stack trace if we signal out.
838   sys::PrintStackTraceOnErrorSignal(argv[0]);
839   PrettyStackTraceProgram X(argc, argv);
840   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
841 
842   llvm::InitializeAllTargetInfos();
843   llvm::InitializeAllTargetMCs();
844   llvm::InitializeAllAsmParsers();
845 
846   StringRef Stem = sys::path::stem(ToolName);
847   if (Stem.find("ranlib") == StringRef::npos &&
848       Stem.find("lib") != StringRef::npos)
849     return libDriverMain(makeArrayRef(argv, argc));
850 
851   // Have the command line options parsed and handle things
852   // like --help and --version.
853   cl::ParseCommandLineOptions(argc, argv,
854     "LLVM Archiver (llvm-ar)\n\n"
855     "  This program archives bitcode files into single libraries\n"
856   );
857 
858   if (Stem.find("ranlib") != StringRef::npos)
859     return ranlib_main();
860   if (Stem.find("ar") != StringRef::npos)
861     return ar_main();
862   fail("Not ranlib, ar or lib!");
863 }
864