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