LLVM 24.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/Archive.h"
16#include "llvm/Object/COFF.h"
19#include "llvm/Option/Arg.h"
20#include "llvm/Option/ArgList.h"
22#include "llvm/Option/Option.h"
23#include "llvm/Support/Path.h"
25
26#include <optional>
27#include <vector>
28
29using namespace llvm;
30using namespace llvm::object;
31using namespace llvm::COFF;
32
33namespace {
34
35enum {
36 OPT_INVALID = 0,
37#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
38#include "Options.inc"
39#undef OPTION
40};
41
42using namespace llvm::opt;
43#define OPTTABLE_CODE
44#include "Options.inc"
45
46class DllOptTable : public opt::OptTable {
47public:
48 DllOptTable() : opt::OptTable(optionTables(), false) {}
49};
50
51// Opens a file. Path has to be resolved already.
52std::unique_ptr<MemoryBuffer> openFile(const Twine &Path) {
54
55 if (std::error_code EC = MB.getError()) {
56 llvm::errs() << "cannot open file " << Path << ": " << EC.message() << "\n";
57 return nullptr;
58 }
59
60 return std::move(*MB);
61}
62
63MachineTypes getEmulation(StringRef S) {
66 .Case("i386:x86-64", IMAGE_FILE_MACHINE_AMD64)
72}
73
74MachineTypes getMachine(Triple T) {
75 switch (T.getArch()) {
76 case Triple::x86:
78 case Triple::x86_64:
80 case Triple::arm:
82 case Triple::aarch64:
83 return T.isWindowsArm64EC() ? COFF::IMAGE_FILE_MACHINE_ARM64EC
85 case Triple::mipsel:
87 default:
89 }
90}
91
92MachineTypes getDefaultMachine() {
93 return getMachine(Triple(sys::getDefaultTargetTriple()));
94}
95
96std::optional<std::string> getPrefix(StringRef Argv0) {
97 StringRef ProgName = llvm::sys::path::stem(Argv0);
98 // x86_64-w64-mingw32-dlltool -> x86_64-w64-mingw32
99 // llvm-dlltool -> None
100 // aarch64-w64-mingw32-llvm-dlltool-10.exe -> aarch64-w64-mingw32
101 ProgName = ProgName.rtrim("0123456789.-");
102 if (!ProgName.consume_back_insensitive("dlltool"))
103 return std::nullopt;
104 ProgName.consume_back_insensitive("llvm-");
105 ProgName.consume_back_insensitive("-");
106 return ProgName.str();
107}
108
109bool parseModuleDefinition(StringRef DefFileName, MachineTypes Machine,
110 bool AddUnderscores,
111 std::vector<COFFShortExport> &Exports,
112 std::string &OutputFile) {
113 std::unique_ptr<MemoryBuffer> MB = openFile(DefFileName);
114 if (!MB)
115 return false;
116
117 if (!MB->getBufferSize()) {
118 llvm::errs() << "definition file empty\n";
119 return false;
120 }
121
123 *MB, Machine, /*MingwDef=*/true, AddUnderscores);
124 if (!Def) {
125 llvm::errs() << "error parsing definition\n"
126 << errorToErrorCode(Def.takeError()).message() << "\n";
127 return false;
128 }
129
130 if (OutputFile.empty())
131 OutputFile = std::move(Def->OutputFile);
132
133 // If ExtName is set (if the "ExtName = Name" syntax was used), overwrite
134 // Name with ExtName and clear ExtName. When only creating an import
135 // library and not linking, the internal name is irrelevant. This avoids
136 // cases where writeImportLibrary tries to transplant decoration from
137 // symbol decoration onto ExtName.
138 for (COFFShortExport &E : Def->Exports) {
139 if (!E.ExtName.empty()) {
140 E.Name = E.ExtName;
141 E.ExtName.clear();
142 }
143 }
144
145 Exports = std::move(Def->Exports);
146 return true;
147}
148
149int printError(llvm::Error E, Twine File) {
150 if (!E)
151 return 0;
152 handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EIB) {
153 llvm::errs() << "error opening " << File << ": " << EIB.message() << "\n";
154 });
155 return 1;
156}
157
158template <typename Callable>
159int forEachCoff(object::Archive &Archive, StringRef Name, Callable Callback) {
160 Error Err = Error::success();
161 for (auto &C : Archive.children(Err)) {
162 Expected<StringRef> NameOrErr = C.getName();
163 if (!NameOrErr)
164 return printError(NameOrErr.takeError(), Name);
165 StringRef Name = *NameOrErr;
166
167 Expected<MemoryBufferRef> ChildMB = C.getMemoryBufferRef();
168 if (!ChildMB)
169 return printError(ChildMB.takeError(), Name);
170
171 if (identify_magic(ChildMB->getBuffer()) == file_magic::coff_object) {
172 auto Obj = object::COFFObjectFile::create(*ChildMB);
173 if (!Obj)
174 return printError(Obj.takeError(), Name);
175 if (!Callback(*Obj->get(), Name))
176 return 1;
177 }
178 }
179 if (Err)
180 return printError(std::move(Err), Name);
181 return 0;
182}
183
184// To find the named of the imported DLL from an import library, we can either
185// inspect the object files that form the import table entries, or we could
186// just look at the archive member names, for MSVC style import libraries.
187// Looking at the archive member names doesn't work for GNU style import
188// libraries though, while inspecting the import table entries works for
189// both. (MSVC style import libraries contain a couple regular object files
190// for the header/trailers.)
191//
192// This implementation does the same as GNU dlltool does; look at the
193// content of ".idata$7" sections, or for MSVC style libraries, look
194// at ".idata$6" sections.
195//
196// For GNU style import libraries, there are also other data chunks in sections
197// named ".idata$7" (entries to the IAT or ILT); these are distinguished
198// by seeing that they contain relocations. (They also look like an empty
199// string when looking for null termination.)
200//
201// Alternatively, we could do things differently - look for any .idata$2
202// section; this would be import directory entries. At offset 0xc in them
203// there is the RVA of the import DLL name; look for a relocation at this
204// spot and locate the symbol that it points at. That symbol may either
205// be within the same object file (in the case of MSVC style import libraries)
206// or another object file (in the case of GNU import libraries).
207bool identifyImportName(const COFFObjectFile &Obj, StringRef ObjName,
208 std::vector<StringRef> &Names, bool IsMsStyleImplib) {
209 StringRef TargetName = IsMsStyleImplib ? ".idata$6" : ".idata$7";
210 for (const auto &S : Obj.sections()) {
211 Expected<StringRef> NameOrErr = S.getName();
212 if (!NameOrErr) {
213 printError(NameOrErr.takeError(), ObjName);
214 return false;
215 }
216 StringRef Name = *NameOrErr;
217 if (Name != TargetName)
218 continue;
219
220 // GNU import libraries contain .idata$7 section in the per function
221 // objects too, but they contain relocations.
222 if (!IsMsStyleImplib && !S.relocations().empty())
223 continue;
224
225 Expected<StringRef> ContentsOrErr = S.getContents();
226 if (!ContentsOrErr) {
227 printError(ContentsOrErr.takeError(), ObjName);
228 return false;
229 }
230 StringRef Contents = *ContentsOrErr;
231 Contents = Contents.substr(0, Contents.find('\0'));
232 if (Contents.empty())
233 continue;
234 Names.push_back(Contents);
235 return true;
236 }
237 return true;
238}
239
240int doIdentify(StringRef File, bool IdentifyStrict) {
242 File, /*IsText=*/false, /*RequiredNullTerminator=*/false);
243 if (!MaybeBuf)
244 return printError(errorCodeToError(MaybeBuf.getError()), File);
245 if (identify_magic(MaybeBuf.get()->getBuffer()) != file_magic::archive) {
246 llvm::errs() << File << " is not a library\n";
247 return 1;
248 }
249
250 std::unique_ptr<MemoryBuffer> B = std::move(MaybeBuf.get());
251 Error Err = Error::success();
252 object::Archive Archive(B->getMemBufferRef(), Err);
253 if (Err)
254 return printError(std::move(Err), B->getBufferIdentifier());
255
256 bool IsMsStyleImplib = false;
257 for (const auto &S : Archive.symbols()) {
258 if (S.getName() == "__NULL_IMPORT_DESCRIPTOR") {
259 IsMsStyleImplib = true;
260 break;
261 }
262 }
263 std::vector<StringRef> Names;
264 if (forEachCoff(Archive, B->getBufferIdentifier(),
265 [&](const COFFObjectFile &Obj, StringRef ObjName) -> bool {
266 return identifyImportName(Obj, ObjName, Names,
267 IsMsStyleImplib);
268 }))
269 return 1;
270
271 if (Names.empty()) {
272 llvm::errs() << "No DLL import name found in " << File << "\n";
273 return 1;
274 }
275 if (Names.size() > 1 && IdentifyStrict) {
276 llvm::errs() << File << "contains imports for two or more DLLs\n";
277 return 1;
278 }
279
280 for (StringRef S : Names)
281 llvm::outs() << S << "\n";
282
283 return 0;
284}
285
286} // namespace
287
289 DllOptTable Table;
290 unsigned MissingIndex;
291 unsigned MissingCount;
293 Table.ParseArgs(ArgsArr.slice(1), MissingIndex, MissingCount);
294 if (MissingCount) {
295 llvm::errs() << Args.getArgString(MissingIndex) << ": missing argument\n";
296 return 1;
297 }
298
299 // Handle when no input or output is specified
300 if (Args.hasArgNoClaim(OPT_INPUT) ||
301 (!Args.hasArgNoClaim(OPT_d) && !Args.hasArgNoClaim(OPT_l) &&
302 !Args.hasArgNoClaim(OPT_I))) {
303 Table.printHelp(outs(), "llvm-dlltool [options] file...", "llvm-dlltool",
304 false);
305 llvm::outs()
306 << "\nTARGETS: i386, i386:x86-64, arm, arm64, arm64ec, r4000\n";
307 return 1;
308 }
309
310 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
311 llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
312 << "\n";
313
314 if (Args.hasArg(OPT_I)) {
315 return doIdentify(Args.getLastArg(OPT_I)->getValue(),
316 Args.hasArg(OPT_identify_strict));
317 }
318
319 if (!Args.hasArg(OPT_d)) {
320 llvm::errs() << "no definition file specified\n";
321 return 1;
322 }
323
324 COFF::MachineTypes Machine = getDefaultMachine();
325 if (std::optional<std::string> Prefix = getPrefix(ArgsArr[0])) {
326 Triple T(*Prefix);
327 if (T.getArch() != Triple::UnknownArch)
328 Machine = getMachine(T);
329 }
330 if (auto *Arg = Args.getLastArg(OPT_m))
331 Machine = getEmulation(Arg->getValue());
332
334 llvm::errs() << "unknown target\n";
335 return 1;
336 }
337
338 bool AddUnderscores = !Args.hasArg(OPT_no_leading_underscore);
339
340 std::string OutputFile;
341 if (auto *Arg = Args.getLastArg(OPT_D))
342 OutputFile = Arg->getValue();
343
344 std::vector<COFFShortExport> Exports, NativeExports;
345
346 if (Args.hasArg(OPT_N)) {
347 if (!isArm64EC(Machine)) {
348 llvm::errs() << "native .def file is supported only on arm64ec target\n";
349 return 1;
350 }
351 if (!parseModuleDefinition(Args.getLastArg(OPT_N)->getValue(),
352 IMAGE_FILE_MACHINE_ARM64, AddUnderscores,
353 NativeExports, OutputFile))
354 return 1;
355 }
356
357 if (!parseModuleDefinition(Args.getLastArg(OPT_d)->getValue(), Machine,
358 AddUnderscores, Exports, OutputFile))
359 return 1;
360
361 if (OutputFile.empty()) {
362 llvm::errs() << "no DLL name specified\n";
363 return 1;
364 }
365
366 if (Machine == IMAGE_FILE_MACHINE_I386 && Args.hasArg(OPT_k)) {
367 for (COFFShortExport &E : Exports) {
368 if (!E.ImportName.empty() || (!E.Name.empty() && E.Name[0] == '?'))
369 continue;
370 E.SymbolName = E.Name;
371 // Trim off the trailing decoration. Symbols will always have a
372 // starting prefix here (either _ for cdecl/stdcall, @ for fastcall
373 // or ? for C++ functions). Vectorcall functions won't have any
374 // fixed prefix, but the function base name will still be at least
375 // one char.
376 E.Name = E.Name.substr(0, E.Name.find('@', 1));
377 // By making sure E.SymbolName != E.Name for decorated symbols,
378 // writeImportLibrary writes these symbols with the type
379 // IMPORT_NAME_UNDECORATE.
380 }
381 }
382
383 std::string Path = std::string(Args.getLastArgValue(OPT_l));
384 if (!Path.empty()) {
385 if (Error E = writeImportLibrary(OutputFile, Path, Exports, Machine,
386 /*MinGW=*/true, NativeExports)) {
387 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
388 llvm::errs() << EI.message() << "\n";
389 });
390 return 1;
391 }
392 }
393 return 0;
394}
Defines the llvm::Arg class for parsed arguments.
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
std::unique_ptr< MemoryBuffer > openFile(const Twine &Path)
Definition LibDriver.cpp:87
#define T
Function const char TargetMachine * Machine
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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:185
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
Represents either an error or a value T.
Definition ErrorOr.h:56
reference get()
Definition ErrorOr.h:149
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
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,...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef rtrim(char Char) const
Return string with consecutive Char characters starting from the right removed.
Definition StringRef.h:838
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool consume_back_insensitive(StringRef Suffix)
Returns true if this StringRef has the given suffix, ignoring case, and removes that suffix.
Definition StringRef.h:701
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ UnknownArch
Definition Triple.h:51
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
iterator_range< symbol_iterator > symbols() const
Definition Archive.h:423
iterator_range< child_iterator > children(Error &Err, bool SkipInternal=true) const
Definition Archive.h:416
static Expected< std::unique_ptr< COFFObjectFile > > create(MemoryBufferRef Object)
A concrete instance of a particular driver option.
Definition Arg.h:35
LLVM_ABI std::string getAsString(const ArgList &Args) const
Return a formatted version of the argument and its values, for diagnostics.
Definition Arg.cpp:67
const char * getValue(unsigned N=0) const
Definition Arg.h:127
Provide access to the Option info table.
Definition OptTable.h:54
MachineTypes
Definition COFF.h:93
@ IMAGE_FILE_MACHINE_ARM64
Definition COFF.h:101
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition COFF.h:96
@ IMAGE_FILE_MACHINE_AMD64
Definition COFF.h:98
@ IMAGE_FILE_MACHINE_ARM64EC
Definition COFF.h:102
@ IMAGE_FILE_MACHINE_R4000
Definition COFF.h:113
@ IMAGE_FILE_MACHINE_I386
Definition COFF.h:105
@ IMAGE_FILE_MACHINE_ARMNT
Definition COFF.h:100
bool isArm64EC(T Machine)
Definition COFF.h:125
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Transport.h:132
LLVM_ABI Expected< COFFModuleDefinition > parseCOFFModuleDefinition(MemoryBufferRef MB, COFF::MachineTypes Machine, bool MingwDef=false, bool AddUnderscores=true)
LLVM_ABI 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.
NodeAddr< DefNode * > Def
Definition RDFGraph.h:384
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:596
LLVM_ABI 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.
LLVM_ABI file_magic identify_magic(StringRef magic)
Identify the type of a binary file based on how magical it is.
Definition Magic.cpp:33
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:1013
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
LLVM_ABI int dlltoolDriverMain(ArrayRef< const char * > ArgsArr)
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
@ archive
ar style archive file
Definition Magic.h:26
@ coff_object
COFF object file.
Definition Magic.h:48