LLVM  9.0.0svn
DlltoolDriver.cpp
Go to the documentation of this file.
1 //===- DlltoolDriver.cpp - dlltool.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 dlltool.exe-compatible driver.
10 //
11 //===----------------------------------------------------------------------===//
12 
14 #include "llvm/Object/COFF.h"
17 #include "llvm/Option/Arg.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Option/Option.h"
20 #include "llvm/Support/Path.h"
21 
22 #include <vector>
23 
24 using namespace llvm;
25 using namespace llvm::object;
26 using namespace llvm::COFF;
27 
28 namespace {
29 
30 enum {
31  OPT_INVALID = 0,
32 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
33 #include "Options.inc"
34 #undef OPTION
35 };
36 
37 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
38 #include "Options.inc"
39 #undef PREFIX
40 
41 static const llvm::opt::OptTable::Info InfoTable[] = {
42 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
43  {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
44  X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
45 #include "Options.inc"
46 #undef OPTION
47 };
48 
49 class DllOptTable : public llvm::opt::OptTable {
50 public:
51  DllOptTable() : OptTable(InfoTable, false) {}
52 };
53 
54 } // namespace
55 
56 // Opens a file. Path has to be resolved already.
57 static std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
59 
60  if (std::error_code EC = MB.getError()) {
61  llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
62  return nullptr;
63  }
64 
65  return std::move(*MB);
66 }
67 
70  .Case("i386", IMAGE_FILE_MACHINE_I386)
71  .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
75 }
76 
77 static std::string getImplibPath(StringRef Path) {
78  SmallString<128> Out = StringRef("lib");
79  Out.append(Path);
81  return Out.str();
82 }
83 
85  DllOptTable Table;
86  unsigned MissingIndex;
87  unsigned MissingCount;
89  Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
90  if (MissingCount) {
91  llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
92  return 1;
93  }
94 
95  // Handle when no input or output is specified
96  if (Args.hasArgNoClaim(OPT_INPUT) ||
97  (!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) {
98  Table.PrintHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool",
99  false);
100  llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64\n";
101  return 1;
102  }
103 
104  if (!Args.hasArgNoClaim(OPT_m) && Args.hasArgNoClaim(OPT_d)) {
105  llvm::errs() << "error: no target machine specified\n"
106  << "supported targets: i386, i386:x86-64, arm, arm64\n";
107  return 1;
108  }
109 
110  for (auto *Arg : Args.filtered(OPT_UNKNOWN))
111  llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
112  << "\n";
113 
114  if (!Args.hasArg(OPT_d)) {
115  llvm::errs() << "no definition file specified\n";
116  return 1;
117  }
118 
119  std::unique_ptr<MemoryBuffer> MB =
120  openFile(Args.getLastArg(OPT_d)->getValue());
121  if (!MB)
122  return 1;
123 
124  if (!MB->getBufferSize()) {
125  llvm::errs() << "definition file empty\n";
126  return 1;
127  }
128 
130  if (auto *Arg = Args.getLastArg(OPT_m))
131  Machine = getEmulation(Arg->getValue());
132 
133  if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
134  llvm::errs() << "unknown target\n";
135  return 1;
136  }
137 
139  parseCOFFModuleDefinition(*MB, Machine, true);
140 
141  if (!Def) {
142  llvm::errs() << "error parsing definition\n"
143  << errorToErrorCode(Def.takeError()).message();
144  return 1;
145  }
146 
147  // Do this after the parser because parseCOFFModuleDefinition sets OutputFile.
148  if (auto *Arg = Args.getLastArg(OPT_D))
149  Def->OutputFile = Arg->getValue();
150 
151  if (Def->OutputFile.empty()) {
152  llvm::errs() << "no output file specified\n";
153  return 1;
154  }
155 
156  std::string Path = Args.getLastArgValue(OPT_l);
157  if (Path.empty())
158  Path = getImplibPath(Def->OutputFile);
159 
160  if (Machine == IMAGE_FILE_MACHINE_I386 && Args.getLastArg(OPT_k)) {
161  for (COFFShortExport& E : Def->Exports) {
162  if (!E.AliasTarget.empty() || (!E.Name.empty() && E.Name[0] == '?'))
163  continue;
164  E.SymbolName = E.Name;
165  // Trim off the trailing decoration. Symbols will always have a
166  // starting prefix here (either _ for cdecl/stdcall, @ for fastcall
167  // or ? for C++ functions). Vectorcall functions won't have any
168  // fixed prefix, but the function base name will still be at least
169  // one char.
170  E.Name = E.Name.substr(0, E.Name.find('@', 1));
171  // By making sure E.SymbolName != E.Name for decorated symbols,
172  // writeImportLibrary writes these symbols with the type
173  // IMPORT_NAME_UNDECORATE.
174  }
175  }
176 
177  if (writeImportLibrary(Def->OutputFile, Path, Def->Exports, Machine, true))
178  return 1;
179  return 0;
180 }
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.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
std::string Name
The name of the export as specified in the .def file or on the command line, i.e. ...
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
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:67
Expected< COFFModuleDefinition > parseCOFFModuleDefinition(MemoryBufferRef MB, COFF::MachineTypes Machine, bool MingwDef=false)
const char * getArgString(unsigned Index) const override
getArgString - Return the input argument string at Index.
Definition: ArgList.h:411
static MachineTypes getEmulation(StringRef S)
MachineTypes
Definition: COFF.h:93
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:80
int dlltoolDriverMain(ArrayRef< const char *> ArgsArr)
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:266
Error writeImportLibrary(StringRef ImportName, StringRef Path, ArrayRef< COFFShortExport > Exports, COFF::MachineTypes Machine, bool MinGW)
bool hasArg(OptSpecifiers ...Ids) const
Definition: ArgList.h:244
std::string AliasTarget
Creates a weak alias.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:365
void append(in_iter S, in_iter E)
Append from an iterator pair.
Definition: SmallString.h:74
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
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:42
Provide access to the Option info table.
Definition: OptTable.h:38
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::error_code getError() const
Definition: ErrorOr.h:159
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Arg * getLastArg(OptSpecifiers ...Ids) const
Return the last argument matching Id, or null.
Definition: ArgList.h:250
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
Defines the llvm::Arg class for parsed arguments.
static std::string getImplibPath(StringRef Path)
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
StringRef getLastArgValue(OptSpecifier Id, StringRef Default="") const
getLastArgValue - Return the value of the last argument, or a default.
Definition: ArgList.cpp:86
std::string SymbolName
The real, mangled symbol name from the object file.
Entry for a single option instance in the option data table.
Definition: OptTable.h:41
static std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
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.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
const char * getValue(unsigned N=0) const
Definition: Arg.h:113
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:93
constexpr char Args[]
Key for Kernel::Metadata::mArgs.