blob: ce5a92cb0bd0900caa5258ea85af0eb9c7ae53e6 [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) {
Rui Ueyamaba16bac2018-02-28 17:32:50 +000056 unsigned H = hash_value(Sig.ReturnType);
Sam Cleggc94d3932017-11-17 18:14:09 +000057 for (int32_t Param : Sig.ParamTypes)
Rui Ueyamaba16bac2018-02-28 17:32:50 +000058 H = hash_combine(H, Param);
59 return H;
Sam Cleggc94d3932017-11-17 18:14:09 +000060 }
61 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
62 return LHS == RHS;
63 }
64};
65
Sam Clegg93102972018-02-23 05:08:53 +000066// An init entry to be written to either the synthetic init func or the
67// linking metadata.
68struct WasmInitEntry {
Sam Clegg811236c2018-01-19 03:31:07 +000069 const Symbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000070 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000071};
72
Sam Cleggc94d3932017-11-17 18:14:09 +000073// The writer writes a SymbolTable result to a file.
74class Writer {
75public:
76 void run();
77
78private:
79 void openFile();
80
Sam Cleggc375e4e2018-01-10 19:18:22 +000081 uint32_t lookupType(const WasmSignature &Sig);
82 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000083
Sam Clegg50686852018-01-12 18:35:13 +000084 void createCtorFunction();
85 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000086 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000088 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000089 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000090 void calculateTypes();
91 void createOutputSegments();
92 void layoutMemory();
93 void createHeader();
94 void createSections();
95 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000096 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000097
98 // Builtin sections
99 void createTypeSection();
100 void createFunctionSection();
101 void createTableSection();
102 void createGlobalSection();
103 void createExportSection();
104 void createImportSection();
105 void createMemorySection();
106 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000107 void createCodeSection();
108 void createDataSection();
109
110 // Custom sections
111 void createRelocSections();
112 void createLinkingSection();
113 void createNameSection();
114
115 void writeHeader();
116 void writeSections();
117
118 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000119 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120
121 std::vector<const WasmSignature *> Types;
122 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000123 std::vector<const Symbol *> ImportedSymbols;
124 unsigned NumImportedFunctions = 0;
125 unsigned NumImportedGlobals = 0;
126 std::vector<Symbol *> ExportedSymbols;
127 std::vector<const DefinedData *> DefinedFakeGlobals;
128 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000129 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000130 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000131 std::vector<const Symbol *> SymtabEntries;
132 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000133
134 // Elements that are used to construct the final output
135 std::string Header;
136 std::vector<OutputSection *> OutputSections;
137
138 std::unique_ptr<FileOutputBuffer> Buffer;
139
140 std::vector<OutputSegment *> Segments;
141 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
142};
143
144} // anonymous namespace
145
146static void debugPrint(const char *fmt, ...) {
147 if (!errorHandler().Verbose)
148 return;
149 fprintf(stderr, "lld: ");
150 va_list ap;
151 va_start(ap, fmt);
152 vfprintf(stderr, fmt, ap);
153 va_end(ap);
154}
155
156void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000157 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000158 if (Config->ImportMemory)
159 ++NumImports;
160
161 if (NumImports == 0)
162 return;
163
164 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
165 raw_ostream &OS = Section->getStream();
166
167 writeUleb128(OS, NumImports, "import count");
168
Sam Cleggc94d3932017-11-17 18:14:09 +0000169 if (Config->ImportMemory) {
170 WasmImport Import;
171 Import.Module = "env";
172 Import.Field = "memory";
173 Import.Kind = WASM_EXTERNAL_MEMORY;
174 Import.Memory.Flags = 0;
175 Import.Memory.Initial = NumMemoryPages;
176 writeImport(OS, Import);
177 }
178
Sam Clegg93102972018-02-23 05:08:53 +0000179 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000180 WasmImport Import;
181 Import.Module = "env";
182 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000183 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
184 Import.Kind = WASM_EXTERNAL_FUNCTION;
185 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
186 } else {
187 auto *GlobalSym = cast<GlobalSymbol>(Sym);
188 Import.Kind = WASM_EXTERNAL_GLOBAL;
189 Import.Global = *GlobalSym->getGlobalType();
190 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000191 writeImport(OS, Import);
192 }
193}
194
195void Writer::createTypeSection() {
196 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
197 raw_ostream &OS = Section->getStream();
198 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000199 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000201}
202
203void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000204 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000205 return;
206
207 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
208 raw_ostream &OS = Section->getStream();
209
Sam Clegg9f934222018-02-21 18:29:23 +0000210 writeUleb128(OS, InputFunctions.size(), "function count");
211 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000212 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000213}
214
215void Writer::createMemorySection() {
216 if (Config->ImportMemory)
217 return;
218
219 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
220 raw_ostream &OS = Section->getStream();
221
222 writeUleb128(OS, 1, "memory count");
223 writeUleb128(OS, 0, "memory limits flags");
224 writeUleb128(OS, NumMemoryPages, "initial pages");
225}
226
227void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000228 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
229 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000230 return;
231
Sam Cleggc94d3932017-11-17 18:14:09 +0000232 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
233 raw_ostream &OS = Section->getStream();
234
Sam Clegg93102972018-02-23 05:08:53 +0000235 writeUleb128(OS, NumGlobals, "global count");
236 for (const InputGlobal *G : InputGlobals)
237 writeGlobal(OS, G->Global);
238 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000239 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000240 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
242 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 writeGlobal(OS, Global);
244 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000245}
246
247void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000248 // Always output a table section, even if there are no indirect calls.
249 // There are two reasons for this:
250 // 1. For executables it is useful to have an empty table slot at 0
251 // which can be filled with a null function call handler.
252 // 2. If we don't do this, any program that contains a call_indirect but
253 // no address-taken function will fail at validation time since it is
254 // a validation error to include a call_indirect instruction if there
255 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000256 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000257
Sam Cleggc94d3932017-11-17 18:14:09 +0000258 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
259 raw_ostream &OS = Section->getStream();
260
261 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000262 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000263 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000264 writeUleb128(OS, TableSize, "table initial size");
265 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000266}
267
268void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000269 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000270
Sam Cleggd3052d52018-01-18 23:40:49 +0000271 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000272 if (!NumExports)
273 return;
274
275 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
276 raw_ostream &OS = Section->getStream();
277
278 writeUleb128(OS, NumExports, "export count");
279
Rui Ueyama7d696882018-02-28 00:18:34 +0000280 if (ExportMemory)
281 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000282
Sam Clegg93102972018-02-23 05:08:53 +0000283 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000286 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000287 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 DEBUG(dbgs() << "Export: " << Name << "\n");
289
290 if (isa<DefinedFunction>(Sym))
291 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
292 else if (isa<DefinedGlobal>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
294 else if (isa<DefinedData>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
296 else
Sam Clegg93102972018-02-23 05:08:53 +0000297 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000298 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000299 }
300}
301
Sam Cleggc94d3932017-11-17 18:14:09 +0000302void 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 Clegg9f934222018-02-21 18:29:23 +0000326 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000327 return;
328
329 log("createCodeSection");
330
Sam Clegg9f934222018-02-21 18:29:23 +0000331 auto Section = make<CodeSection>(InputFunctions);
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++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000351 OutputSection *OSec = OutputSections[i];
352 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000353 if (!Count)
354 continue;
355
Rui Ueyama37254062018-02-28 00:01:31 +0000356 StringRef Name;
357 if (OSec->Type == WASM_SEC_DATA)
358 Name = "reloc.DATA";
359 else if (OSec->Type == WASM_SEC_CODE)
360 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000361 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
Rui Ueyama37254062018-02-28 00:01:31 +0000364 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000366 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000368 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 }
370}
371
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000372static uint32_t getWasmFlags(const Symbol *Sym) {
373 uint32_t Flags = 0;
374 if (Sym->isLocal())
375 Flags |= WASM_SYMBOL_BINDING_LOCAL;
376 if (Sym->isWeak())
377 Flags |= WASM_SYMBOL_BINDING_WEAK;
378 if (Sym->isHidden())
379 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
380 if (Sym->isUndefined())
381 Flags |= WASM_SYMBOL_UNDEFINED;
382 return Flags;
383}
384
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000385// Some synthetic sections (e.g. "name" and "linking") have subsections.
386// Just like the synthetic sections themselves these need to be created before
387// they can be written out (since they are preceded by their length). This
388// class is used to create subsections and then write them into the stream
389// of the parent section.
390class SubSection {
391public:
392 explicit SubSection(uint32_t Type) : Type(Type) {}
393
394 void writeTo(raw_ostream &To) {
395 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000396 writeUleb128(To, Type, "subsection type");
397 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000398 To.write(Body.data(), Body.size());
399 }
400
401private:
402 uint32_t Type;
403 std::string Body;
404
405public:
406 raw_string_ostream OS{Body};
407};
408
Sam Clegg49ed9262017-12-01 00:53:21 +0000409// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000410// This is only created when relocatable output is requested.
411void Writer::createLinkingSection() {
412 SyntheticSection *Section =
413 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
414 raw_ostream &OS = Section->getStream();
415
Sam Clegg0d0dd392017-12-19 17:09:45 +0000416 if (!Config->Relocatable)
417 return;
418
Sam Clegg93102972018-02-23 05:08:53 +0000419 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000420 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000421 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
422
Sam Clegg93102972018-02-23 05:08:53 +0000423 for (const Symbol *Sym : SymtabEntries) {
424 assert(Sym->isDefined() || Sym->isUndefined());
425 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000426 uint32_t Flags = getWasmFlags(Sym);
427
Sam Clegg8518e7d2018-03-01 18:06:39 +0000428 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000429 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000430
Sam Clegg93102972018-02-23 05:08:53 +0000431 switch (Kind) {
432 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
433 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000434 writeUleb128(Sub.OS, Sym->getOutputIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000435 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000436 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000437 break;
438 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000440 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
442 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000443 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000444 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000445 }
446 break;
447 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000448 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000449
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000450 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000451 }
452
Sam Clegg0d0dd392017-12-19 17:09:45 +0000453 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000454 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000455 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000456 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeStr(Sub.OS, S->Name, "segment name");
458 writeUleb128(Sub.OS, S->Alignment, "alignment");
459 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000460 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000461 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000463
Sam Clegg0d0dd392017-12-19 17:09:45 +0000464 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000465 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000466 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000467 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 writeUleb128(Sub.OS, F.Priority, "priority");
469 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000470 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000471 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000472 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000473
474 struct ComdatEntry { unsigned Kind; uint32_t Index; };
475 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
476
Sam Clegg9f934222018-02-21 18:29:23 +0000477 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000478 StringRef Comdat = F->getComdat();
479 if (!Comdat.empty())
480 Comdats[Comdat].emplace_back(
481 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
482 }
483 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000484 const auto &InputSegments = Segments[I]->InputSegments;
485 if (InputSegments.empty())
486 continue;
487 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000488#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000489 for (const InputSegment *IS : InputSegments)
490 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000491#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000492 if (!Comdat.empty())
493 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
494 }
495
496 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000497 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000498 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000499 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeStr(Sub.OS, C.first, "comdat name");
501 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
502 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000504 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000505 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000506 }
507 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000508 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000509 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000510}
511
512// Create the custom "name" section containing debug symbol names.
513void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000514 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000515 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000516 if (!F->getName().empty())
517 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000518
Sam Clegg1963d712018-01-17 20:19:04 +0000519 if (NumNames == 0)
520 return;
Sam Clegg50686852018-01-12 18:35:13 +0000521
Sam Cleggc94d3932017-11-17 18:14:09 +0000522 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
523
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000524 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000526
Sam Clegg93102972018-02-23 05:08:53 +0000527 // Names must appear in function index order. As it happens ImportedSymbols
528 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000529 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000530 for (const Symbol *S : ImportedSymbols) {
531 if (!isa<FunctionSymbol>(S))
532 continue;
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000533 writeUleb128(Sub.OS, S->getOutputIndex(), "import index");
534 writeStr(Sub.OS, S->getName(), "symbol name");
Sam Cleggc94d3932017-11-17 18:14:09 +0000535 }
Sam Clegg9f934222018-02-21 18:29:23 +0000536 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000537 if (!F->getName().empty()) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000538 writeUleb128(Sub.OS, F->getOutputIndex(), "func index");
539 writeStr(Sub.OS, F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000540 }
541 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000542
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000543 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000544}
545
546void Writer::writeHeader() {
547 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
548}
549
550void Writer::writeSections() {
551 uint8_t *Buf = Buffer->getBufferStart();
552 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
553}
554
555// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000556// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000557// The memory layout is as follows, from low to high.
558// - initialized data (starting at Config->GlobalBase)
559// - BSS data (not currently implemented in llvm)
560// - explicit stack (Config->ZStackSize)
561// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000562void Writer::layoutMemory() {
563 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000564 MemoryPtr = Config->GlobalBase;
565 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000566
567 createOutputSegments();
568
Sam Cleggf0d433d2018-02-02 22:59:56 +0000569 // Arbitrarily set __dso_handle handle to point to the start of the data
570 // segments.
571 if (WasmSym::DsoHandle)
572 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
573
Sam Cleggc94d3932017-11-17 18:14:09 +0000574 for (OutputSegment *Seg : Segments) {
575 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
576 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000577 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000578 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
579 MemoryPtr += Seg->Size;
580 }
581
Sam Cleggf0d433d2018-02-02 22:59:56 +0000582 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000583 if (WasmSym::DataEnd)
584 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585
Sam Clegg99eb42c2018-02-27 23:58:03 +0000586 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000587
Sam Cleggf0d433d2018-02-02 22:59:56 +0000588 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000589 if (!Config->Relocatable) {
590 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
591 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
592 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
593 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
594 debugPrint("mem: stack base = %d\n", MemoryPtr);
595 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000596 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000598
Sam Clegg51bcdc22018-01-17 01:34:31 +0000599 // Set `__heap_base` to directly follow the end of the stack. We don't
600 // allocate any heap memory up front, but instead really on the malloc/brk
601 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000602 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000603 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000604 }
605
606 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
607 NumMemoryPages = MemSize / WasmPageSize;
608 debugPrint("mem: total pages = %d\n", NumMemoryPages);
609}
610
611SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000612 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000613 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000614 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 OutputSections.push_back(Sec);
616 return Sec;
617}
618
619void Writer::createSections() {
620 // Known sections
621 createTypeSection();
622 createImportSection();
623 createFunctionSection();
624 createTableSection();
625 createMemorySection();
626 createGlobalSection();
627 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000628 createElemSection();
629 createCodeSection();
630 createDataSection();
631
632 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000633 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000635 createLinkingSection();
636 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000637 if (!Config->StripDebug && !Config->StripAll)
638 createNameSection();
639
640 for (OutputSection *S : OutputSections) {
641 S->setOffset(FileSize);
642 S->finalizeContents();
643 FileSize += S->getSize();
644 }
645}
646
Sam Cleggc94d3932017-11-17 18:14:09 +0000647void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000648 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000649 if (!Sym->isUndefined())
650 continue;
651 if (isa<DataSymbol>(Sym))
652 continue;
653 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000654 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000655
Sam Clegg93102972018-02-23 05:08:53 +0000656 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
657 Sym->setOutputIndex(ImportedSymbols.size());
658 ImportedSymbols.emplace_back(Sym);
659 if (isa<FunctionSymbol>(Sym))
660 ++NumImportedFunctions;
661 else
662 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000663 }
664}
665
Sam Cleggd3052d52018-01-18 23:40:49 +0000666void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000667 if (Config->Relocatable)
668 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000669
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000670 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000671 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000672 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000673 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000674 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000675 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000676 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000677
678 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
679
Nicholas Wilsonf2f6d5e2018-03-02 14:51:36 +0000680 if (auto *D = dyn_cast<DefinedData>(Sym))
Sam Clegg93102972018-02-23 05:08:53 +0000681 DefinedFakeGlobals.emplace_back(D);
Sam Clegg93102972018-02-23 05:08:53 +0000682 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000683 }
Sam Clegg93102972018-02-23 05:08:53 +0000684}
685
686void Writer::assignSymtab() {
687 if (!Config->Relocatable)
688 return;
689
690 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000691 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000692 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000693 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000694 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000695 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000696 if (!Sym->isLive())
697 return;
698 Sym->setOutputSymbolIndex(SymbolIndex++);
699 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000700 }
701 }
702
Sam Clegg93102972018-02-23 05:08:53 +0000703 // For the moment, relocatable output doesn't contain any synthetic functions,
704 // so no need to look through the Symtab for symbols not referenced by
705 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000706}
707
Sam Cleggc375e4e2018-01-10 19:18:22 +0000708uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000709 auto It = TypeIndices.find(Sig);
710 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000711 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000712 return 0;
713 }
714 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000715}
716
717uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000718 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000719 if (Pair.second) {
720 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000721 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000722 }
Sam Cleggb8621592017-11-30 01:40:08 +0000723 return Pair.first->second;
724}
725
Sam Cleggc94d3932017-11-17 18:14:09 +0000726void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000727 // The output type section is the union of the following sets:
728 // 1. Any signature used in the TYPE relocation
729 // 2. The signatures of all imported functions
730 // 3. The signatures of all defined functions
731
Sam Cleggc94d3932017-11-17 18:14:09 +0000732 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000733 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
734 for (uint32_t I = 0; I < Types.size(); I++)
735 if (File->TypeIsUsed[I])
736 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000737 }
Sam Clegg50686852018-01-12 18:35:13 +0000738
Sam Clegg93102972018-02-23 05:08:53 +0000739 for (const Symbol *Sym : ImportedSymbols)
740 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
741 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000742
Sam Clegg9f934222018-02-21 18:29:23 +0000743 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000744 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000745}
746
Sam Clegg8d146bb2018-01-09 23:56:44 +0000747void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000748 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000749 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000750 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
751 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000752 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000753 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000754 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000755 Func->setOutputIndex(FunctionIndex++);
756 }
757 }
758
Sam Clegg93102972018-02-23 05:08:53 +0000759 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000760 auto HandleRelocs = [&](InputChunk *Chunk) {
761 if (!Chunk->Live)
762 return;
763 ObjFile *File = Chunk->File;
764 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000765 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000766 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
767 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
768 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
769 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
770 continue;
771 Sym->setTableIndex(TableIndex++);
772 IndirectFunctions.emplace_back(Sym);
773 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000774 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000775 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
776 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000777 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
778 // Mark target global as live
779 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
780 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
781 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
782 G->Global->Live = true;
783 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000784 }
785 }
786 };
787
Sam Clegg8d146bb2018-01-09 23:56:44 +0000788 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000789 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000790 for (InputChunk *Chunk : File->Functions)
791 HandleRelocs(Chunk);
792 for (InputChunk *Chunk : File->Segments)
793 HandleRelocs(Chunk);
794 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000795
Sam Clegg93102972018-02-23 05:08:53 +0000796 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
797 auto AddDefinedGlobal = [&](InputGlobal *Global) {
798 if (Global->Live) {
799 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
800 Global->setOutputIndex(GlobalIndex++);
801 InputGlobals.push_back(Global);
802 }
803 };
804
805 if (WasmSym::StackPointer)
806 AddDefinedGlobal(WasmSym::StackPointer->Global);
807
808 for (ObjFile *File : Symtab->ObjectFiles) {
809 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
810 for (InputGlobal *Global : File->Globals)
811 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000812 }
813}
814
815static StringRef getOutputDataSegmentName(StringRef Name) {
816 if (Config->Relocatable)
817 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000818 if (Name.startswith(".text."))
819 return ".text";
820 if (Name.startswith(".data."))
821 return ".data";
822 if (Name.startswith(".bss."))
823 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000824 return Name;
825}
826
827void Writer::createOutputSegments() {
828 for (ObjFile *File : Symtab->ObjectFiles) {
829 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000830 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000831 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000832 StringRef Name = getOutputDataSegmentName(Segment->getName());
833 OutputSegment *&S = SegmentMap[Name];
834 if (S == nullptr) {
835 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000836 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000837 Segments.push_back(S);
838 }
839 S->addInputSegment(Segment);
840 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000841 }
842 }
843}
844
Sam Clegg50686852018-01-12 18:35:13 +0000845static const int OPCODE_CALL = 0x10;
846static const int OPCODE_END = 0xb;
847
848// Create synthetic "__wasm_call_ctors" function based on ctor functions
849// in input object.
850void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000851 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000852 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000853
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000854 // First write the body's contents to a string.
855 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000856 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000857 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000858 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000859 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000860 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000861 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000862 }
863 writeU8(OS, OPCODE_END, "END");
864 }
865
866 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000867 std::string FunctionBody;
868 {
869 raw_string_ostream OS(FunctionBody);
870 writeUleb128(OS, BodyContent.size(), "function size");
871 OS << BodyContent;
872 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000873
874 const WasmSignature *Sig = WasmSym::CallCtors->getFunctionType();
875 SyntheticFunction *F = make<SyntheticFunction>(
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000876 *Sig, std::move(FunctionBody), WasmSym::CallCtors->getName());
Rui Ueyama29abfe42018-02-28 17:43:15 +0000877
Sam Clegg011dce22018-02-21 18:37:44 +0000878 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000879 F->Live = true;
880 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000881 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000882}
883
884// Populate InitFunctions vector with init functions from all input objects.
885// This is then used either when creating the output linking section or to
886// synthesize the "__wasm_call_ctors" function.
887void Writer::calculateInitFunctions() {
888 for (ObjFile *File : Symtab->ObjectFiles) {
889 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000890 for (const WasmInitFunc &F : L.InitFunctions) {
891 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
892 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
893 error("invalid signature for init func: " + toString(*Sym));
894 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
895 }
Sam Clegg50686852018-01-12 18:35:13 +0000896 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000897
Sam Clegg50686852018-01-12 18:35:13 +0000898 // Sort in order of priority (lowest first) so that they are called
899 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000900 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000901 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000902 return L.Priority < R.Priority;
903 });
Sam Clegg50686852018-01-12 18:35:13 +0000904}
905
Sam Cleggc94d3932017-11-17 18:14:09 +0000906void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000907 if (Config->Relocatable)
908 Config->GlobalBase = 0;
909
Sam Cleggc94d3932017-11-17 18:14:09 +0000910 log("-- calculateImports");
911 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000912 log("-- assignIndexes");
913 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000914 log("-- calculateInitFunctions");
915 calculateInitFunctions();
916 if (!Config->Relocatable)
917 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000918 log("-- calculateTypes");
919 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000920 log("-- layoutMemory");
921 layoutMemory();
922 log("-- calculateExports");
923 calculateExports();
924 log("-- assignSymtab");
925 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000926
927 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000928 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000929 log("Defined Globals : " + Twine(InputGlobals.size()));
930 log("Function Imports : " + Twine(NumImportedFunctions));
931 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000932 for (ObjFile *File : Symtab->ObjectFiles)
933 File->dumpInfo();
934 }
935
Sam Cleggc94d3932017-11-17 18:14:09 +0000936 createHeader();
937 log("-- createSections");
938 createSections();
939
940 log("-- openFile");
941 openFile();
942 if (errorCount())
943 return;
944
945 writeHeader();
946
947 log("-- writeSections");
948 writeSections();
949 if (errorCount())
950 return;
951
952 if (Error E = Buffer->commit())
953 fatal("failed to write the output file: " + toString(std::move(E)));
954}
955
956// Open a result file.
957void Writer::openFile() {
958 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000959
960 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
961 FileOutputBuffer::create(Config->OutputFile, FileSize,
962 FileOutputBuffer::F_executable);
963
964 if (!BufferOrErr)
965 error("failed to open " + Config->OutputFile + ": " +
966 toString(BufferOrErr.takeError()));
967 else
968 Buffer = std::move(*BufferOrErr);
969}
970
971void Writer::createHeader() {
972 raw_string_ostream OS(Header);
973 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
974 writeU32(OS, WasmVersion, "wasm version");
975 OS.flush();
976 FileSize += Header.size();
977}
978
979void lld::wasm::writeResult() { Writer().run(); }