LLVM  9.0.0svn
LibDriver.cpp
Go to the documentation of this file.
1 //===- LibDriver.cpp - lib.exe-compatible driver --------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Defines an interface to a lib.exe-compatible driver that also understands
10 // bitcode files. Used by llvm-lib and lld-link /lib.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Option/Arg.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Option/Option.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/Process.h"
26 
27 using namespace llvm;
28 
29 namespace {
30 
31 enum {
32  OPT_INVALID = 0,
33 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
34 #include "Options.inc"
35 #undef OPTION
36 };
37 
38 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
39 #include "Options.inc"
40 #undef PREFIX
41 
42 static const opt::OptTable::Info InfoTable[] = {
43 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
44  {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
45  X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
46 #include "Options.inc"
47 #undef OPTION
48 };
49 
50 class LibOptTable : public opt::OptTable {
51 public:
52  LibOptTable() : OptTable(InfoTable, true) {}
53 };
54 
55 }
56 
57 static std::string getOutputPath(opt::InputArgList *Args,
58  const NewArchiveMember &FirstMember) {
59  if (auto *Arg = Args->getLastArg(OPT_out))
60  return Arg->getValue();
61  SmallString<128> Val = StringRef(FirstMember.Buf->getBufferIdentifier());
62  sys::path::replace_extension(Val, ".lib");
63  return Val.str();
64 }
65 
66 static std::vector<StringRef> getSearchPaths(opt::InputArgList *Args,
67  StringSaver &Saver) {
68  std::vector<StringRef> Ret;
69  // Add current directory as first item of the search path.
70  Ret.push_back("");
71 
72  // Add /libpath flags.
73  for (auto *Arg : Args->filtered(OPT_libpath))
74  Ret.push_back(Arg->getValue());
75 
76  // Add $LIB.
78  if (!EnvOpt.hasValue())
79  return Ret;
80  StringRef Env = Saver.save(*EnvOpt);
81  while (!Env.empty()) {
82  StringRef Path;
83  std::tie(Path, Env) = Env.split(';');
84  Ret.push_back(Path);
85  }
86  return Ret;
87 }
88 
89 static std::string findInputFile(StringRef File, ArrayRef<StringRef> Paths) {
90  for (StringRef Dir : Paths) {
91  SmallString<128> Path = Dir;
92  sys::path::append(Path, File);
93  if (sys::fs::exists(Path))
94  return Path.str().str();
95  }
96  return "";
97 }
98 
100  if (!E)
101  return;
102  handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
103  llvm::errs() << "error opening '" << File << "': " << EIB.message() << '\n';
104  exit(1);
105  });
106 }
107 
109  // lib.exe prints the contents of the first archive file.
110  std::unique_ptr<MemoryBuffer> B;
111  for (auto *Arg : Args.filtered(OPT_INPUT)) {
112  // Create or open the archive object.
114  MemoryBuffer::getFile(Arg->getValue(), -1, false);
115  fatalOpenError(errorCodeToError(MaybeBuf.getError()), Arg->getValue());
116 
117  if (identify_magic(MaybeBuf.get()->getBuffer()) == file_magic::archive) {
118  B = std::move(MaybeBuf.get());
119  break;
120  }
121  }
122 
123  // lib.exe doesn't print an error if no .lib files are passed.
124  if (!B)
125  return;
126 
127  Error Err = Error::success();
128  object::Archive Archive(B.get()->getMemBufferRef(), Err);
129  fatalOpenError(std::move(Err), B->getBufferIdentifier());
130 
131  for (auto &C : Archive.children(Err)) {
132  Expected<StringRef> NameOrErr = C.getName();
133  fatalOpenError(NameOrErr.takeError(), B->getBufferIdentifier());
134  StringRef Name = NameOrErr.get();
135  llvm::outs() << Name << '\n';
136  }
137  fatalOpenError(std::move(Err), B->getBufferIdentifier());
138 }
139 
141  BumpPtrAllocator Alloc;
142  StringSaver Saver(Alloc);
143 
144  // Parse command line arguments.
145  SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end());
147  ArgsArr = NewArgs;
148 
149  LibOptTable Table;
150  unsigned MissingIndex;
151  unsigned MissingCount;
153  Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
154  if (MissingCount) {
155  llvm::errs() << "missing arg value for \""
156  << Args.getArgString(MissingIndex) << "\", expected "
157  << MissingCount
158  << (MissingCount == 1 ? " argument.\n" : " arguments.\n");
159  return 1;
160  }
161  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
162  llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
163 
164  // Handle /help
165  if (Args.hasArg(OPT_help)) {
166  Table.PrintHelp(outs(), "llvm-lib [options] file...", "LLVM Lib");
167  return 0;
168  }
169 
170  // If no input files, silently do nothing to match lib.exe.
171  if (!Args.hasArgNoClaim(OPT_INPUT))
172  return 0;
173 
174  if (Args.hasArg(OPT_lst)) {
175  doList(Args);
176  return 0;
177  }
178 
179  std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver);
180 
181  // Create a NewArchiveMember for each input file.
182  std::vector<NewArchiveMember> Members;
183  for (auto *Arg : Args.filtered(OPT_INPUT)) {
184  std::string Path = findInputFile(Arg->getValue(), SearchPaths);
185  if (Path.empty()) {
186  llvm::errs() << Arg->getValue() << ": no such file or directory\n";
187  return 1;
188  }
189 
191  NewArchiveMember::getFile(Saver.save(Path), /*Deterministic=*/true);
192  if (!MOrErr) {
193  handleAllErrors(MOrErr.takeError(), [&](const ErrorInfoBase &EIB) {
194  llvm::errs() << Arg->getValue() << ": " << EIB.message() << "\n";
195  });
196  return 1;
197  }
198 
199  file_magic Magic = identify_magic(MOrErr->Buf->getBuffer());
200  if (Magic != file_magic::coff_object && Magic != file_magic::bitcode &&
201  Magic != file_magic::windows_resource) {
202  llvm::errs() << Arg->getValue()
203  << ": not a COFF object, bitcode or resource file\n";
204  return 1;
205  }
206  Members.emplace_back(std::move(*MOrErr));
207  }
208 
209  // Create an archive file.
210  std::string OutputPath = getOutputPath(&Args, Members[0]);
211  // llvm-lib uses relative paths for both regular and thin archives, unlike
212  // standard GNU ar, which only uses relative paths for thin archives and
213  // basenames for regular archives.
214  for (NewArchiveMember &Member : Members)
215  Member.MemberName =
216  Saver.save(computeArchiveRelativePath(OutputPath, Member.MemberName));
217 
218  if (Error E =
219  writeArchive(OutputPath, Members,
220  /*WriteSymtab=*/true, object::Archive::K_GNU,
221  /*Deterministic*/ true, Args.hasArg(OPT_llvmlibthin))) {
222  handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
223  llvm::errs() << OutputPath << ": " << EI.message() << "\n";
224  });
225  return 1;
226  }
227 
228  return 0;
229 }
uint64_t CallInst * C
Represents either an error or a value T.
Definition: ErrorOr.h:56
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:218
This class represents lattice values for constants.
Definition: AllocatorList.h:23
iterator begin() const
Definition: ArrayRef.h:136
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
static std::string findInputFile(StringRef File, ArrayRef< StringRef > Paths)
Definition: LibDriver.cpp:89
Windows compiled resource file (.res)
Definition: Magic.h:47
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:56
iterator_range< filtered_iterator< sizeof...(OptSpecifiers)> > filtered(OptSpecifiers ...Ids) const
Definition: ArgList.h:205
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
Base class for error info classes.
Definition: Error.h:48
Error writeArchive(StringRef ArcName, ArrayRef< NewArchiveMember > NewMembers, bool WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, std::unique_ptr< MemoryBuffer > OldArchiveBuf=nullptr)
Bitcode file.
Definition: Magic.h:23
const char * getArgString(unsigned Index) const override
getArgString - Return the input argument string at Index.
Definition: ArgList.h:409
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:455
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition: Magic.cpp:34
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char *> &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows command line which may contain quotes and escaped quotes.
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:126
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
static std::vector< StringRef > getSearchPaths(opt::InputArgList *Args, StringSaver &Saver)
Definition: LibDriver.cpp:66
bool hasArg(OptSpecifiers ...Ids) const
Definition: ArgList.h:244
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
raw_ostream & outs()
This returns a reference to a raw_ostream for standard output.
bool hasArgNoClaim(OptSpecifiers ...Ids) const
hasArg - Does the arg list contain any option matching Id.
Definition: ArgList.h:240
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void fatalOpenError(llvm::Error E, Twine File)
Definition: LibDriver.cpp:99
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:140
Instrumentation for Order File
Provide access to the Option info table.
Definition: OptTable.h:38
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
std::error_code getError() const
Definition: ErrorOr.h:159
static void doList(opt::InputArgList &Args)
Definition: LibDriver.cpp:108
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
int libDriverMain(ArrayRef< const char *> ARgs)
Definition: LibDriver.cpp:140
COFF object file.
Definition: Magic.h:44
Arg * getLastArg(OptSpecifiers ...Ids) const
Return the last argument matching Id, or null.
Definition: ArgList.h:250
static const char *const Magic
Definition: Archive.cpp:41
ar style archive file
Definition: Magic.h:24
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:904
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:841
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:480
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:696
iterator end() const
Definition: ArrayRef.h:137
reference get()
Returns a reference to the stored T value.
Definition: Error.h:532
StringRef save(const char *S)
Definition: StringSaver.h:28
Defines the llvm::Arg class for parsed arguments.
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array...
Definition: ArrayRef.h:178
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
Definition: StringSaver.h:21
bool hasValue() const
Definition: Optional.h:259
Provides a library for accessing information about this process and other processes on the operating ...
static std::string getOutputPath(opt::InputArgList *Args, const NewArchiveMember &FirstMember)
Definition: LibDriver.cpp:57
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
Entry for a single option instance in the option data table.
Definition: OptTable.h:41
static Expected< NewArchiveMember > getFile(StringRef FileName, bool Deterministic)
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
std::string computeArchiveRelativePath(StringRef From, StringRef To)
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char *> &Argv, bool MarkEOLs=false, bool RelativeNames=false)
Expand response files on a command line recursively using the given StringSaver and tokenization stra...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
std::unique_ptr< MemoryBuffer > Buf
Definition: ArchiveWriter.h:24
bool exists(const basic_file_status &status)
Does file exist?
Definition: Path.cpp:1025
static Optional< std::string > GetEnv(StringRef name)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
reference get()
Definition: ErrorOr.h:156
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: Magic.h:20