LLVM 17.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"
20#include "llvm/Option/Option.h"
21#include "llvm/Support/Path.h"
23
24#include <optional>
25#include <vector>
26
27using namespace llvm;
28using namespace llvm::object;
29using namespace llvm::COFF;
30
31namespace {
32
33enum {
34 OPT_INVALID = 0,
35#define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
36#include "Options.inc"
37#undef OPTION
38};
39
40#define PREFIX(NAME, VALUE) \
41 static constexpr StringLiteral NAME##_init[] = VALUE; \
42 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \
43 std::size(NAME##_init) - 1);
44#include "Options.inc"
45#undef PREFIX
46
47static constexpr opt::OptTable::Info InfoTable[] = {
48#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
49 {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
50 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
51#include "Options.inc"
52#undef OPTION
53};
54
55class DllOptTable : public opt::GenericOptTable {
56public:
57 DllOptTable() : opt::GenericOptTable(InfoTable, false) {}
58};
59
60// Opens a file. Path has to be resolved already.
61std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
63
64 if (std::error_code EC = MB.getError()) {
65 llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
66 return nullptr;
67 }
68
69 return std::move(*MB);
70}
71
72MachineTypes getEmulation(StringRef S) {
75 .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
79}
80
81MachineTypes getMachine(Triple T) {
82 switch (T.getArch()) {
83 case Triple::x86:
85 case Triple::x86_64:
87 case Triple::arm:
89 case Triple::aarch64:
91 default:
93 }
94}
95
96MachineTypes getDefaultMachine() {
97 return getMachine(Triple(sys::getDefaultTargetTriple()));
98}
99
100std::optional<std::string> getPrefix(StringRef Argv0) {
101 StringRef ProgName = llvm::sys::path::stem(Argv0);
102 // x86_64-w64-mingw32-dlltool -> x86_64-w64-mingw32
103 // llvm-dlltool -> None
104 // aarch64-w64-mingw32-llvm-dlltool-10.exe -> aarch64-w64-mingw32
105 ProgName = ProgName.rtrim("0123456789.-");
106 if (!ProgName.consume_back_insensitive("dlltool"))
107 return std::nullopt;
108 ProgName.consume_back_insensitive("llvm-");
109 ProgName.consume_back_insensitive("-");
110 return ProgName.str();
111}
112
113} // namespace
114
116 DllOptTable Table;
117 unsigned MissingIndex;
118 unsigned MissingCount;
120 Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
121 if (MissingCount) {
122 llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
123 return 1;
124 }
125
126 // Handle when no input or output is specified
127 if (Args.hasArgNoClaim(OPT_INPUT) ||
128 (!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l))) {
129 Table.printHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool",
130 false);
131 llvm::outs() << "\nTARGETS: i386, i386:x86-64, arm, arm64\n";
132 return 1;
133 }
134
135 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
136 llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
137 << "\n";
138
139 if (!Args.hasArg(OPT_d)) {
140 llvm::errs() << "no definition file specified\n";
141 return 1;
142 }
143
144 std::unique_ptr<MemoryBuffer> MB =
145 openFile(Args.getLastArg(OPT_d)->getValue());
146 if (!MB)
147 return 1;
148
149 if (!MB->getBufferSize()) {
150 llvm::errs() << "definition file empty\n";
151 return 1;
152 }
153
154 COFF::MachineTypes Machine = getDefaultMachine();
155 if (std::optional<std::string> Prefix = getPrefix(ArgsArr[0])) {
156 Triple T(*Prefix);
157 if (T.getArch() != Triple::UnknownArch)
158 Machine = getMachine(T);
159 }
160 if (auto *Arg = Args.getLastArg(OPT_m))
161 Machine = getEmulation(Arg->getValue());
162
163 if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
164 llvm::errs() << "unknown target\n";
165 return 1;
166 }
167
169 parseCOFFModuleDefinition(*MB, Machine, true);
170
171 if (!Def) {
172 llvm::errs() << "error parsing definition\n"
173 << errorToErrorCode(Def.takeError()).message();
174 return 1;
175 }
176
177 // Do this after the parser because parseCOFFModuleDefinition sets OutputFile.
178 if (auto *Arg = Args.getLastArg(OPT_D))
179 Def->OutputFile = Arg->getValue();
180
181 if (Def->OutputFile.empty()) {
182 llvm::errs() << "no DLL name specified\n";
183 return 1;
184 }
185
186 std::string Path = std::string(Args.getLastArgValue(OPT_l));
187
188 // If ExtName is set (if the "ExtName = Name" syntax was used), overwrite
189 // Name with ExtName and clear ExtName. When only creating an import
190 // library and not linking, the internal name is irrelevant. This avoids
191 // cases where writeImportLibrary tries to transplant decoration from
192 // symbol decoration onto ExtName.
193 for (COFFShortExport& E : Def->Exports) {
194 if (!E.ExtName.empty()) {
195 E.Name = E.ExtName;
196 E.ExtName.clear();
197 }
198 }
199
200 if (Machine == IMAGE_FILE_MACHINE_I386 && Args.getLastArg(OPT_k)) {
201 for (COFFShortExport& E : Def->Exports) {
202 if (!E.AliasTarget.empty() || (!E.Name.empty() && E.Name[0] == '?'))
203 continue;
204 E.SymbolName = E.Name;
205 // Trim off the trailing decoration. Symbols will always have a
206 // starting prefix here (either _ for cdecl/stdcall, @ for fastcall
207 // or ? for C++ functions). Vectorcall functions won't have any
208 // fixed prefix, but the function base name will still be at least
209 // one char.
210 E.Name = E.Name.substr(0, E.Name.find('@', 1));
211 // By making sure E.SymbolName != E.Name for decorated symbols,
212 // writeImportLibrary writes these symbols with the type
213 // IMPORT_NAME_UNDECORATE.
214 }
215 }
216
217 if (!Path.empty() &&
218 writeImportLibrary(Def->OutputFile, Path, Def->Exports, Machine, true))
219 return 1;
220 return 0;
221}
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
arm prera ldst opt
Defines the llvm::Arg class for parsed arguments.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition: LibDriver.cpp:97
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:193
Represents either an error or a value T.
Definition: ErrorOr.h:56
std::error_code getError() const
Definition: ErrorOr.h:153
Tagged union holding either a T or a Error.
Definition: Error.h:470
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:50
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:222
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
Definition: StringRef.h:790
bool consume_back_insensitive(StringRef Suffix)
Returns true if this StringRef has the given suffix, ignoring case, and removes that suffix.
Definition: StringRef.h:652
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
Specialization of OptTable.
Definition: OptTable.h:267
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_I386
Definition: COFF.h:103
@ IMAGE_FILE_MACHINE_ARMNT
Definition: COFF.h:99
Expected< COFFModuleDefinition > parseCOFFModuleDefinition(MemoryBufferRef MB, COFF::MachineTypes Machine, bool MingwDef=false)
Error writeImportLibrary(StringRef ImportName, StringRef Path, ArrayRef< COFFShortExport > Exports, COFF::MachineTypes Machine, bool MinGW)
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
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:98
Entry for a single option instance in the option data table.
Definition: OptTable.h:43