llvm-ar.cpp revision 309124
1160814Ssimon//===-- llvm-ar.cpp - LLVM archive librarian utility ----------------------===//
2160814Ssimon//
3160814Ssimon//                     The LLVM Compiler Infrastructure
4160814Ssimon//
5160814Ssimon// This file is distributed under the University of Illinois Open Source
6238405Sjkim// License. See LICENSE.TXT for details.
7160814Ssimon//
8160814Ssimon//===----------------------------------------------------------------------===//
9160814Ssimon//
10160814Ssimon// Builds up (relatively) standard unix archive files (.a) containing LLVM
11160814Ssimon// bitcode or other files.
12160814Ssimon//
13280304Sjkim//===----------------------------------------------------------------------===//
14160814Ssimon
15160814Ssimon#include "llvm/ADT/StringSwitch.h"
16160814Ssimon#include "llvm/ADT/Triple.h"
17160814Ssimon#include "llvm/IR/LLVMContext.h"
18160814Ssimon#include "llvm/IR/Module.h"
19160814Ssimon#include "llvm/LibDriver/LibDriver.h"
20160814Ssimon#include "llvm/Object/Archive.h"
21160814Ssimon#include "llvm/Object/ArchiveWriter.h"
22160814Ssimon#include "llvm/Object/MachO.h"
23160814Ssimon#include "llvm/Object/ObjectFile.h"
24160814Ssimon#include "llvm/Support/CommandLine.h"
25160814Ssimon#include "llvm/Support/Errc.h"
26160814Ssimon#include "llvm/Support/FileSystem.h"
27160814Ssimon#include "llvm/Support/Format.h"
28160814Ssimon#include "llvm/Support/LineIterator.h"
29160814Ssimon#include "llvm/Support/ManagedStatic.h"
30160814Ssimon#include "llvm/Support/MemoryBuffer.h"
31160814Ssimon#include "llvm/Support/Path.h"
32160814Ssimon#include "llvm/Support/PrettyStackTrace.h"
33160814Ssimon#include "llvm/Support/Signals.h"
34160814Ssimon#include "llvm/Support/TargetSelect.h"
35160814Ssimon#include "llvm/Support/ToolOutputFile.h"
36160814Ssimon#include "llvm/Support/raw_ostream.h"
37160814Ssimon#include <algorithm>
38160814Ssimon#include <cstdlib>
39160814Ssimon#include <memory>
40160814Ssimon
41160814Ssimon#if !defined(_MSC_VER) && !defined(__MINGW32__)
42160814Ssimon#include <unistd.h>
43160814Ssimon#else
44160814Ssimon#include <io.h>
45160814Ssimon#endif
46160814Ssimon
47160814Ssimonusing namespace llvm;
48160814Ssimon
49160814Ssimon// The name this program was invoked as.
50160814Ssimonstatic StringRef ToolName;
51160814Ssimon
52160814Ssimon// Show the error message and exit.
53160814SsimonLLVM_ATTRIBUTE_NORETURN static void fail(Twine Error) {
54160814Ssimon  outs() << ToolName << ": " << Error << ".\n";
55160814Ssimon  exit(1);
56160814Ssimon}
57160814Ssimon
58160814Ssimonstatic void failIfError(std::error_code EC, Twine Context = "") {
59160814Ssimon  if (!EC)
60160814Ssimon    return;
61280304Sjkim
62160814Ssimon  std::string ContextStr = Context.str();
63160814Ssimon  if (ContextStr == "")
64160814Ssimon    fail(EC.message());
65160814Ssimon  fail(Context + ": " + EC.message());
66160814Ssimon}
67280304Sjkim
68160814Ssimonstatic void failIfError(Error E, Twine Context = "") {
69160814Ssimon  if (!E)
70160814Ssimon    return;
71160814Ssimon
72160814Ssimon  handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
73160814Ssimon    std::string ContextStr = Context.str();
74160814Ssimon    if (ContextStr == "")
75238405Sjkim      fail(EIB.message());
76160814Ssimon    fail(Context + ": " + EIB.message());
77238405Sjkim  });
78280304Sjkim}
79280304Sjkim
80280304Sjkim// llvm-ar/llvm-ranlib remaining positional arguments.
81280304Sjkimstatic cl::list<std::string>
82160814Ssimon    RestOfArgs(cl::Positional, cl::ZeroOrMore,
83160814Ssimon               cl::desc("[relpos] [count] <archive-file> [members]..."));
84160814Ssimon
85280304Sjkimstatic cl::opt<bool> MRI("M", cl::desc(""));
86280304Sjkimstatic cl::opt<std::string> Plugin("plugin", cl::desc("plugin (ignored for compatibility"));
87280304Sjkim
88280304Sjkimnamespace {
89280304Sjkimenum Format { Default, GNU, BSD };
90280304Sjkim}
91280304Sjkim
92280304Sjkimstatic cl::opt<Format>
93280304Sjkim    FormatOpt("format", cl::desc("Archive format to create"),
94280304Sjkim              cl::values(clEnumValN(Default, "default", "default"),
95280304Sjkim                         clEnumValN(GNU, "gnu", "gnu"),
96280304Sjkim                         clEnumValN(BSD, "bsd", "bsd"), clEnumValEnd));
97280304Sjkim
98280304Sjkimstatic std::string Options;
99280304Sjkim
100280304Sjkim// Provide additional help output explaining the operations and modifiers of
101280304Sjkim// llvm-ar. This object instructs the CommandLine library to print the text of
102280304Sjkim// the constructor when the --help option is given.
103280304Sjkimstatic cl::extrahelp MoreHelp(
104280304Sjkim  "\nOPERATIONS:\n"
105280304Sjkim  "  d[NsS]       - delete file(s) from the archive\n"
106280304Sjkim  "  m[abiSs]     - move file(s) in the archive\n"
107280304Sjkim  "  p[kN]        - print file(s) found in the archive\n"
108280304Sjkim  "  q[ufsS]      - quick append file(s) to the archive\n"
109280304Sjkim  "  r[abfiuRsS]  - replace or insert file(s) into the archive\n"
110280304Sjkim  "  t            - display contents of archive\n"
111280304Sjkim  "  x[No]        - extract file(s) from the archive\n"
112280304Sjkim  "\nMODIFIERS (operation specific):\n"
113280304Sjkim  "  [a] - put file(s) after [relpos]\n"
114280304Sjkim  "  [b] - put file(s) before [relpos] (same as [i])\n"
115280304Sjkim  "  [i] - put file(s) before [relpos] (same as [b])\n"
116238405Sjkim  "  [o] - preserve original dates\n"
117280304Sjkim  "  [s] - create an archive index (cf. ranlib)\n"
118280304Sjkim  "  [S] - do not build a symbol table\n"
119280304Sjkim  "  [u] - update only files newer than archive contents\n"
120280304Sjkim  "\nMODIFIERS (generic):\n"
121280304Sjkim  "  [c] - do not warn if the library had to be created\n"
122280304Sjkim  "  [v] - be verbose about actions taken\n"
123280304Sjkim);
124280304Sjkim
125280304Sjkim// This enumeration delineates the kinds of operations on an archive
126280304Sjkim// that are permitted.
127280304Sjkimenum ArchiveOperation {
128280304Sjkim  Print,            ///< Print the contents of the archive
129280304Sjkim  Delete,           ///< Delete the specified members
130280304Sjkim  Move,             ///< Move members to end or as given by {a,b,i} modifiers
131280304Sjkim  QuickAppend,      ///< Quickly append to end of archive
132280304Sjkim  ReplaceOrInsert,  ///< Replace or Insert members
133280304Sjkim  DisplayTable,     ///< Display the table of contents
134280304Sjkim  Extract,          ///< Extract files back to file system
135280304Sjkim  CreateSymTab      ///< Create a symbol table in an existing archive
136280304Sjkim};
137280304Sjkim
138280304Sjkim// Modifiers to follow operation to vary behavior
139280304Sjkimstatic bool AddAfter = false;      ///< 'a' modifier
140280304Sjkimstatic bool AddBefore = false;     ///< 'b' modifier
141280304Sjkimstatic bool Create = false;        ///< 'c' modifier
142280304Sjkimstatic bool OriginalDates = false; ///< 'o' modifier
143280304Sjkimstatic bool OnlyUpdate = false;    ///< 'u' modifier
144280304Sjkimstatic bool Verbose = false;       ///< 'v' modifier
145280304Sjkimstatic bool Symtab = true;         ///< 's' modifier
146280304Sjkimstatic bool Deterministic = true;  ///< 'D' and 'U' modifiers
147280304Sjkimstatic bool Thin = false;          ///< 'T' modifier
148280304Sjkim
149280304Sjkim// Relative Positional Argument (for insert/move). This variable holds
150280304Sjkim// the name of the archive member to which the 'a', 'b' or 'i' modifier
151280304Sjkim// refers. Only one of 'a', 'b' or 'i' can be specified so we only need
152280304Sjkim// one variable.
153280304Sjkimstatic std::string RelPos;
154160814Ssimon
155280304Sjkim// This variable holds the name of the archive file as given on the
156280304Sjkim// command line.
157280304Sjkimstatic std::string ArchiveName;
158280304Sjkim
159280304Sjkim// This variable holds the list of member files to proecess, as given
160280304Sjkim// on the command line.
161280304Sjkimstatic std::vector<StringRef> Members;
162280304Sjkim
163280304Sjkim// Show the error message, the help message and exit.
164280304SjkimLLVM_ATTRIBUTE_NORETURN static void
165280304Sjkimshow_help(const std::string &msg) {
166280304Sjkim  errs() << ToolName << ": " << msg << "\n\n";
167280304Sjkim  cl::PrintHelpMessage();
168280304Sjkim  std::exit(1);
169280304Sjkim}
170280304Sjkim
171280304Sjkim// Extract the member filename from the command line for the [relpos] argument
172280304Sjkim// associated with a, b, and i modifiers
173280304Sjkimstatic void getRelPos() {
174280304Sjkim  if(RestOfArgs.size() == 0)
175280304Sjkim    show_help("Expected [relpos] for a, b, or i modifier");
176280304Sjkim  RelPos = RestOfArgs[0];
177280304Sjkim  RestOfArgs.erase(RestOfArgs.begin());
178280304Sjkim}
179280304Sjkim
180280304Sjkimstatic void getOptions() {
181280304Sjkim  if(RestOfArgs.size() == 0)
182280304Sjkim    show_help("Expected options");
183280304Sjkim  Options = RestOfArgs[0];
184280304Sjkim  RestOfArgs.erase(RestOfArgs.begin());
185280304Sjkim}
186280304Sjkim
187280304Sjkim// Get the archive file name from the command line
188280304Sjkimstatic void getArchive() {
189280304Sjkim  if(RestOfArgs.size() == 0)
190280304Sjkim    show_help("An archive name must be specified");
191280304Sjkim  ArchiveName = RestOfArgs[0];
192280304Sjkim  RestOfArgs.erase(RestOfArgs.begin());
193280304Sjkim}
194280304Sjkim
195280304Sjkim// Copy over remaining items in RestOfArgs to our Members vector
196280304Sjkimstatic void getMembers() {
197280304Sjkim  for (auto &Arg : RestOfArgs)
198238405Sjkim    Members.push_back(Arg);
199280304Sjkim}
200280304Sjkim
201280304Sjkimstatic void runMRIScript();
202280304Sjkim
203280304Sjkim// Parse the command line options as presented and return the operation
204280304Sjkim// specified. Process all modifiers and check to make sure that constraints on
205280304Sjkim// modifier/operation pairs have not been violated.
206280304Sjkimstatic ArchiveOperation parseCommandLine() {
207280304Sjkim  if (MRI) {
208280304Sjkim    if (!RestOfArgs.empty())
209280304Sjkim      fail("Cannot mix -M and other options");
210280304Sjkim    runMRIScript();
211280304Sjkim  }
212280304Sjkim
213280304Sjkim  getOptions();
214280304Sjkim
215280304Sjkim  // Keep track of number of operations. We can only specify one
216280304Sjkim  // per execution.
217280304Sjkim  unsigned NumOperations = 0;
218280304Sjkim
219280304Sjkim  // Keep track of the number of positional modifiers (a,b,i). Only
220280304Sjkim  // one can be specified.
221280304Sjkim  unsigned NumPositional = 0;
222280304Sjkim
223280304Sjkim  // Keep track of which operation was requested
224280304Sjkim  ArchiveOperation Operation;
225280304Sjkim
226280304Sjkim  bool MaybeJustCreateSymTab = false;
227280304Sjkim
228280304Sjkim  for(unsigned i=0; i<Options.size(); ++i) {
229280304Sjkim    switch(Options[i]) {
230280304Sjkim    case 'd': ++NumOperations; Operation = Delete; break;
231280304Sjkim    case 'm': ++NumOperations; Operation = Move ; break;
232280304Sjkim    case 'p': ++NumOperations; Operation = Print; break;
233280304Sjkim    case 'q': ++NumOperations; Operation = QuickAppend; break;
234280304Sjkim    case 'r': ++NumOperations; Operation = ReplaceOrInsert; break;
235280304Sjkim    case 't': ++NumOperations; Operation = DisplayTable; break;
236280304Sjkim    case 'x': ++NumOperations; Operation = Extract; break;
237280304Sjkim    case 'c': Create = true; break;
238280304Sjkim    case 'l': /* accepted but unused */ break;
239280304Sjkim    case 'o': OriginalDates = true; break;
240280304Sjkim    case 's':
241280304Sjkim      Symtab = true;
242280304Sjkim      MaybeJustCreateSymTab = true;
243280304Sjkim      break;
244280304Sjkim    case 'S':
245280304Sjkim      Symtab = false;
246280304Sjkim      break;
247280304Sjkim    case 'u': OnlyUpdate = true; break;
248280304Sjkim    case 'v': Verbose = true; break;
249280304Sjkim    case 'a':
250280304Sjkim      getRelPos();
251280304Sjkim      AddAfter = true;
252280304Sjkim      NumPositional++;
253280304Sjkim      break;
254160814Ssimon    case 'b':
255160814Ssimon      getRelPos();
256280304Sjkim      AddBefore = true;
257280304Sjkim      NumPositional++;
258280304Sjkim      break;
259280304Sjkim    case 'i':
260280304Sjkim      getRelPos();
261280304Sjkim      AddBefore = true;
262280304Sjkim      NumPositional++;
263280304Sjkim      break;
264280304Sjkim    case 'D':
265280304Sjkim      Deterministic = true;
266280304Sjkim      break;
267280304Sjkim    case 'U':
268280304Sjkim      Deterministic = false;
269280304Sjkim      break;
270280304Sjkim    case 'T':
271280304Sjkim      Thin = true;
272280304Sjkim      break;
273280304Sjkim    default:
274280304Sjkim      cl::PrintHelpMessage();
275280304Sjkim    }
276280304Sjkim  }
277280304Sjkim
278280304Sjkim  // At this point, the next thing on the command line must be
279280304Sjkim  // the archive name.
280280304Sjkim  getArchive();
281280304Sjkim
282280304Sjkim  // Everything on the command line at this point is a member.
283280304Sjkim  getMembers();
284280304Sjkim
285280304Sjkim if (NumOperations == 0 && MaybeJustCreateSymTab) {
286280304Sjkim    NumOperations = 1;
287238405Sjkim    Operation = CreateSymTab;
288280304Sjkim    if (!Members.empty())
289280304Sjkim      show_help("The s operation takes only an archive as argument");
290280304Sjkim  }
291280304Sjkim
292280304Sjkim  // Perform various checks on the operation/modifier specification
293280304Sjkim  // to make sure we are dealing with a legal request.
294280304Sjkim  if (NumOperations == 0)
295280304Sjkim    show_help("You must specify at least one of the operations");
296280304Sjkim  if (NumOperations > 1)
297280304Sjkim    show_help("Only one operation may be specified");
298280304Sjkim  if (NumPositional > 1)
299280304Sjkim    show_help("You may only specify one of a, b, and i modifiers");
300280304Sjkim  if (AddAfter || AddBefore) {
301280304Sjkim    if (Operation != Move && Operation != ReplaceOrInsert)
302280304Sjkim      show_help("The 'a', 'b' and 'i' modifiers can only be specified with "
303280304Sjkim            "the 'm' or 'r' operations");
304280304Sjkim  }
305280304Sjkim  if (OriginalDates && Operation != Extract)
306280304Sjkim    show_help("The 'o' modifier is only applicable to the 'x' operation");
307280304Sjkim  if (OnlyUpdate && Operation != ReplaceOrInsert)
308280304Sjkim    show_help("The 'u' modifier is only applicable to the 'r' operation");
309280304Sjkim
310280304Sjkim  // Return the parsed operation to the caller
311280304Sjkim  return Operation;
312280304Sjkim}
313280304Sjkim
314280304Sjkim// Implements the 'p' operation. This function traverses the archive
315280304Sjkim// looking for members that match the path list.
316280304Sjkimstatic void doPrint(StringRef Name, const object::Archive::Child &C) {
317280304Sjkim  if (Verbose)
318280304Sjkim    outs() << "Printing " << Name << "\n";
319160814Ssimon
320280304Sjkim  ErrorOr<StringRef> DataOrErr = C.getBuffer();
321280304Sjkim  failIfError(DataOrErr.getError());
322280304Sjkim  StringRef Data = *DataOrErr;
323280304Sjkim  outs().write(Data.data(), Data.size());
324280304Sjkim}
325280304Sjkim
326280304Sjkim// Utility function for printing out the file mode when the 't' operation is in
327280304Sjkim// verbose mode.
328280304Sjkimstatic void printMode(unsigned mode) {
329280304Sjkim  outs() << ((mode & 004) ? "r" : "-");
330280304Sjkim  outs() << ((mode & 002) ? "w" : "-");
331280304Sjkim  outs() << ((mode & 001) ? "x" : "-");
332280304Sjkim}
333280304Sjkim
334280304Sjkim// Implement the 't' operation. This function prints out just
335280304Sjkim// the file names of each of the members. However, if verbose mode is requested
336280304Sjkim// ('v' modifier) then the file type, permission mode, user, group, size, and
337280304Sjkim// modification time are also printed.
338280304Sjkimstatic void doDisplayTable(StringRef Name, const object::Archive::Child &C) {
339280304Sjkim  if (Verbose) {
340280304Sjkim    sys::fs::perms Mode = C.getAccessMode();
341280304Sjkim    printMode((Mode >> 6) & 007);
342280304Sjkim    printMode((Mode >> 3) & 007);
343280304Sjkim    printMode(Mode & 007);
344280304Sjkim    outs() << ' ' << C.getUID();
345280304Sjkim    outs() << '/' << C.getGID();
346280304Sjkim    ErrorOr<uint64_t> Size = C.getSize();
347280304Sjkim    failIfError(Size.getError());
348280304Sjkim    outs() << ' ' << format("%6llu", Size.get());
349280304Sjkim    outs() << ' ' << C.getLastModified().str();
350280304Sjkim    outs() << ' ';
351280304Sjkim  }
352280304Sjkim  outs() << Name << "\n";
353280304Sjkim}
354280304Sjkim
355280304Sjkim// Implement the 'x' operation. This function extracts files back to the file
356280304Sjkim// system.
357238405Sjkimstatic void doExtract(StringRef Name, const object::Archive::Child &C) {
358280304Sjkim  // Retain the original mode.
359280304Sjkim  sys::fs::perms Mode = C.getAccessMode();
360280304Sjkim
361280304Sjkim  int FD;
362280304Sjkim  failIfError(sys::fs::openFileForWrite(Name, FD, sys::fs::F_None, Mode), Name);
363280304Sjkim
364280304Sjkim  {
365280304Sjkim    raw_fd_ostream file(FD, false);
366280304Sjkim
367280304Sjkim    // Get the data and its length
368280304Sjkim    StringRef Data = *C.getBuffer();
369280304Sjkim
370280304Sjkim    // Write the data.
371280304Sjkim    file.write(Data.data(), Data.size());
372280304Sjkim  }
373280304Sjkim
374280304Sjkim  // If we're supposed to retain the original modification times, etc. do so
375280304Sjkim  // now.
376280304Sjkim  if (OriginalDates)
377280304Sjkim    failIfError(
378280304Sjkim        sys::fs::setLastModificationAndAccessTime(FD, C.getLastModified()));
379280304Sjkim
380280304Sjkim  if (close(FD))
381280304Sjkim    fail("Could not close the file");
382280304Sjkim}
383280304Sjkim
384280304Sjkimstatic bool shouldCreateArchive(ArchiveOperation Op) {
385280304Sjkim  switch (Op) {
386280304Sjkim  case Print:
387280304Sjkim  case Delete:
388280304Sjkim  case Move:
389280304Sjkim  case DisplayTable:
390280304Sjkim  case Extract:
391280304Sjkim  case CreateSymTab:
392280304Sjkim    return false;
393280304Sjkim
394280304Sjkim  case QuickAppend:
395160814Ssimon  case ReplaceOrInsert:
396280304Sjkim    return true;
397280304Sjkim  }
398280304Sjkim
399280304Sjkim  llvm_unreachable("Missing entry in covered switch.");
400280304Sjkim}
401280304Sjkim
402280304Sjkimstatic void performReadOperation(ArchiveOperation Operation,
403280304Sjkim                                 object::Archive *OldArchive) {
404280304Sjkim  if (Operation == Extract && OldArchive->isThin())
405280304Sjkim    fail("extracting from a thin archive is not supported");
406280304Sjkim
407280304Sjkim  bool Filter = !Members.empty();
408280304Sjkim  {
409280304Sjkim    Error Err;
410280304Sjkim    for (auto &C : OldArchive->children(Err)) {
411280304Sjkim      ErrorOr<StringRef> NameOrErr = C.getName();
412280304Sjkim      failIfError(NameOrErr.getError());
413280304Sjkim      StringRef Name = NameOrErr.get();
414280304Sjkim
415280304Sjkim      if (Filter) {
416280304Sjkim        auto I = std::find(Members.begin(), Members.end(), Name);
417280304Sjkim        if (I == Members.end())
418280304Sjkim          continue;
419280304Sjkim        Members.erase(I);
420280304Sjkim      }
421280304Sjkim
422280304Sjkim      switch (Operation) {
423280304Sjkim      default:
424280304Sjkim        llvm_unreachable("Not a read operation");
425280304Sjkim      case Print:
426280304Sjkim        doPrint(Name, C);
427280304Sjkim        break;
428280304Sjkim      case DisplayTable:
429280304Sjkim        doDisplayTable(Name, C);
430280304Sjkim        break;
431280304Sjkim      case Extract:
432280304Sjkim        doExtract(Name, C);
433238405Sjkim        break;
434280304Sjkim      }
435280304Sjkim    }
436280304Sjkim    failIfError(std::move(Err));
437280304Sjkim  }
438280304Sjkim
439280304Sjkim  if (Members.empty())
440280304Sjkim    return;
441280304Sjkim  for (StringRef Name : Members)
442280304Sjkim    errs() << Name << " was not found\n";
443280304Sjkim  std::exit(1);
444280304Sjkim}
445280304Sjkim
446280304Sjkimstatic void addMember(std::vector<NewArchiveMember> &Members,
447280304Sjkim                      StringRef FileName, int Pos = -1) {
448280304Sjkim  Expected<NewArchiveMember> NMOrErr =
449280304Sjkim      NewArchiveMember::getFile(FileName, Deterministic);
450280304Sjkim  failIfError(NMOrErr.takeError(), FileName);
451280304Sjkim  if (Pos == -1)
452280304Sjkim    Members.push_back(std::move(*NMOrErr));
453280304Sjkim  else
454280304Sjkim    Members[Pos] = std::move(*NMOrErr);
455280304Sjkim}
456280304Sjkim
457280304Sjkimstatic void addMember(std::vector<NewArchiveMember> &Members,
458280304Sjkim                      const object::Archive::Child &M, int Pos = -1) {
459280304Sjkim  if (Thin && !M.getParent()->isThin())
460280304Sjkim    fail("Cannot convert a regular archive to a thin one");
461280304Sjkim  Expected<NewArchiveMember> NMOrErr =
462280304Sjkim      NewArchiveMember::getOldMember(M, Deterministic);
463280304Sjkim  failIfError(NMOrErr.takeError());
464280304Sjkim  if (Pos == -1)
465280304Sjkim    Members.push_back(std::move(*NMOrErr));
466280304Sjkim  else
467280304Sjkim    Members[Pos] = std::move(*NMOrErr);
468280304Sjkim}
469280304Sjkim
470280304Sjkimenum InsertAction {
471238405Sjkim  IA_AddOldMember,
472160814Ssimon  IA_AddNewMeber,
473280304Sjkim  IA_Delete,
474280304Sjkim  IA_MoveOldMember,
475280304Sjkim  IA_MoveNewMember
476280304Sjkim};
477280304Sjkim
478280304Sjkimstatic InsertAction computeInsertAction(ArchiveOperation Operation,
479280304Sjkim                                        const object::Archive::Child &Member,
480280304Sjkim                                        StringRef Name,
481280304Sjkim                                        std::vector<StringRef>::iterator &Pos) {
482280304Sjkim  if (Operation == QuickAppend || Members.empty())
483280304Sjkim    return IA_AddOldMember;
484280304Sjkim
485280304Sjkim  auto MI =
486280304Sjkim      std::find_if(Members.begin(), Members.end(), [Name](StringRef Path) {
487280304Sjkim        return Name == sys::path::filename(Path);
488280304Sjkim      });
489280304Sjkim
490280304Sjkim  if (MI == Members.end())
491280304Sjkim    return IA_AddOldMember;
492280304Sjkim
493280304Sjkim  Pos = MI;
494280304Sjkim
495280304Sjkim  if (Operation == Delete)
496280304Sjkim    return IA_Delete;
497280304Sjkim
498280304Sjkim  if (Operation == Move)
499280304Sjkim    return IA_MoveOldMember;
500280304Sjkim
501280304Sjkim  if (Operation == ReplaceOrInsert) {
502280304Sjkim    StringRef PosName = sys::path::filename(RelPos);
503280304Sjkim    if (!OnlyUpdate) {
504238405Sjkim      if (PosName.empty())
505280304Sjkim        return IA_AddNewMeber;
506280304Sjkim      return IA_MoveNewMember;
507280304Sjkim    }
508280304Sjkim
509280304Sjkim    // We could try to optimize this to a fstat, but it is not a common
510280304Sjkim    // operation.
511280304Sjkim    sys::fs::file_status Status;
512280304Sjkim    failIfError(sys::fs::status(*MI, Status), *MI);
513280304Sjkim    if (Status.getLastModificationTime() < Member.getLastModified()) {
514280304Sjkim      if (PosName.empty())
515280304Sjkim        return IA_AddOldMember;
516280304Sjkim      return IA_MoveOldMember;
517280304Sjkim    }
518280304Sjkim
519280304Sjkim    if (PosName.empty())
520280304Sjkim      return IA_AddNewMeber;
521280304Sjkim    return IA_MoveNewMember;
522280304Sjkim  }
523280304Sjkim  llvm_unreachable("No such operation");
524280304Sjkim}
525280304Sjkim
526280304Sjkim// We have to walk this twice and computing it is not trivial, so creating an
527280304Sjkim// explicit std::vector is actually fairly efficient.
528280304Sjkimstatic std::vector<NewArchiveMember>
529280304SjkimcomputeNewArchiveMembers(ArchiveOperation Operation,
530280304Sjkim                         object::Archive *OldArchive) {
531280304Sjkim  std::vector<NewArchiveMember> Ret;
532280304Sjkim  std::vector<NewArchiveMember> Moved;
533280304Sjkim  int InsertPos = -1;
534280304Sjkim  StringRef PosName = sys::path::filename(RelPos);
535280304Sjkim  if (OldArchive) {
536160814Ssimon    Error Err;
537280304Sjkim    for (auto &Child : OldArchive->children(Err)) {
538280304Sjkim      int Pos = Ret.size();
539280304Sjkim      ErrorOr<StringRef> NameOrErr = Child.getName();
540280304Sjkim      failIfError(NameOrErr.getError());
541280304Sjkim      StringRef Name = NameOrErr.get();
542280304Sjkim      if (Name == PosName) {
543280304Sjkim        assert(AddAfter || AddBefore);
544280304Sjkim        if (AddBefore)
545280304Sjkim          InsertPos = Pos;
546280304Sjkim        else
547280304Sjkim          InsertPos = Pos + 1;
548280304Sjkim      }
549280304Sjkim
550280304Sjkim      std::vector<StringRef>::iterator MemberI = Members.end();
551280304Sjkim      InsertAction Action =
552280304Sjkim          computeInsertAction(Operation, Child, Name, MemberI);
553280304Sjkim      switch (Action) {
554280304Sjkim      case IA_AddOldMember:
555280304Sjkim        addMember(Ret, Child);
556280304Sjkim        break;
557280304Sjkim      case IA_AddNewMeber:
558280304Sjkim        addMember(Ret, *MemberI);
559280304Sjkim        break;
560280304Sjkim      case IA_Delete:
561280304Sjkim        break;
562280304Sjkim      case IA_MoveOldMember:
563280304Sjkim        addMember(Moved, Child);
564280304Sjkim        break;
565280304Sjkim      case IA_MoveNewMember:
566280304Sjkim        addMember(Moved, *MemberI);
567280304Sjkim        break;
568238405Sjkim      }
569280304Sjkim      if (MemberI != Members.end())
570280304Sjkim        Members.erase(MemberI);
571280304Sjkim    }
572280304Sjkim    failIfError(std::move(Err));
573280304Sjkim  }
574280304Sjkim
575280304Sjkim  if (Operation == Delete)
576280304Sjkim    return Ret;
577280304Sjkim
578280304Sjkim  if (!RelPos.empty() && InsertPos == -1)
579280304Sjkim    fail("Insertion point not found");
580280304Sjkim
581280304Sjkim  if (RelPos.empty())
582280304Sjkim    InsertPos = Ret.size();
583280304Sjkim
584280304Sjkim  assert(unsigned(InsertPos) <= Ret.size());
585280304Sjkim  int Pos = InsertPos;
586280304Sjkim  for (auto &M : Moved) {
587280304Sjkim    Ret.insert(Ret.begin() + Pos, std::move(M));
588280304Sjkim    ++Pos;
589280304Sjkim  }
590280304Sjkim
591280304Sjkim  for (unsigned I = 0; I != Members.size(); ++I)
592280304Sjkim    Ret.insert(Ret.begin() + InsertPos, NewArchiveMember());
593280304Sjkim  Pos = InsertPos;
594280304Sjkim  for (auto &Member : Members) {
595280304Sjkim    addMember(Ret, Member, Pos);
596280304Sjkim    ++Pos;
597280304Sjkim  }
598280304Sjkim
599280304Sjkim  return Ret;
600160814Ssimon}
601280304Sjkim
602280304Sjkimstatic object::Archive::Kind getDefaultForHost() {
603280304Sjkim  return Triple(sys::getProcessTriple()).isOSDarwin() ? object::Archive::K_BSD
604280304Sjkim                                                      : object::Archive::K_GNU;
605280304Sjkim}
606280304Sjkim
607280304Sjkimstatic object::Archive::Kind getKindFromMember(const NewArchiveMember &Member) {
608280304Sjkim  Expected<std::unique_ptr<object::ObjectFile>> OptionalObject =
609280304Sjkim      object::ObjectFile::createObjectFile(Member.Buf->getMemBufferRef());
610280304Sjkim
611280304Sjkim  if (OptionalObject)
612280304Sjkim    return isa<object::MachOObjectFile>(**OptionalObject)
613280304Sjkim               ? object::Archive::K_BSD
614280304Sjkim               : object::Archive::K_GNU;
615280304Sjkim
616280304Sjkim  // squelch the error in case we had a non-object file
617280304Sjkim  consumeError(OptionalObject.takeError());
618280304Sjkim  return getDefaultForHost();
619280304Sjkim}
620280304Sjkim
621280304Sjkimstatic void
622280304SjkimperformWriteOperation(ArchiveOperation Operation,
623280304Sjkim                      object::Archive *OldArchive,
624280304Sjkim                      std::unique_ptr<MemoryBuffer> OldArchiveBuf,
625280304Sjkim                      std::vector<NewArchiveMember> *NewMembersP) {
626280304Sjkim  std::vector<NewArchiveMember> NewMembers;
627280304Sjkim  if (!NewMembersP)
628280304Sjkim    NewMembers = computeNewArchiveMembers(Operation, OldArchive);
629280304Sjkim
630238405Sjkim  object::Archive::Kind Kind;
631280304Sjkim  switch (FormatOpt) {
632280304Sjkim  case Default:
633280304Sjkim    if (Thin)
634280304Sjkim      Kind = object::Archive::K_GNU;
635280304Sjkim    else if (OldArchive)
636280304Sjkim      Kind = OldArchive->kind();
637280304Sjkim    else if (NewMembersP)
638280304Sjkim      Kind = NewMembersP->size() ? getKindFromMember(NewMembersP->front())
639280304Sjkim                                 : getDefaultForHost();
640280304Sjkim    else
641280304Sjkim      Kind = NewMembers.size() ? getKindFromMember(NewMembers.front())
642280304Sjkim                               : getDefaultForHost();
643280304Sjkim    break;
644280304Sjkim  case GNU:
645280304Sjkim    Kind = object::Archive::K_GNU;
646280304Sjkim    break;
647280304Sjkim  case BSD:
648280304Sjkim    if (Thin)
649280304Sjkim      fail("Only the gnu format has a thin mode");
650280304Sjkim    Kind = object::Archive::K_BSD;
651280304Sjkim    break;
652280304Sjkim  }
653280304Sjkim
654280304Sjkim  std::pair<StringRef, std::error_code> Result =
655280304Sjkim      writeArchive(ArchiveName, NewMembersP ? *NewMembersP : NewMembers, Symtab,
656280304Sjkim                   Kind, Deterministic, Thin, std::move(OldArchiveBuf));
657280304Sjkim  failIfError(Result.second, Result.first);
658280304Sjkim}
659280304Sjkim
660280304Sjkimstatic void createSymbolTable(object::Archive *OldArchive) {
661280304Sjkim  // When an archive is created or modified, if the s option is given, the
662160814Ssimon  // resulting archive will have a current symbol table. If the S option
663280304Sjkim  // is given, it will have no symbol table.
664280304Sjkim  // In summary, we only need to update the symbol table if we have none.
665280304Sjkim  // This is actually very common because of broken build systems that think
666280304Sjkim  // they have to run ranlib.
667280304Sjkim  if (OldArchive->hasSymbolTable())
668280304Sjkim    return;
669280304Sjkim
670280304Sjkim  performWriteOperation(CreateSymTab, OldArchive, nullptr, nullptr);
671280304Sjkim}
672280304Sjkim
673280304Sjkimstatic void performOperation(ArchiveOperation Operation,
674280304Sjkim                             object::Archive *OldArchive,
675280304Sjkim                             std::unique_ptr<MemoryBuffer> OldArchiveBuf,
676280304Sjkim                             std::vector<NewArchiveMember> *NewMembers) {
677280304Sjkim  switch (Operation) {
678280304Sjkim  case Print:
679280304Sjkim  case DisplayTable:
680280304Sjkim  case Extract:
681280304Sjkim    performReadOperation(Operation, OldArchive);
682280304Sjkim    return;
683280304Sjkim
684280304Sjkim  case Delete:
685280304Sjkim  case Move:
686280304Sjkim  case QuickAppend:
687280304Sjkim  case ReplaceOrInsert:
688280304Sjkim    performWriteOperation(Operation, OldArchive, std::move(OldArchiveBuf),
689280304Sjkim                          NewMembers);
690280304Sjkim    return;
691280304Sjkim  case CreateSymTab:
692280304Sjkim    createSymbolTable(OldArchive);
693280304Sjkim    return;
694238405Sjkim  }
695280304Sjkim  llvm_unreachable("Unknown operation.");
696280304Sjkim}
697280304Sjkim
698280304Sjkimstatic int performOperation(ArchiveOperation Operation,
699280304Sjkim                            std::vector<NewArchiveMember> *NewMembers) {
700280304Sjkim  // Create or open the archive object.
701280304Sjkim  ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
702280304Sjkim      MemoryBuffer::getFile(ArchiveName, -1, false);
703280304Sjkim  std::error_code EC = Buf.getError();
704280304Sjkim  if (EC && EC != errc::no_such_file_or_directory)
705280304Sjkim    fail("error opening '" + ArchiveName + "': " + EC.message() + "!");
706280304Sjkim
707280304Sjkim  if (!EC) {
708280304Sjkim    Error Err;
709280304Sjkim    object::Archive Archive(Buf.get()->getMemBufferRef(), Err);
710280304Sjkim    EC = errorToErrorCode(std::move(Err));
711280304Sjkim    failIfError(EC,
712280304Sjkim                "error loading '" + ArchiveName + "': " + EC.message() + "!");
713280304Sjkim    performOperation(Operation, &Archive, std::move(Buf.get()), NewMembers);
714280304Sjkim    return 0;
715280304Sjkim  }
716280304Sjkim
717280304Sjkim  assert(EC == errc::no_such_file_or_directory);
718280304Sjkim
719280304Sjkim  if (!shouldCreateArchive(Operation)) {
720280304Sjkim    failIfError(EC, Twine("error loading '") + ArchiveName + "'");
721280304Sjkim  } else {
722280304Sjkim    if (!Create) {
723280304Sjkim      // Produce a warning if we should and we're creating the archive
724160814Ssimon      errs() << ToolName << ": creating " << ArchiveName << "\n";
725280304Sjkim    }
726280304Sjkim  }
727280304Sjkim
728280304Sjkim  performOperation(Operation, nullptr, nullptr, NewMembers);
729280304Sjkim  return 0;
730280304Sjkim}
731280304Sjkim
732280304Sjkimstatic void runMRIScript() {
733280304Sjkim  enum class MRICommand { AddLib, AddMod, Create, Save, End, Invalid };
734280304Sjkim
735280304Sjkim  ErrorOr<std::unique_ptr<MemoryBuffer>> Buf = MemoryBuffer::getSTDIN();
736280304Sjkim  failIfError(Buf.getError());
737280304Sjkim  const MemoryBuffer &Ref = *Buf.get();
738280304Sjkim  bool Saved = false;
739280304Sjkim  std::vector<NewArchiveMember> NewMembers;
740280304Sjkim  std::vector<std::unique_ptr<MemoryBuffer>> ArchiveBuffers;
741280304Sjkim  std::vector<std::unique_ptr<object::Archive>> Archives;
742280304Sjkim
743280304Sjkim  for (line_iterator I(Ref, /*SkipBlanks*/ true, ';'), E; I != E; ++I) {
744280304Sjkim    StringRef Line = *I;
745280304Sjkim    StringRef CommandStr, Rest;
746280304Sjkim    std::tie(CommandStr, Rest) = Line.split(' ');
747280304Sjkim    Rest = Rest.trim();
748280304Sjkim    if (!Rest.empty() && Rest.front() == '"' && Rest.back() == '"')
749280304Sjkim      Rest = Rest.drop_front().drop_back();
750280304Sjkim    auto Command = StringSwitch<MRICommand>(CommandStr.lower())
751280304Sjkim                       .Case("addlib", MRICommand::AddLib)
752280304Sjkim                       .Case("addmod", MRICommand::AddMod)
753280304Sjkim                       .Case("create", MRICommand::Create)
754280304Sjkim                       .Case("save", MRICommand::Save)
755280304Sjkim                       .Case("end", MRICommand::End)
756280304Sjkim                       .Default(MRICommand::Invalid);
757280304Sjkim
758280304Sjkim    switch (Command) {
759280304Sjkim    case MRICommand::AddLib: {
760160814Ssimon      auto BufOrErr = MemoryBuffer::getFile(Rest, -1, false);
761280304Sjkim      failIfError(BufOrErr.getError(), "Could not open library");
762280304Sjkim      ArchiveBuffers.push_back(std::move(*BufOrErr));
763280304Sjkim      auto LibOrErr =
764280304Sjkim          object::Archive::create(ArchiveBuffers.back()->getMemBufferRef());
765280304Sjkim      failIfError(errorToErrorCode(LibOrErr.takeError()),
766280304Sjkim                  "Could not parse library");
767280304Sjkim      Archives.push_back(std::move(*LibOrErr));
768280304Sjkim      object::Archive &Lib = *Archives.back();
769280304Sjkim      {
770280304Sjkim        Error Err;
771280304Sjkim        for (auto &Member : Lib.children(Err))
772280304Sjkim          addMember(NewMembers, Member);
773280304Sjkim        failIfError(std::move(Err));
774280304Sjkim      }
775280304Sjkim      break;
776280304Sjkim    }
777280304Sjkim    case MRICommand::AddMod:
778280304Sjkim      addMember(NewMembers, Rest);
779280304Sjkim      break;
780280304Sjkim    case MRICommand::Create:
781280304Sjkim      Create = true;
782280304Sjkim      if (!ArchiveName.empty())
783280304Sjkim        fail("Editing multiple archives not supported");
784280304Sjkim      if (Saved)
785280304Sjkim        fail("File already saved");
786280304Sjkim      ArchiveName = Rest;
787280304Sjkim      break;
788280304Sjkim    case MRICommand::Save:
789280304Sjkim      Saved = true;
790280304Sjkim      break;
791280304Sjkim    case MRICommand::End:
792280304Sjkim      break;
793280304Sjkim    case MRICommand::Invalid:
794280304Sjkim      fail("Unknown command: " + CommandStr);
795280304Sjkim    }
796238405Sjkim  }
797160814Ssimon
798280304Sjkim  // Nothing to do if not saved.
799280304Sjkim  if (Saved)
800280304Sjkim    performOperation(ReplaceOrInsert, &NewMembers);
801280304Sjkim  exit(0);
802280304Sjkim}
803280304Sjkim
804280304Sjkimstatic int ar_main() {
805280304Sjkim  // Do our own parsing of the command line because the CommandLine utility
806280304Sjkim  // can't handle the grouped positional parameters without a dash.
807280304Sjkim  ArchiveOperation Operation = parseCommandLine();
808280304Sjkim  return performOperation(Operation, nullptr);
809280304Sjkim}
810280304Sjkim
811280304Sjkimstatic int ranlib_main() {
812280304Sjkim  if (RestOfArgs.size() != 1)
813280304Sjkim    fail(ToolName + " takes just one archive as an argument");
814280304Sjkim  ArchiveName = RestOfArgs[0];
815280304Sjkim  return performOperation(CreateSymTab, nullptr);
816280304Sjkim}
817280304Sjkim
818280304Sjkimint main(int argc, char **argv) {
819280304Sjkim  ToolName = argv[0];
820280304Sjkim  // Print a stack trace if we signal out.
821280304Sjkim  sys::PrintStackTraceOnErrorSignal(argv[0]);
822280304Sjkim  PrettyStackTraceProgram X(argc, argv);
823280304Sjkim  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
824280304Sjkim
825280304Sjkim  llvm::InitializeAllTargetInfos();
826280304Sjkim  llvm::InitializeAllTargetMCs();
827160814Ssimon  llvm::InitializeAllAsmParsers();
828280304Sjkim
829280304Sjkim  StringRef Stem = sys::path::stem(ToolName);
830280304Sjkim  if (Stem.find("ranlib") == StringRef::npos &&
831280304Sjkim      Stem.find("lib") != StringRef::npos)
832280304Sjkim    return libDriverMain(makeArrayRef(argv, argc));
833280304Sjkim
834280304Sjkim  // Have the command line options parsed and handle things
835280304Sjkim  // like --help and --version.
836280304Sjkim  cl::ParseCommandLineOptions(argc, argv,
837280304Sjkim    "LLVM Archiver (llvm-ar)\n\n"
838280304Sjkim    "  This program archives bitcode files into single libraries\n"
839280304Sjkim  );
840280304Sjkim
841280304Sjkim  if (Stem.find("ranlib") != StringRef::npos)
842280304Sjkim    return ranlib_main();
843280304Sjkim  if (Stem.find("ar") != StringRef::npos)
844280304Sjkim    return ar_main();
845280304Sjkim  fail("Not ranlib, ar or lib!");
846280304Sjkim}
847280304Sjkim