blob: b5abb6b141b0342b5cd679d7536fe4a258bae323 [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"
Nicholas Wilson8269f372018-03-07 10:37:50 +000020#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000021#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000022#include "llvm/ADT/DenseSet.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000023#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000024#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000025#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000026#include "llvm/Support/FileOutputBuffer.h"
27#include "llvm/Support/Format.h"
28#include "llvm/Support/FormatVariadic.h"
29#include "llvm/Support/LEB128.h"
30
31#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000032#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000033
34#define DEBUG_TYPE "lld"
35
36using namespace llvm;
37using namespace llvm::wasm;
38using namespace lld;
39using namespace lld::wasm;
40
41static constexpr int kStackAlignment = 16;
Nicholas Wilson874eedd2018-03-27 17:38:51 +000042static constexpr const char *kFunctionTableName = "__indirect_function_table";
Sam Cleggc94d3932017-11-17 18:14:09 +000043
44namespace {
45
Sam Clegg93102972018-02-23 05:08:53 +000046// An init entry to be written to either the synthetic init func or the
47// linking metadata.
48struct WasmInitEntry {
Sam Clegge3f3ccf2018-03-12 19:56:23 +000049 const FunctionSymbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000050 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000051};
52
Sam Cleggc94d3932017-11-17 18:14:09 +000053// The writer writes a SymbolTable result to a file.
54class Writer {
55public:
56 void run();
57
58private:
59 void openFile();
60
Sam Cleggc375e4e2018-01-10 19:18:22 +000061 uint32_t lookupType(const WasmSignature &Sig);
62 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000063
Sam Clegg50686852018-01-12 18:35:13 +000064 void createCtorFunction();
65 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000066 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000067 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000068 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000069 void calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +000070 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000071 void calculateTypes();
72 void createOutputSegments();
73 void layoutMemory();
74 void createHeader();
75 void createSections();
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +000076 SyntheticSection *createSyntheticSection(uint32_t Type, StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000077
78 // Builtin sections
79 void createTypeSection();
80 void createFunctionSection();
81 void createTableSection();
82 void createGlobalSection();
83 void createExportSection();
84 void createImportSection();
85 void createMemorySection();
86 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void createCodeSection();
88 void createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +000089 void createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000090
91 // Custom sections
Sam Cleggbfb75342018-11-15 00:37:21 +000092 void createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +000093 void createRelocSections();
94 void createLinkingSection();
95 void createNameSection();
96
97 void writeHeader();
98 void writeSections();
99
100 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000101 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000102 uint32_t NumMemoryPages = 0;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000103 uint32_t MaxMemoryPages = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +0000104 // Memory size and aligment. Written to the "dylink" section
105 // when build with -shared or -pie.
106 uint32_t MemAlign = 0;
107 uint32_t MemSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000108
109 std::vector<const WasmSignature *> Types;
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +0000110 DenseMap<WasmSignature, int32_t> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000111 std::vector<const Symbol *> ImportedSymbols;
112 unsigned NumImportedFunctions = 0;
113 unsigned NumImportedGlobals = 0;
Sam Cleggd6beb322018-05-10 18:10:34 +0000114 std::vector<WasmExport> Exports;
Sam Clegg93102972018-02-23 05:08:53 +0000115 std::vector<const DefinedData *> DefinedFakeGlobals;
116 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000117 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000118 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000119 std::vector<const Symbol *> SymtabEntries;
120 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000121
Sam Clegg80ba4382018-04-10 16:12:49 +0000122 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
Sam Cleggd177ab22018-05-04 23:14:42 +0000123 llvm::StringMap<SectionSymbol *> CustomSectionSymbols;
Sam Clegg80ba4382018-04-10 16:12:49 +0000124
Sam Cleggc94d3932017-11-17 18:14:09 +0000125 // Elements that are used to construct the final output
126 std::string Header;
127 std::vector<OutputSection *> OutputSections;
128
129 std::unique_ptr<FileOutputBuffer> Buffer;
130
131 std::vector<OutputSegment *> Segments;
132 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
133};
134
135} // anonymous namespace
136
Sam Cleggc94d3932017-11-17 18:14:09 +0000137void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000138 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000139 if (Config->ImportMemory)
140 ++NumImports;
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000141 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000142 ++NumImports;
Sam Cleggc94d3932017-11-17 18:14:09 +0000143
144 if (NumImports == 0)
145 return;
146
147 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
148 raw_ostream &OS = Section->getStream();
149
150 writeUleb128(OS, NumImports, "import count");
151
Sam Cleggc94d3932017-11-17 18:14:09 +0000152 if (Config->ImportMemory) {
153 WasmImport Import;
154 Import.Module = "env";
155 Import.Field = "memory";
156 Import.Kind = WASM_EXTERNAL_MEMORY;
157 Import.Memory.Flags = 0;
158 Import.Memory.Initial = NumMemoryPages;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000159 if (MaxMemoryPages != 0) {
160 Import.Memory.Flags |= WASM_LIMITS_FLAG_HAS_MAX;
161 Import.Memory.Maximum = MaxMemoryPages;
162 }
Derek Schuff786760a2018-11-06 18:02:39 +0000163 if (Config->SharedMemory)
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000164 Import.Memory.Flags |= WASM_LIMITS_FLAG_IS_SHARED;
Sam Cleggc94d3932017-11-17 18:14:09 +0000165 writeImport(OS, Import);
166 }
167
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000168 if (Config->ImportTable) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000169 uint32_t TableSize = TableBase + IndirectFunctions.size();
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000170 WasmImport Import;
171 Import.Module = "env";
172 Import.Field = kFunctionTableName;
173 Import.Kind = WASM_EXTERNAL_TABLE;
174 Import.Table.ElemType = WASM_TYPE_ANYFUNC;
175 Import.Table.Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
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;
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000185 Import.SigIndex = lookupType(*FunctionSym->FunctionType);
Sam Clegg93102972018-02-23 05:08:53 +0000186 } 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
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000222 bool HasMax = MaxMemoryPages != 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000223 writeUleb128(OS, 1, "memory count");
Derek Schuff786760a2018-11-06 18:02:39 +0000224 unsigned Flags = 0;
225 if (HasMax)
226 Flags |= WASM_LIMITS_FLAG_HAS_MAX;
Derek Schuff3bea8bc2018-11-06 17:59:32 +0000227 if (Config->SharedMemory)
228 Flags |= WASM_LIMITS_FLAG_IS_SHARED;
229 writeUleb128(OS, Flags, "memory limits flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000230 writeUleb128(OS, NumMemoryPages, "initial pages");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000231 if (HasMax)
232 writeUleb128(OS, MaxMemoryPages, "max pages");
Sam Cleggc94d3932017-11-17 18:14:09 +0000233}
234
235void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000236 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
237 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000238 return;
239
Sam Cleggc94d3932017-11-17 18:14:09 +0000240 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
241 raw_ostream &OS = Section->getStream();
242
Sam Clegg93102972018-02-23 05:08:53 +0000243 writeUleb128(OS, NumGlobals, "global count");
244 for (const InputGlobal *G : InputGlobals)
245 writeGlobal(OS, G->Global);
246 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000247 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000248 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000249 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
250 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000251 writeGlobal(OS, Global);
252 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000253}
254
255void Writer::createTableSection() {
Nicholas Wilsonfc90b302018-03-28 12:53:29 +0000256 if (Config->ImportTable)
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000257 return;
258
259 // Always output a table section (or table import), even if there are no
260 // indirect calls. There are two reasons for this:
Sam Cleggfc1a9122017-12-11 22:00:56 +0000261 // 1. For executables it is useful to have an empty table slot at 0
262 // which can be filled with a null function call handler.
263 // 2. If we don't do this, any program that contains a call_indirect but
264 // no address-taken function will fail at validation time since it is
265 // a validation error to include a call_indirect instruction if there
266 // is not table.
Sam Cleggbfb75342018-11-15 00:37:21 +0000267 uint32_t TableSize = TableBase + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000268
Sam Cleggc94d3932017-11-17 18:14:09 +0000269 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
270 raw_ostream &OS = Section->getStream();
271
272 writeUleb128(OS, 1, "table count");
Nicholas Wilson874eedd2018-03-27 17:38:51 +0000273 WasmLimits Limits = {WASM_LIMITS_FLAG_HAS_MAX, TableSize, TableSize};
274 writeTableType(OS, WasmTable{WASM_TYPE_ANYFUNC, Limits});
Sam Cleggc94d3932017-11-17 18:14:09 +0000275}
276
277void Writer::createExportSection() {
Sam Cleggd6beb322018-05-10 18:10:34 +0000278 if (!Exports.size())
Sam Cleggc94d3932017-11-17 18:14:09 +0000279 return;
280
281 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
282 raw_ostream &OS = Section->getStream();
283
Sam Cleggd6beb322018-05-10 18:10:34 +0000284 writeUleb128(OS, Exports.size(), "export count");
285 for (const WasmExport &Export : Exports)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000286 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000287}
288
Sam Cleggd177ab22018-05-04 23:14:42 +0000289void Writer::calculateCustomSections() {
290 log("calculateCustomSections");
291 bool StripDebug = Config->StripDebug || Config->StripAll;
292 for (ObjFile *File : Symtab->ObjectFiles) {
293 for (InputSection *Section : File->CustomSections) {
294 StringRef Name = Section->getName();
295 // These custom sections are known the linker and synthesized rather than
296 // blindly copied
297 if (Name == "linking" || Name == "name" || Name.startswith("reloc."))
298 continue;
299 // .. or it is a debug section
300 if (StripDebug && Name.startswith(".debug_"))
301 continue;
302 CustomSectionMapping[Name].push_back(Section);
303 }
304 }
305}
306
Sam Clegg80ba4382018-04-10 16:12:49 +0000307void Writer::createCustomSections() {
308 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000309 for (auto &Pair : CustomSectionMapping) {
310 StringRef Name = Pair.first();
Sam Cleggd177ab22018-05-04 23:14:42 +0000311
312 auto P = CustomSectionSymbols.find(Name);
313 if (P != CustomSectionSymbols.end()) {
314 uint32_t SectionIndex = OutputSections.size();
315 P->second->setOutputSectionIndex(SectionIndex);
316 }
317
Nicola Zaghene7245b42018-05-15 13:36:20 +0000318 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg80ba4382018-04-10 16:12:49 +0000319 OutputSections.push_back(make<CustomSection>(Name, Pair.second));
320 }
321}
322
Sam Cleggc94d3932017-11-17 18:14:09 +0000323void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000324 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000325 return;
326
327 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
328 raw_ostream &OS = Section->getStream();
329
330 writeUleb128(OS, 1, "segment count");
331 writeUleb128(OS, 0, "table index");
332 WasmInitExpr InitExpr;
Sam Cleggbfb75342018-11-15 00:37:21 +0000333 if (Config->Pic) {
334 InitExpr.Opcode = WASM_OPCODE_GET_GLOBAL;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000335 InitExpr.Value.Global = WasmSym::TableBase->getGlobalIndex();
Sam Cleggbfb75342018-11-15 00:37:21 +0000336 } else {
337 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
338 InitExpr.Value.Int32 = TableBase;
339 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000340 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000341 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000342
Sam Cleggbfb75342018-11-15 00:37:21 +0000343 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000344 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000345 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000346 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000347 ++TableIndex;
348 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000349}
350
351void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000352 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000353 return;
354
355 log("createCodeSection");
356
Sam Clegg9f934222018-02-21 18:29:23 +0000357 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000358 OutputSections.push_back(Section);
359}
360
361void Writer::createDataSection() {
362 if (!Segments.size())
363 return;
364
365 log("createDataSection");
366 auto Section = make<DataSection>(Segments);
367 OutputSections.push_back(Section);
368}
369
Sam Cleggd451da12017-12-19 19:56:27 +0000370// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000371// These are only created when relocatable output is requested.
372void Writer::createRelocSections() {
373 log("createRelocSections");
374 // Don't use iterator here since we are adding to OutputSection
375 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000376 for (size_t I = 0; I < OrigSize; I++) {
377 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000378 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000379 if (!Count)
380 continue;
381
Rui Ueyama37254062018-02-28 00:01:31 +0000382 StringRef Name;
383 if (OSec->Type == WASM_SEC_DATA)
384 Name = "reloc.DATA";
385 else if (OSec->Type == WASM_SEC_CODE)
386 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000387 else if (OSec->Type == WASM_SEC_CUSTOM)
388 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000389 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000390 llvm_unreachable(
391 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000392
Rui Ueyama37254062018-02-28 00:01:31 +0000393 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000394 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000395 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000396 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000397 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000398 }
399}
400
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000401static uint32_t getWasmFlags(const Symbol *Sym) {
402 uint32_t Flags = 0;
403 if (Sym->isLocal())
404 Flags |= WASM_SYMBOL_BINDING_LOCAL;
405 if (Sym->isWeak())
406 Flags |= WASM_SYMBOL_BINDING_WEAK;
407 if (Sym->isHidden())
408 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
409 if (Sym->isUndefined())
410 Flags |= WASM_SYMBOL_UNDEFINED;
411 return Flags;
412}
413
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000414// Some synthetic sections (e.g. "name" and "linking") have subsections.
415// Just like the synthetic sections themselves these need to be created before
416// they can be written out (since they are preceded by their length). This
417// class is used to create subsections and then write them into the stream
418// of the parent section.
419class SubSection {
420public:
421 explicit SubSection(uint32_t Type) : Type(Type) {}
422
423 void writeTo(raw_ostream &To) {
424 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000425 writeUleb128(To, Type, "subsection type");
426 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000427 To.write(Body.data(), Body.size());
428 }
429
430private:
431 uint32_t Type;
432 std::string Body;
433
434public:
435 raw_string_ostream OS{Body};
436};
437
Sam Cleggbfb75342018-11-15 00:37:21 +0000438// Create the custom "dylink" section containing information for the dynamic
439// linker.
440// See
441// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
442void Writer::createDylinkSection() {
443 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
444 raw_ostream &OS = Section->getStream();
445
446 writeUleb128(OS, MemSize, "MemSize");
447 writeUleb128(OS, int(log2(MemAlign)), "MemAlign");
448 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
449 writeUleb128(OS, 0, "TableAlign");
450}
451
Sam Clegg49ed9262017-12-01 00:53:21 +0000452// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000453// This is only created when relocatable output is requested.
454void Writer::createLinkingSection() {
455 SyntheticSection *Section =
456 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
457 raw_ostream &OS = Section->getStream();
458
Sam Clegg2b8b1792018-04-26 18:17:21 +0000459 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000460
Sam Clegg93102972018-02-23 05:08:53 +0000461 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000462 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000463 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
464
Sam Clegg93102972018-02-23 05:08:53 +0000465 for (const Symbol *Sym : SymtabEntries) {
466 assert(Sym->isDefined() || Sym->isUndefined());
467 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000468 uint32_t Flags = getWasmFlags(Sym);
469
Sam Clegg8518e7d2018-03-01 18:06:39 +0000470 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000471 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000472
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000473 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
474 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000475 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000476 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000477 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
478 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
479 if (Sym->isDefined())
480 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000481 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000482 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000483 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000484 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
485 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000486 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000487 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000488 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000489 } else {
490 auto *S = cast<SectionSymbol>(Sym);
491 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000492 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000493 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000494
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000495 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000496 }
497
Sam Clegg0d0dd392017-12-19 17:09:45 +0000498 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000499 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000501 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000502 writeStr(Sub.OS, S->Name, "segment name");
503 writeUleb128(Sub.OS, S->Alignment, "alignment");
504 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000505 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000506 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000507 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000508
Sam Clegg0d0dd392017-12-19 17:09:45 +0000509 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000510 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000511 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000512 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000513 writeUleb128(Sub.OS, F.Priority, "priority");
514 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000515 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000516 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000517 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000518
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000519 struct ComdatEntry {
520 unsigned Kind;
521 uint32_t Index;
522 };
523 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000524
Sam Clegg9f934222018-02-21 18:29:23 +0000525 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000526 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000527 if (!Comdat.empty())
528 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000529 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000530 }
531 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000532 const auto &InputSegments = Segments[I]->InputSegments;
533 if (InputSegments.empty())
534 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000535 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000536#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000537 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000538 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000539#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000540 if (!Comdat.empty())
541 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
542 }
543
544 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000545 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000546 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000547 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000548 writeStr(Sub.OS, C.first, "comdat name");
549 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
550 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000551 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000552 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000553 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000554 }
555 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000556 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000557 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000558}
559
560// Create the custom "name" section containing debug symbol names.
561void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000562 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000563 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000564 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000565 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000566
Sam Clegg1963d712018-01-17 20:19:04 +0000567 if (NumNames == 0)
568 return;
Sam Clegg50686852018-01-12 18:35:13 +0000569
Sam Cleggc94d3932017-11-17 18:14:09 +0000570 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
571
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000572 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000573 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000574
Sam Clegg93102972018-02-23 05:08:53 +0000575 // Names must appear in function index order. As it happens ImportedSymbols
576 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000577 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000578 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000579 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
580 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000581 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000582 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000583 }
Sam Clegg9f934222018-02-21 18:29:23 +0000584 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000585 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000586 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000587 if (!F->getDebugName().empty()) {
588 writeStr(Sub.OS, F->getDebugName(), "symbol name");
589 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000590 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000591 }
Sam Clegg1963d712018-01-17 20:19:04 +0000592 }
593 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000594
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000595 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000596}
597
598void Writer::writeHeader() {
599 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
600}
601
602void Writer::writeSections() {
603 uint8_t *Buf = Buffer->getBufferStart();
604 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
605}
606
607// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000608// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000609// The default memory layout is as follows, from low to high.
610//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000611// - initialized data (starting at Config->GlobalBase)
612// - BSS data (not currently implemented in llvm)
613// - explicit stack (Config->ZStackSize)
614// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000615//
616// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000617// This can be useful since it means that stack overflow traps immediately
618// rather than overwriting global data, but also increases code size since all
619// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000620void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000621 createOutputSegments();
622
Sam Clegga0f095e2018-05-03 17:21:53 +0000623 uint32_t MemoryPtr = 0;
624
625 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000626 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000627 return;
628 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
629 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
630 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
631 log("mem: stack size = " + Twine(Config->ZStackSize));
632 log("mem: stack base = " + Twine(MemoryPtr));
633 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000634 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
635 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000636 log("mem: stack top = " + Twine(MemoryPtr));
637 };
638
639 if (Config->StackFirst) {
640 PlaceStack();
641 } else {
642 MemoryPtr = Config->GlobalBase;
643 log("mem: global base = " + Twine(Config->GlobalBase));
644 }
645
646 uint32_t DataStart = MemoryPtr;
647
Sam Cleggf0d433d2018-02-02 22:59:56 +0000648 // Arbitrarily set __dso_handle handle to point to the start of the data
649 // segments.
650 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000651 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000652
Sam Cleggbfb75342018-11-15 00:37:21 +0000653 MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000654 for (OutputSegment *Seg : Segments) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000655 MemAlign = std::max(MemAlign, Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000656 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
657 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000658 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
659 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000660 MemoryPtr += Seg->Size;
661 }
662
Sam Cleggf0d433d2018-02-02 22:59:56 +0000663 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000664 if (WasmSym::DataEnd)
665 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000666
Sam Clegga0f095e2018-05-03 17:21:53 +0000667 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000668
Sam Clegg2dad4e22018-11-15 18:15:54 +0000669 if (Config->Shared) {
670 MemSize = MemoryPtr;
671 return;
672 }
673
Sam Clegga0f095e2018-05-03 17:21:53 +0000674 if (!Config->StackFirst)
675 PlaceStack();
676
677 // Set `__heap_base` to directly follow the end of the stack or global data.
678 // The fact that this comes last means that a malloc/brk implementation
679 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000680 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000681 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000682 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000683 }
684
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000685 if (Config->InitialMemory != 0) {
686 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
687 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
688 if (MemoryPtr > Config->InitialMemory)
689 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
690 else
691 MemoryPtr = Config->InitialMemory;
692 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000693 MemSize = MemoryPtr;
694 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000695 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000696
697 if (Config->MaxMemory != 0) {
698 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
699 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
700 if (MemoryPtr > Config->MaxMemory)
701 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
702 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
703 log("mem: max pages = " + Twine(MaxMemoryPages));
704 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000705}
706
707SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000708 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000709 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000710 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000711 OutputSections.push_back(Sec);
712 return Sec;
713}
714
715void Writer::createSections() {
716 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000717 if (Config->Pic)
718 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000719 createTypeSection();
720 createImportSection();
721 createFunctionSection();
722 createTableSection();
723 createMemorySection();
724 createGlobalSection();
725 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000726 createElemSection();
727 createCodeSection();
728 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000729 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000730
731 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000732 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000733 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000734 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000735 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000736 if (!Config->StripDebug && !Config->StripAll)
737 createNameSection();
738
739 for (OutputSection *S : OutputSections) {
740 S->setOffset(FileSize);
741 S->finalizeContents();
742 FileSize += S->getSize();
743 }
744}
745
Sam Cleggc94d3932017-11-17 18:14:09 +0000746void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000747 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000748 if (!Sym->isUndefined())
749 continue;
750 if (isa<DataSymbol>(Sym))
751 continue;
752 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000753 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000754 if (!Sym->isLive())
755 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000756 if (!Sym->IsUsedInRegularObj)
757 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000758
Nicola Zaghene7245b42018-05-15 13:36:20 +0000759 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000760 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000761 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
762 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000763 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000764 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000765 }
766}
767
Sam Cleggd3052d52018-01-18 23:40:49 +0000768void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000769 if (Config->Relocatable)
770 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000771
Sam Cleggd6beb322018-05-10 18:10:34 +0000772 if (!Config->Relocatable && !Config->ImportMemory)
773 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
774
775 if (!Config->Relocatable && Config->ExportTable)
776 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
777
778 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
779
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000780 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000781 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000782 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000783 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000784 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000785
Sam Cleggd6beb322018-05-10 18:10:34 +0000786 StringRef Name = Sym->getName();
787 WasmExport Export;
788 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
789 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
790 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000791 // TODO(sbc): Remove this check once to mutable global proposal is
792 // implement in all major browsers.
793 // See: https://github.com/WebAssembly/mutable-global
794 if (G->getGlobalType()->Mutable) {
795 // Only the __stack_pointer should ever be create as mutable.
796 assert(G == WasmSym::StackPointer);
797 continue;
798 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000799 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
800 } else {
801 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000802 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000803 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
804 }
805
Nicola Zaghene7245b42018-05-15 13:36:20 +0000806 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000807 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000808 }
Sam Clegg93102972018-02-23 05:08:53 +0000809}
810
811void Writer::assignSymtab() {
812 if (!Config->Relocatable)
813 return;
814
Sam Cleggd177ab22018-05-04 23:14:42 +0000815 StringMap<uint32_t> SectionSymbolIndices;
816
Sam Clegg93102972018-02-23 05:08:53 +0000817 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000818 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000819 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000820 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000821 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000822 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000823
824 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
825 StringRef Name = S->getName();
826 if (CustomSectionMapping.count(Name) == 0)
827 continue;
828
829 auto SSI = SectionSymbolIndices.find(Name);
830 if (SSI != SectionSymbolIndices.end()) {
831 Sym->setOutputSymbolIndex(SSI->second);
832 continue;
833 }
834
835 SectionSymbolIndices[Name] = SymbolIndex;
836 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
837
838 Sym->markLive();
839 }
840
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000841 // (Since this is relocatable output, GC is not performed so symbols must
842 // be live.)
843 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000844 Sym->setOutputSymbolIndex(SymbolIndex++);
845 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000846 }
847 }
848
Sam Clegg93102972018-02-23 05:08:53 +0000849 // For the moment, relocatable output doesn't contain any synthetic functions,
850 // so no need to look through the Symtab for symbols not referenced by
851 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000852}
853
Sam Cleggc375e4e2018-01-10 19:18:22 +0000854uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000855 auto It = TypeIndices.find(Sig);
856 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000857 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000858 return 0;
859 }
860 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000861}
862
863uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000864 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000865 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000866 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000867 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000868 }
Sam Cleggb8621592017-11-30 01:40:08 +0000869 return Pair.first->second;
870}
871
Sam Cleggc94d3932017-11-17 18:14:09 +0000872void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000873 // The output type section is the union of the following sets:
874 // 1. Any signature used in the TYPE relocation
875 // 2. The signatures of all imported functions
876 // 3. The signatures of all defined functions
877
Sam Cleggc94d3932017-11-17 18:14:09 +0000878 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000879 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
880 for (uint32_t I = 0; I < Types.size(); I++)
881 if (File->TypeIsUsed[I])
882 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000883 }
Sam Clegg50686852018-01-12 18:35:13 +0000884
Sam Clegg93102972018-02-23 05:08:53 +0000885 for (const Symbol *Sym : ImportedSymbols)
886 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000887 registerType(*F->FunctionType);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000888
Sam Clegg9f934222018-02-21 18:29:23 +0000889 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000890 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000891}
892
Sam Clegg8d146bb2018-01-09 23:56:44 +0000893void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000894 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000895 auto AddDefinedFunction = [&](InputFunction *Func) {
896 if (!Func->Live)
897 return;
898 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000899 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000900 };
901
Nicholas Wilson5639da82018-03-12 15:44:07 +0000902 for (InputFunction *Func : Symtab->SyntheticFunctions)
903 AddDefinedFunction(Func);
904
Sam Clegg87e61922018-01-08 23:39:11 +0000905 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000906 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000907 for (InputFunction *Func : File->Functions)
908 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000909 }
910
Sam Cleggbfb75342018-11-15 00:37:21 +0000911 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000912 auto HandleRelocs = [&](InputChunk *Chunk) {
913 if (!Chunk->Live)
914 return;
915 ObjFile *File = Chunk->File;
916 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000917 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000918 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
919 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
920 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000921 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000922 continue;
923 Sym->setTableIndex(TableIndex++);
924 IndirectFunctions.emplace_back(Sym);
925 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000926 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000927 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
928 File->TypeIsUsed[Reloc.Index] = true;
929 }
930 }
931 };
932
Sam Clegg8d146bb2018-01-09 23:56:44 +0000933 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000934 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000935 for (InputChunk *Chunk : File->Functions)
936 HandleRelocs(Chunk);
937 for (InputChunk *Chunk : File->Segments)
938 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +0000939 for (auto &P : File->CustomSections)
940 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +0000941 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000942
Sam Clegg93102972018-02-23 05:08:53 +0000943 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
944 auto AddDefinedGlobal = [&](InputGlobal *Global) {
945 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000946 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000947 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000948 InputGlobals.push_back(Global);
949 }
950 };
951
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000952 for (InputGlobal *Global : Symtab->SyntheticGlobals)
953 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000954
955 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000956 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000957 for (InputGlobal *Global : File->Globals)
958 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000959 }
960}
961
962static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000963 // With PIC code we currently only support a single data segment since
964 // we only have a single __memory_base to use as our base address.
965 if (Config->Pic)
966 return "data";
Sam Clegg66844762018-05-10 18:23:51 +0000967 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000968 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000969 if (Name.startswith(".text."))
970 return ".text";
971 if (Name.startswith(".data."))
972 return ".data";
973 if (Name.startswith(".bss."))
974 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000975 if (Name.startswith(".rodata."))
976 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000977 return Name;
978}
979
980void Writer::createOutputSegments() {
981 for (ObjFile *File : Symtab->ObjectFiles) {
982 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000983 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000984 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000985 StringRef Name = getOutputDataSegmentName(Segment->getName());
986 OutputSegment *&S = SegmentMap[Name];
987 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000988 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000989 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000990 Segments.push_back(S);
991 }
992 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000993 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000994 }
995 }
996}
997
Sam Clegg50686852018-01-12 18:35:13 +0000998static const int OPCODE_CALL = 0x10;
999static const int OPCODE_END = 0xb;
1000
1001// Create synthetic "__wasm_call_ctors" function based on ctor functions
1002// in input object.
1003void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001004 // First write the body's contents to a string.
1005 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001006 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001007 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001008 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001009 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001010 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001011 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001012 }
1013 writeU8(OS, OPCODE_END, "END");
1014 }
1015
1016 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001017 std::string FunctionBody;
1018 {
1019 raw_string_ostream OS(FunctionBody);
1020 writeUleb128(OS, BodyContent.size(), "function size");
1021 OS << BodyContent;
1022 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001023
Sam Cleggea656472018-10-22 08:35:39 +00001024 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001025 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001026}
1027
1028// Populate InitFunctions vector with init functions from all input objects.
1029// This is then used either when creating the output linking section or to
1030// synthesize the "__wasm_call_ctors" function.
1031void Writer::calculateInitFunctions() {
1032 for (ObjFile *File : Symtab->ObjectFiles) {
1033 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001034 for (const WasmInitFunc &F : L.InitFunctions) {
1035 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Derek Schuff371842b2018-10-03 22:25:32 +00001036 if (*Sym->FunctionType != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001037 error("invalid signature for init func: " + toString(*Sym));
1038 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1039 }
Sam Clegg50686852018-01-12 18:35:13 +00001040 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001041
Sam Clegg50686852018-01-12 18:35:13 +00001042 // Sort in order of priority (lowest first) so that they are called
1043 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001044 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001045 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001046 return L.Priority < R.Priority;
1047 });
Sam Clegg50686852018-01-12 18:35:13 +00001048}
1049
Sam Cleggc94d3932017-11-17 18:14:09 +00001050void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001051 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001052 Config->GlobalBase = 0;
1053
Sam Cleggbfb75342018-11-15 00:37:21 +00001054 // For PIC code the table base is assigned dynamically by the loader.
1055 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1056 if (!Config->Pic)
1057 TableBase = 1;
1058
Sam Cleggc94d3932017-11-17 18:14:09 +00001059 log("-- calculateImports");
1060 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001061 log("-- assignIndexes");
1062 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001063 log("-- calculateInitFunctions");
1064 calculateInitFunctions();
1065 if (!Config->Relocatable)
1066 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001067 log("-- calculateTypes");
1068 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001069 log("-- layoutMemory");
1070 layoutMemory();
1071 log("-- calculateExports");
1072 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001073 log("-- calculateCustomSections");
1074 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001075 log("-- assignSymtab");
1076 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001077
1078 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001079 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001080 log("Defined Globals : " + Twine(InputGlobals.size()));
1081 log("Function Imports : " + Twine(NumImportedFunctions));
1082 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +00001083 for (ObjFile *File : Symtab->ObjectFiles)
1084 File->dumpInfo();
1085 }
1086
Sam Cleggc94d3932017-11-17 18:14:09 +00001087 createHeader();
1088 log("-- createSections");
1089 createSections();
1090
1091 log("-- openFile");
1092 openFile();
1093 if (errorCount())
1094 return;
1095
1096 writeHeader();
1097
1098 log("-- writeSections");
1099 writeSections();
1100 if (errorCount())
1101 return;
1102
1103 if (Error E = Buffer->commit())
1104 fatal("failed to write the output file: " + toString(std::move(E)));
1105}
1106
1107// Open a result file.
1108void Writer::openFile() {
1109 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001110
1111 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1112 FileOutputBuffer::create(Config->OutputFile, FileSize,
1113 FileOutputBuffer::F_executable);
1114
1115 if (!BufferOrErr)
1116 error("failed to open " + Config->OutputFile + ": " +
1117 toString(BufferOrErr.takeError()));
1118 else
1119 Buffer = std::move(*BufferOrErr);
1120}
1121
1122void Writer::createHeader() {
1123 raw_string_ostream OS(Header);
1124 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1125 writeU32(OS, WasmVersion, "wasm version");
1126 OS.flush();
1127 FileSize += Header.size();
1128}
1129
1130void lld::wasm::writeResult() { Writer().run(); }