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