blob: 88813828dc7f43068384af50e2b4b3787d9c7294 [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 Clegg93102972018-02-23 05:08:53 +000013#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000014#include "OutputSections.h"
15#include "OutputSegment.h"
16#include "SymbolTable.h"
17#include "WriterUtils.h"
18#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000019#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000020#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000021#include "llvm/ADT/DenseSet.h"
Sam Clegg93102972018-02-23 05:08:53 +000022#include "llvm/BinaryFormat/Wasm.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000023#include "llvm/Support/FileOutputBuffer.h"
24#include "llvm/Support/Format.h"
25#include "llvm/Support/FormatVariadic.h"
26#include "llvm/Support/LEB128.h"
27
28#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000029#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000030
31#define DEBUG_TYPE "lld"
32
33using namespace llvm;
34using namespace llvm::wasm;
35using namespace lld;
36using namespace lld::wasm;
37
38static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000039static constexpr int kInitialTableOffset = 1;
Sam Cleggc94d3932017-11-17 18:14:09 +000040
41namespace {
42
Sam Cleggc94d3932017-11-17 18:14:09 +000043// Traits for using WasmSignature in a DenseMap.
44struct WasmSignatureDenseMapInfo {
45 static WasmSignature getEmptyKey() {
46 WasmSignature Sig;
47 Sig.ReturnType = 1;
48 return Sig;
49 }
50 static WasmSignature getTombstoneKey() {
51 WasmSignature Sig;
52 Sig.ReturnType = 2;
53 return Sig;
54 }
55 static unsigned getHashValue(const WasmSignature &Sig) {
56 uintptr_t Value = 0;
57 Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType);
58 for (int32_t Param : Sig.ParamTypes)
59 Value += DenseMapInfo<int32_t>::getHashValue(Param);
60 return Value;
61 }
62 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
63 return LHS == RHS;
64 }
65};
66
Sam Clegg93102972018-02-23 05:08:53 +000067// An init entry to be written to either the synthetic init func or the
68// linking metadata.
69struct WasmInitEntry {
Sam Clegg811236c2018-01-19 03:31:07 +000070 const Symbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000071 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000072};
73
Sam Cleggc94d3932017-11-17 18:14:09 +000074// The writer writes a SymbolTable result to a file.
75class Writer {
76public:
77 void run();
78
79private:
80 void openFile();
81
Sam Cleggc375e4e2018-01-10 19:18:22 +000082 uint32_t lookupType(const WasmSignature &Sig);
83 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000084
Sam Clegg50686852018-01-12 18:35:13 +000085 void createCtorFunction();
86 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000087 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000088 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000089 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000090 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000091 void calculateTypes();
92 void createOutputSegments();
93 void layoutMemory();
94 void createHeader();
95 void createSections();
96 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000097 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000098
99 // Builtin sections
100 void createTypeSection();
101 void createFunctionSection();
102 void createTableSection();
103 void createGlobalSection();
104 void createExportSection();
105 void createImportSection();
106 void createMemorySection();
107 void createElemSection();
108 void createStartSection();
109 void createCodeSection();
110 void createDataSection();
111
112 // Custom sections
113 void createRelocSections();
114 void createLinkingSection();
115 void createNameSection();
116
117 void writeHeader();
118 void writeSections();
119
120 uint64_t FileSize = 0;
121 uint32_t DataSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000122 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000123
124 std::vector<const WasmSignature *> Types;
125 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000126 std::vector<const Symbol *> ImportedSymbols;
127 unsigned NumImportedFunctions = 0;
128 unsigned NumImportedGlobals = 0;
129 std::vector<Symbol *> ExportedSymbols;
130 std::vector<const DefinedData *> DefinedFakeGlobals;
131 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000132 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000133 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000134 std::vector<const Symbol *> SymtabEntries;
135 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000136
137 // Elements that are used to construct the final output
138 std::string Header;
139 std::vector<OutputSection *> OutputSections;
140
141 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000142 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000143
144 std::vector<OutputSegment *> Segments;
145 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
146};
147
148} // anonymous namespace
149
150static void debugPrint(const char *fmt, ...) {
151 if (!errorHandler().Verbose)
152 return;
153 fprintf(stderr, "lld: ");
154 va_list ap;
155 va_start(ap, fmt);
156 vfprintf(stderr, fmt, ap);
157 va_end(ap);
158}
159
160void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000161 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000162 if (Config->ImportMemory)
163 ++NumImports;
164
165 if (NumImports == 0)
166 return;
167
168 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
169 raw_ostream &OS = Section->getStream();
170
171 writeUleb128(OS, NumImports, "import count");
172
Sam Cleggc94d3932017-11-17 18:14:09 +0000173 if (Config->ImportMemory) {
174 WasmImport Import;
175 Import.Module = "env";
176 Import.Field = "memory";
177 Import.Kind = WASM_EXTERNAL_MEMORY;
178 Import.Memory.Flags = 0;
179 Import.Memory.Initial = NumMemoryPages;
180 writeImport(OS, Import);
181 }
182
Sam Clegg93102972018-02-23 05:08:53 +0000183 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000184 WasmImport Import;
185 Import.Module = "env";
186 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000187 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
188 Import.Kind = WASM_EXTERNAL_FUNCTION;
189 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
190 } else {
191 auto *GlobalSym = cast<GlobalSymbol>(Sym);
192 Import.Kind = WASM_EXTERNAL_GLOBAL;
193 Import.Global = *GlobalSym->getGlobalType();
194 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000195 writeImport(OS, Import);
196 }
197}
198
199void Writer::createTypeSection() {
200 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
201 raw_ostream &OS = Section->getStream();
202 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000203 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000204 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000205}
206
207void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000208 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000209 return;
210
211 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
212 raw_ostream &OS = Section->getStream();
213
Sam Clegg9f934222018-02-21 18:29:23 +0000214 writeUleb128(OS, InputFunctions.size(), "function count");
215 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000216 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000217}
218
219void Writer::createMemorySection() {
220 if (Config->ImportMemory)
221 return;
222
223 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
224 raw_ostream &OS = Section->getStream();
225
226 writeUleb128(OS, 1, "memory count");
227 writeUleb128(OS, 0, "memory limits flags");
228 writeUleb128(OS, NumMemoryPages, "initial pages");
229}
230
231void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000232 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
233 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000234 return;
235
Sam Cleggc94d3932017-11-17 18:14:09 +0000236 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
237 raw_ostream &OS = Section->getStream();
238
Sam Clegg93102972018-02-23 05:08:53 +0000239 writeUleb128(OS, NumGlobals, "global count");
240 for (const InputGlobal *G : InputGlobals)
241 writeGlobal(OS, G->Global);
242 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000243 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000244 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000245 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
246 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000247 writeGlobal(OS, Global);
248 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000249}
250
251void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000252 // Always output a table section, even if there are no indirect calls.
253 // There are two reasons for this:
254 // 1. For executables it is useful to have an empty table slot at 0
255 // which can be filled with a null function call handler.
256 // 2. If we don't do this, any program that contains a call_indirect but
257 // no address-taken function will fail at validation time since it is
258 // a validation error to include a call_indirect instruction if there
259 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000260 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000261
Sam Cleggc94d3932017-11-17 18:14:09 +0000262 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
263 raw_ostream &OS = Section->getStream();
264
265 writeUleb128(OS, 1, "table count");
266 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
267 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000268 writeUleb128(OS, TableSize, "table initial size");
269 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000270}
271
272void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000273 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000274
Sam Cleggd3052d52018-01-18 23:40:49 +0000275 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000276 if (!NumExports)
277 return;
278
279 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
280 raw_ostream &OS = Section->getStream();
281
282 writeUleb128(OS, NumExports, "export count");
283
284 if (ExportMemory) {
285 WasmExport MemoryExport;
286 MemoryExport.Name = "memory";
287 MemoryExport.Kind = WASM_EXTERNAL_MEMORY;
288 MemoryExport.Index = 0;
289 writeExport(OS, MemoryExport);
290 }
291
Sam Clegg93102972018-02-23 05:08:53 +0000292 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
293 for (const Symbol *Sym : ExportedSymbols) {
294 DEBUG(dbgs() << "Export: " << Sym->getName() << "\n");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000295 WasmExport Export;
Sam Clegg93102972018-02-23 05:08:53 +0000296 Export.Name = Sym->getName();
297 if (isa<FunctionSymbol>(Sym)) {
298 Export.Index = Sym->getOutputIndex();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000299 Export.Kind = WASM_EXTERNAL_FUNCTION;
Sam Clegg93102972018-02-23 05:08:53 +0000300 } else if (isa<GlobalSymbol>(Sym)) {
301 Export.Index = Sym->getOutputIndex();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000302 Export.Kind = WASM_EXTERNAL_GLOBAL;
Sam Clegg93102972018-02-23 05:08:53 +0000303 } else if (isa<DataSymbol>(Sym)) {
304 Export.Index = FakeGlobalIndex++;
305 Export.Kind = WASM_EXTERNAL_GLOBAL;
306 } else {
307 llvm_unreachable("unexpected symbol type");
308 }
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000309 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000310 }
311}
312
313void Writer::createStartSection() {}
314
315void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000316 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000317 return;
318
319 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
320 raw_ostream &OS = Section->getStream();
321
322 writeUleb128(OS, 1, "segment count");
323 writeUleb128(OS, 0, "table index");
324 WasmInitExpr InitExpr;
325 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000326 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000327 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000328 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000329
Sam Clegg48bbd632018-01-24 21:37:30 +0000330 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000331 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000332 assert(Sym->getTableIndex() == TableIndex);
333 writeUleb128(OS, Sym->getOutputIndex(), "function index");
334 ++TableIndex;
335 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000336}
337
338void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000339 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000340 return;
341
342 log("createCodeSection");
343
Sam Clegg9f934222018-02-21 18:29:23 +0000344 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000345 OutputSections.push_back(Section);
346}
347
348void Writer::createDataSection() {
349 if (!Segments.size())
350 return;
351
352 log("createDataSection");
353 auto Section = make<DataSection>(Segments);
354 OutputSections.push_back(Section);
355}
356
Sam Cleggd451da12017-12-19 19:56:27 +0000357// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000358// These are only created when relocatable output is requested.
359void Writer::createRelocSections() {
360 log("createRelocSections");
361 // Don't use iterator here since we are adding to OutputSection
362 size_t OrigSize = OutputSections.size();
363 for (size_t i = 0; i < OrigSize; i++) {
364 OutputSection *S = OutputSections[i];
365 const char *name;
366 uint32_t Count = S->numRelocations();
367 if (!Count)
368 continue;
369
370 if (S->Type == WASM_SEC_DATA)
371 name = "reloc.DATA";
372 else if (S->Type == WASM_SEC_CODE)
373 name = "reloc.CODE";
374 else
Sam Cleggd451da12017-12-19 19:56:27 +0000375 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000376
377 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, name);
378 raw_ostream &OS = Section->getStream();
379 writeUleb128(OS, S->Type, "reloc section");
380 writeUleb128(OS, Count, "reloc count");
381 S->writeRelocations(OS);
382 }
383}
384
Sam Clegg49ed9262017-12-01 00:53:21 +0000385// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000386// This is only created when relocatable output is requested.
387void Writer::createLinkingSection() {
388 SyntheticSection *Section =
389 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
390 raw_ostream &OS = Section->getStream();
391
392 SubSection DataSizeSubSection(WASM_DATA_SIZE);
393 writeUleb128(DataSizeSubSection.getStream(), DataSize, "data size");
394 DataSizeSubSection.finalizeContents();
395 DataSizeSubSection.writeToStream(OS);
396
Sam Clegg0d0dd392017-12-19 17:09:45 +0000397 if (!Config->Relocatable)
398 return;
399
Sam Clegg93102972018-02-23 05:08:53 +0000400 if (!SymtabEntries.empty()) {
401 SubSection SubSection(WASM_SYMBOL_TABLE);
402 writeUleb128(SubSection.getStream(), SymtabEntries.size(), "num symbols");
403 for (const Symbol *Sym : SymtabEntries) {
404 assert(Sym->isDefined() || Sym->isUndefined());
405 WasmSymbolType Kind = Sym->getWasmType();
406 uint32_t Flags = Sym->isLocal() ? WASM_SYMBOL_BINDING_LOCAL : 0;
407 if (Sym->isWeak())
408 Flags |= WASM_SYMBOL_BINDING_WEAK;
409 if (Sym->isHidden())
410 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
411 if (Sym->isUndefined())
412 Flags |= WASM_SYMBOL_UNDEFINED;
413 writeUleb128(SubSection.getStream(), Kind, "sym kind");
414 writeUleb128(SubSection.getStream(), Flags, "sym flags");
415 switch (Kind) {
416 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
417 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
418 writeUleb128(SubSection.getStream(), Sym->getOutputIndex(), "index");
419 if (Sym->isDefined())
420 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
421 break;
422 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
423 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
424 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
425 writeUleb128(SubSection.getStream(), DataSym->getOutputSegmentIndex(),
426 "index");
427 writeUleb128(SubSection.getStream(),
428 DataSym->getOutputSegmentOffset(), "data offset");
429 writeUleb128(SubSection.getStream(), DataSym->getSize(), "data size");
430 }
431 break;
432 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000433 }
434 SubSection.finalizeContents();
435 SubSection.writeToStream(OS);
436 }
437
Sam Clegg0d0dd392017-12-19 17:09:45 +0000438 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000439 SubSection SubSection(WASM_SEGMENT_INFO);
440 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
441 for (const OutputSegment *S : Segments) {
442 writeStr(SubSection.getStream(), S->Name, "segment name");
443 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
444 writeUleb128(SubSection.getStream(), 0, "flags");
445 }
446 SubSection.finalizeContents();
447 SubSection.writeToStream(OS);
448 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000449
Sam Clegg0d0dd392017-12-19 17:09:45 +0000450 if (!InitFunctions.empty()) {
451 SubSection SubSection(WASM_INIT_FUNCS);
452 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000453 "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000454 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg0d0dd392017-12-19 17:09:45 +0000455 writeUleb128(SubSection.getStream(), F.Priority, "priority");
Sam Clegg93102972018-02-23 05:08:53 +0000456 writeUleb128(SubSection.getStream(), F.Sym->getOutputSymbolIndex(),
457 "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000458 }
459 SubSection.finalizeContents();
460 SubSection.writeToStream(OS);
461 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000462
463 struct ComdatEntry { unsigned Kind; uint32_t Index; };
464 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
465
Sam Clegg9f934222018-02-21 18:29:23 +0000466 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000467 StringRef Comdat = F->getComdat();
468 if (!Comdat.empty())
469 Comdats[Comdat].emplace_back(
470 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
471 }
472 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000473 const auto &InputSegments = Segments[I]->InputSegments;
474 if (InputSegments.empty())
475 continue;
476 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000477#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000478 for (const InputSegment *IS : InputSegments)
479 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000480#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000481 if (!Comdat.empty())
482 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
483 }
484
485 if (!Comdats.empty()) {
486 SubSection SubSection(WASM_COMDAT_INFO);
487 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
488 for (const auto &C : Comdats) {
489 writeStr(SubSection.getStream(), C.first, "comdat name");
490 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
491 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
492 for (const ComdatEntry &Entry : C.second) {
493 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
494 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
495 }
496 }
497 SubSection.finalizeContents();
498 SubSection.writeToStream(OS);
499 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000500}
501
502// Create the custom "name" section containing debug symbol names.
503void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000504 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000505 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000506 if (!F->getName().empty())
507 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000508
Sam Clegg1963d712018-01-17 20:19:04 +0000509 if (NumNames == 0)
510 return;
Sam Clegg50686852018-01-12 18:35:13 +0000511
Sam Cleggc94d3932017-11-17 18:14:09 +0000512 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
513
Sam Cleggc94d3932017-11-17 18:14:09 +0000514 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
515 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000516 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000517
Sam Clegg93102972018-02-23 05:08:53 +0000518 // Names must appear in function index order. As it happens ImportedSymbols
519 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000520 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000521 for (const Symbol *S : ImportedSymbols) {
522 if (!isa<FunctionSymbol>(S))
523 continue;
Sam Clegg1963d712018-01-17 20:19:04 +0000524 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000525 writeStr(OS, S->getName(), "symbol name");
526 }
Sam Clegg9f934222018-02-21 18:29:23 +0000527 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000528 if (!F->getName().empty()) {
529 writeUleb128(OS, F->getOutputIndex(), "func index");
530 writeStr(OS, F->getName(), "symbol name");
531 }
532 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000533
534 FunctionSubsection.finalizeContents();
535 FunctionSubsection.writeToStream(Section->getStream());
536}
537
538void Writer::writeHeader() {
539 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
540}
541
542void Writer::writeSections() {
543 uint8_t *Buf = Buffer->getBufferStart();
544 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
545}
546
547// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000548// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000549// The memory layout is as follows, from low to high.
550// - initialized data (starting at Config->GlobalBase)
551// - BSS data (not currently implemented in llvm)
552// - explicit stack (Config->ZStackSize)
553// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000554void Writer::layoutMemory() {
555 uint32_t MemoryPtr = 0;
556 if (!Config->Relocatable) {
557 MemoryPtr = Config->GlobalBase;
558 debugPrint("mem: global base = %d\n", Config->GlobalBase);
559 }
560
561 createOutputSegments();
562
Sam Cleggf0d433d2018-02-02 22:59:56 +0000563 // Arbitrarily set __dso_handle handle to point to the start of the data
564 // segments.
565 if (WasmSym::DsoHandle)
566 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
567
Sam Cleggc94d3932017-11-17 18:14:09 +0000568 for (OutputSegment *Seg : Segments) {
569 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
570 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000571 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000572 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
573 MemoryPtr += Seg->Size;
574 }
575
Sam Cleggf0d433d2018-02-02 22:59:56 +0000576 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000577 if (WasmSym::DataEnd)
578 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000579
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 DataSize = MemoryPtr;
581 if (!Config->Relocatable)
582 DataSize -= Config->GlobalBase;
583 debugPrint("mem: static data = %d\n", DataSize);
584
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000586 if (!Config->Relocatable) {
587 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
588 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
589 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
590 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
591 debugPrint("mem: stack base = %d\n", MemoryPtr);
592 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000593 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000594 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000595
Sam Clegg51bcdc22018-01-17 01:34:31 +0000596 // Set `__heap_base` to directly follow the end of the stack. We don't
597 // allocate any heap memory up front, but instead really on the malloc/brk
598 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000599 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000600 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000601 }
602
603 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
604 NumMemoryPages = MemSize / WasmPageSize;
605 debugPrint("mem: total pages = %d\n", NumMemoryPages);
606}
607
608SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000609 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000610 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000611 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000612 OutputSections.push_back(Sec);
613 return Sec;
614}
615
616void Writer::createSections() {
617 // Known sections
618 createTypeSection();
619 createImportSection();
620 createFunctionSection();
621 createTableSection();
622 createMemorySection();
623 createGlobalSection();
624 createExportSection();
625 createStartSection();
626 createElemSection();
627 createCodeSection();
628 createDataSection();
629
630 // Custom sections
Sam Cleggff2b1222018-01-22 21:55:43 +0000631 if (Config->Relocatable)
Sam Cleggc94d3932017-11-17 18:14:09 +0000632 createRelocSections();
633 createLinkingSection();
634 if (!Config->StripDebug && !Config->StripAll)
635 createNameSection();
636
637 for (OutputSection *S : OutputSections) {
638 S->setOffset(FileSize);
639 S->finalizeContents();
640 FileSize += S->getSize();
641 }
642}
643
Sam Cleggc94d3932017-11-17 18:14:09 +0000644void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000645 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000646 if (!Sym->isUndefined())
647 continue;
648 if (isa<DataSymbol>(Sym))
649 continue;
650 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000651 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000652
Sam Clegg93102972018-02-23 05:08:53 +0000653 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
654 Sym->setOutputIndex(ImportedSymbols.size());
655 ImportedSymbols.emplace_back(Sym);
656 if (isa<FunctionSymbol>(Sym))
657 ++NumImportedFunctions;
658 else
659 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000660 }
661}
662
Sam Cleggd3052d52018-01-18 23:40:49 +0000663void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000664 if (Config->Relocatable)
665 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000666
Sam Clegg93102972018-02-23 05:08:53 +0000667 auto ExportSym = [&](Symbol *Sym) {
668 if (!Sym->isDefined())
669 return;
670 if (Sym->isHidden() || Sym->isLocal())
671 return;
672 if (!Sym->isLive())
673 return;
674
675 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
676
677 if (auto *D = dyn_cast<DefinedData>(Sym)) {
678 // TODO Remove this check here; for non-relocatable output we actually
679 // used only to create fake-global exports for the synthetic symbols. Fix
680 // this in a future commit
681 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
682 return;
683 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000684 }
Sam Clegg93102972018-02-23 05:08:53 +0000685 ExportedSymbols.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000686 };
687
Sam Clegg93102972018-02-23 05:08:53 +0000688 // TODO The two loops below should be replaced with this single loop, with
689 // ExportSym inlined:
690 // for (Symbol *Sym : Symtab->getSymbols())
691 // ExportSym(Sym);
692 // Making that change would reorder the output though, so it should be done as
693 // a separate commit.
Sam Cleggd3052d52018-01-18 23:40:49 +0000694
Sam Clegg93102972018-02-23 05:08:53 +0000695 for (ObjFile *File : Symtab->ObjectFiles)
696 for (Symbol *Sym : File->getSymbols())
697 if (File == Sym->getFile())
698 ExportSym(Sym);
699
700 for (Symbol *Sym : Symtab->getSymbols())
701 if (Sym->getFile() == nullptr)
702 ExportSym(Sym);
703}
704
705void Writer::assignSymtab() {
706 if (!Config->Relocatable)
707 return;
708
709 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000710 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000711 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000712 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000713 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000714 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000715 if (!Sym->isLive())
716 return;
717 Sym->setOutputSymbolIndex(SymbolIndex++);
718 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000719 }
720 }
721
Sam Clegg93102972018-02-23 05:08:53 +0000722 // For the moment, relocatable output doesn't contain any synthetic functions,
723 // so no need to look through the Symtab for symbols not referenced by
724 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000725}
726
Sam Cleggc375e4e2018-01-10 19:18:22 +0000727uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000728 auto It = TypeIndices.find(Sig);
729 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000730 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000731 return 0;
732 }
733 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000734}
735
736uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000737 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000738 if (Pair.second) {
739 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000740 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000741 }
Sam Cleggb8621592017-11-30 01:40:08 +0000742 return Pair.first->second;
743}
744
Sam Cleggc94d3932017-11-17 18:14:09 +0000745void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000746 // The output type section is the union of the following sets:
747 // 1. Any signature used in the TYPE relocation
748 // 2. The signatures of all imported functions
749 // 3. The signatures of all defined functions
750
Sam Cleggc94d3932017-11-17 18:14:09 +0000751 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000752 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
753 for (uint32_t I = 0; I < Types.size(); I++)
754 if (File->TypeIsUsed[I])
755 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000756 }
Sam Clegg50686852018-01-12 18:35:13 +0000757
Sam Clegg93102972018-02-23 05:08:53 +0000758 for (const Symbol *Sym : ImportedSymbols)
759 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
760 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000761
Sam Clegg9f934222018-02-21 18:29:23 +0000762 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000763 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000764}
765
Sam Clegg8d146bb2018-01-09 23:56:44 +0000766void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000767 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000768 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000769 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
770 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000771 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000772 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000773 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000774 Func->setOutputIndex(FunctionIndex++);
775 }
776 }
777
Sam Clegg93102972018-02-23 05:08:53 +0000778 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000779 auto HandleRelocs = [&](InputChunk *Chunk) {
780 if (!Chunk->Live)
781 return;
782 ObjFile *File = Chunk->File;
783 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000784 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000785 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
786 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
787 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
788 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
789 continue;
790 Sym->setTableIndex(TableIndex++);
791 IndirectFunctions.emplace_back(Sym);
792 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000793 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000794 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
795 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000796 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
797 // Mark target global as live
798 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
799 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
800 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
801 G->Global->Live = true;
802 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000803 }
804 }
805 };
806
Sam Clegg8d146bb2018-01-09 23:56:44 +0000807 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000808 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000809 for (InputChunk *Chunk : File->Functions)
810 HandleRelocs(Chunk);
811 for (InputChunk *Chunk : File->Segments)
812 HandleRelocs(Chunk);
813 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000814
Sam Clegg93102972018-02-23 05:08:53 +0000815 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
816 auto AddDefinedGlobal = [&](InputGlobal *Global) {
817 if (Global->Live) {
818 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
819 Global->setOutputIndex(GlobalIndex++);
820 InputGlobals.push_back(Global);
821 }
822 };
823
824 if (WasmSym::StackPointer)
825 AddDefinedGlobal(WasmSym::StackPointer->Global);
826
827 for (ObjFile *File : Symtab->ObjectFiles) {
828 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
829 for (InputGlobal *Global : File->Globals)
830 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000831 }
832}
833
834static StringRef getOutputDataSegmentName(StringRef Name) {
835 if (Config->Relocatable)
836 return Name;
837
838 for (StringRef V :
839 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
840 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
841 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
842 StringRef Prefix = V.drop_back();
843 if (Name.startswith(V) || Name == Prefix)
844 return Prefix;
845 }
846
847 return Name;
848}
849
850void Writer::createOutputSegments() {
851 for (ObjFile *File : Symtab->ObjectFiles) {
852 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000853 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000854 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000855 StringRef Name = getOutputDataSegmentName(Segment->getName());
856 OutputSegment *&S = SegmentMap[Name];
857 if (S == nullptr) {
858 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000859 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000860 Segments.push_back(S);
861 }
862 S->addInputSegment(Segment);
863 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000864 }
865 }
866}
867
Sam Clegg50686852018-01-12 18:35:13 +0000868static const int OPCODE_CALL = 0x10;
869static const int OPCODE_END = 0xb;
870
871// Create synthetic "__wasm_call_ctors" function based on ctor functions
872// in input object.
873void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000874 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000875 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000876
877 // First write the body bytes to a string.
878 std::string FunctionBody;
Sam Clegg93102972018-02-23 05:08:53 +0000879 const WasmSignature *Signature = WasmSym::CallCtors->getFunctionType();
Sam Clegg50686852018-01-12 18:35:13 +0000880 {
881 raw_string_ostream OS(FunctionBody);
882 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000883 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000884 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000885 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000886 }
887 writeU8(OS, OPCODE_END, "END");
888 }
889
890 // Once we know the size of the body we can create the final function body
891 raw_string_ostream OS(CtorFunctionBody);
892 writeUleb128(OS, FunctionBody.size(), "function size");
893 OS.flush();
894 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000895 ArrayRef<uint8_t> BodyArray(
896 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
897 CtorFunctionBody.size());
Sam Clegg93102972018-02-23 05:08:53 +0000898 SyntheticFunction *F = make<SyntheticFunction>(*Signature, BodyArray,
Sam Clegg011dce22018-02-21 18:37:44 +0000899 WasmSym::CallCtors->getName());
900 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000901 F->Live = true;
902 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000903 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000904}
905
906// Populate InitFunctions vector with init functions from all input objects.
907// This is then used either when creating the output linking section or to
908// synthesize the "__wasm_call_ctors" function.
909void Writer::calculateInitFunctions() {
910 for (ObjFile *File : Symtab->ObjectFiles) {
911 const WasmLinkingData &L = File->getWasmObj()->linkingData();
912 InitFunctions.reserve(InitFunctions.size() + L.InitFunctions.size());
913 for (const WasmInitFunc &F : L.InitFunctions)
Sam Clegg93102972018-02-23 05:08:53 +0000914 InitFunctions.emplace_back(
915 WasmInitEntry{File->getFunctionSymbol(F.Symbol), F.Priority});
Sam Clegg50686852018-01-12 18:35:13 +0000916 }
917 // Sort in order of priority (lowest first) so that they are called
918 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000919 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000920 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000921 return L.Priority < R.Priority;
922 });
Sam Clegg50686852018-01-12 18:35:13 +0000923}
924
Sam Cleggc94d3932017-11-17 18:14:09 +0000925void Writer::run() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000926 log("-- calculateImports");
927 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000928 log("-- assignIndexes");
929 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000930 log("-- calculateInitFunctions");
931 calculateInitFunctions();
932 if (!Config->Relocatable)
933 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000934 log("-- calculateTypes");
935 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000936 log("-- layoutMemory");
937 layoutMemory();
938 log("-- calculateExports");
939 calculateExports();
940 log("-- assignSymtab");
941 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000942
943 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000944 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000945 log("Defined Globals : " + Twine(InputGlobals.size()));
946 log("Function Imports : " + Twine(NumImportedFunctions));
947 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000948 for (ObjFile *File : Symtab->ObjectFiles)
949 File->dumpInfo();
950 }
951
Sam Cleggc94d3932017-11-17 18:14:09 +0000952 createHeader();
953 log("-- createSections");
954 createSections();
955
956 log("-- openFile");
957 openFile();
958 if (errorCount())
959 return;
960
961 writeHeader();
962
963 log("-- writeSections");
964 writeSections();
965 if (errorCount())
966 return;
967
968 if (Error E = Buffer->commit())
969 fatal("failed to write the output file: " + toString(std::move(E)));
970}
971
972// Open a result file.
973void Writer::openFile() {
974 log("writing: " + Config->OutputFile);
975 ::remove(Config->OutputFile.str().c_str());
976
977 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
978 FileOutputBuffer::create(Config->OutputFile, FileSize,
979 FileOutputBuffer::F_executable);
980
981 if (!BufferOrErr)
982 error("failed to open " + Config->OutputFile + ": " +
983 toString(BufferOrErr.takeError()));
984 else
985 Buffer = std::move(*BufferOrErr);
986}
987
988void Writer::createHeader() {
989 raw_string_ostream OS(Header);
990 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
991 writeU32(OS, WasmVersion, "wasm version");
992 OS.flush();
993 FileSize += Header.size();
994}
995
996void lld::wasm::writeResult() { Writer().run(); }