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
13#include "llvm/ToolDrivers/llvm-dlltool/DlltoolDriver.h"
14#include "llvm/ADT/StringSwitch.h"
15#include "llvm/Object/Archive.h"
16#include "llvm/Object/COFF.h"
17#include "llvm/Object/COFFImportFile.h"
18#include "llvm/Object/COFFModuleDefinition.h"
19#include "llvm/Option/Arg.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/Option/OptTable.h"
22#include "llvm/Option/Option.h"
23#include "llvm/Support/Path.h"
24#include "llvm/TargetParser/Host.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) {
53 ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MB = MemoryBuffer::getFile(Filename: 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) {
64 return StringSwitch<MachineTypes>(S)
65 .Case(S: "i386", Value: IMAGE_FILE_MACHINE_I386)
66 .Case(S: "i386:x86-64", Value: IMAGE_FILE_MACHINE_AMD64)
67 .Case(S: "arm", Value: IMAGE_FILE_MACHINE_ARMNT)
68 .Case(S: "arm64", Value: IMAGE_FILE_MACHINE_ARM64)
69 .Case(S: "arm64ec", Value: IMAGE_FILE_MACHINE_ARM64EC)
70 .Case(S: "r4000", Value: IMAGE_FILE_MACHINE_R4000)
71 .Default(Value: IMAGE_FILE_MACHINE_UNKNOWN);
72}
73
74MachineTypes getMachine(Triple T) {
75 switch (T.getArch()) {
76 case Triple::x86:
77 return COFF::IMAGE_FILE_MACHINE_I386;
78 case Triple::x86_64:
79 return COFF::IMAGE_FILE_MACHINE_AMD64;
80 case Triple::arm:
81 return COFF::IMAGE_FILE_MACHINE_ARMNT;
82 case Triple::aarch64:
83 return T.isWindowsArm64EC() ? COFF::IMAGE_FILE_MACHINE_ARM64EC
84 : COFF::IMAGE_FILE_MACHINE_ARM64;
85 case Triple::mipsel:
86 return COFF::IMAGE_FILE_MACHINE_R4000;
87 default:
88 return COFF::IMAGE_FILE_MACHINE_UNKNOWN;
89 }
90}
91
92MachineTypes getDefaultMachine() {
93 return getMachine(T: Triple(sys::getDefaultTargetTriple()));
94}
95
96std::optional<std::string> getPrefix(StringRef Argv0) {
97 StringRef ProgName = llvm::sys::path::stem(path: 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(Chars: "0123456789.-");
102 if (!ProgName.consume_back_insensitive(Suffix: "dlltool"))
103 return std::nullopt;
104 ProgName.consume_back_insensitive(Suffix: "llvm-");
105 ProgName.consume_back_insensitive(Suffix: "-");
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(Path: DefFileName);
114 if (!MB)
115 return false;
116
117 if (!MB->getBufferSize()) {
118 llvm::errs() << "definition file empty\n";
119 return false;
120 }
121
122 Expected<COFFModuleDefinition> Def = parseCOFFModuleDefinition(
123 MB: *MB, Machine, /*MingwDef=*/true, AddUnderscores);
124 if (!Def) {
125 llvm::errs() << "error parsing definition\n"
126 << errorToErrorCode(Err: 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(E: std::move(E), Handlers: [&](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(E: NameOrErr.takeError(), File: Name);
165 StringRef Name = *NameOrErr;
166
167 Expected<MemoryBufferRef> ChildMB = C.getMemoryBufferRef();
168 if (!ChildMB)
169 return printError(E: ChildMB.takeError(), File: Name);
170
171 if (identify_magic(magic: ChildMB->getBuffer()) == file_magic::coff_object) {
172 auto Obj = object::COFFObjectFile::create(Object: *ChildMB);
173 if (!Obj)
174 return printError(E: Obj.takeError(), File: Name);
175 if (!Callback(*Obj->get(), Name))
176 return 1;
177 }
178 }
179 if (Err)
180 return printError(E: std::move(Err), File: 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(E: NameOrErr.takeError(), File: 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(E: ContentsOrErr.takeError(), File: ObjName);
228 return false;
229 }
230 StringRef Contents = *ContentsOrErr;
231 Contents = Contents.substr(Start: 0, N: Contents.find(C: '\0'));
232 if (Contents.empty())
233 continue;
234 Names.push_back(x: Contents);
235 return true;
236 }
237 return true;
238}
239
240int doIdentify(StringRef File, bool IdentifyStrict) {
241 ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf = MemoryBuffer::getFile(
242 Filename: File, /*IsText=*/false, /*RequiredNullTerminator=*/RequiresNullTerminator: false);
243 if (!MaybeBuf)
244 return printError(E: errorCodeToError(EC: MaybeBuf.getError()), File);
245 if (identify_magic(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(E: std::move(Err), File: 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, Name: B->getBufferIdentifier(),
265 Callback: [&](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
288int llvm::dlltoolDriverMain(llvm::ArrayRef<const char *> ArgsArr) {
289 DllOptTable Table;
290 unsigned MissingIndex;
291 unsigned MissingCount;
292 llvm::opt::InputArgList Args =
293 Table.ParseArgs(Args: ArgsArr.slice(N: 1), MissingArgIndex&: MissingIndex, MissingArgCount&: MissingCount);
294 if (MissingCount) {
295 llvm::errs() << Args.getArgString(Index: MissingIndex) << ": missing argument\n";
296 return 1;
297 }
298
299 // Handle when no input or output is specified
300 if (Args.hasArgNoClaim(Ids: OPT_INPUT) ||
301 (!Args.hasArgNoClaim(Ids: OPT_d) && !Args.hasArgNoClaim(Ids: OPT_l) &&
302 !Args.hasArgNoClaim(Ids: OPT_I))) {
303 Table.printHelp(OS&: outs(), Usage: "llvm-dlltool [options] file...", Title: "llvm-dlltool",
304 ShowHidden: 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(Ids: OPT_UNKNOWN))
311 llvm::errs() << "ignoring unknown argument: " << Arg->getAsString(Args)
312 << "\n";
313
314 if (Args.hasArg(Ids: OPT_I)) {
315 return doIdentify(File: Args.getLastArg(Ids: OPT_I)->getValue(),
316 IdentifyStrict: Args.hasArg(Ids: OPT_identify_strict));
317 }
318
319 if (!Args.hasArg(Ids: 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(Argv0: ArgsArr[0])) {
326 Triple T(*Prefix);
327 if (T.getArch() != Triple::UnknownArch)
328 Machine = getMachine(T);
329 }
330 if (auto *Arg = Args.getLastArg(Ids: OPT_m))
331 Machine = getEmulation(S: Arg->getValue());
332
333 if (Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
334 llvm::errs() << "unknown target\n";
335 return 1;
336 }
337
338 bool AddUnderscores = !Args.hasArg(Ids: OPT_no_leading_underscore);
339
340 std::string OutputFile;
341 if (auto *Arg = Args.getLastArg(Ids: OPT_D))
342 OutputFile = Arg->getValue();
343
344 std::vector<COFFShortExport> Exports, NativeExports;
345
346 if (Args.hasArg(Ids: 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(DefFileName: Args.getLastArg(Ids: OPT_N)->getValue(),
352 Machine: IMAGE_FILE_MACHINE_ARM64, AddUnderscores,
353 Exports&: NativeExports, OutputFile))
354 return 1;
355 }
356
357 if (!parseModuleDefinition(DefFileName: Args.getLastArg(Ids: 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(Ids: 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(pos: 0, n: E.Name.find(c: '@', pos: 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(Id: OPT_l));
384 if (!Path.empty()) {
385 if (Error E = writeImportLibrary(ImportName: OutputFile, Path, Exports, Machine,
386 /*MinGW=*/true, NativeExports)) {
387 handleAllErrors(E: std::move(E), Handlers: [&](const ErrorInfoBase &EI) {
388 llvm::errs() << EI.message() << "\n";
389 });
390 return 1;
391 }
392 }
393 return 0;
394}
395