blob: a03fc12bd6dadd1b359f33e5003122425fdda108 [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000011#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000012#include "InputChunks.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000013#include "OutputSections.h"
14#include "OutputSegment.h"
15#include "SymbolTable.h"
16#include "WriterUtils.h"
17#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000018#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000019#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000020#include "llvm/ADT/DenseSet.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000021#include "llvm/Support/FileOutputBuffer.h"
22#include "llvm/Support/Format.h"
23#include "llvm/Support/FormatVariadic.h"
24#include "llvm/Support/LEB128.h"
25
26#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000027#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000028
29#define DEBUG_TYPE "lld"
30
31using namespace llvm;
32using namespace llvm::wasm;
33using namespace lld;
34using namespace lld::wasm;
35
36static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000037static constexpr int kInitialTableOffset = 1;
Sam Cleggc94d3932017-11-17 18:14:09 +000038
39namespace {
40
Sam Cleggc94d3932017-11-17 18:14:09 +000041// Traits for using WasmSignature in a DenseMap.
42struct WasmSignatureDenseMapInfo {
43 static WasmSignature getEmptyKey() {
44 WasmSignature Sig;
45 Sig.ReturnType = 1;
46 return Sig;
47 }
48 static WasmSignature getTombstoneKey() {
49 WasmSignature Sig;
50 Sig.ReturnType = 2;
51 return Sig;
52 }
53 static unsigned getHashValue(const WasmSignature &Sig) {
54 uintptr_t Value = 0;
55 Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType);
56 for (int32_t Param : Sig.ParamTypes)
57 Value += DenseMapInfo<int32_t>::getHashValue(Param);
58 return Value;
59 }
60 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
61 return LHS == RHS;
62 }
63};
64
Sam Cleggd3052d52018-01-18 23:40:49 +000065// A Wasm export to be written into the export section.
66struct WasmExportEntry {
Sam Clegg811236c2018-01-19 03:31:07 +000067 const Symbol *Sym;
Sam Cleggd3052d52018-01-18 23:40:49 +000068 StringRef FieldName; // may not match the Symbol name
69};
70
Sam Cleggc94d3932017-11-17 18:14:09 +000071// The writer writes a SymbolTable result to a file.
72class Writer {
73public:
74 void run();
75
76private:
77 void openFile();
78
Sam Cleggc375e4e2018-01-10 19:18:22 +000079 uint32_t lookupType(const WasmSignature &Sig);
80 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg50686852018-01-12 18:35:13 +000081 void createCtorFunction();
82 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000083 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000084 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000085 void calculateExports();
Sam Cleggc94d3932017-11-17 18:14:09 +000086 void calculateTypes();
87 void createOutputSegments();
88 void layoutMemory();
89 void createHeader();
90 void createSections();
91 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000092 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000093
94 // Builtin sections
95 void createTypeSection();
96 void createFunctionSection();
97 void createTableSection();
98 void createGlobalSection();
99 void createExportSection();
100 void createImportSection();
101 void createMemorySection();
102 void createElemSection();
103 void createStartSection();
104 void createCodeSection();
105 void createDataSection();
106
107 // Custom sections
108 void createRelocSections();
109 void createLinkingSection();
110 void createNameSection();
111
112 void writeHeader();
113 void writeSections();
114
115 uint64_t FileSize = 0;
116 uint32_t DataSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000117 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000118
119 std::vector<const WasmSignature *> Types;
120 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000121 std::vector<const FunctionSymbol *> ImportedFunctions;
122 std::vector<const GlobalSymbol *> ImportedGlobals;
Sam Cleggd3052d52018-01-18 23:40:49 +0000123 std::vector<WasmExportEntry> ExportedSymbols;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000124 std::vector<const DefinedGlobal *> DefinedGlobals;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000125 std::vector<InputFunction *> DefinedFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000126 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg50686852018-01-12 18:35:13 +0000127 std::vector<WasmInitFunc> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000128
129 // Elements that are used to construct the final output
130 std::string Header;
131 std::vector<OutputSection *> OutputSections;
132
133 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000134 std::unique_ptr<SyntheticFunction> CtorFunction;
135 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000136
137 std::vector<OutputSegment *> Segments;
138 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
139};
140
141} // anonymous namespace
142
143static void debugPrint(const char *fmt, ...) {
144 if (!errorHandler().Verbose)
145 return;
146 fprintf(stderr, "lld: ");
147 va_list ap;
148 va_start(ap, fmt);
149 vfprintf(stderr, fmt, ap);
150 va_end(ap);
151}
152
153void Writer::createImportSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000154 uint32_t NumImports = ImportedFunctions.size() + ImportedGlobals.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000155 if (Config->ImportMemory)
156 ++NumImports;
157
158 if (NumImports == 0)
159 return;
160
161 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
162 raw_ostream &OS = Section->getStream();
163
164 writeUleb128(OS, NumImports, "import count");
165
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000166 for (const FunctionSymbol *Sym : ImportedFunctions) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000167 WasmImport Import;
168 Import.Module = "env";
169 Import.Field = Sym->getName();
170 Import.Kind = WASM_EXTERNAL_FUNCTION;
Sam Clegg3f8db982018-02-16 23:50:23 +0000171 Import.SigIndex = lookupType(*Sym->getFunctionType());
Sam Cleggc94d3932017-11-17 18:14:09 +0000172 writeImport(OS, Import);
173 }
174
175 if (Config->ImportMemory) {
176 WasmImport Import;
177 Import.Module = "env";
178 Import.Field = "memory";
179 Import.Kind = WASM_EXTERNAL_MEMORY;
180 Import.Memory.Flags = 0;
181 Import.Memory.Initial = NumMemoryPages;
182 writeImport(OS, Import);
183 }
184
Sam Clegg8d146bb2018-01-09 23:56:44 +0000185 for (const Symbol *Sym : ImportedGlobals) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 WasmImport Import;
187 Import.Module = "env";
188 Import.Field = Sym->getName();
189 Import.Kind = WASM_EXTERNAL_GLOBAL;
190 Import.Global.Mutable = false;
Sam Cleggd451da12017-12-19 19:56:27 +0000191 Import.Global.Type = WASM_TYPE_I32;
Sam Cleggc94d3932017-11-17 18:14:09 +0000192 writeImport(OS, Import);
193 }
194}
195
196void Writer::createTypeSection() {
197 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
198 raw_ostream &OS = Section->getStream();
199 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000200 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000201 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000202}
203
204void Writer::createFunctionSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000205 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000206 return;
207
208 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
209 raw_ostream &OS = Section->getStream();
210
Sam Clegg8d146bb2018-01-09 23:56:44 +0000211 writeUleb128(OS, DefinedFunctions.size(), "function count");
212 for (const InputFunction *Func : DefinedFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000213 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000214}
215
216void Writer::createMemorySection() {
217 if (Config->ImportMemory)
218 return;
219
220 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
221 raw_ostream &OS = Section->getStream();
222
223 writeUleb128(OS, 1, "memory count");
224 writeUleb128(OS, 0, "memory limits flags");
225 writeUleb128(OS, NumMemoryPages, "initial pages");
226}
227
228void Writer::createGlobalSection() {
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000229 if (DefinedGlobals.empty())
230 return;
231
Sam Cleggc94d3932017-11-17 18:14:09 +0000232 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
233 raw_ostream &OS = Section->getStream();
234
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000235 writeUleb128(OS, DefinedGlobals.size(), "global count");
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000236 for (const DefinedGlobal *Sym : DefinedGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000237 WasmGlobal Global;
Sam Clegg1a9b7b92018-01-31 19:54:34 +0000238 Global.Type.Type = WASM_TYPE_I32;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000239 Global.Type.Mutable = Sym == WasmSym::StackPointer;
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000240 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
241 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000242 writeGlobal(OS, Global);
243 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000244}
245
246void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000247 // Always output a table section, even if there are no indirect calls.
248 // There are two reasons for this:
249 // 1. For executables it is useful to have an empty table slot at 0
250 // which can be filled with a null function call handler.
251 // 2. If we don't do this, any program that contains a call_indirect but
252 // no address-taken function will fail at validation time since it is
253 // a validation error to include a call_indirect instruction if there
254 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000255 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000256
Sam Cleggc94d3932017-11-17 18:14:09 +0000257 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
258 raw_ostream &OS = Section->getStream();
259
260 writeUleb128(OS, 1, "table count");
261 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
262 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000263 writeUleb128(OS, TableSize, "table initial size");
264 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000265}
266
267void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000268 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000269
Sam Cleggd3052d52018-01-18 23:40:49 +0000270 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000271 if (!NumExports)
272 return;
273
274 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
275 raw_ostream &OS = Section->getStream();
276
277 writeUleb128(OS, NumExports, "export count");
278
279 if (ExportMemory) {
280 WasmExport MemoryExport;
281 MemoryExport.Name = "memory";
282 MemoryExport.Kind = WASM_EXTERNAL_MEMORY;
283 MemoryExport.Index = 0;
284 writeExport(OS, MemoryExport);
285 }
286
Sam Cleggd3052d52018-01-18 23:40:49 +0000287 for (const WasmExportEntry &E : ExportedSymbols) {
Sam Clegg811236c2018-01-19 03:31:07 +0000288 DEBUG(dbgs() << "Export: " << E.Sym->getName() << "\n");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000289 WasmExport Export;
Sam Cleggd3052d52018-01-18 23:40:49 +0000290 Export.Name = E.FieldName;
Sam Clegg811236c2018-01-19 03:31:07 +0000291 Export.Index = E.Sym->getOutputIndex();
Sam Cleggcaca8d52018-02-17 00:44:21 +0000292 if (isa<FunctionSymbol>(E.Sym))
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000293 Export.Kind = WASM_EXTERNAL_FUNCTION;
294 else
295 Export.Kind = WASM_EXTERNAL_GLOBAL;
296 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000297 }
298}
299
300void Writer::createStartSection() {}
301
302void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000303 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000304 return;
305
306 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
307 raw_ostream &OS = Section->getStream();
308
309 writeUleb128(OS, 1, "segment count");
310 writeUleb128(OS, 0, "table index");
311 WasmInitExpr InitExpr;
312 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000313 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000314 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000315 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000316
Sam Clegg48bbd632018-01-24 21:37:30 +0000317 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000318 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000319 assert(Sym->getTableIndex() == TableIndex);
320 writeUleb128(OS, Sym->getOutputIndex(), "function index");
321 ++TableIndex;
322 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000323}
324
325void Writer::createCodeSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000326 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000327 return;
328
329 log("createCodeSection");
330
Sam Clegg8d146bb2018-01-09 23:56:44 +0000331 auto Section = make<CodeSection>(DefinedFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000332 OutputSections.push_back(Section);
333}
334
335void Writer::createDataSection() {
336 if (!Segments.size())
337 return;
338
339 log("createDataSection");
340 auto Section = make<DataSection>(Segments);
341 OutputSections.push_back(Section);
342}
343
Sam Cleggd451da12017-12-19 19:56:27 +0000344// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000345// These are only created when relocatable output is requested.
346void Writer::createRelocSections() {
347 log("createRelocSections");
348 // Don't use iterator here since we are adding to OutputSection
349 size_t OrigSize = OutputSections.size();
350 for (size_t i = 0; i < OrigSize; i++) {
351 OutputSection *S = OutputSections[i];
352 const char *name;
353 uint32_t Count = S->numRelocations();
354 if (!Count)
355 continue;
356
357 if (S->Type == WASM_SEC_DATA)
358 name = "reloc.DATA";
359 else if (S->Type == WASM_SEC_CODE)
360 name = "reloc.CODE";
361 else
Sam Cleggd451da12017-12-19 19:56:27 +0000362 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000363
364 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, name);
365 raw_ostream &OS = Section->getStream();
366 writeUleb128(OS, S->Type, "reloc section");
367 writeUleb128(OS, Count, "reloc count");
368 S->writeRelocations(OS);
369 }
370}
371
Sam Clegg49ed9262017-12-01 00:53:21 +0000372// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000373// This is only created when relocatable output is requested.
374void Writer::createLinkingSection() {
375 SyntheticSection *Section =
376 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
377 raw_ostream &OS = Section->getStream();
378
379 SubSection DataSizeSubSection(WASM_DATA_SIZE);
380 writeUleb128(DataSizeSubSection.getStream(), DataSize, "data size");
381 DataSizeSubSection.finalizeContents();
382 DataSizeSubSection.writeToStream(OS);
383
Sam Clegg0d0dd392017-12-19 17:09:45 +0000384 if (!Config->Relocatable)
385 return;
386
Sam Cleggd3052d52018-01-18 23:40:49 +0000387 std::vector<std::pair<StringRef, uint32_t>> SymbolInfo;
Sam Clegg04b76f42018-01-19 21:49:41 +0000388 auto addSymInfo = [&](const Symbol *Sym, StringRef ExternalName) {
Sam Cleggd3052d52018-01-18 23:40:49 +0000389 uint32_t Flags =
Sam Clegg04b76f42018-01-19 21:49:41 +0000390 (Sym->isLocal() ? WASM_SYMBOL_BINDING_LOCAL :
391 Sym->isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0) |
392 (Sym->isHidden() ? WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
Sam Cleggd3052d52018-01-18 23:40:49 +0000393 if (Flags)
Sam Clegg04b76f42018-01-19 21:49:41 +0000394 SymbolInfo.emplace_back(ExternalName, Flags);
395 };
396 // (Imports can't have internal linkage, their names don't need to be budged.)
397 for (const Symbol *Sym : ImportedFunctions)
398 addSymInfo(Sym, Sym->getName());
399 for (const Symbol *Sym : ImportedGlobals)
400 addSymInfo(Sym, Sym->getName());
401 for (const WasmExportEntry &E : ExportedSymbols)
402 addSymInfo(E.Sym, E.FieldName);
Sam Cleggd3052d52018-01-18 23:40:49 +0000403 if (!SymbolInfo.empty()) {
404 SubSection SubSection(WASM_SYMBOL_INFO);
405 writeUleb128(SubSection.getStream(), SymbolInfo.size(), "num sym info");
406 for (auto Pair: SymbolInfo) {
407 writeStr(SubSection.getStream(), Pair.first, "sym name");
408 writeUleb128(SubSection.getStream(), Pair.second, "sym flags");
409 }
410 SubSection.finalizeContents();
411 SubSection.writeToStream(OS);
412 }
413
Sam Clegg0d0dd392017-12-19 17:09:45 +0000414 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000415 SubSection SubSection(WASM_SEGMENT_INFO);
416 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
417 for (const OutputSegment *S : Segments) {
418 writeStr(SubSection.getStream(), S->Name, "segment name");
419 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
420 writeUleb128(SubSection.getStream(), 0, "flags");
421 }
422 SubSection.finalizeContents();
423 SubSection.writeToStream(OS);
424 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000425
Sam Clegg0d0dd392017-12-19 17:09:45 +0000426 if (!InitFunctions.empty()) {
427 SubSection SubSection(WASM_INIT_FUNCS);
428 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000429 "num init functions");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000430 for (const WasmInitFunc &F : InitFunctions) {
431 writeUleb128(SubSection.getStream(), F.Priority, "priority");
432 writeUleb128(SubSection.getStream(), F.FunctionIndex, "function index");
433 }
434 SubSection.finalizeContents();
435 SubSection.writeToStream(OS);
436 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000437
438 struct ComdatEntry { unsigned Kind; uint32_t Index; };
439 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
440
441 for (const InputFunction *F : DefinedFunctions) {
442 StringRef Comdat = F->getComdat();
443 if (!Comdat.empty())
444 Comdats[Comdat].emplace_back(
445 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
446 }
447 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000448 const auto &InputSegments = Segments[I]->InputSegments;
449 if (InputSegments.empty())
450 continue;
451 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000452#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000453 for (const InputSegment *IS : InputSegments)
454 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000455#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000456 if (!Comdat.empty())
457 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
458 }
459
460 if (!Comdats.empty()) {
461 SubSection SubSection(WASM_COMDAT_INFO);
462 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
463 for (const auto &C : Comdats) {
464 writeStr(SubSection.getStream(), C.first, "comdat name");
465 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
466 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
467 for (const ComdatEntry &Entry : C.second) {
468 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
469 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
470 }
471 }
472 SubSection.finalizeContents();
473 SubSection.writeToStream(OS);
474 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000475}
476
477// Create the custom "name" section containing debug symbol names.
478void Writer::createNameSection() {
Sam Clegg1963d712018-01-17 20:19:04 +0000479 unsigned NumNames = ImportedFunctions.size();
480 for (const InputFunction *F : DefinedFunctions)
481 if (!F->getName().empty())
482 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000483
Sam Clegg1963d712018-01-17 20:19:04 +0000484 if (NumNames == 0)
485 return;
Sam Clegg50686852018-01-12 18:35:13 +0000486
Sam Cleggc94d3932017-11-17 18:14:09 +0000487 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
488
Sam Cleggc94d3932017-11-17 18:14:09 +0000489 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
490 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000491 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000492
Sam Clegg1963d712018-01-17 20:19:04 +0000493 // Names must appear in function index order. As it happens ImportedFunctions
494 // and DefinedFunctions are numbers in order with imported functions coming
495 // first.
496 for (const Symbol *S : ImportedFunctions) {
497 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000498 writeStr(OS, S->getName(), "symbol name");
499 }
Sam Clegg1963d712018-01-17 20:19:04 +0000500 for (const InputFunction *F : DefinedFunctions) {
501 if (!F->getName().empty()) {
502 writeUleb128(OS, F->getOutputIndex(), "func index");
503 writeStr(OS, F->getName(), "symbol name");
504 }
505 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000506
507 FunctionSubsection.finalizeContents();
508 FunctionSubsection.writeToStream(Section->getStream());
509}
510
511void Writer::writeHeader() {
512 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
513}
514
515void Writer::writeSections() {
516 uint8_t *Buf = Buffer->getBufferStart();
517 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
518}
519
520// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000521// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000522// The memory layout is as follows, from low to high.
523// - initialized data (starting at Config->GlobalBase)
524// - BSS data (not currently implemented in llvm)
525// - explicit stack (Config->ZStackSize)
526// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000527void Writer::layoutMemory() {
528 uint32_t MemoryPtr = 0;
529 if (!Config->Relocatable) {
530 MemoryPtr = Config->GlobalBase;
531 debugPrint("mem: global base = %d\n", Config->GlobalBase);
532 }
533
534 createOutputSegments();
535
Sam Cleggf0d433d2018-02-02 22:59:56 +0000536 // Arbitrarily set __dso_handle handle to point to the start of the data
537 // segments.
538 if (WasmSym::DsoHandle)
539 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
540
Sam Cleggc94d3932017-11-17 18:14:09 +0000541 for (OutputSegment *Seg : Segments) {
542 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
543 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000544 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000545 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
546 MemoryPtr += Seg->Size;
547 }
548
Sam Cleggf0d433d2018-02-02 22:59:56 +0000549 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000550 if (WasmSym::DataEnd)
551 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000552
Sam Cleggc94d3932017-11-17 18:14:09 +0000553 DataSize = MemoryPtr;
554 if (!Config->Relocatable)
555 DataSize -= Config->GlobalBase;
556 debugPrint("mem: static data = %d\n", DataSize);
557
Sam Cleggf0d433d2018-02-02 22:59:56 +0000558 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000559 if (!Config->Relocatable) {
560 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
561 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
562 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
563 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
564 debugPrint("mem: stack base = %d\n", MemoryPtr);
565 MemoryPtr += Config->ZStackSize;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000566 WasmSym::StackPointer->setVirtualAddress(MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000567 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000568 // Set `__heap_base` to directly follow the end of the stack. We don't
569 // allocate any heap memory up front, but instead really on the malloc/brk
570 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000572 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000573 }
574
575 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
576 NumMemoryPages = MemSize / WasmPageSize;
577 debugPrint("mem: total pages = %d\n", NumMemoryPages);
578}
579
580SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000581 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000582 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000583 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000584 OutputSections.push_back(Sec);
585 return Sec;
586}
587
588void Writer::createSections() {
589 // Known sections
590 createTypeSection();
591 createImportSection();
592 createFunctionSection();
593 createTableSection();
594 createMemorySection();
595 createGlobalSection();
596 createExportSection();
597 createStartSection();
598 createElemSection();
599 createCodeSection();
600 createDataSection();
601
602 // Custom sections
Sam Cleggff2b1222018-01-22 21:55:43 +0000603 if (Config->Relocatable)
Sam Cleggc94d3932017-11-17 18:14:09 +0000604 createRelocSections();
605 createLinkingSection();
606 if (!Config->StripDebug && !Config->StripAll)
607 createNameSection();
608
609 for (OutputSection *S : OutputSections) {
610 S->setOffset(FileSize);
611 S->finalizeContents();
612 FileSize += S->getSize();
613 }
614}
615
Sam Cleggc94d3932017-11-17 18:14:09 +0000616void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000617 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggff2b1222018-01-22 21:55:43 +0000618 if (!Sym->isUndefined() || (Sym->isWeak() && !Config->Relocatable))
Sam Clegg574d7ce2017-12-15 19:23:49 +0000619 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000620
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000621 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
622 F->setOutputIndex(ImportedFunctions.size());
623 ImportedFunctions.push_back(F);
624 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
625 G->setOutputIndex(ImportedGlobals.size());
626 ImportedGlobals.push_back(G);
Sam Cleggc94d3932017-11-17 18:14:09 +0000627 }
628 }
629}
630
Sam Cleggd3052d52018-01-18 23:40:49 +0000631void Writer::calculateExports() {
Sam Cleggff2b1222018-01-22 21:55:43 +0000632 bool ExportHidden = Config->Relocatable;
Sam Cleggd3052d52018-01-18 23:40:49 +0000633 StringSet<> UsedNames;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000634
Sam Cleggd3052d52018-01-18 23:40:49 +0000635 auto BudgeLocalName = [&](const Symbol *Sym) {
636 StringRef SymName = Sym->getName();
637 // We can't budge non-local names.
638 if (!Sym->isLocal())
639 return SymName;
640 // We must budge local names that have a collision with a symbol that we
641 // haven't yet processed.
642 if (!Symtab->find(SymName) && UsedNames.insert(SymName).second)
643 return SymName;
644 for (unsigned I = 1; ; ++I) {
645 std::string NameBuf = (SymName + "." + Twine(I)).str();
646 if (!UsedNames.count(NameBuf)) {
647 StringRef Name = Saver.save(NameBuf);
648 UsedNames.insert(Name); // Insert must use safe StringRef from save()
649 return Name;
650 }
651 }
652 };
653
Sam Cleggf0d433d2018-02-02 22:59:56 +0000654 if (WasmSym::CallCtors && (!WasmSym::CallCtors->isHidden() || ExportHidden))
Sam Cleggd3052d52018-01-18 23:40:49 +0000655 ExportedSymbols.emplace_back(
Sam Cleggf0d433d2018-02-02 22:59:56 +0000656 WasmExportEntry{WasmSym::CallCtors, WasmSym::CallCtors->getName()});
Sam Cleggd3052d52018-01-18 23:40:49 +0000657
658 for (ObjFile *File : Symtab->ObjectFiles) {
659 for (Symbol *Sym : File->getSymbols()) {
660 if (!Sym->isDefined() || File != Sym->getFile())
661 continue;
Sam Cleggcaca8d52018-02-17 00:44:21 +0000662 if (isa<GlobalSymbol>(Sym))
Sam Cleggd3052d52018-01-18 23:40:49 +0000663 continue;
Sam Clegg447ae402018-02-13 20:29:38 +0000664 if (!Sym->getChunk()->Live)
Sam Cleggd3052d52018-01-18 23:40:49 +0000665 continue;
666
667 if ((Sym->isHidden() || Sym->isLocal()) && !ExportHidden)
668 continue;
Sam Cleggd3052d52018-01-18 23:40:49 +0000669 ExportedSymbols.emplace_back(WasmExportEntry{Sym, BudgeLocalName(Sym)});
670 }
671 }
672
673 for (const Symbol *Sym : DefinedGlobals) {
Sam Clegg14ae6e72018-01-18 23:57:55 +0000674 // Can't export the SP right now because its mutable, and mutuable globals
Sam Cleggff2b1222018-01-22 21:55:43 +0000675 // are yet supported in the official binary format.
Sam Clegg14ae6e72018-01-18 23:57:55 +0000676 // TODO(sbc): Remove this if/when the "mutable global" proposal is accepted.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000677 if (Sym == WasmSym::StackPointer)
Sam Cleggd3052d52018-01-18 23:40:49 +0000678 continue;
679 ExportedSymbols.emplace_back(WasmExportEntry{Sym, BudgeLocalName(Sym)});
680 }
681}
682
Sam Cleggc375e4e2018-01-10 19:18:22 +0000683uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000684 auto It = TypeIndices.find(Sig);
685 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000686 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000687 return 0;
688 }
689 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000690}
691
692uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000693 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000694 if (Pair.second) {
695 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000696 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000697 }
Sam Cleggb8621592017-11-30 01:40:08 +0000698 return Pair.first->second;
699}
700
Sam Cleggc94d3932017-11-17 18:14:09 +0000701void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000702 // The output type section is the union of the following sets:
703 // 1. Any signature used in the TYPE relocation
704 // 2. The signatures of all imported functions
705 // 3. The signatures of all defined functions
706
Sam Cleggc94d3932017-11-17 18:14:09 +0000707 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000708 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
709 for (uint32_t I = 0; I < Types.size(); I++)
710 if (File->TypeIsUsed[I])
711 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000712 }
Sam Clegg50686852018-01-12 18:35:13 +0000713
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000714 for (const FunctionSymbol *Sym : ImportedFunctions)
Sam Clegg3f8db982018-02-16 23:50:23 +0000715 registerType(*Sym->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000716
717 for (const InputFunction *F : DefinedFunctions)
718 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000719}
720
Sam Clegg8d146bb2018-01-09 23:56:44 +0000721void Writer::assignIndexes() {
Sam Clegg50686852018-01-12 18:35:13 +0000722 uint32_t GlobalIndex = ImportedGlobals.size() + DefinedGlobals.size();
723 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000724
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000725 auto AddDefinedGlobal = [&](DefinedGlobal *Sym) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000726 if (Sym) {
727 DefinedGlobals.emplace_back(Sym);
728 Sym->setOutputIndex(GlobalIndex++);
729 }
730 };
731 AddDefinedGlobal(WasmSym::StackPointer);
732 AddDefinedGlobal(WasmSym::HeapBase);
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000733 AddDefinedGlobal(WasmSym::DataEnd);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000734
Sam Cleggff2b1222018-01-22 21:55:43 +0000735 if (Config->Relocatable)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000736 DefinedGlobals.reserve(Symtab->getSymbols().size());
737
Sam Clegg48bbd632018-01-24 21:37:30 +0000738 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggfc1a9122017-12-11 22:00:56 +0000739
Sam Cleggf0d433d2018-02-02 22:59:56 +0000740 if (Config->Relocatable) {
741 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000742 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
743 for (Symbol *Sym : File->getSymbols()) {
744 // Create wasm globals for data symbols defined in this file
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000745 if (File != Sym->getFile())
Sam Clegg8d146bb2018-01-09 23:56:44 +0000746 continue;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000747 if (auto *G = dyn_cast<DefinedGlobal>(Sym))
748 AddDefinedGlobal(G);
Sam Cleggc94d3932017-11-17 18:14:09 +0000749 }
750 }
Sam Clegg87e61922018-01-08 23:39:11 +0000751 }
Sam Cleggfc1a9122017-12-11 22:00:56 +0000752
Sam Clegg87e61922018-01-08 23:39:11 +0000753 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000754 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
755 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000756 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000757 continue;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000758 DefinedFunctions.emplace_back(Func);
759 Func->setOutputIndex(FunctionIndex++);
760 }
761 }
762
763 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000764 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
765 auto HandleRelocs = [&](InputChunk *Chunk) {
Sam Clegg447ae402018-02-13 20:29:38 +0000766 if (!Chunk->Live)
Sam Cleggab604a92018-01-23 01:25:56 +0000767 return;
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000768 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Cleggab604a92018-01-23 01:25:56 +0000769 for (const WasmRelocation& Reloc : Chunk->getRelocations()) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000770 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
771 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000772 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000773 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
774 continue;
775 Sym->setTableIndex(TableIndex++);
776 IndirectFunctions.emplace_back(Sym);
777 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
778 Chunk->File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
779 Chunk->File->TypeIsUsed[Reloc.Index] = true;
780 }
Sam Cleggab604a92018-01-23 01:25:56 +0000781 }
782 };
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000783
Sam Cleggab604a92018-01-23 01:25:56 +0000784 for (InputFunction* Function : File->Functions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000785 HandleRelocs(Function);
Sam Cleggab604a92018-01-23 01:25:56 +0000786 for (InputSegment* Segment : File->Segments)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000787 HandleRelocs(Segment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000788 }
789}
790
791static StringRef getOutputDataSegmentName(StringRef Name) {
792 if (Config->Relocatable)
793 return Name;
794
795 for (StringRef V :
796 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
797 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
798 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
799 StringRef Prefix = V.drop_back();
800 if (Name.startswith(V) || Name == Prefix)
801 return Prefix;
802 }
803
804 return Name;
805}
806
807void Writer::createOutputSegments() {
808 for (ObjFile *File : Symtab->ObjectFiles) {
809 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000810 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000811 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000812 StringRef Name = getOutputDataSegmentName(Segment->getName());
813 OutputSegment *&S = SegmentMap[Name];
814 if (S == nullptr) {
815 DEBUG(dbgs() << "new segment: " << Name << "\n");
816 S = make<OutputSegment>(Name);
817 Segments.push_back(S);
818 }
819 S->addInputSegment(Segment);
820 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000821 }
822 }
823}
824
Sam Clegg50686852018-01-12 18:35:13 +0000825static const int OPCODE_CALL = 0x10;
826static const int OPCODE_END = 0xb;
827
828// Create synthetic "__wasm_call_ctors" function based on ctor functions
829// in input object.
830void Writer::createCtorFunction() {
831 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000832 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000833
834 // First write the body bytes to a string.
835 std::string FunctionBody;
836 static WasmSignature Signature = {{}, WASM_TYPE_NORESULT};
837 {
838 raw_string_ostream OS(FunctionBody);
839 writeUleb128(OS, 0, "num locals");
840 for (const WasmInitFunc &F : InitFunctions) {
841 writeU8(OS, OPCODE_CALL, "CALL");
842 writeUleb128(OS, F.FunctionIndex, "function index");
843 }
844 writeU8(OS, OPCODE_END, "END");
845 }
846
847 // Once we know the size of the body we can create the final function body
848 raw_string_ostream OS(CtorFunctionBody);
849 writeUleb128(OS, FunctionBody.size(), "function size");
850 OS.flush();
851 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000852 ArrayRef<uint8_t> BodyArray(
853 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
854 CtorFunctionBody.size());
Sam Clegg1963d712018-01-17 20:19:04 +0000855 CtorFunction = llvm::make_unique<SyntheticFunction>(
Sam Cleggf0d433d2018-02-02 22:59:56 +0000856 Signature, BodyArray, WasmSym::CallCtors->getName());
Sam Clegg1963d712018-01-17 20:19:04 +0000857 CtorFunction->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000858 DefinedFunctions.emplace_back(CtorFunction.get());
859}
860
861// Populate InitFunctions vector with init functions from all input objects.
862// This is then used either when creating the output linking section or to
863// synthesize the "__wasm_call_ctors" function.
864void Writer::calculateInitFunctions() {
865 for (ObjFile *File : Symtab->ObjectFiles) {
866 const WasmLinkingData &L = File->getWasmObj()->linkingData();
867 InitFunctions.reserve(InitFunctions.size() + L.InitFunctions.size());
868 for (const WasmInitFunc &F : L.InitFunctions)
869 InitFunctions.emplace_back(WasmInitFunc{
870 F.Priority, File->relocateFunctionIndex(F.FunctionIndex)});
871 }
872 // Sort in order of priority (lowest first) so that they are called
873 // in the correct order.
874 std::sort(InitFunctions.begin(), InitFunctions.end(),
875 [](const WasmInitFunc &L, const WasmInitFunc &R) {
876 return L.Priority < R.Priority;
877 });
878}
879
Sam Cleggc94d3932017-11-17 18:14:09 +0000880void Writer::run() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000881 log("-- calculateImports");
882 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000883 log("-- assignIndexes");
884 assignIndexes();
Sam Cleggd3052d52018-01-18 23:40:49 +0000885 log("-- calculateExports");
886 calculateExports();
Sam Clegg50686852018-01-12 18:35:13 +0000887 log("-- calculateInitFunctions");
888 calculateInitFunctions();
889 if (!Config->Relocatable)
890 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000891 log("-- calculateTypes");
892 calculateTypes();
Sam Cleggc94d3932017-11-17 18:14:09 +0000893
894 if (errorHandler().Verbose) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000895 log("Defined Functions: " + Twine(DefinedFunctions.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000896 log("Defined Globals : " + Twine(DefinedGlobals.size()));
Sam Clegg8d146bb2018-01-09 23:56:44 +0000897 log("Function Imports : " + Twine(ImportedFunctions.size()));
898 log("Global Imports : " + Twine(ImportedGlobals.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000899 log("Total Imports : " +
Sam Clegg8d146bb2018-01-09 23:56:44 +0000900 Twine(ImportedFunctions.size() + ImportedGlobals.size()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000901 for (ObjFile *File : Symtab->ObjectFiles)
902 File->dumpInfo();
903 }
904
Sam Cleggc94d3932017-11-17 18:14:09 +0000905 log("-- layoutMemory");
906 layoutMemory();
907
908 createHeader();
909 log("-- createSections");
910 createSections();
911
912 log("-- openFile");
913 openFile();
914 if (errorCount())
915 return;
916
917 writeHeader();
918
919 log("-- writeSections");
920 writeSections();
921 if (errorCount())
922 return;
923
924 if (Error E = Buffer->commit())
925 fatal("failed to write the output file: " + toString(std::move(E)));
926}
927
928// Open a result file.
929void Writer::openFile() {
930 log("writing: " + Config->OutputFile);
931 ::remove(Config->OutputFile.str().c_str());
932
933 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
934 FileOutputBuffer::create(Config->OutputFile, FileSize,
935 FileOutputBuffer::F_executable);
936
937 if (!BufferOrErr)
938 error("failed to open " + Config->OutputFile + ": " +
939 toString(BufferOrErr.takeError()));
940 else
941 Buffer = std::move(*BufferOrErr);
942}
943
944void Writer::createHeader() {
945 raw_string_ostream OS(Header);
946 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
947 writeU32(OS, WasmVersion, "wasm version");
948 OS.flush();
949 FileSize += Header.size();
950}
951
952void lld::wasm::writeResult() { Writer().run(); }