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