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