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