blob: 285f71913861ff85c68fb0c74b9cfd2abf57b783 [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();
Sam Cleggc94d3932017-11-17 18:14:09 +0000108 void createCodeSection();
109 void createDataSection();
110
111 // Custom sections
112 void createRelocSections();
113 void createLinkingSection();
114 void createNameSection();
115
116 void writeHeader();
117 void writeSections();
118
119 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000121
122 std::vector<const WasmSignature *> Types;
123 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000124 std::vector<const Symbol *> ImportedSymbols;
125 unsigned NumImportedFunctions = 0;
126 unsigned NumImportedGlobals = 0;
127 std::vector<Symbol *> ExportedSymbols;
128 std::vector<const DefinedData *> DefinedFakeGlobals;
129 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000130 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000131 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000132 std::vector<const Symbol *> SymtabEntries;
133 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000134
135 // Elements that are used to construct the final output
136 std::string Header;
137 std::vector<OutputSection *> OutputSections;
138
139 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000140 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000141
142 std::vector<OutputSegment *> Segments;
143 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
144};
145
146} // anonymous namespace
147
148static void debugPrint(const char *fmt, ...) {
149 if (!errorHandler().Verbose)
150 return;
151 fprintf(stderr, "lld: ");
152 va_list ap;
153 va_start(ap, fmt);
154 vfprintf(stderr, fmt, ap);
155 va_end(ap);
156}
157
158void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000159 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000160 if (Config->ImportMemory)
161 ++NumImports;
162
163 if (NumImports == 0)
164 return;
165
166 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
167 raw_ostream &OS = Section->getStream();
168
169 writeUleb128(OS, NumImports, "import count");
170
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 if (Config->ImportMemory) {
172 WasmImport Import;
173 Import.Module = "env";
174 Import.Field = "memory";
175 Import.Kind = WASM_EXTERNAL_MEMORY;
176 Import.Memory.Flags = 0;
177 Import.Memory.Initial = NumMemoryPages;
178 writeImport(OS, Import);
179 }
180
Sam Clegg93102972018-02-23 05:08:53 +0000181 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000182 WasmImport Import;
183 Import.Module = "env";
184 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000185 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
186 Import.Kind = WASM_EXTERNAL_FUNCTION;
187 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
188 } else {
189 auto *GlobalSym = cast<GlobalSymbol>(Sym);
190 Import.Kind = WASM_EXTERNAL_GLOBAL;
191 Import.Global = *GlobalSym->getGlobalType();
192 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000193 writeImport(OS, Import);
194 }
195}
196
197void Writer::createTypeSection() {
198 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
199 raw_ostream &OS = Section->getStream();
200 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000201 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000202 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000203}
204
205void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000206 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000207 return;
208
209 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
210 raw_ostream &OS = Section->getStream();
211
Sam Clegg9f934222018-02-21 18:29:23 +0000212 writeUleb128(OS, InputFunctions.size(), "function count");
213 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000214 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000215}
216
217void Writer::createMemorySection() {
218 if (Config->ImportMemory)
219 return;
220
221 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
222 raw_ostream &OS = Section->getStream();
223
224 writeUleb128(OS, 1, "memory count");
225 writeUleb128(OS, 0, "memory limits flags");
226 writeUleb128(OS, NumMemoryPages, "initial pages");
227}
228
229void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000230 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
231 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000232 return;
233
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
235 raw_ostream &OS = Section->getStream();
236
Sam Clegg93102972018-02-23 05:08:53 +0000237 writeUleb128(OS, NumGlobals, "global count");
238 for (const InputGlobal *G : InputGlobals)
239 writeGlobal(OS, G->Global);
240 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000242 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000243 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
244 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 writeGlobal(OS, Global);
246 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000247}
248
249void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000250 // Always output a table section, even if there are no indirect calls.
251 // There are two reasons for this:
252 // 1. For executables it is useful to have an empty table slot at 0
253 // which can be filled with a null function call handler.
254 // 2. If we don't do this, any program that contains a call_indirect but
255 // no address-taken function will fail at validation time since it is
256 // a validation error to include a call_indirect instruction if there
257 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000258 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000259
Sam Cleggc94d3932017-11-17 18:14:09 +0000260 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
261 raw_ostream &OS = Section->getStream();
262
263 writeUleb128(OS, 1, "table count");
264 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
265 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000266 writeUleb128(OS, TableSize, "table initial size");
267 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000268}
269
270void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000271 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000272
Sam Cleggd3052d52018-01-18 23:40:49 +0000273 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000274 if (!NumExports)
275 return;
276
277 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
278 raw_ostream &OS = Section->getStream();
279
280 writeUleb128(OS, NumExports, "export count");
281
Rui Ueyama7d696882018-02-28 00:18:34 +0000282 if (ExportMemory)
283 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000286
Sam Clegg93102972018-02-23 05:08:53 +0000287 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000289 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000290 DEBUG(dbgs() << "Export: " << Name << "\n");
291
292 if (isa<DefinedFunction>(Sym))
293 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
294 else if (isa<DefinedGlobal>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
296 else if (isa<DefinedData>(Sym))
297 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
298 else
Sam Clegg93102972018-02-23 05:08:53 +0000299 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000300 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000301 }
302}
303
Sam Cleggc94d3932017-11-17 18:14:09 +0000304void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000305 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000306 return;
307
308 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
309 raw_ostream &OS = Section->getStream();
310
311 writeUleb128(OS, 1, "segment count");
312 writeUleb128(OS, 0, "table index");
313 WasmInitExpr InitExpr;
314 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000315 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000316 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000317 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000318
Sam Clegg48bbd632018-01-24 21:37:30 +0000319 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000320 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000321 assert(Sym->getTableIndex() == TableIndex);
322 writeUleb128(OS, Sym->getOutputIndex(), "function index");
323 ++TableIndex;
324 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000325}
326
327void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000328 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000329 return;
330
331 log("createCodeSection");
332
Sam Clegg9f934222018-02-21 18:29:23 +0000333 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000334 OutputSections.push_back(Section);
335}
336
337void Writer::createDataSection() {
338 if (!Segments.size())
339 return;
340
341 log("createDataSection");
342 auto Section = make<DataSection>(Segments);
343 OutputSections.push_back(Section);
344}
345
Sam Cleggd451da12017-12-19 19:56:27 +0000346// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000347// These are only created when relocatable output is requested.
348void Writer::createRelocSections() {
349 log("createRelocSections");
350 // Don't use iterator here since we are adding to OutputSection
351 size_t OrigSize = OutputSections.size();
352 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000353 OutputSection *OSec = OutputSections[i];
354 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000355 if (!Count)
356 continue;
357
Rui Ueyama37254062018-02-28 00:01:31 +0000358 StringRef Name;
359 if (OSec->Type == WASM_SEC_DATA)
360 Name = "reloc.DATA";
361 else if (OSec->Type == WASM_SEC_CODE)
362 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000363 else
Sam Cleggd451da12017-12-19 19:56:27 +0000364 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000365
Rui Ueyama37254062018-02-28 00:01:31 +0000366 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000368 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000370 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000371 }
372}
373
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000374static uint32_t getWasmFlags(const Symbol *Sym) {
375 uint32_t Flags = 0;
376 if (Sym->isLocal())
377 Flags |= WASM_SYMBOL_BINDING_LOCAL;
378 if (Sym->isWeak())
379 Flags |= WASM_SYMBOL_BINDING_WEAK;
380 if (Sym->isHidden())
381 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
382 if (Sym->isUndefined())
383 Flags |= WASM_SYMBOL_UNDEFINED;
384 return Flags;
385}
386
Sam Clegg49ed9262017-12-01 00:53:21 +0000387// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000388// This is only created when relocatable output is requested.
389void Writer::createLinkingSection() {
390 SyntheticSection *Section =
391 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
392 raw_ostream &OS = Section->getStream();
393
Sam Clegg0d0dd392017-12-19 17:09:45 +0000394 if (!Config->Relocatable)
395 return;
396
Sam Clegg93102972018-02-23 05:08:53 +0000397 if (!SymtabEntries.empty()) {
398 SubSection SubSection(WASM_SYMBOL_TABLE);
399 writeUleb128(SubSection.getStream(), SymtabEntries.size(), "num symbols");
400 for (const Symbol *Sym : SymtabEntries) {
401 assert(Sym->isDefined() || Sym->isUndefined());
402 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000403 uint32_t Flags = getWasmFlags(Sym);
404
Sam Clegg93102972018-02-23 05:08:53 +0000405 writeUleb128(SubSection.getStream(), Kind, "sym kind");
406 writeUleb128(SubSection.getStream(), Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000407
Sam Clegg93102972018-02-23 05:08:53 +0000408 switch (Kind) {
409 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
410 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
411 writeUleb128(SubSection.getStream(), Sym->getOutputIndex(), "index");
412 if (Sym->isDefined())
413 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
414 break;
415 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
416 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
417 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
418 writeUleb128(SubSection.getStream(), DataSym->getOutputSegmentIndex(),
419 "index");
420 writeUleb128(SubSection.getStream(),
421 DataSym->getOutputSegmentOffset(), "data offset");
422 writeUleb128(SubSection.getStream(), DataSym->getSize(), "data size");
423 }
424 break;
425 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000426 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000427
Sam Cleggd3052d52018-01-18 23:40:49 +0000428 SubSection.finalizeContents();
429 SubSection.writeToStream(OS);
430 }
431
Sam Clegg0d0dd392017-12-19 17:09:45 +0000432 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000433 SubSection SubSection(WASM_SEGMENT_INFO);
434 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
435 for (const OutputSegment *S : Segments) {
436 writeStr(SubSection.getStream(), S->Name, "segment name");
437 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
438 writeUleb128(SubSection.getStream(), 0, "flags");
439 }
440 SubSection.finalizeContents();
441 SubSection.writeToStream(OS);
442 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000443
Sam Clegg0d0dd392017-12-19 17:09:45 +0000444 if (!InitFunctions.empty()) {
445 SubSection SubSection(WASM_INIT_FUNCS);
446 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000447 "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000448 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg0d0dd392017-12-19 17:09:45 +0000449 writeUleb128(SubSection.getStream(), F.Priority, "priority");
Sam Clegg93102972018-02-23 05:08:53 +0000450 writeUleb128(SubSection.getStream(), F.Sym->getOutputSymbolIndex(),
451 "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000452 }
453 SubSection.finalizeContents();
454 SubSection.writeToStream(OS);
455 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000456
457 struct ComdatEntry { unsigned Kind; uint32_t Index; };
458 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
459
Sam Clegg9f934222018-02-21 18:29:23 +0000460 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000461 StringRef Comdat = F->getComdat();
462 if (!Comdat.empty())
463 Comdats[Comdat].emplace_back(
464 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
465 }
466 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000467 const auto &InputSegments = Segments[I]->InputSegments;
468 if (InputSegments.empty())
469 continue;
470 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000471#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000472 for (const InputSegment *IS : InputSegments)
473 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000474#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000475 if (!Comdat.empty())
476 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
477 }
478
479 if (!Comdats.empty()) {
480 SubSection SubSection(WASM_COMDAT_INFO);
481 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
482 for (const auto &C : Comdats) {
483 writeStr(SubSection.getStream(), C.first, "comdat name");
484 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
485 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
486 for (const ComdatEntry &Entry : C.second) {
487 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
488 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
489 }
490 }
491 SubSection.finalizeContents();
492 SubSection.writeToStream(OS);
493 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000494}
495
496// Create the custom "name" section containing debug symbol names.
497void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000498 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000499 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000500 if (!F->getName().empty())
501 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000502
Sam Clegg1963d712018-01-17 20:19:04 +0000503 if (NumNames == 0)
504 return;
Sam Clegg50686852018-01-12 18:35:13 +0000505
Sam Cleggc94d3932017-11-17 18:14:09 +0000506 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
507
Sam Cleggc94d3932017-11-17 18:14:09 +0000508 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
509 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000510 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000511
Sam Clegg93102972018-02-23 05:08:53 +0000512 // Names must appear in function index order. As it happens ImportedSymbols
513 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000514 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000515 for (const Symbol *S : ImportedSymbols) {
516 if (!isa<FunctionSymbol>(S))
517 continue;
Sam Clegg1963d712018-01-17 20:19:04 +0000518 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000519 writeStr(OS, S->getName(), "symbol name");
520 }
Sam Clegg9f934222018-02-21 18:29:23 +0000521 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000522 if (!F->getName().empty()) {
523 writeUleb128(OS, F->getOutputIndex(), "func index");
524 writeStr(OS, F->getName(), "symbol name");
525 }
526 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000527
528 FunctionSubsection.finalizeContents();
529 FunctionSubsection.writeToStream(Section->getStream());
530}
531
532void Writer::writeHeader() {
533 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
534}
535
536void Writer::writeSections() {
537 uint8_t *Buf = Buffer->getBufferStart();
538 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
539}
540
541// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000542// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000543// The memory layout is as follows, from low to high.
544// - initialized data (starting at Config->GlobalBase)
545// - BSS data (not currently implemented in llvm)
546// - explicit stack (Config->ZStackSize)
547// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000548void Writer::layoutMemory() {
549 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000550 MemoryPtr = Config->GlobalBase;
551 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000552
553 createOutputSegments();
554
Sam Cleggf0d433d2018-02-02 22:59:56 +0000555 // Arbitrarily set __dso_handle handle to point to the start of the data
556 // segments.
557 if (WasmSym::DsoHandle)
558 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
559
Sam Cleggc94d3932017-11-17 18:14:09 +0000560 for (OutputSegment *Seg : Segments) {
561 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
562 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000563 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000564 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
565 MemoryPtr += Seg->Size;
566 }
567
Sam Cleggf0d433d2018-02-02 22:59:56 +0000568 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000569 if (WasmSym::DataEnd)
570 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571
Sam Clegg99eb42c2018-02-27 23:58:03 +0000572 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000573
Sam Cleggf0d433d2018-02-02 22:59:56 +0000574 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000575 if (!Config->Relocatable) {
576 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
577 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
578 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
579 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
580 debugPrint("mem: stack base = %d\n", MemoryPtr);
581 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000582 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000583 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000584
Sam Clegg51bcdc22018-01-17 01:34:31 +0000585 // Set `__heap_base` to directly follow the end of the stack. We don't
586 // allocate any heap memory up front, but instead really on the malloc/brk
587 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000588 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000589 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000590 }
591
592 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
593 NumMemoryPages = MemSize / WasmPageSize;
594 debugPrint("mem: total pages = %d\n", NumMemoryPages);
595}
596
597SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000598 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000600 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000601 OutputSections.push_back(Sec);
602 return Sec;
603}
604
605void Writer::createSections() {
606 // Known sections
607 createTypeSection();
608 createImportSection();
609 createFunctionSection();
610 createTableSection();
611 createMemorySection();
612 createGlobalSection();
613 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000614 createElemSection();
615 createCodeSection();
616 createDataSection();
617
618 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000619 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000620 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000621 createLinkingSection();
622 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000623 if (!Config->StripDebug && !Config->StripAll)
624 createNameSection();
625
626 for (OutputSection *S : OutputSections) {
627 S->setOffset(FileSize);
628 S->finalizeContents();
629 FileSize += S->getSize();
630 }
631}
632
Sam Cleggc94d3932017-11-17 18:14:09 +0000633void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000634 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000635 if (!Sym->isUndefined())
636 continue;
637 if (isa<DataSymbol>(Sym))
638 continue;
639 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000640 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000641
Sam Clegg93102972018-02-23 05:08:53 +0000642 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
643 Sym->setOutputIndex(ImportedSymbols.size());
644 ImportedSymbols.emplace_back(Sym);
645 if (isa<FunctionSymbol>(Sym))
646 ++NumImportedFunctions;
647 else
648 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000649 }
650}
651
Sam Cleggd3052d52018-01-18 23:40:49 +0000652void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000653 if (Config->Relocatable)
654 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000655
Sam Clegg93102972018-02-23 05:08:53 +0000656 auto ExportSym = [&](Symbol *Sym) {
657 if (!Sym->isDefined())
658 return;
659 if (Sym->isHidden() || Sym->isLocal())
660 return;
661 if (!Sym->isLive())
662 return;
663
664 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
665
666 if (auto *D = dyn_cast<DefinedData>(Sym)) {
667 // TODO Remove this check here; for non-relocatable output we actually
668 // used only to create fake-global exports for the synthetic symbols. Fix
669 // this in a future commit
670 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
671 return;
672 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000673 }
Sam Clegg93102972018-02-23 05:08:53 +0000674 ExportedSymbols.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000675 };
676
Sam Clegg93102972018-02-23 05:08:53 +0000677 // TODO The two loops below should be replaced with this single loop, with
678 // ExportSym inlined:
679 // for (Symbol *Sym : Symtab->getSymbols())
680 // ExportSym(Sym);
681 // Making that change would reorder the output though, so it should be done as
682 // a separate commit.
Sam Cleggd3052d52018-01-18 23:40:49 +0000683
Sam Clegg93102972018-02-23 05:08:53 +0000684 for (ObjFile *File : Symtab->ObjectFiles)
685 for (Symbol *Sym : File->getSymbols())
686 if (File == Sym->getFile())
687 ExportSym(Sym);
688
689 for (Symbol *Sym : Symtab->getSymbols())
690 if (Sym->getFile() == nullptr)
691 ExportSym(Sym);
692}
693
694void Writer::assignSymtab() {
695 if (!Config->Relocatable)
696 return;
697
698 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000699 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000700 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000701 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000702 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000703 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000704 if (!Sym->isLive())
705 return;
706 Sym->setOutputSymbolIndex(SymbolIndex++);
707 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000708 }
709 }
710
Sam Clegg93102972018-02-23 05:08:53 +0000711 // For the moment, relocatable output doesn't contain any synthetic functions,
712 // so no need to look through the Symtab for symbols not referenced by
713 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000714}
715
Sam Cleggc375e4e2018-01-10 19:18:22 +0000716uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000717 auto It = TypeIndices.find(Sig);
718 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000719 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000720 return 0;
721 }
722 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000723}
724
725uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000726 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000727 if (Pair.second) {
728 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000729 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000730 }
Sam Cleggb8621592017-11-30 01:40:08 +0000731 return Pair.first->second;
732}
733
Sam Cleggc94d3932017-11-17 18:14:09 +0000734void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000735 // The output type section is the union of the following sets:
736 // 1. Any signature used in the TYPE relocation
737 // 2. The signatures of all imported functions
738 // 3. The signatures of all defined functions
739
Sam Cleggc94d3932017-11-17 18:14:09 +0000740 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000741 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
742 for (uint32_t I = 0; I < Types.size(); I++)
743 if (File->TypeIsUsed[I])
744 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000745 }
Sam Clegg50686852018-01-12 18:35:13 +0000746
Sam Clegg93102972018-02-23 05:08:53 +0000747 for (const Symbol *Sym : ImportedSymbols)
748 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
749 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000750
Sam Clegg9f934222018-02-21 18:29:23 +0000751 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000752 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000753}
754
Sam Clegg8d146bb2018-01-09 23:56:44 +0000755void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000756 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000757 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000758 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
759 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000760 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000761 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000762 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000763 Func->setOutputIndex(FunctionIndex++);
764 }
765 }
766
Sam Clegg93102972018-02-23 05:08:53 +0000767 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000768 auto HandleRelocs = [&](InputChunk *Chunk) {
769 if (!Chunk->Live)
770 return;
771 ObjFile *File = Chunk->File;
772 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000773 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000774 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
775 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
776 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
777 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
778 continue;
779 Sym->setTableIndex(TableIndex++);
780 IndirectFunctions.emplace_back(Sym);
781 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000782 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000783 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
784 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000785 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
786 // Mark target global as live
787 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
788 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
789 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
790 G->Global->Live = true;
791 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000792 }
793 }
794 };
795
Sam Clegg8d146bb2018-01-09 23:56:44 +0000796 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000797 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000798 for (InputChunk *Chunk : File->Functions)
799 HandleRelocs(Chunk);
800 for (InputChunk *Chunk : File->Segments)
801 HandleRelocs(Chunk);
802 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000803
Sam Clegg93102972018-02-23 05:08:53 +0000804 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
805 auto AddDefinedGlobal = [&](InputGlobal *Global) {
806 if (Global->Live) {
807 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
808 Global->setOutputIndex(GlobalIndex++);
809 InputGlobals.push_back(Global);
810 }
811 };
812
813 if (WasmSym::StackPointer)
814 AddDefinedGlobal(WasmSym::StackPointer->Global);
815
816 for (ObjFile *File : Symtab->ObjectFiles) {
817 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
818 for (InputGlobal *Global : File->Globals)
819 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000820 }
821}
822
823static StringRef getOutputDataSegmentName(StringRef Name) {
824 if (Config->Relocatable)
825 return Name;
826
827 for (StringRef V :
828 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
829 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
830 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
831 StringRef Prefix = V.drop_back();
832 if (Name.startswith(V) || Name == Prefix)
833 return Prefix;
834 }
835
836 return Name;
837}
838
839void Writer::createOutputSegments() {
840 for (ObjFile *File : Symtab->ObjectFiles) {
841 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000842 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000843 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000844 StringRef Name = getOutputDataSegmentName(Segment->getName());
845 OutputSegment *&S = SegmentMap[Name];
846 if (S == nullptr) {
847 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000848 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000849 Segments.push_back(S);
850 }
851 S->addInputSegment(Segment);
852 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000853 }
854 }
855}
856
Sam Clegg50686852018-01-12 18:35:13 +0000857static const int OPCODE_CALL = 0x10;
858static const int OPCODE_END = 0xb;
859
860// Create synthetic "__wasm_call_ctors" function based on ctor functions
861// in input object.
862void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000863 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000864 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000865
866 // First write the body bytes to a string.
867 std::string FunctionBody;
Sam Clegg93102972018-02-23 05:08:53 +0000868 const WasmSignature *Signature = WasmSym::CallCtors->getFunctionType();
Sam Clegg50686852018-01-12 18:35:13 +0000869 {
870 raw_string_ostream OS(FunctionBody);
871 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000872 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000873 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000874 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000875 }
876 writeU8(OS, OPCODE_END, "END");
877 }
878
879 // Once we know the size of the body we can create the final function body
880 raw_string_ostream OS(CtorFunctionBody);
881 writeUleb128(OS, FunctionBody.size(), "function size");
882 OS.flush();
883 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000884 ArrayRef<uint8_t> BodyArray(
885 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
886 CtorFunctionBody.size());
Sam Clegg93102972018-02-23 05:08:53 +0000887 SyntheticFunction *F = make<SyntheticFunction>(*Signature, BodyArray,
Sam Clegg011dce22018-02-21 18:37:44 +0000888 WasmSym::CallCtors->getName());
889 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000890 F->Live = true;
891 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000892 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000893}
894
895// Populate InitFunctions vector with init functions from all input objects.
896// This is then used either when creating the output linking section or to
897// synthesize the "__wasm_call_ctors" function.
898void Writer::calculateInitFunctions() {
899 for (ObjFile *File : Symtab->ObjectFiles) {
900 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Sam Clegg50686852018-01-12 18:35:13 +0000901 for (const WasmInitFunc &F : L.InitFunctions)
Sam Clegg93102972018-02-23 05:08:53 +0000902 InitFunctions.emplace_back(
903 WasmInitEntry{File->getFunctionSymbol(F.Symbol), F.Priority});
Sam Clegg50686852018-01-12 18:35:13 +0000904 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000905
Sam Clegg50686852018-01-12 18:35:13 +0000906 // Sort in order of priority (lowest first) so that they are called
907 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000908 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000909 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000910 return L.Priority < R.Priority;
911 });
Sam Clegg50686852018-01-12 18:35:13 +0000912}
913
Sam Cleggc94d3932017-11-17 18:14:09 +0000914void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000915 if (Config->Relocatable)
916 Config->GlobalBase = 0;
917
Sam Cleggc94d3932017-11-17 18:14:09 +0000918 log("-- calculateImports");
919 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000920 log("-- assignIndexes");
921 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000922 log("-- calculateInitFunctions");
923 calculateInitFunctions();
924 if (!Config->Relocatable)
925 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000926 log("-- calculateTypes");
927 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000928 log("-- layoutMemory");
929 layoutMemory();
930 log("-- calculateExports");
931 calculateExports();
932 log("-- assignSymtab");
933 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000934
935 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000936 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000937 log("Defined Globals : " + Twine(InputGlobals.size()));
938 log("Function Imports : " + Twine(NumImportedFunctions));
939 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000940 for (ObjFile *File : Symtab->ObjectFiles)
941 File->dumpInfo();
942 }
943
Sam Cleggc94d3932017-11-17 18:14:09 +0000944 createHeader();
945 log("-- createSections");
946 createSections();
947
948 log("-- openFile");
949 openFile();
950 if (errorCount())
951 return;
952
953 writeHeader();
954
955 log("-- writeSections");
956 writeSections();
957 if (errorCount())
958 return;
959
960 if (Error E = Buffer->commit())
961 fatal("failed to write the output file: " + toString(std::move(E)));
962}
963
964// Open a result file.
965void Writer::openFile() {
966 log("writing: " + Config->OutputFile);
967 ::remove(Config->OutputFile.str().c_str());
968
969 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
970 FileOutputBuffer::create(Config->OutputFile, FileSize,
971 FileOutputBuffer::F_executable);
972
973 if (!BufferOrErr)
974 error("failed to open " + Config->OutputFile + ": " +
975 toString(BufferOrErr.takeError()));
976 else
977 Buffer = std::move(*BufferOrErr);
978}
979
980void Writer::createHeader() {
981 raw_string_ostream OS(Header);
982 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
983 writeU32(OS, WasmVersion, "wasm version");
984 OS.flush();
985 FileSize += Header.size();
986}
987
988void lld::wasm::writeResult() { Writer().run(); }