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