LLVM  5.0.0
LibDriver.cpp
Go to the documentation of this file.
1 //===- LibDriver.cpp - lib.exe-compatible driver --------------------------===//
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 // Defines an interface to a lib.exe-compatible driver that also understands
11 // bitcode files. Used by llvm-lib and lld-link /lib.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Option/Arg.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Option/Option.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/Process.h"
27 
28 using namespace llvm;
29 
30 namespace {
31 
32 enum {
33  OPT_INVALID = 0,
34 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
35 #include "Options.inc"
36 #undef OPTION
37 };
38 
39 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
40 #include "Options.inc"
41 #undef PREFIX
42 
43 static const llvm::opt::OptTable::Info infoTable[] = {
44 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10, X11) \
45  {X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, \
46  X8, X7, OPT_##GROUP, OPT_##ALIAS, X6, X11},
47 #include "Options.inc"
48 #undef OPTION
49 };
50 
51 class LibOptTable : public llvm::opt::OptTable {
52 public:
53  LibOptTable() : OptTable(infoTable, true) {}
54 };
55 
56 }
57 
59  const llvm::NewArchiveMember &FirstMember) {
60  if (auto *Arg = Args->getLastArg(OPT_out))
61  return Arg->getValue();
62  SmallString<128> Val = StringRef(FirstMember.Buf->getBufferIdentifier());
64  return Val.str();
65 }
66 
67 static std::vector<StringRef> getSearchPaths(llvm::opt::InputArgList *Args,
68  StringSaver &Saver) {
69  std::vector<StringRef> Ret;
70  // Add current directory as first item of the search path.
71  Ret.push_back("");
72 
73  // Add /libpath flags.
74  for (auto *Arg : Args->filtered(OPT_libpath))
75  Ret.push_back(Arg->getValue());
76 
77  // Add $LIB.
79  if (!EnvOpt.hasValue())
80  return Ret;
81  StringRef Env = Saver.save(*EnvOpt);
82  while (!Env.empty()) {
83  StringRef Path;
84  std::tie(Path, Env) = Env.split(';');
85  Ret.push_back(Path);
86  }
87  return Ret;
88 }
89 
91  ArrayRef<StringRef> Paths) {
92  for (auto Dir : Paths) {
93  SmallString<128> Path = Dir;
94  sys::path::append(Path, File);
95  if (sys::fs::exists(Path))
96  return Path.str().str();
97  }
98  return Optional<std::string>();
99 }
100 
102  SmallVector<const char *, 20> NewArgs(ArgsArr.begin(), ArgsArr.end());
104  StringSaver Saver(Alloc);
106  ArgsArr = NewArgs;
107 
108  LibOptTable Table;
109  unsigned MissingIndex;
110  unsigned MissingCount;
112  Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
113  if (MissingCount) {
114  llvm::errs() << "missing arg value for \""
115  << Args.getArgString(MissingIndex) << "\", expected "
116  << MissingCount
117  << (MissingCount == 1 ? " argument.\n" : " arguments.\n");
118  return 1;
119  }
120  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
121  llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
122 
123  if (!Args.hasArgNoClaim(OPT_INPUT)) {
124  // No input files. To match lib.exe, silently do nothing.
125  return 0;
126  }
127 
128  std::vector<StringRef> SearchPaths = getSearchPaths(&Args, Saver);
129 
130  std::vector<llvm::NewArchiveMember> Members;
131  for (auto *Arg : Args.filtered(OPT_INPUT)) {
132  Optional<std::string> Path = findInputFile(Arg->getValue(), SearchPaths);
133  if (!Path.hasValue()) {
134  llvm::errs() << Arg->getValue() << ": no such file or directory\n";
135  return 1;
136  }
138  NewArchiveMember::getFile(Saver.save(*Path), /*Deterministic=*/true);
139  if (!MOrErr) {
140  handleAllErrors(MOrErr.takeError(), [&](const llvm::ErrorInfoBase &EIB) {
141  llvm::errs() << Arg->getValue() << ": " << EIB.message() << "\n";
142  });
143  return 1;
144  }
145  llvm::file_magic Magic = llvm::identify_magic(MOrErr->Buf->getBuffer());
146  if (Magic != llvm::file_magic::coff_object &&
147  Magic != llvm::file_magic::bitcode &&
149  llvm::errs() << Arg->getValue()
150  << ": not a COFF object, bitcode or resource file\n";
151  return 1;
152  }
153  Members.emplace_back(std::move(*MOrErr));
154  }
155 
156  std::pair<StringRef, std::error_code> Result =
157  llvm::writeArchive(getOutputPath(&Args, Members[0]), Members,
158  /*WriteSymtab=*/true, object::Archive::K_GNU,
159  /*Deterministic*/ true, Args.hasArg(OPT_llvmlibthin));
160 
161  if (Result.second) {
162  if (Result.first.empty())
163  Result.first = ArgsArr[0];
164  llvm::errs() << Result.first << ": " << Result.second.message() << "\n";
165  return 1;
166  }
167 
168  return 0;
169 }
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool hasValue() const
Definition: Optional.h:133
iterator end() const
Definition: ArrayRef.h:138
Windows compiled resource file (.res)
Definition: Magic.h:47
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
Base class for error info classes.
Definition: Error.h:47
Bitcode file.
Definition: Magic.h:24
const char * getArgString(unsigned Index) const override
getArgString - Return the input argument string at Index.
Definition: ArgList.h:411
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:179
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:465
std::pair< StringRef, std::error_code > writeArchive(StringRef ArcName, std::vector< NewArchiveMember > &NewMembers, bool WriteSymtab, object::Archive::Kind Kind, bool Deterministic, bool Thin, std::unique_ptr< MemoryBuffer > OldArchiveBuf=nullptr)
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:23
int libDriverMain(ArrayRef< const char * > ARgs)
Definition: LibDriver.cpp:101
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:138
static Optional< std::string > findInputFile(StringRef File, ArrayRef< StringRef > Paths)
Definition: LibDriver.cpp:90
Provide access to the Option info table.
Definition: OptTable.h:39
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
static std::string getOutputPath(llvm::opt::InputArgList *Args, const llvm::NewArchiveMember &FirstMember)
Definition: LibDriver.cpp:58
iterator_range< filtered_iterator< sizeof...(OptSpecifiers)> > filtered(OptSpecifiers...Ids) const
Definition: ArgList.h:209
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.
iterator begin() const
Definition: ArrayRef.h:137
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
Definition: Error.h:555
LLVM_NODISCARD std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:228
COFF object file.
Definition: Magic.h:44
static const char *const Magic
Definition: Archive.cpp:42
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition: Path.cpp:490
bool hasArgNoClaim(OptSpecifiers...Ids) const
hasArg - Does the arg list contain any option matching Id.
Definition: ArgList.h:244
Arg * getLastArg(OptSpecifiers...Ids) const
Return the last argument matching Id, or null.
Definition: ArgList.h:254
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...
static std::vector< StringRef > getSearchPaths(llvm::opt::InputArgList *Args, StringSaver &Saver)
Definition: LibDriver.cpp:67
StringRef save(const char *S)
Definition: StringSaver.h:26
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
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:727
Defines the llvm::Arg class for parsed arguments.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
Basic Alias true
Saves strings in the inheritor's stable storage and returns a StringRef with a stable character point...
Definition: StringSaver.h:21
Provides a library for accessing information about this process and other processes on the operating ...
Entry for a single option instance in the option data table.
Definition: OptTable.h:42
static Expected< NewArchiveMember > getFile(StringRef FileName, bool Deterministic)
BumpPtrAllocator Alloc
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
bool hasArg(OptSpecifiers...Ids) const
Definition: ArgList.h:248
bool exists(file_status status)
Does file exist?
Definition: Path.cpp:956
std::unique_ptr< MemoryBuffer > Buf
Definition: ArchiveWriter.h:24
static Optional< std::string > GetEnv(StringRef name)
file_magic - An "enum class" enumeration of file types based on magic (the first N bytes of the file)...
Definition: Magic.h:21