1 //===- DlltoolDriver.cpp - dlltool.exe-compatible driver ------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Defines an interface to a dlltool.exe-compatible driver.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/Object/COFF.h"
16 #include "llvm/Object/COFFImportFile.h"
17 #include "llvm/Object/COFFModuleDefinition.h"
18 #include "llvm/Option/Arg.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Option/OptTable.h"
21 #include "llvm/Option/Option.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/TargetParser/Host.h"
29 using namespace llvm::object
;
30 using namespace llvm::COFF
;
34 #define OPTTABLE_STR_TABLE_CODE
35 #include "Options.inc"
36 #undef OPTTABLE_STR_TABLE_CODE
40 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
41 #include "Options.inc"
45 #define OPTTABLE_PREFIXES_TABLE_CODE
46 #include "Options.inc"
47 #undef OPTTABLE_PREFIXES_TABLE_CODE
49 using namespace llvm::opt
;
50 static constexpr opt::OptTable::Info InfoTable
[] = {
51 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
52 #include "Options.inc"
56 class DllOptTable
: public opt::GenericOptTable
{
59 : opt::GenericOptTable(OptionStrTable
, OptionPrefixesTable
, InfoTable
,
63 // Opens a file. Path has to be resolved already.
64 std::unique_ptr
<MemoryBuffer
> openFile(const Twine
&Path
) {
65 ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> MB
= MemoryBuffer::getFile(Path
);
67 if (std::error_code EC
= MB
.getError()) {
68 llvm::errs() << "cannot open file " << Path
<< ": " << EC
.message() << "\n";
72 return std::move(*MB
);
75 MachineTypes
getEmulation(StringRef S
) {
76 return StringSwitch
<MachineTypes
>(S
)
77 .Case("i386", IMAGE_FILE_MACHINE_I386
)
78 .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64
)
79 .Case("arm", IMAGE_FILE_MACHINE_ARMNT
)
80 .Case("arm64", IMAGE_FILE_MACHINE_ARM64
)
81 .Case("arm64ec", IMAGE_FILE_MACHINE_ARM64EC
)
82 .Default(IMAGE_FILE_MACHINE_UNKNOWN
);
85 MachineTypes
getMachine(Triple T
) {
86 switch (T
.getArch()) {
88 return COFF::IMAGE_FILE_MACHINE_I386
;
90 return COFF::IMAGE_FILE_MACHINE_AMD64
;
92 return COFF::IMAGE_FILE_MACHINE_ARMNT
;
94 return T
.isWindowsArm64EC() ? COFF::IMAGE_FILE_MACHINE_ARM64EC
95 : COFF::IMAGE_FILE_MACHINE_ARM64
;
97 return COFF::IMAGE_FILE_MACHINE_UNKNOWN
;
101 MachineTypes
getDefaultMachine() {
102 return getMachine(Triple(sys::getDefaultTargetTriple()));
105 std::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"))
113 ProgName
.consume_back_insensitive("llvm-");
114 ProgName
.consume_back_insensitive("-");
115 return ProgName
.str();
118 bool parseModuleDefinition(StringRef DefFileName
, MachineTypes Machine
,
120 std::vector
<COFFShortExport
> &Exports
,
121 std::string
&OutputFile
) {
122 std::unique_ptr
<MemoryBuffer
> MB
= openFile(DefFileName
);
126 if (!MB
->getBufferSize()) {
127 llvm::errs() << "definition file empty\n";
131 Expected
<COFFModuleDefinition
> Def
= parseCOFFModuleDefinition(
132 *MB
, Machine
, /*MingwDef=*/true, AddUnderscores
);
134 llvm::errs() << "error parsing definition\n"
135 << errorToErrorCode(Def
.takeError()).message() << "\n";
139 if (OutputFile
.empty())
140 OutputFile
= std::move(Def
->OutputFile
);
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()) {
154 Exports
= std::move(Def
->Exports
);
160 int llvm::dlltoolDriverMain(llvm::ArrayRef
<const char *> ArgsArr
) {
162 unsigned MissingIndex
;
163 unsigned MissingCount
;
164 llvm::opt::InputArgList Args
=
165 Table
.ParseArgs(ArgsArr
.slice(1), MissingIndex
, MissingCount
);
167 llvm::errs() << Args
.getArgString(MissingIndex
) << ": missing argument\n";
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",
176 llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64, arm64ec\n";
180 for (auto *Arg
: Args
.filtered(OPT_UNKNOWN
))
181 llvm::errs() << "ignoring unknown argument: " << Arg
->getAsString(Args
)
184 if (!Args
.hasArg(OPT_d
)) {
185 llvm::errs() << "no definition file specified\n";
189 COFF::MachineTypes Machine
= getDefaultMachine();
190 if (std::optional
<std::string
> Prefix
= getPrefix(ArgsArr
[0])) {
192 if (T
.getArch() != Triple::UnknownArch
)
193 Machine
= getMachine(T
);
195 if (auto *Arg
= Args
.getLastArg(OPT_m
))
196 Machine
= getEmulation(Arg
->getValue());
198 if (Machine
== IMAGE_FILE_MACHINE_UNKNOWN
) {
199 llvm::errs() << "unknown target\n";
203 bool AddUnderscores
= !Args
.hasArg(OPT_no_leading_underscore
);
205 std::string OutputFile
;
206 if (auto *Arg
= Args
.getLastArg(OPT_D
))
207 OutputFile
= Arg
->getValue();
209 std::vector
<COFFShortExport
> Exports
, NativeExports
;
211 if (Args
.hasArg(OPT_N
)) {
212 if (!isArm64EC(Machine
)) {
213 llvm::errs() << "native .def file is supported only on arm64ec target\n";
216 if (!parseModuleDefinition(Args
.getLastArg(OPT_N
)->getValue(),
217 IMAGE_FILE_MACHINE_ARM64
, AddUnderscores
,
218 NativeExports
, OutputFile
))
222 if (!parseModuleDefinition(Args
.getLastArg(OPT_d
)->getValue(), Machine
,
223 AddUnderscores
, Exports
, OutputFile
))
226 if (OutputFile
.empty()) {
227 llvm::errs() << "no DLL name specified\n";
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] == '?'))
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
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.
248 std::string Path
= std::string(Args
.getLastArgValue(OPT_l
));
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";