50ddf598efee0ab36be5735bb569d6405add3366
[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   bool Filter = !Members.empty();
395   for (const object::Archive::Child &C : OldArchive->children()) {
396     ErrorOr<StringRef> NameOrErr = C.getName();
397     failIfError(NameOrErr.getError());
398     StringRef Name = NameOrErr.get();
399
400     if (Filter) {
401       auto I = std::find(Members.begin(), Members.end(), Name);
402       if (I == Members.end())
403         continue;
404       Members.erase(I);
405     }
406
407     switch (Operation) {
408     default:
409       llvm_unreachable("Not a read operation");
410     case Print:
411       doPrint(Name, C);
412       break;
413     case DisplayTable:
414       doDisplayTable(Name, C);
415       break;
416     case Extract:
417       doExtract(Name, C);
418       break;
419     }
420   }
421   if (Members.empty())
422     return;
423   for (StringRef Name : Members)
424     errs() << Name << " was not found\n";
425   std::exit(1);
426 }
427
428 template <typename T>
429 void addMember(std::vector<NewArchiveIterator> &Members, T I, StringRef Name,
430                int Pos = -1) {
431   NewArchiveIterator NI(I, Name);
432   if (Pos == -1)
433     Members.push_back(NI);
434   else
435     Members[Pos] = NI;
436 }
437
438 enum InsertAction {
439   IA_AddOldMember,
440   IA_AddNewMeber,
441   IA_Delete,
442   IA_MoveOldMember,
443   IA_MoveNewMember
444 };
445
446 static InsertAction computeInsertAction(ArchiveOperation Operation,
447                                         object::Archive::child_iterator I,
448                                         StringRef Name,
449                                         std::vector<StringRef>::iterator &Pos) {
450   if (Operation == QuickAppend || Members.empty())
451     return IA_AddOldMember;
452
453   auto MI =
454       std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
455         return Name == sys::path::filename(Path);
456       });
457
458   if (MI == Members.end())
459     return IA_AddOldMember;
460
461   Pos = MI;
462
463   if (Operation == Delete)
464     return IA_Delete;
465
466   if (Operation == Move)
467     return IA_MoveOldMember;
468
469   if (Operation == ReplaceOrInsert) {
470     StringRef PosName = sys::path::filename(RelPos);
471     if (!OnlyUpdate) {
472       if (PosName.empty())
473         return IA_AddNewMeber;
474       return IA_MoveNewMember;
475     }
476
477     // We could try to optimize this to a fstat, but it is not a common
478     // operation.
479     sys::fs::file_status Status;
480     failIfError(sys::fs::status(*MI, Status), *MI);
481     if (Status.getLastModificationTime() < I->getLastModified()) {
482       if (PosName.empty())
483         return IA_AddOldMember;
484       return IA_MoveOldMember;
485     }
486
487     if (PosName.empty())
488       return IA_AddNewMeber;
489     return IA_MoveNewMember;
490   }
491   llvm_unreachable("No such operation");
492 }
493
494 // We have to walk this twice and computing it is not trivial, so creating an
495 // explicit std::vector is actually fairly efficient.
496 static std::vector<NewArchiveIterator>
497 computeNewArchiveMembers(ArchiveOperation Operation,
498                          object::Archive *OldArchive) {
499   std::vector<NewArchiveIterator> Ret;
500   std::vector<NewArchiveIterator> Moved;
501   int InsertPos = -1;
502   StringRef PosName = sys::path::filename(RelPos);
503   if (OldArchive) {
504     for (auto &Child : OldArchive->children()) {
505       int Pos = Ret.size();
506       ErrorOr<StringRef> NameOrErr = Child.getName();
507       failIfError(NameOrErr.getError());
508       StringRef Name = NameOrErr.get();
509       if (Name == PosName) {
510         assert(AddAfter || AddBefore);
511         if (AddBefore)
512           InsertPos = Pos;
513         else
514           InsertPos = Pos + 1;
515       }
516
517       std::vector<StringRef>::iterator MemberI = Members.end();
518       InsertAction Action =
519           computeInsertAction(Operation, Child, Name, MemberI);
520       switch (Action) {
521       case IA_AddOldMember:
522         addMember(Ret, Child, Name);
523         break;
524       case IA_AddNewMeber:
525         addMember(Ret, *MemberI, Name);
526         break;
527       case IA_Delete:
528         break;
529       case IA_MoveOldMember:
530         addMember(Moved, Child, Name);
531         break;
532       case IA_MoveNewMember:
533         addMember(Moved, *MemberI, Name);
534         break;
535       }
536       if (MemberI != Members.end())
537         Members.erase(MemberI);
538     }
539   }
540
541   if (Operation == Delete)
542     return Ret;
543
544   if (!RelPos.empty() && InsertPos == -1)
545     fail("Insertion point not found");
546
547   if (RelPos.empty())
548     InsertPos = Ret.size();
549
550   assert(unsigned(InsertPos) <= Ret.size());
551   Ret.insert(Ret.begin() + InsertPos, Moved.begin(), Moved.end());
552
553   Ret.insert(Ret.begin() + InsertPos, Members.size(),
554              NewArchiveIterator("", ""));
555   int Pos = InsertPos;
556   for (auto &Member : Members) {
557     StringRef Name = sys::path::filename(Member);
558     addMember(Ret, Member, Name, Pos);
559     ++Pos;
560   }
561
562   return Ret;
563 }
564
565 static void
566 performWriteOperation(ArchiveOperation Operation, object::Archive *OldArchive,
567                       std::vector<NewArchiveIterator> *NewMembersP) {
568   object::Archive::Kind Kind;
569   switch (FormatOpt) {
570   case Default: {
571     Triple T(sys::getProcessTriple());
572     if (T.isOSDarwin())
573       Kind = object::Archive::K_BSD;
574     else
575       Kind = object::Archive::K_GNU;
576     break;
577   }
578   case GNU:
579     Kind = object::Archive::K_GNU;
580     break;
581   case BSD:
582     Kind = object::Archive::K_BSD;
583     break;
584   }
585   if (NewMembersP) {
586     std::pair<StringRef, std::error_code> Result =
587         writeArchive(ArchiveName, *NewMembersP, Symtab, Kind, Deterministic);
588     failIfError(Result.second, Result.first);
589     return;
590   }
591   std::vector<NewArchiveIterator> NewMembers =
592       computeNewArchiveMembers(Operation, OldArchive);
593   auto Result =
594       writeArchive(ArchiveName, NewMembers, Symtab, Kind, Deterministic);
595   failIfError(Result.second, Result.first);
596 }
597
598 static void createSymbolTable(object::Archive *OldArchive) {
599   // When an archive is created or modified, if the s option is given, the
600   // resulting archive will have a current symbol table. If the S option
601   // is given, it will have no symbol table.
602   // In summary, we only need to update the symbol table if we have none.
603   // This is actually very common because of broken build systems that think
604   // they have to run ranlib.
605   if (OldArchive->hasSymbolTable())
606     return;
607
608   performWriteOperation(CreateSymTab, OldArchive, nullptr);
609 }
610
611 static void performOperation(ArchiveOperation Operation,
612                              object::Archive *OldArchive,
613                              std::vector<NewArchiveIterator> *NewMembers) {
614   switch (Operation) {
615   case Print:
616   case DisplayTable:
617   case Extract:
618     performReadOperation(Operation, OldArchive);
619     return;
620
621   case Delete:
622   case Move:
623   case QuickAppend:
624   case ReplaceOrInsert:
625     performWriteOperation(Operation, OldArchive, NewMembers);
626     return;
627   case CreateSymTab:
628     createSymbolTable(OldArchive);
629     return;
630   }
631   llvm_unreachable("Unknown operation.");
632 }
633
634 static int performOperation(ArchiveOperation Operation,
635                             std::vector<NewArchiveIterator> *NewMembers) {
636   // Create or open the archive object.
637   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
638       MemoryBuffer::getFile(ArchiveName, -1, false);
639   std::error_code EC = Buf.getError();
640   if (EC && EC != errc::no_such_file_or_directory) {
641     errs() << ToolName << ": error opening '" << ArchiveName
642            << "': " << EC.message() << "!\n";
643     return 1;
644   }
645
646   if (!EC) {
647     object::Archive Archive(Buf.get()->getMemBufferRef(), EC);
648
649     if (EC) {
650       errs() << ToolName << ": error loading '" << ArchiveName
651              << "': " << EC.message() << "!\n";
652       return 1;
653     }
654     performOperation(Operation, &Archive, NewMembers);
655     return 0;
656   }
657
658   assert(EC == errc::no_such_file_or_directory);
659
660   if (!shouldCreateArchive(Operation)) {
661     failIfError(EC, Twine("error loading '") + ArchiveName + "'");
662   } else {
663     if (!Create) {
664       // Produce a warning if we should and we're creating the archive
665       errs() << ToolName << ": creating " << ArchiveName << "\n";
666     }
667   }
668
669   performOperation(Operation, nullptr, NewMembers);
670   return 0;
671 }
672
673 static void runMRIScript() {
674   enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
675
676   ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
677   failIfError(Buf.getError());
678   const MemoryBuffer &Ref = *Buf.get();
679   bool Saved = false;
680   std::vector<NewArchiveIterator> NewMembers;
681   std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
682   std::vector<std::unique_ptr<object::Archive>> Archives;
683
684   for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
685     StringRef Line = *I;
686     StringRef CommandStr, Rest;
687     std::tie(CommandStr, Rest) = Line.split(' ');
688     Rest = Rest.trim();
689     if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
690       Rest = Rest.drop_front().drop_back();
691     auto Command = StringSwitch<MRICommand>(CommandStr.lower())
692                        .Case("addlib", MRICommand::AddLib)
693                        .Case("addmod", MRICommand::AddMod)
694                        .Case("create", MRICommand::Create)
695                        .Case("save", MRICommand::Save)
696                        .Case("end", MRICommand::End)
697                        .Default(MRICommand::Invalid);
698
699     switch (Command) {
700     case MRICommand::AddLib: {
701       auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
702       failIfError(BufOrErr.getError(), "Could not open library");
703       ArchiveBuffers.push_back(std::move(*BufOrErr));
704       auto LibOrErr =
705           object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
706       failIfError(LibOrErr.getError(), "Could not parse library");
707       Archives.push_back(std::move(*LibOrErr));
708       object::Archive &Lib = *Archives.back();
709       for (auto &Member : Lib.children()) {
710         ErrorOr<StringRef> NameOrErr = Member.getName();
711         failIfError(NameOrErr.getError());
712         addMember(NewMembers, Member, *NameOrErr);
713       }
714       break;
715     }
716     case MRICommand::AddMod:
717       addMember(NewMembers, Rest, sys::path::filename(Rest));
718       break;
719     case MRICommand::Create:
720       Create = true;
721       if (!ArchiveName.empty())
722         fail("Editing multiple archives not supported");
723       if (Saved)
724         fail("File already saved");
725       ArchiveName = Rest;
726       break;
727     case MRICommand::Save:
728       Saved = true;
729       break;
730     case MRICommand::End:
731       break;
732     case MRICommand::Invalid:
733       fail("Unknown command: " + CommandStr);
734     }
735   }
736
737   // Nothing to do if not saved.
738   if (Saved)
739     performOperation(ReplaceOrInsert, &NewMembers);
740   exit(0);
741 }
742
743 static int ar_main() {
744   // Do our own parsing of the command line because the CommandLine utility
745   // can't handle the grouped positional parameters without a dash.
746   ArchiveOperation Operation = parseCommandLine();
747   return performOperation(Operation, nullptr);
748 }
749
750 static int ranlib_main() {
751   if (RestOfArgs.size() != 1)
752     fail(ToolName + "takes just one archive as argument");
753   ArchiveName = RestOfArgs[0];
754   return performOperation(CreateSymTab, nullptr);
755 }
756
757 int main(int argc, char **argv) {
758   ToolName = argv[0];
759   // Print a stack trace if we signal out.
760   sys::PrintStackTraceOnErrorSignal();
761   PrettyStackTraceProgram X(argc, argv);
762   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
763
764   llvm::InitializeAllTargetInfos();
765   llvm::InitializeAllTargetMCs();
766   llvm::InitializeAllAsmParsers();
767
768   StringRef Stem = sys::path::stem(ToolName);
769   if (Stem.find("ranlib") == StringRef::npos &&
770       Stem.find("lib") != StringRef::npos)
771     return libDriverMain(makeArrayRef(argv, argc));
772
773   // Have the command line options parsed and handle things
774   // like --help and --version.
775   cl::ParseCommandLineOptions(argc, argv,
776     "LLVM Archiver (llvm-ar)\n\n"
777     "  This program archives bitcode files into single libraries\n"
778   );
779
780   if (Stem.find("ar") != StringRef::npos)
781     return ar_main();
782   if (Stem.find("ranlib") != StringRef::npos)
783     return ranlib_main();
784   fail("Not ranlib, ar or lib!");
785 }