LLVM 19.0.0git
COFFModuleDefinition.cpp
Go to the documentation of this file.
1//===--- COFFModuleDefinition.cpp - Simple DEF parser ---------------------===//
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// Windows-specific.
10// A parser for the module-definition file (.def file).
11//
12// The format of module-definition files are described in this document:
13// https://msdn.microsoft.com/en-us/library/28d6s79h.aspx
14//
15//===----------------------------------------------------------------------===//
16
18#include "llvm/ADT/StringRef.h"
21#include "llvm/Object/Error.h"
22#include "llvm/Support/Error.h"
23#include "llvm/Support/Path.h"
24
25using namespace llvm::COFF;
26using namespace llvm;
27
28namespace llvm {
29namespace object {
30
31enum Kind {
50};
51
52struct Token {
53 explicit Token(Kind T = Unknown, StringRef S = "") : K(T), Value(S) {}
56};
57
58static bool isDecorated(StringRef Sym, bool MingwDef) {
59 // In def files, the symbols can either be listed decorated or undecorated.
60 //
61 // - For cdecl symbols, only the undecorated form is allowed.
62 // - For fastcall and vectorcall symbols, both fully decorated or
63 // undecorated forms can be present.
64 // - For stdcall symbols in non-MinGW environments, the decorated form is
65 // fully decorated with leading underscore and trailing stack argument
66 // size - like "_Func@0".
67 // - In MinGW def files, a decorated stdcall symbol does not include the
68 // leading underscore though, like "Func@0".
69
70 // This function controls whether a leading underscore should be added to
71 // the given symbol name or not. For MinGW, treat a stdcall symbol name such
72 // as "Func@0" as undecorated, i.e. a leading underscore must be added.
73 // For non-MinGW, look for '@' in the whole string and consider "_Func@0"
74 // as decorated, i.e. don't add any more leading underscores.
75 // We can't check for a leading underscore here, since function names
76 // themselves can start with an underscore, while a second one still needs
77 // to be added.
78 return Sym.starts_with("@") || Sym.contains("@@") || Sym.starts_with("?") ||
79 (!MingwDef && Sym.contains('@'));
80}
81
82class Lexer {
83public:
84 Lexer(StringRef S) : Buf(S) {}
85
87 Buf = Buf.trim();
88 if (Buf.empty())
89 return Token(Eof);
90
91 switch (Buf[0]) {
92 case '\0':
93 return Token(Eof);
94 case ';': {
95 size_t End = Buf.find('\n');
96 Buf = (End == Buf.npos) ? "" : Buf.drop_front(End);
97 return lex();
98 }
99 case '=':
100 Buf = Buf.drop_front();
101 if (Buf.consume_front("="))
102 return Token(EqualEqual, "==");
103 return Token(Equal, "=");
104 case ',':
105 Buf = Buf.drop_front();
106 return Token(Comma, ",");
107 case '"': {
108 StringRef S;
109 std::tie(S, Buf) = Buf.substr(1).split('"');
110 return Token(Identifier, S);
111 }
112 default: {
113 size_t End = Buf.find_first_of("=,;\r\n \t\v");
114 StringRef Word = Buf.substr(0, End);
116 .Case("BASE", KwBase)
117 .Case("CONSTANT", KwConstant)
118 .Case("DATA", KwData)
119 .Case("EXPORTS", KwExports)
120 .Case("EXPORTAS", KwExportAs)
121 .Case("HEAPSIZE", KwHeapsize)
122 .Case("LIBRARY", KwLibrary)
123 .Case("NAME", KwName)
124 .Case("NONAME", KwNoname)
125 .Case("PRIVATE", KwPrivate)
126 .Case("STACKSIZE", KwStacksize)
127 .Case("VERSION", KwVersion)
129 Buf = (End == Buf.npos) ? "" : Buf.drop_front(End);
130 return Token(K, Word);
131 }
132 }
133 }
134
135private:
136 StringRef Buf;
137};
138
139class Parser {
140public:
141 explicit Parser(StringRef S, MachineTypes M, bool B, bool AU)
142 : Lex(S), Machine(M), MingwDef(B), AddUnderscores(AU) {
143 if (Machine != IMAGE_FILE_MACHINE_I386)
144 AddUnderscores = false;
145 }
146
148 do {
149 if (Error Err = parseOne())
150 return std::move(Err);
151 } while (Tok.K != Eof);
152 return Info;
153 }
154
155private:
156 void read() {
157 if (Stack.empty()) {
158 Tok = Lex.lex();
159 return;
160 }
161 Tok = Stack.back();
162 Stack.pop_back();
163 }
164
165 Error readAsInt(uint64_t *I) {
166 read();
167 if (Tok.K != Identifier || Tok.Value.getAsInteger(10, *I))
168 return createError("integer expected");
169 return Error::success();
170 }
171
172 Error expect(Kind Expected, StringRef Msg) {
173 read();
174 if (Tok.K != Expected)
175 return createError(Msg);
176 return Error::success();
177 }
178
179 void unget() { Stack.push_back(Tok); }
180
181 Error parseOne() {
182 read();
183 switch (Tok.K) {
184 case Eof:
185 return Error::success();
186 case KwExports:
187 for (;;) {
188 read();
189 if (Tok.K != Identifier) {
190 unget();
191 return Error::success();
192 }
193 if (Error Err = parseExport())
194 return Err;
195 }
196 case KwHeapsize:
197 return parseNumbers(&Info.HeapReserve, &Info.HeapCommit);
198 case KwStacksize:
199 return parseNumbers(&Info.StackReserve, &Info.StackCommit);
200 case KwLibrary:
201 case KwName: {
202 bool IsDll = Tok.K == KwLibrary; // Check before parseName.
203 std::string Name;
204 if (Error Err = parseName(&Name, &Info.ImageBase))
205 return Err;
206
207 Info.ImportName = Name;
208
209 // Set the output file, but don't override /out if it was already passed.
210 if (Info.OutputFile.empty()) {
211 Info.OutputFile = Name;
212 // Append the appropriate file extension if not already present.
214 Info.OutputFile += IsDll ? ".dll" : ".exe";
215 }
216
217 return Error::success();
218 }
219 case KwVersion:
220 return parseVersion(&Info.MajorImageVersion, &Info.MinorImageVersion);
221 default:
222 return createError("unknown directive: " + Tok.Value);
223 }
224 }
225
226 Error parseExport() {
227 COFFShortExport E;
228 E.Name = std::string(Tok.Value);
229 read();
230 if (Tok.K == Equal) {
231 read();
232 if (Tok.K != Identifier)
233 return createError("identifier expected, but got " + Tok.Value);
234 E.ExtName = E.Name;
235 E.Name = std::string(Tok.Value);
236 } else {
237 unget();
238 }
239
240 if (AddUnderscores) {
241 if (!isDecorated(E.Name, MingwDef))
242 E.Name = (std::string("_").append(E.Name));
243 if (!E.ExtName.empty() && !isDecorated(E.ExtName, MingwDef))
244 E.ExtName = (std::string("_").append(E.ExtName));
245 }
246
247 for (;;) {
248 read();
249 if (Tok.K == Identifier && Tok.Value[0] == '@') {
250 if (Tok.Value == "@") {
251 // "foo @ 10"
252 read();
253 Tok.Value.getAsInteger(10, E.Ordinal);
254 } else if (Tok.Value.drop_front().getAsInteger(10, E.Ordinal)) {
255 // "foo \n @bar" - Not an ordinal modifier at all, but the next
256 // export (fastcall decorated) - complete the current one.
257 unget();
258 Info.Exports.push_back(E);
259 return Error::success();
260 }
261 // "foo @10"
262 read();
263 if (Tok.K == KwNoname) {
264 E.Noname = true;
265 } else {
266 unget();
267 }
268 continue;
269 }
270 if (Tok.K == KwData) {
271 E.Data = true;
272 continue;
273 }
274 if (Tok.K == KwConstant) {
275 E.Constant = true;
276 continue;
277 }
278 if (Tok.K == KwPrivate) {
279 E.Private = true;
280 continue;
281 }
282 if (Tok.K == EqualEqual) {
283 read();
284 E.AliasTarget = std::string(Tok.Value);
285 if (AddUnderscores && !isDecorated(E.AliasTarget, MingwDef))
286 E.AliasTarget = std::string("_").append(E.AliasTarget);
287 continue;
288 }
289 // EXPORTAS must be at the end of export definition
290 if (Tok.K == KwExportAs) {
291 read();
292 if (Tok.K == Eof)
293 return createError(
294 "unexpected end of file, EXPORTAS identifier expected");
295 E.ExportAs = std::string(Tok.Value);
296 } else {
297 unget();
298 }
299 Info.Exports.push_back(E);
300 return Error::success();
301 }
302 }
303
304 // HEAPSIZE/STACKSIZE reserve[,commit]
305 Error parseNumbers(uint64_t *Reserve, uint64_t *Commit) {
306 if (Error Err = readAsInt(Reserve))
307 return Err;
308 read();
309 if (Tok.K != Comma) {
310 unget();
311 Commit = nullptr;
312 return Error::success();
313 }
314 if (Error Err = readAsInt(Commit))
315 return Err;
316 return Error::success();
317 }
318
319 // NAME outputPath [BASE=address]
320 Error parseName(std::string *Out, uint64_t *Baseaddr) {
321 read();
322 if (Tok.K == Identifier) {
323 *Out = std::string(Tok.Value);
324 } else {
325 *Out = "";
326 unget();
327 return Error::success();
328 }
329 read();
330 if (Tok.K == KwBase) {
331 if (Error Err = expect(Equal, "'=' expected"))
332 return Err;
333 if (Error Err = readAsInt(Baseaddr))
334 return Err;
335 } else {
336 unget();
337 *Baseaddr = 0;
338 }
339 return Error::success();
340 }
341
342 // VERSION major[.minor]
343 Error parseVersion(uint32_t *Major, uint32_t *Minor) {
344 read();
345 if (Tok.K != Identifier)
346 return createError("identifier expected, but got " + Tok.Value);
347 StringRef V1, V2;
348 std::tie(V1, V2) = Tok.Value.split('.');
349 if (V1.getAsInteger(10, *Major))
350 return createError("integer expected, but got " + Tok.Value);
351 if (V2.empty())
352 *Minor = 0;
353 else if (V2.getAsInteger(10, *Minor))
354 return createError("integer expected, but got " + Tok.Value);
355 return Error::success();
356 }
357
358 Lexer Lex;
359 Token Tok;
360 std::vector<Token> Stack;
361 MachineTypes Machine;
362 COFFModuleDefinition Info;
363 bool MingwDef;
364 bool AddUnderscores;
365};
366
369 bool MingwDef,
370 bool AddUnderscores) {
371 return Parser(MB.getBuffer(), Machine, MingwDef, AddUnderscores).parse();
372}
373
374} // namespace object
375} // namespace llvm
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
COFF::MachineTypes Machine
Definition: COFFYAML.cpp:371
std::string Name
bool End
Definition: ELF_riscv.cpp:480
Symbol * Sym
Definition: ELF_riscv.cpp:479
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
StringRef getBuffer() const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:696
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:466
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:567
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:605
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:631
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:373
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:293
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
Definition: StringRef.h:811
static constexpr size_t npos
Definition: StringRef.h:52
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
LLVM Value Representation.
Definition: Value.h:74
Parser(StringRef S, MachineTypes M, bool B, bool AU)
Expected< COFFModuleDefinition > parse()
MachineTypes
Definition: COFF.h:92
@ IMAGE_FILE_MACHINE_I386
Definition: COFF.h:104
Error createError(const Twine &Err)
Definition: Error.h:84
Expected< COFFModuleDefinition > parseCOFFModuleDefinition(MemoryBufferRef MB, COFF::MachineTypes Machine, bool MingwDef=false, bool AddUnderscores=true)
static bool isDecorated(StringRef Sym, bool MingwDef)
bool has_extension(const Twine &path, Style style=Style::native)
Has extension?
Definition: Path.cpp:666
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::vector< COFFShortExport > Exports
Token(Kind T=Unknown, StringRef S="")