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