LLVM 20.0.0git
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
15#include "llvm/Object/COFF.h"
18#include "llvm/Option/Arg.h"
19#include "llvm/Option/ArgList.h"
21#include "llvm/Option/Option.h"
22#include "llvm/Support/Path.h"
24
25#include <optional>
26#include <vector>
27
28using namespace llvm;
29using namespace llvm::object;
30using namespace llvm::COFF;
31
32namespace {
33
34#define OPTTABLE_STR_TABLE_CODE
35#include "Options.inc"
36#undef OPTTABLE_STR_TABLE_CODE
37
38enum {
39 OPT_INVALID = 0,
40#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
41#include "Options.inc"
42#undef OPTION
43};
44
45#define OPTTABLE_PREFIXES_TABLE_CODE
46#include "Options.inc"
47#undef OPTTABLE_PREFIXES_TABLE_CODE
48
49using namespace llvm::opt;
50static constexpr opt::OptTable::Info InfoTable[] = {
51#define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
52#include "Options.inc"
53#undef OPTION
54};
55
56class DllOptTable : public opt::GenericOptTable {
57public:
58 DllOptTable()
59 : opt::GenericOptTable(OptionStrTable, OptionPrefixesTable, InfoTable,
60 false) {}
61};
62
63// Opens a file. Path has to be resolved already.
64std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
66
67 if (std::error_code EC = MB.getError()) {
68 llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
69 return nullptr;
70 }
71
72 return std::move(*MB);
73}
74
75MachineTypes getEmulation(StringRef S) {
78 .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
83}
84
85MachineTypes getMachine(Triple T) {
86 switch (T.getArch()) {
87 case Triple::x86:
89 case Triple::x86_64:
91 case Triple::arm:
93 case Triple::aarch64:
94 return T.isWindowsArm64EC() ? COFF::IMAGE_FILE_MACHINE_ARM64EC
96 default:
98 }
99}
100
101MachineTypes getDefaultMachine() {
102 return getMachine(Triple(sys::getDefaultTargetTriple()));
103}
104
105std::optional<std::string> getPrefix(StringRef Argv0) {
106 StringRef ProgName = llvm::sys::path::stem(Argv0);
107 // x86_64-w64-mingw32-dlltool -> x86_64-w64-mingw32
108 // llvm-dlltool -> None
109 // aarch64-w64-mingw32-llvm-dlltool-10.exe -> aarch64-w64-mingw32
110 ProgName = ProgName.rtrim("0123456789.-");
111 if (!ProgName.consume_back_insensitive("dlltool"))
112 return std::nullopt;
113 ProgName.consume_back_insensitive("llvm-");
114 ProgName.consume_back_insensitive("-");
115 return ProgName.str();
116}
117
118bool parseModuleDefinition(StringRef DefFileName, MachineTypes Machine,
119 bool AddUnderscores,
120 std::vector<COFFShortExport> &Exports,
121 std::string &OutputFile) {
122 std::unique_ptr<MemoryBuffer> MB = openFile(DefFileName);
123 if (!MB)
124 return false;
125
126 if (!MB->getBufferSize()) {
127 llvm::errs() << "definition file empty\n";
128 return false;
129 }
130
132 *MB, Machine, /*MingwDef=*/true, AddUnderscores);
133 if (!Def) {
134 llvm::errs() << "error parsing definition\n"
135 << errorToErrorCode(Def.takeError()).message() << "\n";
136 return false;
137 }
138
139 if (OutputFile.empty())
140 OutputFile = std::move(Def->OutputFile);
141
142 // If ExtName is set (if the "ExtName = Name" syntax was used), overwrite
143 // Name with ExtName and clear ExtName. When only creating an import
144 // library and not linking, the internal name is irrelevant. This avoids
145 // cases where writeImportLibrary tries to transplant decoration from
146 // symbol decoration onto ExtName.
147 for (COFFShortExport &E : Def->Exports) {
148 if (!E.ExtName.empty()) {
149 E.Name = E.ExtName;
150 E.ExtName.clear();
151 }
152 }
153
154 Exports = std::move(Def->Exports);
155 return true;
156}
157
158} // namespace
159
161 DllOptTable Table;
162 unsigned MissingIndex;
163 unsigned MissingCount;
165 Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
166 if (MissingCount) {
167 llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
168 return 1;
169 }
170
171 // Handle when no input or output is specified
172 if (Args.hasArgNoClaim(OPT_INPUT) ||
173 (!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) {
174 Table.printHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool",
175 false);
176 llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64, arm64ec\n";
177 return 1;
178 }
179
180 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
181 llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
182 << "\n";
183
184 if (!Args.hasArg(OPT_d)) {
185 llvm::errs() << "no definition file specified\n";
186 return 1;
187 }
188
189 COFF::MachineTypes Machine = getDefaultMachine();
190 if (std::optional<std::string> Prefix = getPrefix(ArgsArr[0])) {
191 Triple T(*Prefix);
192 if (T.getArch() != Triple::UnknownArch)
193 Machine = getMachine(T);
194 }
195 if (auto *Arg = Args.getLastArg(OPT_m))
196 Machine = getEmulation(Arg->getValue());
197
199 llvm::errs() << "unknown target\n";
200 return 1;
201 }
202
203 bool AddUnderscores = !Args.hasArg(OPT_no_leading_underscore);
204
205 std::string OutputFile;
206 if (auto *Arg = Args.getLastArg(OPT_D))
207 OutputFile = Arg->getValue();
208
209 std::vector<COFFShortExport> Exports, NativeExports;
210
211 if (Args.hasArg(OPT_N)) {
212 if (!isArm64EC(Machine)) {
213 llvm::errs() << "native .def file is supported only on arm64ec target\n";
214 return 1;
215 }
216 if (!parseModuleDefinition(Args.getLastArg(OPT_N)->getValue(),
217 IMAGE_FILE_MACHINE_ARM64, AddUnderscores,
218 NativeExports, OutputFile))
219 return 1;
220 }
221
222 if (!parseModuleDefinition(Args.getLastArg(OPT_d)->getValue(), Machine,
223 AddUnderscores, Exports, OutputFile))
224 return 1;
225
226 if (OutputFile.empty()) {
227 llvm::errs() << "no DLL name specified\n";
228 return 1;
229 }
230
231 if (Machine == IMAGE_FILE_MACHINE_I386 && Args.hasArg(OPT_k)) {
232 for (COFFShortExport &E : Exports) {
233 if (!E.ImportName.empty() || (!E.Name.empty() && E.Name[0] == '?'))
234 continue;
235 E.SymbolName = E.Name;
236 // Trim off the trailing decoration. Symbols will always have a
237 // starting prefix here (either _ for cdecl/stdcall, @ for fastcall
238 // or ? for C++ functions). Vectorcall functions won't have any
239 // fixed prefix, but the function base name will still be at least
240 // one char.
241 E.Name = E.Name.substr(0, E.Name.find('@', 1));
242 // By making sure E.SymbolName != E.Name for decorated symbols,
243 // writeImportLibrary writes these symbols with the type
244 // IMPORT_NAME_UNDECORATE.
245 }
246 }
247
248 std::string Path = std::string(Args.getLastArgValue(OPT_l));
249 if (!Path.empty()) {
250 if (Error E = writeImportLibrary(OutputFile, Path, Exports, Machine,
251 /*MinGW=*/true, NativeExports)) {
252 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
253 llvm::errs() << EI.message() << "\n";
254 });
255 return 1;
256 }
257 }
258 return 0;
259}
arm prera ldst opt
Defines the llvm::Arg class for parsed arguments.
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:390
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition: LibDriver.cpp:100
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
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:198
Base class for error info classes.
Definition: Error.h:45
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:53
Represents either an error or a value T.
Definition: ErrorOr.h:56
std::error_code getError() const
Definition: ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
Tagged union holding either a T or a Error.
Definition: Error.h:481
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:229
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
Definition: StringRef.h:803
bool consume_back_insensitive(StringRef Suffix)
Returns true if this StringRef has the given suffix, ignoring case, and removes that suffix.
Definition: StringRef.h:665
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ UnknownArch
Definition: Triple.h:47
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
A concrete instance of a particular driver option.
Definition: Arg.h:34
std::string getAsString(const ArgList &Args) const
Return a formatted version of the argument and its values, for diagnostics.
Definition: Arg.cpp:66
const char * getValue(unsigned N=0) const
Definition: Arg.h:125
Specialization of OptTable.
Definition: OptTable.h:419
MachineTypes
Definition: COFF.h:92
@ IMAGE_FILE_MACHINE_ARM64
Definition: COFF.h:100
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition: COFF.h:95
@ IMAGE_FILE_MACHINE_AMD64
Definition: COFF.h:97
@ IMAGE_FILE_MACHINE_ARM64EC
Definition: COFF.h:101
@ IMAGE_FILE_MACHINE_I386
Definition: COFF.h:104
@ IMAGE_FILE_MACHINE_ARMNT
Definition: COFF.h:99
bool isArm64EC(T Machine)
Definition: COFF.h:124
Expected< COFFModuleDefinition > parseCOFFModuleDefinition(MemoryBufferRef MB, COFF::MachineTypes Machine, bool MingwDef=false, bool AddUnderscores=true)
Error writeImportLibrary(StringRef ImportName, StringRef Path, ArrayRef< COFFShortExport > Exports, COFF::MachineTypes Machine, bool MinGW, ArrayRef< COFFShortExport > NativeExports={})
Writes a COFF import library containing entries described by the Exports array.
Definition: Arg.h:26
NodeAddr< DefNode * > Def
Definition: RDFGraph.h:384
StringRef stem(StringRef path, Style style=Style::native)
Get stem.
Definition: Path.cpp:579
std::string getDefaultTargetTriple()
getDefaultTargetTriple() - Return the default target triple the compiler has been configured to produ...
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:977
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
int dlltoolDriverMain(ArrayRef< const char * > ArgsArr)
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition: Error.cpp:117
std::string Name
The name of the export as specified in the .def file or on the command line, i.e.
std::string SymbolName
The real, mangled symbol name from the object file.
std::string ImportName
Creates an import library entry that imports from a DLL export with a different name.
std::string ExtName
The external, exported name.
Entry for a single option instance in the option data table.
Definition: OptTable.h:55