1//===- DLL.cpp ------------------------------------------------------------===//
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// This file defines various types of chunks for the DLL import or export
10// descriptor tables. They are inherently Windows-specific.
11// You need to read Microsoft PE/COFF spec to understand details
12// about the data structures.
13//
14// If you are not particularly interested in linking against Windows
15// DLL, you can skip this file, and you should still be able to
16// understand the rest of the linker.
17//
18//===----------------------------------------------------------------------===//
19
20#include "DLL.h"
21#include "COFFLinkerContext.h"
22#include "Chunks.h"
23#include "SymbolTable.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/Object/COFF.h"
26#include "llvm/Support/Endian.h"
27#include "llvm/Support/Path.h"
28
29using namespace llvm;
30using namespace llvm::object;
31using namespace llvm::support::endian;
32using namespace llvm::COFF;
33
34namespace lld::coff {
35namespace {
36
37// Import table
38
39// A chunk for the import descriptor table.
40class HintNameChunk : public NonSectionChunk {
41public:
42 HintNameChunk(StringRef n, uint16_t h) : name(n), hint(h) {}
43
44 size_t getSize() const override {
45 // Starts with 2 byte Hint field, followed by a null-terminated string,
46 // ends with 0 or 1 byte padding.
47 return alignTo(Value: name.size() + 3, Align: 2);
48 }
49
50 void writeTo(uint8_t *buf) const override {
51 memset(s: buf, c: 0, n: getSize());
52 write16le(P: buf, V: hint);
53 memcpy(dest: buf + 2, src: name.data(), n: name.size());
54 }
55
56private:
57 StringRef name;
58 uint16_t hint;
59};
60
61// A chunk for the import descriptor table.
62class LookupChunk : public NonSectionChunk {
63public:
64 explicit LookupChunk(COFFLinkerContext &ctx, Chunk *c)
65 : hintName(c), ctx(ctx) {
66 setAlignment(ctx.config.wordsize);
67 }
68 size_t getSize() const override { return ctx.config.wordsize; }
69
70 void writeTo(uint8_t *buf) const override {
71 if (ctx.config.is64())
72 write64le(P: buf, V: hintName->getRVA());
73 else
74 write32le(P: buf, V: hintName->getRVA());
75 }
76
77 Chunk *hintName;
78
79private:
80 COFFLinkerContext &ctx;
81};
82
83// A chunk for the import descriptor table.
84// This chunk represent import-by-ordinal symbols.
85// See Microsoft PE/COFF spec 7.1. Import Header for details.
86class OrdinalOnlyChunk : public NonSectionChunk {
87public:
88 explicit OrdinalOnlyChunk(COFFLinkerContext &c, uint16_t v)
89 : ordinal(v), ctx(c) {
90 setAlignment(ctx.config.wordsize);
91 }
92 size_t getSize() const override { return ctx.config.wordsize; }
93
94 void writeTo(uint8_t *buf) const override {
95 // An import-by-ordinal slot has MSB 1 to indicate that
96 // this is import-by-ordinal (and not import-by-name).
97 if (ctx.config.is64()) {
98 write64le(P: buf, V: (1ULL << 63) | ordinal);
99 } else {
100 write32le(P: buf, V: (1ULL << 31) | ordinal);
101 }
102 }
103
104 uint16_t ordinal;
105
106private:
107 COFFLinkerContext &ctx;
108};
109
110// A chunk for the import descriptor table.
111class ImportDirectoryChunk : public NonSectionChunk {
112public:
113 explicit ImportDirectoryChunk(Chunk *n) : dllName(n) { setAlignment(4); }
114 size_t getSize() const override { return sizeof(ImportDirectoryTableEntry); }
115
116 void writeTo(uint8_t *buf) const override {
117 memset(s: buf, c: 0, n: getSize());
118
119 auto *e = (coff_import_directory_table_entry *)(buf);
120 e->ImportLookupTableRVA = lookupTab->getRVA();
121 e->NameRVA = dllName->getRVA();
122 e->ImportAddressTableRVA = addressTab->getRVA();
123 }
124
125 Chunk *dllName;
126 Chunk *lookupTab;
127 Chunk *addressTab;
128};
129
130// A chunk representing null terminator in the import table.
131// Contents of this chunk is always null bytes.
132class NullChunk : public NonSectionChunk {
133public:
134 explicit NullChunk(size_t n, uint32_t align) : size(n) {
135 setAlignment(align);
136 }
137 explicit NullChunk(COFFLinkerContext &ctx)
138 : NullChunk(ctx.config.wordsize, ctx.config.wordsize) {}
139 explicit NullChunk(COFFLinkerContext &ctx, size_t n)
140 : NullChunk(n, ctx.config.wordsize) {}
141 size_t getSize() const override { return size; }
142
143 void writeTo(uint8_t *buf) const override {
144 memset(s: buf, c: 0, n: size);
145 }
146
147private:
148 size_t size;
149};
150
151// A chunk for ARM64EC auxiliary IAT.
152class AuxImportChunk : public NonSectionChunk {
153public:
154 explicit AuxImportChunk(ImportFile *file) : file(file) {
155 setAlignment(sizeof(uint64_t));
156 }
157 size_t getSize() const override { return sizeof(uint64_t); }
158
159 void writeTo(uint8_t *buf) const override {
160 uint64_t impchkVA = 0;
161 if (file->impchkThunk)
162 impchkVA =
163 file->impchkThunk->getRVA() + file->symtab.ctx.config.imageBase;
164 write64le(P: buf, V: impchkVA);
165 }
166
167 void getBaserels(std::vector<Baserel> *res) override {
168 if (file->impchkThunk)
169 res->emplace_back(args&: rva, args&: file->symtab.machine);
170 }
171
172private:
173 ImportFile *file;
174};
175
176static std::vector<std::vector<DefinedImportData *>>
177binImports(COFFLinkerContext &ctx,
178 const std::vector<DefinedImportData *> &imports) {
179 // Group DLL-imported symbols by DLL name because that's how
180 // symbols are laid out in the import descriptor table.
181 auto less = [&ctx](const std::string &a, const std::string &b) {
182 return ctx.config.dllOrder[a] < ctx.config.dllOrder[b];
183 };
184 std::map<std::string, std::vector<DefinedImportData *>, decltype(less)> m(
185 less);
186 for (DefinedImportData *sym : imports)
187 m[sym->getDLLName().lower()].push_back(x: sym);
188
189 std::vector<std::vector<DefinedImportData *>> v;
190 for (auto &kv : m) {
191 // Sort symbols by name for each group.
192 std::vector<DefinedImportData *> &syms = kv.second;
193 llvm::sort(C&: syms, Comp: [](DefinedImportData *a, DefinedImportData *b) {
194 auto getBaseName = [](DefinedImportData *sym) {
195 StringRef name = sym->getName();
196 name.consume_front(Prefix: "__imp_");
197 // Skip aux_ part of ARM64EC function symbol name.
198 if (sym->file->impchkThunk)
199 name.consume_front(Prefix: "aux_");
200 return name;
201 };
202 return getBaseName(a) < getBaseName(b);
203 });
204 v.push_back(x: std::move(syms));
205 }
206 return v;
207}
208
209// See Microsoft PE/COFF spec 4.3 for details.
210
211// A chunk for the delay import descriptor table etnry.
212class DelayDirectoryChunk : public NonSectionChunk {
213public:
214 explicit DelayDirectoryChunk(Chunk *n) : dllName(n) { setAlignment(4); }
215
216 size_t getSize() const override {
217 return sizeof(delay_import_directory_table_entry);
218 }
219
220 void writeTo(uint8_t *buf) const override {
221 memset(s: buf, c: 0, n: getSize());
222
223 auto *e = (delay_import_directory_table_entry *)(buf);
224 e->Attributes = 1;
225 e->Name = dllName->getRVA();
226 e->ModuleHandle = moduleHandle->getRVA();
227 e->DelayImportAddressTable = addressTab->getRVA();
228 e->DelayImportNameTable = nameTab->getRVA();
229 }
230
231 Chunk *dllName;
232 Chunk *moduleHandle;
233 Chunk *addressTab;
234 Chunk *nameTab;
235};
236
237// Initial contents for delay-loaded functions.
238// This code calls __delayLoadHelper2 function to resolve a symbol
239// which then overwrites its jump table slot with the result
240// for subsequent function calls.
241static const uint8_t thunkX64[] = {
242 0x48, 0x8D, 0x05, 0, 0, 0, 0, // lea rax, [__imp_<FUNCNAME>]
243 0xE9, 0, 0, 0, 0, // jmp __tailMerge_<lib>
244};
245
246static const uint8_t tailMergeX64[] = {
247 0x48, 0x89, 0x4C, 0x24, 0x08, // mov qword ptr [rsp+8], rcx
248 0x48, 0x89, 0x54, 0x24, 0x10, // mov qword ptr [rsp+10h], rdx
249 0x4C, 0x89, 0x44, 0x24, 0x18, // mov qword ptr [rsp+18h], r8
250 0x4C, 0x89, 0x4C, 0x24, 0x20, // mov qword ptr [rsp+20h], r9
251 0x48, 0x83, 0xEC, 0x68, // sub rsp, 68h
252 0x66, 0x0F, 0x7F, 0x44, 0x24, 0x20, // movdqa xmmword ptr [rsp+20h], xmm0
253 0x66, 0x0F, 0x7F, 0x4C, 0x24, 0x30, // movdqa xmmword ptr [rsp+30h], xmm1
254 0x66, 0x0F, 0x7F, 0x54, 0x24, 0x40, // movdqa xmmword ptr [rsp+40h], xmm2
255 0x66, 0x0F, 0x7F, 0x5C, 0x24, 0x50, // movdqa xmmword ptr [rsp+50h], xmm3
256 0x48, 0x8B, 0xD0, // mov rdx, rax
257 0x48, 0x8D, 0x0D, 0, 0, 0, 0, // lea rcx, [___DELAY_IMPORT_...]
258 0xE8, 0, 0, 0, 0, // call __delayLoadHelper2
259 0x66, 0x0F, 0x6F, 0x44, 0x24, 0x20, // movdqa xmm0, xmmword ptr [rsp+20h]
260 0x66, 0x0F, 0x6F, 0x4C, 0x24, 0x30, // movdqa xmm1, xmmword ptr [rsp+30h]
261 0x66, 0x0F, 0x6F, 0x54, 0x24, 0x40, // movdqa xmm2, xmmword ptr [rsp+40h]
262 0x66, 0x0F, 0x6F, 0x5C, 0x24, 0x50, // movdqa xmm3, xmmword ptr [rsp+50h]
263 0x48, 0x8B, 0x4C, 0x24, 0x70, // mov rcx, qword ptr [rsp+70h]
264 0x48, 0x8B, 0x54, 0x24, 0x78, // mov rdx, qword ptr [rsp+78h]
265 0x4C, 0x8B, 0x84, 0x24, 0x80, 0, 0, 0, // mov r8, qword ptr [rsp+80h]
266 0x4C, 0x8B, 0x8C, 0x24, 0x88, 0, 0, 0, // mov r9, qword ptr [rsp+88h]
267 0x48, 0x83, 0xC4, 0x68, // add rsp, 68h
268 0xFF, 0xE0, // jmp rax
269};
270
271static const uint8_t tailMergeUnwindInfoX64[] = {
272 0x01, // Version=1, Flags=UNW_FLAG_NHANDLER
273 0x18, // Size of prolog
274 0x01, // Count of unwind codes
275 0x00, // No frame register
276 0x18, 0xC2, // Offset 0x18: UWOP_ALLOC_SMALL(0x68)
277 0x00, 0x00 // Padding to align on 32-bits
278};
279
280static const uint8_t thunkX86[] = {
281 0xB8, 0, 0, 0, 0, // mov eax, offset ___imp__<FUNCNAME>
282 0xE9, 0, 0, 0, 0, // jmp __tailMerge_<lib>
283};
284
285static const uint8_t tailMergeX86[] = {
286 0x51, // push ecx
287 0x52, // push edx
288 0x50, // push eax
289 0x68, 0, 0, 0, 0, // push offset ___DELAY_IMPORT_DESCRIPTOR_<DLLNAME>_dll
290 0xE8, 0, 0, 0, 0, // call ___delayLoadHelper2@8
291 0x5A, // pop edx
292 0x59, // pop ecx
293 0xFF, 0xE0, // jmp eax
294};
295
296static const uint8_t thunkARM[] = {
297 0x40, 0xf2, 0x00, 0x0c, // mov.w ip, #0 __imp_<FUNCNAME>
298 0xc0, 0xf2, 0x00, 0x0c, // mov.t ip, #0 __imp_<FUNCNAME>
299 0x00, 0xf0, 0x00, 0xb8, // b.w __tailMerge_<lib>
300};
301
302static const uint8_t tailMergeARM[] = {
303 0x2d, 0xe9, 0x0f, 0x48, // push.w {r0, r1, r2, r3, r11, lr}
304 0x0d, 0xf2, 0x10, 0x0b, // addw r11, sp, #16
305 0x2d, 0xed, 0x10, 0x0b, // vpush {d0, d1, d2, d3, d4, d5, d6, d7}
306 0x61, 0x46, // mov r1, ip
307 0x40, 0xf2, 0x00, 0x00, // mov.w r0, #0 DELAY_IMPORT_DESCRIPTOR
308 0xc0, 0xf2, 0x00, 0x00, // mov.t r0, #0 DELAY_IMPORT_DESCRIPTOR
309 0x40, 0xf2, 0x00, 0x02, // mov.w r2, #0 __delayLoadHelper2
310 0xc0, 0xf2, 0x00, 0x02, // mov.t r2, #0 __delayLoadHelper2
311 0x90, 0x47, // blx r2
312 0x84, 0x46, // mov ip, r0
313 0xbd, 0xec, 0x10, 0x0b, // vpop {d0, d1, d2, d3, d4, d5, d6, d7}
314 0xbd, 0xe8, 0x0f, 0x48, // pop.w {r0, r1, r2, r3, r11, lr}
315 0x60, 0x47, // bx ip
316};
317
318static const uint8_t thunkARM64[] = {
319 0x11, 0x00, 0x00, 0x90, // adrp x17, #0 __imp_<FUNCNAME>
320 0x31, 0x02, 0x00, 0x91, // add x17, x17, #0 :lo12:__imp_<FUNCNAME>
321 0x00, 0x00, 0x00, 0x14, // b __tailMerge_<lib>
322};
323
324static const uint8_t tailMergeARM64[] = {
325 0xfd, 0x7b, 0xb2, 0xa9, // stp x29, x30, [sp, #-224]!
326 0xfd, 0x03, 0x00, 0x91, // mov x29, sp
327 0xe0, 0x07, 0x01, 0xa9, // stp x0, x1, [sp, #16]
328 0xe2, 0x0f, 0x02, 0xa9, // stp x2, x3, [sp, #32]
329 0xe4, 0x17, 0x03, 0xa9, // stp x4, x5, [sp, #48]
330 0xe6, 0x1f, 0x04, 0xa9, // stp x6, x7, [sp, #64]
331 0xe8, 0x2b, 0x00, 0xf9, // str x8, [sp, #80]
332 0xe0, 0x07, 0x03, 0xad, // stp q0, q1, [sp, #96]
333 0xe2, 0x0f, 0x04, 0xad, // stp q2, q3, [sp, #128]
334 0xe4, 0x17, 0x05, 0xad, // stp q4, q5, [sp, #160]
335 0xe6, 0x1f, 0x06, 0xad, // stp q6, q7, [sp, #192]
336 0xe1, 0x03, 0x11, 0xaa, // mov x1, x17
337 0x00, 0x00, 0x00, 0x90, // adrp x0, #0 DELAY_IMPORT_DESCRIPTOR
338 0x00, 0x00, 0x00, 0x91, // add x0, x0, #0 :lo12:DELAY_IMPORT_DESCRIPTOR
339 0x02, 0x00, 0x00, 0x90, // adrp x2, #0 __delayLoadHelper2
340 0x42, 0x00, 0x00, 0x91, // add x2, x2, #0 :lo12:__delayLoadHelper2
341 0x40, 0x00, 0x3f, 0xd6, // blr x2
342 0xf0, 0x03, 0x00, 0xaa, // mov x16, x0
343 0xe6, 0x1f, 0x46, 0xad, // ldp q6, q7, [sp, #192]
344 0xe4, 0x17, 0x45, 0xad, // ldp q4, q5, [sp, #160]
345 0xe2, 0x0f, 0x44, 0xad, // ldp q2, q3, [sp, #128]
346 0xe0, 0x07, 0x43, 0xad, // ldp q0, q1, [sp, #96]
347 0xe8, 0x2b, 0x40, 0xf9, // ldr x8, [sp, #80]
348 0xe6, 0x1f, 0x44, 0xa9, // ldp x6, x7, [sp, #64]
349 0xe4, 0x17, 0x43, 0xa9, // ldp x4, x5, [sp, #48]
350 0xe2, 0x0f, 0x42, 0xa9, // ldp x2, x3, [sp, #32]
351 0xe0, 0x07, 0x41, 0xa9, // ldp x0, x1, [sp, #16]
352 0xfd, 0x7b, 0xce, 0xa8, // ldp x29, x30, [sp], #224
353 0x00, 0x02, 0x1f, 0xd6, // br x16
354};
355
356// A chunk for the delay import thunk.
357class ThunkChunkX64 : public NonSectionCodeChunk {
358public:
359 ThunkChunkX64(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
360
361 size_t getSize() const override { return sizeof(thunkX64); }
362 MachineTypes getMachine() const override { return AMD64; }
363
364 void writeTo(uint8_t *buf) const override {
365 memcpy(dest: buf, src: thunkX64, n: sizeof(thunkX64));
366 write32le(P: buf + 3, V: imp->getRVA() - rva - 7);
367 write32le(P: buf + 8, V: tailMerge->getRVA() - rva - 12);
368 }
369
370 Defined *imp = nullptr;
371 Chunk *tailMerge = nullptr;
372};
373
374class TailMergeChunkX64 : public NonSectionCodeChunk {
375public:
376 TailMergeChunkX64(Chunk *d, Defined *h) : desc(d), helper(h) {}
377
378 size_t getSize() const override { return sizeof(tailMergeX64); }
379 MachineTypes getMachine() const override { return AMD64; }
380
381 void writeTo(uint8_t *buf) const override {
382 memcpy(dest: buf, src: tailMergeX64, n: sizeof(tailMergeX64));
383 write32le(P: buf + 54, V: desc->getRVA() - rva - 58);
384 write32le(P: buf + 59, V: helper->getRVA() - rva - 63);
385 }
386
387 Chunk *desc = nullptr;
388 Defined *helper = nullptr;
389};
390
391class TailMergePDataChunkX64 : public NonSectionChunk {
392public:
393 TailMergePDataChunkX64(Chunk *tm, Chunk *unwind) : tm(tm), unwind(unwind) {
394 // See
395 // https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-runtime_function
396 setAlignment(4);
397 }
398
399 size_t getSize() const override { return 3 * sizeof(uint32_t); }
400 MachineTypes getMachine() const override { return AMD64; }
401
402 void writeTo(uint8_t *buf) const override {
403 write32le(P: buf + 0, V: tm->getRVA()); // TailMergeChunk start RVA
404 write32le(P: buf + 4, V: tm->getRVA() + tm->getSize()); // TailMergeChunk stop RVA
405 write32le(P: buf + 8, V: unwind->getRVA()); // UnwindInfo RVA
406 }
407
408 Chunk *tm = nullptr;
409 Chunk *unwind = nullptr;
410};
411
412class TailMergeUnwindInfoX64 : public NonSectionChunk {
413public:
414 TailMergeUnwindInfoX64() {
415 // See
416 // https://learn.microsoft.com/en-us/cpp/build/exception-handling-x64#struct-unwind_info
417 setAlignment(4);
418 }
419
420 size_t getSize() const override { return sizeof(tailMergeUnwindInfoX64); }
421 MachineTypes getMachine() const override { return AMD64; }
422
423 void writeTo(uint8_t *buf) const override {
424 memcpy(dest: buf, src: tailMergeUnwindInfoX64, n: sizeof(tailMergeUnwindInfoX64));
425 }
426};
427
428class ThunkChunkX86 : public NonSectionCodeChunk {
429public:
430 ThunkChunkX86(COFFLinkerContext &ctx, Defined *i, Chunk *tm)
431 : imp(i), tailMerge(tm), ctx(ctx) {}
432
433 size_t getSize() const override { return sizeof(thunkX86); }
434 MachineTypes getMachine() const override { return I386; }
435
436 void writeTo(uint8_t *buf) const override {
437 memcpy(dest: buf, src: thunkX86, n: sizeof(thunkX86));
438 write32le(P: buf + 1, V: imp->getRVA() + ctx.config.imageBase);
439 write32le(P: buf + 6, V: tailMerge->getRVA() - rva - 10);
440 }
441
442 void getBaserels(std::vector<Baserel> *res) override {
443 res->emplace_back(args: rva + 1, args: ctx.config.machine);
444 }
445
446 Defined *imp = nullptr;
447 Chunk *tailMerge = nullptr;
448
449private:
450 const COFFLinkerContext &ctx;
451};
452
453class TailMergeChunkX86 : public NonSectionCodeChunk {
454public:
455 TailMergeChunkX86(COFFLinkerContext &ctx, Chunk *d, Defined *h)
456 : desc(d), helper(h), ctx(ctx) {}
457
458 size_t getSize() const override { return sizeof(tailMergeX86); }
459 MachineTypes getMachine() const override { return I386; }
460
461 void writeTo(uint8_t *buf) const override {
462 memcpy(dest: buf, src: tailMergeX86, n: sizeof(tailMergeX86));
463 write32le(P: buf + 4, V: desc->getRVA() + ctx.config.imageBase);
464 write32le(P: buf + 9, V: helper->getRVA() - rva - 13);
465 }
466
467 void getBaserels(std::vector<Baserel> *res) override {
468 res->emplace_back(args: rva + 4, args: ctx.config.machine);
469 }
470
471 Chunk *desc = nullptr;
472 Defined *helper = nullptr;
473
474private:
475 const COFFLinkerContext &ctx;
476};
477
478class ThunkChunkARM : public NonSectionCodeChunk {
479public:
480 ThunkChunkARM(COFFLinkerContext &ctx, Defined *i, Chunk *tm)
481 : imp(i), tailMerge(tm), ctx(ctx) {
482 setAlignment(2);
483 }
484
485 size_t getSize() const override { return sizeof(thunkARM); }
486 MachineTypes getMachine() const override { return ARMNT; }
487
488 void writeTo(uint8_t *buf) const override {
489 memcpy(dest: buf, src: thunkARM, n: sizeof(thunkARM));
490 applyMOV32T(off: buf + 0, v: imp->getRVA() + ctx.config.imageBase);
491 applyBranch24T(off: buf + 8, v: tailMerge->getRVA() - rva - 12);
492 }
493
494 void getBaserels(std::vector<Baserel> *res) override {
495 res->emplace_back(args: rva + 0, args: IMAGE_REL_BASED_ARM_MOV32T);
496 }
497
498 Defined *imp = nullptr;
499 Chunk *tailMerge = nullptr;
500
501private:
502 const COFFLinkerContext &ctx;
503};
504
505class TailMergeChunkARM : public NonSectionCodeChunk {
506public:
507 TailMergeChunkARM(COFFLinkerContext &ctx, Chunk *d, Defined *h)
508 : desc(d), helper(h), ctx(ctx) {
509 setAlignment(2);
510 }
511
512 size_t getSize() const override { return sizeof(tailMergeARM); }
513 MachineTypes getMachine() const override { return ARMNT; }
514
515 void writeTo(uint8_t *buf) const override {
516 memcpy(dest: buf, src: tailMergeARM, n: sizeof(tailMergeARM));
517 applyMOV32T(off: buf + 14, v: desc->getRVA() + ctx.config.imageBase);
518 // The helper can be more than 16 MiB away, out of reach of a bl.
519 applyMOV32T(off: buf + 22, v: (helper->getRVA() + ctx.config.imageBase) | 1);
520 }
521
522 void getBaserels(std::vector<Baserel> *res) override {
523 res->emplace_back(args: rva + 14, args: IMAGE_REL_BASED_ARM_MOV32T);
524 res->emplace_back(args: rva + 22, args: IMAGE_REL_BASED_ARM_MOV32T);
525 }
526
527 Chunk *desc = nullptr;
528 Defined *helper = nullptr;
529
530private:
531 const COFFLinkerContext &ctx;
532};
533
534class ThunkChunkARM64 : public NonSectionCodeChunk {
535public:
536 ThunkChunkARM64(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {
537 setAlignment(4);
538 }
539
540 size_t getSize() const override { return sizeof(thunkARM64); }
541 MachineTypes getMachine() const override { return ARM64; }
542
543 void writeTo(uint8_t *buf) const override {
544 memcpy(dest: buf, src: thunkARM64, n: sizeof(thunkARM64));
545 applyArm64Addr(off: buf + 0, s: imp->getRVA(), p: rva + 0, shift: 12);
546 applyArm64Imm(off: buf + 4, imm: imp->getRVA() & 0xfff, rangeLimit: 0);
547 applyArm64Branch26(off: buf + 8, v: tailMerge->getRVA() - rva - 8);
548 }
549
550 Defined *imp = nullptr;
551 Chunk *tailMerge = nullptr;
552};
553
554class TailMergeChunkARM64 : public NonSectionCodeChunk {
555public:
556 TailMergeChunkARM64(Chunk *d, Defined *h) : desc(d), helper(h) {
557 setAlignment(4);
558 }
559
560 size_t getSize() const override { return sizeof(tailMergeARM64); }
561 MachineTypes getMachine() const override { return ARM64; }
562
563 void writeTo(uint8_t *buf) const override {
564 memcpy(dest: buf, src: tailMergeARM64, n: sizeof(tailMergeARM64));
565 applyArm64Addr(off: buf + 48, s: desc->getRVA(), p: rva + 48, shift: 12);
566 applyArm64Imm(off: buf + 52, imm: desc->getRVA() & 0xfff, rangeLimit: 0);
567 if (helper) {
568 applyArm64Addr(off: buf + 56, s: helper->getRVA(), p: rva + 56, shift: 12);
569 applyArm64Imm(off: buf + 60, imm: helper->getRVA() & 0xfff, rangeLimit: 0);
570 }
571 }
572
573 Chunk *desc = nullptr;
574 Defined *helper = nullptr;
575};
576
577// A chunk for the import descriptor table.
578class DelayAddressChunk : public NonSectionChunk {
579public:
580 explicit DelayAddressChunk(COFFLinkerContext &ctx, Chunk *c)
581 : thunk(c), ctx(ctx) {
582 setAlignment(ctx.config.wordsize);
583 }
584 size_t getSize() const override { return ctx.config.wordsize; }
585
586 void writeTo(uint8_t *buf) const override {
587 if (ctx.config.is64()) {
588 write64le(P: buf, V: thunk->getRVA() + ctx.config.imageBase);
589 } else {
590 uint32_t bit = 0;
591 // Pointer to thumb code must have the LSB set, so adjust it.
592 if (ctx.config.machine == ARMNT)
593 bit = 1;
594 write32le(P: buf, V: (thunk->getRVA() + ctx.config.imageBase) | bit);
595 }
596 }
597
598 void getBaserels(std::vector<Baserel> *res) override {
599 res->emplace_back(args&: rva, args: ctx.config.machine);
600 }
601
602 Chunk *thunk;
603
604private:
605 const COFFLinkerContext &ctx;
606};
607
608// Export table
609// Read Microsoft PE/COFF spec 5.3 for details.
610
611// A chunk for the export descriptor table.
612class ExportDirectoryChunk : public NonSectionChunk {
613public:
614 ExportDirectoryChunk(int baseOrdinal, int maxOrdinal, int nameTabSize,
615 Chunk *d, Chunk *a, Chunk *n, Chunk *o)
616 : baseOrdinal(baseOrdinal), maxOrdinal(maxOrdinal),
617 nameTabSize(nameTabSize), dllName(d), addressTab(a), nameTab(n),
618 ordinalTab(o) {}
619
620 size_t getSize() const override {
621 return sizeof(export_directory_table_entry);
622 }
623
624 void writeTo(uint8_t *buf) const override {
625 memset(s: buf, c: 0, n: getSize());
626
627 auto *e = (export_directory_table_entry *)(buf);
628 e->NameRVA = dllName->getRVA();
629 e->OrdinalBase = baseOrdinal;
630 e->AddressTableEntries = (maxOrdinal - baseOrdinal) + 1;
631 e->NumberOfNamePointers = nameTabSize;
632 e->ExportAddressTableRVA = addressTab->getRVA();
633 e->NamePointerRVA = nameTab->getRVA();
634 e->OrdinalTableRVA = ordinalTab->getRVA();
635 }
636
637 uint16_t baseOrdinal;
638 uint16_t maxOrdinal;
639 uint16_t nameTabSize;
640 Chunk *dllName;
641 Chunk *addressTab;
642 Chunk *nameTab;
643 Chunk *ordinalTab;
644};
645
646class AddressTableChunk : public NonSectionChunk {
647public:
648 explicit AddressTableChunk(SymbolTable &symtab, size_t baseOrdinal,
649 size_t maxOrdinal)
650 : baseOrdinal(baseOrdinal), size((maxOrdinal - baseOrdinal) + 1),
651 symtab(symtab) {}
652 size_t getSize() const override { return size * 4; }
653
654 void writeTo(uint8_t *buf) const override {
655 memset(s: buf, c: 0, n: getSize());
656
657 for (const Export &e : symtab.exports) {
658 assert(e.ordinal >= baseOrdinal && "Export symbol has invalid ordinal");
659 // Subtract the OrdinalBase to get the index.
660 uint8_t *p = buf + (e.ordinal - baseOrdinal) * 4;
661 uint32_t bit = 0;
662 // Pointer to thumb code must have the LSB set, so adjust it.
663 if (symtab.machine == ARMNT && !e.data)
664 bit = 1;
665 if (e.forwardChunk) {
666 write32le(P: p, V: e.forwardChunk->getRVA() | bit);
667 } else {
668 assert(cast<Defined>(e.sym)->getRVA() != 0 &&
669 "Exported symbol unmapped");
670 write32le(P: p, V: cast<Defined>(Val: e.sym)->getRVA() | bit);
671 }
672 }
673 }
674
675private:
676 size_t baseOrdinal;
677 size_t size;
678 const SymbolTable &symtab;
679};
680
681class NamePointersChunk : public NonSectionChunk {
682public:
683 explicit NamePointersChunk(std::vector<Chunk *> &v) : chunks(v) {}
684 size_t getSize() const override { return chunks.size() * 4; }
685
686 void writeTo(uint8_t *buf) const override {
687 for (Chunk *c : chunks) {
688 write32le(P: buf, V: c->getRVA());
689 buf += 4;
690 }
691 }
692
693private:
694 std::vector<Chunk *> chunks;
695};
696
697class ExportOrdinalChunk : public NonSectionChunk {
698public:
699 explicit ExportOrdinalChunk(const SymbolTable &symtab, size_t baseOrdinal,
700 size_t tableSize)
701 : baseOrdinal(baseOrdinal), size(tableSize), symtab(symtab) {}
702 size_t getSize() const override { return size * 2; }
703
704 void writeTo(uint8_t *buf) const override {
705 for (const Export &e : symtab.exports) {
706 if (e.noname)
707 continue;
708 assert(e.ordinal >= baseOrdinal && "Export symbol has invalid ordinal");
709 // This table stores unbiased indices, so subtract OrdinalBase.
710 write16le(P: buf, V: e.ordinal - baseOrdinal);
711 buf += 2;
712 }
713 }
714
715private:
716 size_t baseOrdinal;
717 size_t size;
718 const SymbolTable &symtab;
719};
720
721} // anonymous namespace
722
723void IdataContents::create(COFFLinkerContext &ctx) {
724 std::vector<std::vector<DefinedImportData *>> v = binImports(ctx, imports);
725
726 // In hybrid images, EC and native code are usually very similar,
727 // resulting in a highly similar set of imported symbols. Consequently,
728 // their import tables can be shared, with ARM64X relocations handling any
729 // differences. Identify matching import files used by EC and native code, and
730 // merge them into a single hybrid import entry.
731 if (ctx.hybridSymtab) {
732 for (std::vector<DefinedImportData *> &syms : v) {
733 std::vector<DefinedImportData *> hybridSyms;
734 ImportFile *prev = nullptr;
735 for (DefinedImportData *sym : syms) {
736 ImportFile *file = sym->file;
737 // At this stage, symbols are sorted by base name, ensuring that
738 // compatible import files, if present, are adjacent. Check if the
739 // current symbol's file imports the same symbol as the previously added
740 // one (if any and if it was not already merged). Additionally, verify
741 // that one of them is native while the other is EC. In rare cases,
742 // separate matching import entries may exist within the same namespace,
743 // which cannot be merged.
744 if (!prev || file->isEC() == prev->isEC() ||
745 !file->isSameImport(other: prev)) {
746 // We can't merge the import file, just add it to hybridSyms
747 // and set prev to its file so that we can try to match the next
748 // symbol.
749 hybridSyms.push_back(x: sym);
750 prev = file;
751 continue;
752 }
753
754 // A matching symbol may appear in syms in any order. The native variant
755 // exposes a subset of EC symbols and chunks, so always use the EC
756 // variant as the hybrid import file. If the native file was already
757 // added, replace it with the EC symbol in hybridSyms. Otherwise, the EC
758 // variant is already pushed, so we can simply merge it.
759 if (file->isEC()) {
760 hybridSyms.pop_back();
761 hybridSyms.push_back(x: sym);
762 }
763
764 // Merge import files by storing their hybrid form in the corresponding
765 // file class.
766 prev->hybridFile = file;
767 file->hybridFile = prev;
768 prev = nullptr; // A hybrid import file cannot be merged again.
769 }
770
771 // Sort symbols by type: native-only files first, followed by merged
772 // hybrid files, and then EC-only files.
773 llvm::stable_sort(Range&: hybridSyms,
774 C: [](DefinedImportData *a, DefinedImportData *b) {
775 if (a->file->hybridFile)
776 return !b->file->hybridFile && b->file->isEC();
777 return !a->file->isEC() && b->file->isEC();
778 });
779 syms = std::move(hybridSyms);
780 }
781 }
782
783 // Create .idata contents for each DLL.
784 for (std::vector<DefinedImportData *> &syms : v) {
785 // Create lookup and address tables. If they have external names,
786 // we need to create hintName chunks to store the names.
787 // If they don't (if they are import-by-ordinals), we store only
788 // ordinal values to the table.
789 size_t base = lookups.size();
790 Chunk *lookupsTerminator = nullptr, *addressesTerminator = nullptr;
791 uint32_t nativeOnly = 0;
792 for (DefinedImportData *s : syms) {
793 uint16_t ord = s->getOrdinal();
794 HintNameChunk *hintChunk = nullptr;
795 Chunk *lookupsChunk, *addressesChunk;
796
797 if (s->getExternalName().empty()) {
798 lookupsChunk = make<OrdinalOnlyChunk>(args&: ctx, args&: ord);
799 addressesChunk = make<OrdinalOnlyChunk>(args&: ctx, args&: ord);
800 } else {
801 hintChunk = make<HintNameChunk>(args: s->getExternalName(), args&: ord);
802 lookupsChunk = make<LookupChunk>(args&: ctx, args&: hintChunk);
803 addressesChunk = make<LookupChunk>(args&: ctx, args&: hintChunk);
804 hints.push_back(x: hintChunk);
805 }
806
807 // Detect the first EC-only import in the hybrid IAT. Emit null chunk
808 // as a terminator for the native view, and add an ARM64X relocation to
809 // replace it with the correct import for the EC view.
810 //
811 // Additionally, for MSVC compatibility, store the lookup and address
812 // chunks and append them at the end of EC-only imports, where a null
813 // terminator chunk would typically be placed. Since they appear after
814 // the native terminator, they will be ignored in the native view.
815 // In the EC view, they should act as terminators, so emit ZEROFILL
816 // relocations overriding them.
817 if (ctx.config.machine == ARM64X && !lookupsTerminator &&
818 s->file->isEC() && !s->file->hybridFile) {
819 lookupsTerminator = lookupsChunk;
820 addressesTerminator = addressesChunk;
821 lookupsChunk = make<NullChunk>(args&: ctx);
822 addressesChunk = make<NullChunk>(args&: ctx);
823
824 Arm64XRelocVal relocVal = hintChunk;
825 if (!hintChunk)
826 relocVal = (1ULL << 63) | ord;
827 ctx.dynamicRelocs->add(type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE,
828 size: sizeof(uint64_t), offset: lookupsChunk, value: relocVal);
829 ctx.dynamicRelocs->add(type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE,
830 size: sizeof(uint64_t), offset: addressesChunk, value: relocVal);
831 ctx.dynamicRelocs->add(type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL,
832 size: sizeof(uint64_t), offset: lookupsTerminator);
833 ctx.dynamicRelocs->add(type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL,
834 size: sizeof(uint64_t), offset: addressesTerminator);
835 }
836
837 lookups.push_back(x: lookupsChunk);
838 addresses.push_back(x: addressesChunk);
839
840 if (s->file->isEC()) {
841 auto chunk = make<AuxImportChunk>(args&: s->file);
842 auxIat.push_back(x: chunk);
843 s->file->impECSym->setLocation(chunk);
844
845 chunk = make<AuxImportChunk>(args&: s->file);
846 auxIatCopy.push_back(x: chunk);
847 s->file->auxImpCopySym->setLocation(chunk);
848 } else if (ctx.hybridSymtab) {
849 // Fill the auxiliary IAT with null chunks for native-only imports.
850 auxIat.push_back(x: make<NullChunk>(args&: ctx));
851 auxIatCopy.push_back(x: make<NullChunk>(args&: ctx));
852 ++nativeOnly;
853 }
854 }
855 // Terminate with null values.
856 lookups.push_back(x: lookupsTerminator ? lookupsTerminator
857 : make<NullChunk>(args&: ctx));
858 addresses.push_back(x: addressesTerminator ? addressesTerminator
859 : make<NullChunk>(args&: ctx));
860 if (ctx.symtab.isEC()) {
861 auxIat.push_back(x: make<NullChunk>(args&: ctx));
862 auxIatCopy.push_back(x: make<NullChunk>(args&: ctx));
863 }
864
865 for (int i = 0, e = syms.size(); i < e; ++i) {
866 syms[i]->setLocation(addresses[base + i]);
867 if (syms[i]->file->hybridFile)
868 syms[i]->file->hybridFile->impSym->setLocation(addresses[base + i]);
869 }
870
871 // Create the import table header.
872 dllNames.push_back(x: make<StringChunk>(args: syms[0]->getDLLName()));
873 auto *dir = make<ImportDirectoryChunk>(args&: dllNames.back());
874
875 if (ctx.hybridSymtab && nativeOnly) {
876 if (ctx.config.machine != ARM64X)
877 // On pure ARM64EC targets, skip native-only imports in the import
878 // directory.
879 base += nativeOnly;
880 else if (nativeOnly) {
881 // If native-only imports exist, they will appear as a prefix to all
882 // imports. Emit ARM64X relocations to skip them in the EC view.
883 ctx.dynamicRelocs->add(
884 type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA, size: 0,
885 offset: Arm64XRelocVal(
886 dir, offsetof(ImportDirectoryTableEntry, ImportLookupTableRVA)),
887 value: nativeOnly * sizeof(uint64_t));
888 ctx.dynamicRelocs->add(
889 type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA, size: 0,
890 offset: Arm64XRelocVal(dir, offsetof(ImportDirectoryTableEntry,
891 ImportAddressTableRVA)),
892 value: nativeOnly * sizeof(uint64_t));
893 }
894 }
895
896 dir->lookupTab = lookups[base];
897 dir->addressTab = addresses[base];
898 dirs.push_back(x: dir);
899 }
900 // Add null terminator.
901 dirs.push_back(x: make<NullChunk>(args: sizeof(ImportDirectoryTableEntry), args: 4));
902}
903
904std::vector<Chunk *> DelayLoadContents::getChunks() {
905 std::vector<Chunk *> v;
906 v.insert(position: v.end(), first: dirs.begin(), last: dirs.end());
907 v.insert(position: v.end(), first: names.begin(), last: names.end());
908 v.insert(position: v.end(), first: hintNames.begin(), last: hintNames.end());
909 v.insert(position: v.end(), first: dllNames.begin(), last: dllNames.end());
910 return v;
911}
912
913std::vector<Chunk *> DelayLoadContents::getDataChunks() {
914 std::vector<Chunk *> v;
915 v.insert(position: v.end(), first: moduleHandles.begin(), last: moduleHandles.end());
916 v.insert(position: v.end(), first: addresses.begin(), last: addresses.end());
917 return v;
918}
919
920uint64_t DelayLoadContents::getDirSize() {
921 return dirs.size() * sizeof(delay_import_directory_table_entry);
922}
923
924void DelayLoadContents::create() {
925 std::vector<std::vector<DefinedImportData *>> v = binImports(ctx, imports);
926
927 // Create .didat contents for each DLL.
928 for (std::vector<DefinedImportData *> &syms : v) {
929 // Create the delay import table header.
930 dllNames.push_back(x: make<StringChunk>(args: syms[0]->getDLLName()));
931 auto *dir = make<DelayDirectoryChunk>(args&: dllNames.back());
932
933 size_t base = addresses.size();
934 ctx.forEachSymtab(f: [&](SymbolTable &symtab) {
935 if (symtab.isEC()) {
936 if (ctx.config.machine == ARM64X) {
937 // For hybrid images, emit null-terminated native import entries
938 // followed by null-terminated EC entries. If a view is missing
939 // imports for a given module, only terminators are emitted. Emit
940 // ARM64X relocations to skip native entries in the EC view.
941 ctx.dynamicRelocs->add(
942 type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA, size: 0,
943 offset: Arm64XRelocVal(dir, offsetof(delay_import_directory_table_entry,
944 DelayImportAddressTable)),
945 value: (addresses.size() - base) * sizeof(uint64_t));
946 ctx.dynamicRelocs->add(
947 type: IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA, size: 0,
948 offset: Arm64XRelocVal(dir, offsetof(delay_import_directory_table_entry,
949 DelayImportNameTable)),
950 value: (addresses.size() - base) * sizeof(uint64_t));
951 } else {
952 base = addresses.size();
953 }
954 }
955
956 Chunk *tm = nullptr;
957
958 for (DefinedImportData *s : syms) {
959 // Process only the symbols belonging to the current symtab.
960 if (symtab.isEC() != s->file->isEC())
961 continue;
962
963 if (!tm) {
964 tm = newTailMergeChunk(symtab, dir);
965 Chunk *pdataChunk = newTailMergePDataChunk(symtab, tm);
966 if (pdataChunk)
967 pdata.push_back(x: pdataChunk);
968 }
969
970 Chunk *t = newThunkChunk(s, tailMerge: tm);
971 auto *a = make<DelayAddressChunk>(args&: ctx, args&: t);
972 addresses.push_back(x: a);
973 s->setLocation(a);
974 thunks.push_back(x: t);
975 StringRef extName = s->getExternalName();
976 if (extName.empty()) {
977 names.push_back(x: make<OrdinalOnlyChunk>(args&: ctx, args: s->getOrdinal()));
978 } else {
979 auto *c = make<HintNameChunk>(args&: extName, args: 0);
980 names.push_back(x: make<LookupChunk>(args&: ctx, args&: c));
981 hintNames.push_back(x: c);
982 // Add a synthetic symbol for this load thunk, using the
983 // "__imp___load" prefix, in case this thunk needs to be added to the
984 // list of valid call targets for Control Flow Guard.
985 StringRef symName = saver().save(S: "__imp___load_" + extName);
986 s->loadThunkSym =
987 cast<DefinedSynthetic>(Val: symtab.addSynthetic(n: symName, c: t));
988 }
989
990 if (symtab.isEC()) {
991 auto chunk = make<AuxImportChunk>(args&: s->file);
992 auxIat.push_back(x: chunk);
993 s->file->impECSym->setLocation(chunk);
994
995 chunk = make<AuxImportChunk>(args&: s->file);
996 auxIatCopy.push_back(x: chunk);
997 s->file->auxImpCopySym->setLocation(chunk);
998 } else if (ctx.config.machine == ARM64X) {
999 // Fill the auxiliary IAT with null chunks for native imports.
1000 auxIat.push_back(x: make<NullChunk>(args&: ctx));
1001 auxIatCopy.push_back(x: make<NullChunk>(args&: ctx));
1002 }
1003 }
1004
1005 if (tm) {
1006 thunks.push_back(x: tm);
1007 StringRef tmName =
1008 saver().save(S: "__tailMerge_" + syms[0]->getDLLName().lower());
1009 symtab.addSynthetic(n: tmName, c: tm);
1010 }
1011
1012 // Skip terminators on pure ARM64EC target if there are no native imports.
1013 if (!tm && !symtab.isEC() && ctx.config.machine != ARM64X)
1014 return;
1015
1016 // Terminate with null values.
1017 addresses.push_back(x: make<NullChunk>(args&: ctx, args: 8));
1018 names.push_back(x: make<NullChunk>(args&: ctx, args: 8));
1019 if (ctx.symtab.isEC()) {
1020 auxIat.push_back(x: make<NullChunk>(args&: ctx, args: 8));
1021 auxIatCopy.push_back(x: make<NullChunk>(args&: ctx, args: 8));
1022 }
1023 });
1024
1025 auto *mh = make<NullChunk>(args: 8, args: 8);
1026 moduleHandles.push_back(x: mh);
1027
1028 // Fill the delay import table header fields.
1029 dir->moduleHandle = mh;
1030 dir->addressTab = addresses[base];
1031 dir->nameTab = names[base];
1032 dirs.push_back(x: dir);
1033 }
1034
1035 ctx.forEachSymtab(f: [&](SymbolTable &symtab) {
1036 if (symtab.tailMergeUnwindInfoChunk)
1037 unwindinfo.push_back(x: symtab.tailMergeUnwindInfoChunk);
1038 });
1039 // Add null terminator.
1040 dirs.push_back(
1041 x: make<NullChunk>(args: sizeof(delay_import_directory_table_entry), args: 4));
1042}
1043
1044Chunk *DelayLoadContents::newTailMergeChunk(SymbolTable &symtab, Chunk *dir) {
1045 auto helper = cast_or_null<Defined>(Val: symtab.delayLoadHelper);
1046 switch (symtab.machine) {
1047 case AMD64:
1048 case ARM64EC:
1049 return make<TailMergeChunkX64>(args&: dir, args&: helper);
1050 case I386:
1051 return make<TailMergeChunkX86>(args&: ctx, args&: dir, args&: helper);
1052 case ARMNT:
1053 return make<TailMergeChunkARM>(args&: ctx, args&: dir, args&: helper);
1054 case ARM64:
1055 return make<TailMergeChunkARM64>(args&: dir, args&: helper);
1056 default:
1057 llvm_unreachable("unsupported machine type");
1058 }
1059}
1060
1061Chunk *DelayLoadContents::newTailMergePDataChunk(SymbolTable &symtab,
1062 Chunk *tm) {
1063 switch (symtab.machine) {
1064 case AMD64:
1065 case ARM64EC:
1066 if (!symtab.tailMergeUnwindInfoChunk)
1067 symtab.tailMergeUnwindInfoChunk = make<TailMergeUnwindInfoX64>();
1068 return make<TailMergePDataChunkX64>(args&: tm, args&: symtab.tailMergeUnwindInfoChunk);
1069 // FIXME: Add support for other architectures.
1070 default:
1071 return nullptr; // Just don't generate unwind info.
1072 }
1073}
1074
1075Chunk *DelayLoadContents::newThunkChunk(DefinedImportData *s,
1076 Chunk *tailMerge) {
1077 switch (s->file->getMachineType()) {
1078 case AMD64:
1079 case ARM64EC:
1080 return make<ThunkChunkX64>(args&: s, args&: tailMerge);
1081 case I386:
1082 return make<ThunkChunkX86>(args&: ctx, args&: s, args&: tailMerge);
1083 case ARMNT:
1084 return make<ThunkChunkARM>(args&: ctx, args&: s, args&: tailMerge);
1085 case ARM64:
1086 return make<ThunkChunkARM64>(args&: s, args&: tailMerge);
1087 default:
1088 llvm_unreachable("unsupported machine type");
1089 }
1090}
1091
1092void createEdataChunks(SymbolTable &symtab, std::vector<Chunk *> &chunks) {
1093 unsigned baseOrdinal = 1 << 16, maxOrdinal = 0;
1094 for (Export &e : symtab.exports) {
1095 baseOrdinal = std::min(a: baseOrdinal, b: (unsigned)e.ordinal);
1096 maxOrdinal = std::max(a: maxOrdinal, b: (unsigned)e.ordinal);
1097 }
1098 // Ordinals must start at 1 as suggested in:
1099 // https://learn.microsoft.com/en-us/cpp/build/reference/export-exports-a-function?view=msvc-170
1100 assert(baseOrdinal >= 1);
1101
1102 auto *dllName =
1103 make<StringChunk>(args: sys::path::filename(path: symtab.ctx.config.outputFile));
1104 auto *addressTab = make<AddressTableChunk>(args&: symtab, args&: baseOrdinal, args&: maxOrdinal);
1105 std::vector<Chunk *> names;
1106 for (Export &e : symtab.exports)
1107 if (!e.noname)
1108 names.push_back(x: make<StringChunk>(args&: e.exportName));
1109
1110 std::vector<Chunk *> forwards;
1111 for (Export &e : symtab.exports) {
1112 if (e.forwardTo.empty())
1113 continue;
1114 e.forwardChunk = make<StringChunk>(args&: e.forwardTo);
1115 forwards.push_back(x: e.forwardChunk);
1116 }
1117
1118 auto *nameTab = make<NamePointersChunk>(args&: names);
1119 auto *ordinalTab =
1120 make<ExportOrdinalChunk>(args&: symtab, args&: baseOrdinal, args: names.size());
1121 auto *dir =
1122 make<ExportDirectoryChunk>(args&: baseOrdinal, args&: maxOrdinal, args: names.size(), args&: dllName,
1123 args&: addressTab, args&: nameTab, args&: ordinalTab);
1124 chunks.push_back(x: dir);
1125 chunks.push_back(x: dllName);
1126 chunks.push_back(x: addressTab);
1127 chunks.push_back(x: nameTab);
1128 chunks.push_back(x: ordinalTab);
1129 chunks.insert(position: chunks.end(), first: names.begin(), last: names.end());
1130 chunks.insert(position: chunks.end(), first: forwards.begin(), last: forwards.end());
1131}
1132
1133} // namespace lld::coff
1134