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