xref: /freebsd/contrib/llvm-project/lld/COFF/DLL.cpp (revision 1323ec57)
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 "Chunks.h"
22 #include "SymbolTable.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Path.h"
26 
27 using namespace llvm;
28 using namespace llvm::object;
29 using namespace llvm::support::endian;
30 using namespace llvm::COFF;
31 
32 namespace lld {
33 namespace coff {
34 namespace {
35 
36 // Import table
37 
38 // A chunk for the import descriptor table.
39 class HintNameChunk : public NonSectionChunk {
40 public:
41   HintNameChunk(StringRef n, uint16_t h) : name(n), hint(h) {}
42 
43   size_t getSize() const override {
44     // Starts with 2 byte Hint field, followed by a null-terminated string,
45     // ends with 0 or 1 byte padding.
46     return alignTo(name.size() + 3, 2);
47   }
48 
49   void writeTo(uint8_t *buf) const override {
50     memset(buf, 0, getSize());
51     write16le(buf, hint);
52     memcpy(buf + 2, name.data(), name.size());
53   }
54 
55 private:
56   StringRef name;
57   uint16_t hint;
58 };
59 
60 // A chunk for the import descriptor table.
61 class LookupChunk : public NonSectionChunk {
62 public:
63   explicit LookupChunk(Chunk *c) : hintName(c) {
64     setAlignment(config->wordsize);
65   }
66   size_t getSize() const override { return config->wordsize; }
67 
68   void writeTo(uint8_t *buf) const override {
69     if (config->is64())
70       write64le(buf, hintName->getRVA());
71     else
72       write32le(buf, hintName->getRVA());
73   }
74 
75   Chunk *hintName;
76 };
77 
78 // A chunk for the import descriptor table.
79 // This chunk represent import-by-ordinal symbols.
80 // See Microsoft PE/COFF spec 7.1. Import Header for details.
81 class OrdinalOnlyChunk : public NonSectionChunk {
82 public:
83   explicit OrdinalOnlyChunk(uint16_t v) : ordinal(v) {
84     setAlignment(config->wordsize);
85   }
86   size_t getSize() const override { return config->wordsize; }
87 
88   void writeTo(uint8_t *buf) const override {
89     // An import-by-ordinal slot has MSB 1 to indicate that
90     // this is import-by-ordinal (and not import-by-name).
91     if (config->is64()) {
92       write64le(buf, (1ULL << 63) | ordinal);
93     } else {
94       write32le(buf, (1ULL << 31) | ordinal);
95     }
96   }
97 
98   uint16_t ordinal;
99 };
100 
101 // A chunk for the import descriptor table.
102 class ImportDirectoryChunk : public NonSectionChunk {
103 public:
104   explicit ImportDirectoryChunk(Chunk *n) : dllName(n) {}
105   size_t getSize() const override { return sizeof(ImportDirectoryTableEntry); }
106 
107   void writeTo(uint8_t *buf) const override {
108     memset(buf, 0, getSize());
109 
110     auto *e = (coff_import_directory_table_entry *)(buf);
111     e->ImportLookupTableRVA = lookupTab->getRVA();
112     e->NameRVA = dllName->getRVA();
113     e->ImportAddressTableRVA = addressTab->getRVA();
114   }
115 
116   Chunk *dllName;
117   Chunk *lookupTab;
118   Chunk *addressTab;
119 };
120 
121 // A chunk representing null terminator in the import table.
122 // Contents of this chunk is always null bytes.
123 class NullChunk : public NonSectionChunk {
124 public:
125   explicit NullChunk(size_t n) : size(n) { hasData = false; }
126   size_t getSize() const override { return size; }
127 
128   void writeTo(uint8_t *buf) const override {
129     memset(buf, 0, size);
130   }
131 
132 private:
133   size_t size;
134 };
135 
136 static std::vector<std::vector<DefinedImportData *>>
137 binImports(const std::vector<DefinedImportData *> &imports) {
138   // Group DLL-imported symbols by DLL name because that's how
139   // symbols are laid out in the import descriptor table.
140   auto less = [](const std::string &a, const std::string &b) {
141     return config->dllOrder[a] < config->dllOrder[b];
142   };
143   std::map<std::string, std::vector<DefinedImportData *>,
144            bool(*)(const std::string &, const std::string &)> m(less);
145   for (DefinedImportData *sym : imports)
146     m[sym->getDLLName().lower()].push_back(sym);
147 
148   std::vector<std::vector<DefinedImportData *>> v;
149   for (auto &kv : m) {
150     // Sort symbols by name for each group.
151     std::vector<DefinedImportData *> &syms = kv.second;
152     std::sort(syms.begin(), syms.end(),
153               [](DefinedImportData *a, DefinedImportData *b) {
154                 return a->getName() < b->getName();
155               });
156     v.push_back(std::move(syms));
157   }
158   return v;
159 }
160 
161 // See Microsoft PE/COFF spec 4.3 for details.
162 
163 // A chunk for the delay import descriptor table etnry.
164 class DelayDirectoryChunk : public NonSectionChunk {
165 public:
166   explicit DelayDirectoryChunk(Chunk *n) : dllName(n) {}
167 
168   size_t getSize() const override {
169     return sizeof(delay_import_directory_table_entry);
170   }
171 
172   void writeTo(uint8_t *buf) const override {
173     memset(buf, 0, getSize());
174 
175     auto *e = (delay_import_directory_table_entry *)(buf);
176     e->Attributes = 1;
177     e->Name = dllName->getRVA();
178     e->ModuleHandle = moduleHandle->getRVA();
179     e->DelayImportAddressTable = addressTab->getRVA();
180     e->DelayImportNameTable = nameTab->getRVA();
181   }
182 
183   Chunk *dllName;
184   Chunk *moduleHandle;
185   Chunk *addressTab;
186   Chunk *nameTab;
187 };
188 
189 // Initial contents for delay-loaded functions.
190 // This code calls __delayLoadHelper2 function to resolve a symbol
191 // which then overwrites its jump table slot with the result
192 // for subsequent function calls.
193 static const uint8_t thunkX64[] = {
194     0x48, 0x8D, 0x05, 0, 0, 0, 0,       // lea     rax, [__imp_<FUNCNAME>]
195     0xE9, 0, 0, 0, 0,                   // jmp     __tailMerge_<lib>
196 };
197 
198 static const uint8_t tailMergeX64[] = {
199     0x51,                               // push    rcx
200     0x52,                               // push    rdx
201     0x41, 0x50,                         // push    r8
202     0x41, 0x51,                         // push    r9
203     0x48, 0x83, 0xEC, 0x48,             // sub     rsp, 48h
204     0x66, 0x0F, 0x7F, 0x04, 0x24,       // movdqa  xmmword ptr [rsp], xmm0
205     0x66, 0x0F, 0x7F, 0x4C, 0x24, 0x10, // movdqa  xmmword ptr [rsp+10h], xmm1
206     0x66, 0x0F, 0x7F, 0x54, 0x24, 0x20, // movdqa  xmmword ptr [rsp+20h], xmm2
207     0x66, 0x0F, 0x7F, 0x5C, 0x24, 0x30, // movdqa  xmmword ptr [rsp+30h], xmm3
208     0x48, 0x8B, 0xD0,                   // mov     rdx, rax
209     0x48, 0x8D, 0x0D, 0, 0, 0, 0,       // lea     rcx, [___DELAY_IMPORT_...]
210     0xE8, 0, 0, 0, 0,                   // call    __delayLoadHelper2
211     0x66, 0x0F, 0x6F, 0x04, 0x24,       // movdqa  xmm0, xmmword ptr [rsp]
212     0x66, 0x0F, 0x6F, 0x4C, 0x24, 0x10, // movdqa  xmm1, xmmword ptr [rsp+10h]
213     0x66, 0x0F, 0x6F, 0x54, 0x24, 0x20, // movdqa  xmm2, xmmword ptr [rsp+20h]
214     0x66, 0x0F, 0x6F, 0x5C, 0x24, 0x30, // movdqa  xmm3, xmmword ptr [rsp+30h]
215     0x48, 0x83, 0xC4, 0x48,             // add     rsp, 48h
216     0x41, 0x59,                         // pop     r9
217     0x41, 0x58,                         // pop     r8
218     0x5A,                               // pop     rdx
219     0x59,                               // pop     rcx
220     0xFF, 0xE0,                         // jmp     rax
221 };
222 
223 static const uint8_t thunkX86[] = {
224     0xB8, 0, 0, 0, 0,  // mov   eax, offset ___imp__<FUNCNAME>
225     0xE9, 0, 0, 0, 0,  // jmp   __tailMerge_<lib>
226 };
227 
228 static const uint8_t tailMergeX86[] = {
229     0x51,              // push  ecx
230     0x52,              // push  edx
231     0x50,              // push  eax
232     0x68, 0, 0, 0, 0,  // push  offset ___DELAY_IMPORT_DESCRIPTOR_<DLLNAME>_dll
233     0xE8, 0, 0, 0, 0,  // call  ___delayLoadHelper2@8
234     0x5A,              // pop   edx
235     0x59,              // pop   ecx
236     0xFF, 0xE0,        // jmp   eax
237 };
238 
239 static const uint8_t thunkARM[] = {
240     0x40, 0xf2, 0x00, 0x0c, // mov.w   ip, #0 __imp_<FUNCNAME>
241     0xc0, 0xf2, 0x00, 0x0c, // mov.t   ip, #0 __imp_<FUNCNAME>
242     0x00, 0xf0, 0x00, 0xb8, // b.w     __tailMerge_<lib>
243 };
244 
245 static const uint8_t tailMergeARM[] = {
246     0x2d, 0xe9, 0x0f, 0x48, // push.w  {r0, r1, r2, r3, r11, lr}
247     0x0d, 0xf2, 0x10, 0x0b, // addw    r11, sp, #16
248     0x2d, 0xed, 0x10, 0x0b, // vpush   {d0, d1, d2, d3, d4, d5, d6, d7}
249     0x61, 0x46,             // mov     r1, ip
250     0x40, 0xf2, 0x00, 0x00, // mov.w   r0, #0 DELAY_IMPORT_DESCRIPTOR
251     0xc0, 0xf2, 0x00, 0x00, // mov.t   r0, #0 DELAY_IMPORT_DESCRIPTOR
252     0x00, 0xf0, 0x00, 0xd0, // bl      #0 __delayLoadHelper2
253     0x84, 0x46,             // mov     ip, r0
254     0xbd, 0xec, 0x10, 0x0b, // vpop    {d0, d1, d2, d3, d4, d5, d6, d7}
255     0xbd, 0xe8, 0x0f, 0x48, // pop.w   {r0, r1, r2, r3, r11, lr}
256     0x60, 0x47,             // bx      ip
257 };
258 
259 static const uint8_t thunkARM64[] = {
260     0x11, 0x00, 0x00, 0x90, // adrp    x17, #0      __imp_<FUNCNAME>
261     0x31, 0x02, 0x00, 0x91, // add     x17, x17, #0 :lo12:__imp_<FUNCNAME>
262     0x00, 0x00, 0x00, 0x14, // b       __tailMerge_<lib>
263 };
264 
265 static const uint8_t tailMergeARM64[] = {
266     0xfd, 0x7b, 0xb3, 0xa9, // stp     x29, x30, [sp, #-208]!
267     0xfd, 0x03, 0x00, 0x91, // mov     x29, sp
268     0xe0, 0x07, 0x01, 0xa9, // stp     x0, x1, [sp, #16]
269     0xe2, 0x0f, 0x02, 0xa9, // stp     x2, x3, [sp, #32]
270     0xe4, 0x17, 0x03, 0xa9, // stp     x4, x5, [sp, #48]
271     0xe6, 0x1f, 0x04, 0xa9, // stp     x6, x7, [sp, #64]
272     0xe0, 0x87, 0x02, 0xad, // stp     q0, q1, [sp, #80]
273     0xe2, 0x8f, 0x03, 0xad, // stp     q2, q3, [sp, #112]
274     0xe4, 0x97, 0x04, 0xad, // stp     q4, q5, [sp, #144]
275     0xe6, 0x9f, 0x05, 0xad, // stp     q6, q7, [sp, #176]
276     0xe1, 0x03, 0x11, 0xaa, // mov     x1, x17
277     0x00, 0x00, 0x00, 0x90, // adrp    x0, #0     DELAY_IMPORT_DESCRIPTOR
278     0x00, 0x00, 0x00, 0x91, // add     x0, x0, #0 :lo12:DELAY_IMPORT_DESCRIPTOR
279     0x00, 0x00, 0x00, 0x94, // bl      #0 __delayLoadHelper2
280     0xf0, 0x03, 0x00, 0xaa, // mov     x16, x0
281     0xe6, 0x9f, 0x45, 0xad, // ldp     q6, q7, [sp, #176]
282     0xe4, 0x97, 0x44, 0xad, // ldp     q4, q5, [sp, #144]
283     0xe2, 0x8f, 0x43, 0xad, // ldp     q2, q3, [sp, #112]
284     0xe0, 0x87, 0x42, 0xad, // ldp     q0, q1, [sp, #80]
285     0xe6, 0x1f, 0x44, 0xa9, // ldp     x6, x7, [sp, #64]
286     0xe4, 0x17, 0x43, 0xa9, // ldp     x4, x5, [sp, #48]
287     0xe2, 0x0f, 0x42, 0xa9, // ldp     x2, x3, [sp, #32]
288     0xe0, 0x07, 0x41, 0xa9, // ldp     x0, x1, [sp, #16]
289     0xfd, 0x7b, 0xcd, 0xa8, // ldp     x29, x30, [sp], #208
290     0x00, 0x02, 0x1f, 0xd6, // br      x16
291 };
292 
293 // A chunk for the delay import thunk.
294 class ThunkChunkX64 : public NonSectionChunk {
295 public:
296   ThunkChunkX64(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
297 
298   size_t getSize() const override { return sizeof(thunkX64); }
299 
300   void writeTo(uint8_t *buf) const override {
301     memcpy(buf, thunkX64, sizeof(thunkX64));
302     write32le(buf + 3, imp->getRVA() - rva - 7);
303     write32le(buf + 8, tailMerge->getRVA() - rva - 12);
304   }
305 
306   Defined *imp = nullptr;
307   Chunk *tailMerge = nullptr;
308 };
309 
310 class TailMergeChunkX64 : public NonSectionChunk {
311 public:
312   TailMergeChunkX64(Chunk *d, Defined *h) : desc(d), helper(h) {}
313 
314   size_t getSize() const override { return sizeof(tailMergeX64); }
315 
316   void writeTo(uint8_t *buf) const override {
317     memcpy(buf, tailMergeX64, sizeof(tailMergeX64));
318     write32le(buf + 39, desc->getRVA() - rva - 43);
319     write32le(buf + 44, helper->getRVA() - rva - 48);
320   }
321 
322   Chunk *desc = nullptr;
323   Defined *helper = nullptr;
324 };
325 
326 class ThunkChunkX86 : public NonSectionChunk {
327 public:
328   ThunkChunkX86(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {}
329 
330   size_t getSize() const override { return sizeof(thunkX86); }
331 
332   void writeTo(uint8_t *buf) const override {
333     memcpy(buf, thunkX86, sizeof(thunkX86));
334     write32le(buf + 1, imp->getRVA() + config->imageBase);
335     write32le(buf + 6, tailMerge->getRVA() - rva - 10);
336   }
337 
338   void getBaserels(std::vector<Baserel> *res) override {
339     res->emplace_back(rva + 1);
340   }
341 
342   Defined *imp = nullptr;
343   Chunk *tailMerge = nullptr;
344 };
345 
346 class TailMergeChunkX86 : public NonSectionChunk {
347 public:
348   TailMergeChunkX86(Chunk *d, Defined *h) : desc(d), helper(h) {}
349 
350   size_t getSize() const override { return sizeof(tailMergeX86); }
351 
352   void writeTo(uint8_t *buf) const override {
353     memcpy(buf, tailMergeX86, sizeof(tailMergeX86));
354     write32le(buf + 4, desc->getRVA() + config->imageBase);
355     write32le(buf + 9, helper->getRVA() - rva - 13);
356   }
357 
358   void getBaserels(std::vector<Baserel> *res) override {
359     res->emplace_back(rva + 4);
360   }
361 
362   Chunk *desc = nullptr;
363   Defined *helper = nullptr;
364 };
365 
366 class ThunkChunkARM : public NonSectionChunk {
367 public:
368   ThunkChunkARM(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {
369     setAlignment(2);
370   }
371 
372   size_t getSize() const override { return sizeof(thunkARM); }
373 
374   void writeTo(uint8_t *buf) const override {
375     memcpy(buf, thunkARM, sizeof(thunkARM));
376     applyMOV32T(buf + 0, imp->getRVA() + config->imageBase);
377     applyBranch24T(buf + 8, tailMerge->getRVA() - rva - 12);
378   }
379 
380   void getBaserels(std::vector<Baserel> *res) override {
381     res->emplace_back(rva + 0, IMAGE_REL_BASED_ARM_MOV32T);
382   }
383 
384   Defined *imp = nullptr;
385   Chunk *tailMerge = nullptr;
386 };
387 
388 class TailMergeChunkARM : public NonSectionChunk {
389 public:
390   TailMergeChunkARM(Chunk *d, Defined *h) : desc(d), helper(h) {
391     setAlignment(2);
392   }
393 
394   size_t getSize() const override { return sizeof(tailMergeARM); }
395 
396   void writeTo(uint8_t *buf) const override {
397     memcpy(buf, tailMergeARM, sizeof(tailMergeARM));
398     applyMOV32T(buf + 14, desc->getRVA() + config->imageBase);
399     applyBranch24T(buf + 22, helper->getRVA() - rva - 26);
400   }
401 
402   void getBaserels(std::vector<Baserel> *res) override {
403     res->emplace_back(rva + 14, IMAGE_REL_BASED_ARM_MOV32T);
404   }
405 
406   Chunk *desc = nullptr;
407   Defined *helper = nullptr;
408 };
409 
410 class ThunkChunkARM64 : public NonSectionChunk {
411 public:
412   ThunkChunkARM64(Defined *i, Chunk *tm) : imp(i), tailMerge(tm) {
413     setAlignment(4);
414   }
415 
416   size_t getSize() const override { return sizeof(thunkARM64); }
417 
418   void writeTo(uint8_t *buf) const override {
419     memcpy(buf, thunkARM64, sizeof(thunkARM64));
420     applyArm64Addr(buf + 0, imp->getRVA(), rva + 0, 12);
421     applyArm64Imm(buf + 4, imp->getRVA() & 0xfff, 0);
422     applyArm64Branch26(buf + 8, tailMerge->getRVA() - rva - 8);
423   }
424 
425   Defined *imp = nullptr;
426   Chunk *tailMerge = nullptr;
427 };
428 
429 class TailMergeChunkARM64 : public NonSectionChunk {
430 public:
431   TailMergeChunkARM64(Chunk *d, Defined *h) : desc(d), helper(h) {
432     setAlignment(4);
433   }
434 
435   size_t getSize() const override { return sizeof(tailMergeARM64); }
436 
437   void writeTo(uint8_t *buf) const override {
438     memcpy(buf, tailMergeARM64, sizeof(tailMergeARM64));
439     applyArm64Addr(buf + 44, desc->getRVA(), rva + 44, 12);
440     applyArm64Imm(buf + 48, desc->getRVA() & 0xfff, 0);
441     applyArm64Branch26(buf + 52, helper->getRVA() - rva - 52);
442   }
443 
444   Chunk *desc = nullptr;
445   Defined *helper = nullptr;
446 };
447 
448 // A chunk for the import descriptor table.
449 class DelayAddressChunk : public NonSectionChunk {
450 public:
451   explicit DelayAddressChunk(Chunk *c) : thunk(c) {
452     setAlignment(config->wordsize);
453   }
454   size_t getSize() const override { return config->wordsize; }
455 
456   void writeTo(uint8_t *buf) const override {
457     if (config->is64()) {
458       write64le(buf, thunk->getRVA() + config->imageBase);
459     } else {
460       uint32_t bit = 0;
461       // Pointer to thumb code must have the LSB set, so adjust it.
462       if (config->machine == ARMNT)
463         bit = 1;
464       write32le(buf, (thunk->getRVA() + config->imageBase) | bit);
465     }
466   }
467 
468   void getBaserels(std::vector<Baserel> *res) override {
469     res->emplace_back(rva);
470   }
471 
472   Chunk *thunk;
473 };
474 
475 // Export table
476 // Read Microsoft PE/COFF spec 5.3 for details.
477 
478 // A chunk for the export descriptor table.
479 class ExportDirectoryChunk : public NonSectionChunk {
480 public:
481   ExportDirectoryChunk(int i, int j, Chunk *d, Chunk *a, Chunk *n, Chunk *o)
482       : maxOrdinal(i), nameTabSize(j), dllName(d), addressTab(a), nameTab(n),
483         ordinalTab(o) {}
484 
485   size_t getSize() const override {
486     return sizeof(export_directory_table_entry);
487   }
488 
489   void writeTo(uint8_t *buf) const override {
490     memset(buf, 0, getSize());
491 
492     auto *e = (export_directory_table_entry *)(buf);
493     e->NameRVA = dllName->getRVA();
494     e->OrdinalBase = 0;
495     e->AddressTableEntries = maxOrdinal + 1;
496     e->NumberOfNamePointers = nameTabSize;
497     e->ExportAddressTableRVA = addressTab->getRVA();
498     e->NamePointerRVA = nameTab->getRVA();
499     e->OrdinalTableRVA = ordinalTab->getRVA();
500   }
501 
502   uint16_t maxOrdinal;
503   uint16_t nameTabSize;
504   Chunk *dllName;
505   Chunk *addressTab;
506   Chunk *nameTab;
507   Chunk *ordinalTab;
508 };
509 
510 class AddressTableChunk : public NonSectionChunk {
511 public:
512   explicit AddressTableChunk(size_t maxOrdinal) : size(maxOrdinal + 1) {}
513   size_t getSize() const override { return size * 4; }
514 
515   void writeTo(uint8_t *buf) const override {
516     memset(buf, 0, getSize());
517 
518     for (const Export &e : config->exports) {
519       uint8_t *p = buf + e.ordinal * 4;
520       uint32_t bit = 0;
521       // Pointer to thumb code must have the LSB set, so adjust it.
522       if (config->machine == ARMNT && !e.data)
523         bit = 1;
524       if (e.forwardChunk) {
525         write32le(p, e.forwardChunk->getRVA() | bit);
526       } else {
527         assert(cast<Defined>(e.sym)->getRVA() != 0 &&
528                "Exported symbol unmapped");
529         write32le(p, cast<Defined>(e.sym)->getRVA() | bit);
530       }
531     }
532   }
533 
534 private:
535   size_t size;
536 };
537 
538 class NamePointersChunk : public NonSectionChunk {
539 public:
540   explicit NamePointersChunk(std::vector<Chunk *> &v) : chunks(v) {}
541   size_t getSize() const override { return chunks.size() * 4; }
542 
543   void writeTo(uint8_t *buf) const override {
544     for (Chunk *c : chunks) {
545       write32le(buf, c->getRVA());
546       buf += 4;
547     }
548   }
549 
550 private:
551   std::vector<Chunk *> chunks;
552 };
553 
554 class ExportOrdinalChunk : public NonSectionChunk {
555 public:
556   explicit ExportOrdinalChunk(size_t i) : size(i) {}
557   size_t getSize() const override { return size * 2; }
558 
559   void writeTo(uint8_t *buf) const override {
560     for (Export &e : config->exports) {
561       if (e.noname)
562         continue;
563       write16le(buf, e.ordinal);
564       buf += 2;
565     }
566   }
567 
568 private:
569   size_t size;
570 };
571 
572 } // anonymous namespace
573 
574 void IdataContents::create() {
575   std::vector<std::vector<DefinedImportData *>> v = binImports(imports);
576 
577   // Create .idata contents for each DLL.
578   for (std::vector<DefinedImportData *> &syms : v) {
579     // Create lookup and address tables. If they have external names,
580     // we need to create hintName chunks to store the names.
581     // If they don't (if they are import-by-ordinals), we store only
582     // ordinal values to the table.
583     size_t base = lookups.size();
584     for (DefinedImportData *s : syms) {
585       uint16_t ord = s->getOrdinal();
586       if (s->getExternalName().empty()) {
587         lookups.push_back(make<OrdinalOnlyChunk>(ord));
588         addresses.push_back(make<OrdinalOnlyChunk>(ord));
589         continue;
590       }
591       auto *c = make<HintNameChunk>(s->getExternalName(), ord);
592       lookups.push_back(make<LookupChunk>(c));
593       addresses.push_back(make<LookupChunk>(c));
594       hints.push_back(c);
595     }
596     // Terminate with null values.
597     lookups.push_back(make<NullChunk>(config->wordsize));
598     addresses.push_back(make<NullChunk>(config->wordsize));
599 
600     for (int i = 0, e = syms.size(); i < e; ++i)
601       syms[i]->setLocation(addresses[base + i]);
602 
603     // Create the import table header.
604     dllNames.push_back(make<StringChunk>(syms[0]->getDLLName()));
605     auto *dir = make<ImportDirectoryChunk>(dllNames.back());
606     dir->lookupTab = lookups[base];
607     dir->addressTab = addresses[base];
608     dirs.push_back(dir);
609   }
610   // Add null terminator.
611   dirs.push_back(make<NullChunk>(sizeof(ImportDirectoryTableEntry)));
612 }
613 
614 std::vector<Chunk *> DelayLoadContents::getChunks() {
615   std::vector<Chunk *> v;
616   v.insert(v.end(), dirs.begin(), dirs.end());
617   v.insert(v.end(), names.begin(), names.end());
618   v.insert(v.end(), hintNames.begin(), hintNames.end());
619   v.insert(v.end(), dllNames.begin(), dllNames.end());
620   return v;
621 }
622 
623 std::vector<Chunk *> DelayLoadContents::getDataChunks() {
624   std::vector<Chunk *> v;
625   v.insert(v.end(), moduleHandles.begin(), moduleHandles.end());
626   v.insert(v.end(), addresses.begin(), addresses.end());
627   return v;
628 }
629 
630 uint64_t DelayLoadContents::getDirSize() {
631   return dirs.size() * sizeof(delay_import_directory_table_entry);
632 }
633 
634 void DelayLoadContents::create(Defined *h) {
635   helper = h;
636   std::vector<std::vector<DefinedImportData *>> v = binImports(imports);
637 
638   // Create .didat contents for each DLL.
639   for (std::vector<DefinedImportData *> &syms : v) {
640     // Create the delay import table header.
641     dllNames.push_back(make<StringChunk>(syms[0]->getDLLName()));
642     auto *dir = make<DelayDirectoryChunk>(dllNames.back());
643 
644     size_t base = addresses.size();
645     Chunk *tm = newTailMergeChunk(dir);
646     for (DefinedImportData *s : syms) {
647       Chunk *t = newThunkChunk(s, tm);
648       auto *a = make<DelayAddressChunk>(t);
649       addresses.push_back(a);
650       thunks.push_back(t);
651       StringRef extName = s->getExternalName();
652       if (extName.empty()) {
653         names.push_back(make<OrdinalOnlyChunk>(s->getOrdinal()));
654       } else {
655         auto *c = make<HintNameChunk>(extName, 0);
656         names.push_back(make<LookupChunk>(c));
657         hintNames.push_back(c);
658         // Add a syntentic symbol for this load thunk, using the "__imp_load"
659         // prefix, in case this thunk needs to be added to the list of valid
660         // call targets for Control Flow Guard.
661         StringRef symName = saver.save("__imp_load_" + extName);
662         s->loadThunkSym =
663             cast<DefinedSynthetic>(symtab->addSynthetic(symName, t));
664       }
665     }
666     thunks.push_back(tm);
667     StringRef tmName =
668         saver.save("__tailMerge_" + syms[0]->getDLLName().lower());
669     symtab->addSynthetic(tmName, tm);
670     // Terminate with null values.
671     addresses.push_back(make<NullChunk>(8));
672     names.push_back(make<NullChunk>(8));
673 
674     for (int i = 0, e = syms.size(); i < e; ++i)
675       syms[i]->setLocation(addresses[base + i]);
676     auto *mh = make<NullChunk>(8);
677     mh->setAlignment(8);
678     moduleHandles.push_back(mh);
679 
680     // Fill the delay import table header fields.
681     dir->moduleHandle = mh;
682     dir->addressTab = addresses[base];
683     dir->nameTab = names[base];
684     dirs.push_back(dir);
685   }
686   // Add null terminator.
687   dirs.push_back(make<NullChunk>(sizeof(delay_import_directory_table_entry)));
688 }
689 
690 Chunk *DelayLoadContents::newTailMergeChunk(Chunk *dir) {
691   switch (config->machine) {
692   case AMD64:
693     return make<TailMergeChunkX64>(dir, helper);
694   case I386:
695     return make<TailMergeChunkX86>(dir, helper);
696   case ARMNT:
697     return make<TailMergeChunkARM>(dir, helper);
698   case ARM64:
699     return make<TailMergeChunkARM64>(dir, helper);
700   default:
701     llvm_unreachable("unsupported machine type");
702   }
703 }
704 
705 Chunk *DelayLoadContents::newThunkChunk(DefinedImportData *s,
706                                         Chunk *tailMerge) {
707   switch (config->machine) {
708   case AMD64:
709     return make<ThunkChunkX64>(s, tailMerge);
710   case I386:
711     return make<ThunkChunkX86>(s, tailMerge);
712   case ARMNT:
713     return make<ThunkChunkARM>(s, tailMerge);
714   case ARM64:
715     return make<ThunkChunkARM64>(s, tailMerge);
716   default:
717     llvm_unreachable("unsupported machine type");
718   }
719 }
720 
721 EdataContents::EdataContents() {
722   uint16_t maxOrdinal = 0;
723   for (Export &e : config->exports)
724     maxOrdinal = std::max(maxOrdinal, e.ordinal);
725 
726   auto *dllName = make<StringChunk>(sys::path::filename(config->outputFile));
727   auto *addressTab = make<AddressTableChunk>(maxOrdinal);
728   std::vector<Chunk *> names;
729   for (Export &e : config->exports)
730     if (!e.noname)
731       names.push_back(make<StringChunk>(e.exportName));
732 
733   std::vector<Chunk *> forwards;
734   for (Export &e : config->exports) {
735     if (e.forwardTo.empty())
736       continue;
737     e.forwardChunk = make<StringChunk>(e.forwardTo);
738     forwards.push_back(e.forwardChunk);
739   }
740 
741   auto *nameTab = make<NamePointersChunk>(names);
742   auto *ordinalTab = make<ExportOrdinalChunk>(names.size());
743   auto *dir = make<ExportDirectoryChunk>(maxOrdinal, names.size(), dllName,
744                                          addressTab, nameTab, ordinalTab);
745   chunks.push_back(dir);
746   chunks.push_back(dllName);
747   chunks.push_back(addressTab);
748   chunks.push_back(nameTab);
749   chunks.push_back(ordinalTab);
750   chunks.insert(chunks.end(), names.begin(), names.end());
751   chunks.insert(chunks.end(), forwards.begin(), forwards.end());
752 }
753 
754 } // namespace coff
755 } // namespace lld
756