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