blob: 604850812499fc4c149833bf52e1493611f28d8d [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;
335 InitExpr.Value.Global =
336 cast<GlobalSymbol>(WasmSym::TableBase)->getGlobalIndex();
337 } else {
338 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
339 InitExpr.Value.Int32 = TableBase;
340 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000341 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000342 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000343
Sam Cleggbfb75342018-11-15 00:37:21 +0000344 uint32_t TableIndex = TableBase;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000345 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000346 assert(Sym->getTableIndex() == TableIndex);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000347 writeUleb128(OS, Sym->getFunctionIndex(), "function index");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000348 ++TableIndex;
349 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000350}
351
352void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000353 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000354 return;
355
356 log("createCodeSection");
357
Sam Clegg9f934222018-02-21 18:29:23 +0000358 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000359 OutputSections.push_back(Section);
360}
361
362void Writer::createDataSection() {
363 if (!Segments.size())
364 return;
365
366 log("createDataSection");
367 auto Section = make<DataSection>(Segments);
368 OutputSections.push_back(Section);
369}
370
Sam Cleggd451da12017-12-19 19:56:27 +0000371// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000372// These are only created when relocatable output is requested.
373void Writer::createRelocSections() {
374 log("createRelocSections");
375 // Don't use iterator here since we are adding to OutputSection
376 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000377 for (size_t I = 0; I < OrigSize; I++) {
378 OutputSection *OSec = OutputSections[I];
Rui Ueyama37254062018-02-28 00:01:31 +0000379 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000380 if (!Count)
381 continue;
382
Rui Ueyama37254062018-02-28 00:01:31 +0000383 StringRef Name;
384 if (OSec->Type == WASM_SEC_DATA)
385 Name = "reloc.DATA";
386 else if (OSec->Type == WASM_SEC_CODE)
387 Name = "reloc.CODE";
Sam Cleggd177ab22018-05-04 23:14:42 +0000388 else if (OSec->Type == WASM_SEC_CUSTOM)
389 Name = Saver.save("reloc." + OSec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000390 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000391 llvm_unreachable(
392 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000393
Rui Ueyama37254062018-02-28 00:01:31 +0000394 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000395 raw_ostream &OS = Section->getStream();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000396 writeUleb128(OS, I, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000397 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000398 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000399 }
400}
401
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000402static uint32_t getWasmFlags(const Symbol *Sym) {
403 uint32_t Flags = 0;
404 if (Sym->isLocal())
405 Flags |= WASM_SYMBOL_BINDING_LOCAL;
406 if (Sym->isWeak())
407 Flags |= WASM_SYMBOL_BINDING_WEAK;
408 if (Sym->isHidden())
409 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
410 if (Sym->isUndefined())
411 Flags |= WASM_SYMBOL_UNDEFINED;
412 return Flags;
413}
414
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000415// Some synthetic sections (e.g. "name" and "linking") have subsections.
416// Just like the synthetic sections themselves these need to be created before
417// they can be written out (since they are preceded by their length). This
418// class is used to create subsections and then write them into the stream
419// of the parent section.
420class SubSection {
421public:
422 explicit SubSection(uint32_t Type) : Type(Type) {}
423
424 void writeTo(raw_ostream &To) {
425 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000426 writeUleb128(To, Type, "subsection type");
427 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000428 To.write(Body.data(), Body.size());
429 }
430
431private:
432 uint32_t Type;
433 std::string Body;
434
435public:
436 raw_string_ostream OS{Body};
437};
438
Sam Cleggbfb75342018-11-15 00:37:21 +0000439// Create the custom "dylink" section containing information for the dynamic
440// linker.
441// See
442// https://github.com/WebAssembly/tool-conventions/blob/master/DynamicLinking.md
443void Writer::createDylinkSection() {
444 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "dylink");
445 raw_ostream &OS = Section->getStream();
446
447 writeUleb128(OS, MemSize, "MemSize");
448 writeUleb128(OS, int(log2(MemAlign)), "MemAlign");
449 writeUleb128(OS, IndirectFunctions.size(), "TableSize");
450 writeUleb128(OS, 0, "TableAlign");
451}
452
Sam Clegg49ed9262017-12-01 00:53:21 +0000453// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000454// This is only created when relocatable output is requested.
455void Writer::createLinkingSection() {
456 SyntheticSection *Section =
457 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
458 raw_ostream &OS = Section->getStream();
459
Sam Clegg2b8b1792018-04-26 18:17:21 +0000460 writeUleb128(OS, WasmMetadataVersion, "Version");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000461
Sam Clegg93102972018-02-23 05:08:53 +0000462 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000463 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000464 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
465
Sam Clegg93102972018-02-23 05:08:53 +0000466 for (const Symbol *Sym : SymtabEntries) {
467 assert(Sym->isDefined() || Sym->isUndefined());
468 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000469 uint32_t Flags = getWasmFlags(Sym);
470
Sam Clegg8518e7d2018-03-01 18:06:39 +0000471 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000472 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000473
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000474 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
475 writeUleb128(Sub.OS, F->getFunctionIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000476 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000477 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000478 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
479 writeUleb128(Sub.OS, G->getGlobalIndex(), "index");
480 if (Sym->isDefined())
481 writeStr(Sub.OS, Sym->getName(), "sym name");
Andrea Di Biagio25c1a2f2018-05-05 10:53:31 +0000482 } else if (isa<DataSymbol>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000483 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000484 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000485 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
486 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000487 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000488 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000489 }
Sam Cleggd177ab22018-05-04 23:14:42 +0000490 } else {
491 auto *S = cast<SectionSymbol>(Sym);
492 writeUleb128(Sub.OS, S->getOutputSectionIndex(), "sym section index");
Sam Clegg93102972018-02-23 05:08:53 +0000493 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000494 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000495
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000496 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000497 }
498
Sam Clegg0d0dd392017-12-19 17:09:45 +0000499 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000500 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000501 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000502 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000503 writeStr(Sub.OS, S->Name, "segment name");
504 writeUleb128(Sub.OS, S->Alignment, "alignment");
505 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000506 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000507 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000508 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000509
Sam Clegg0d0dd392017-12-19 17:09:45 +0000510 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000511 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000512 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000513 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000514 writeUleb128(Sub.OS, F.Priority, "priority");
515 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000516 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000517 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000518 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000519
Nicholas Wilsondbd90bf2018-03-07 13:28:16 +0000520 struct ComdatEntry {
521 unsigned Kind;
522 uint32_t Index;
523 };
524 std::map<StringRef, std::vector<ComdatEntry>> Comdats;
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000525
Sam Clegg9f934222018-02-21 18:29:23 +0000526 for (const InputFunction *F : InputFunctions) {
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000527 StringRef Comdat = F->getComdatName();
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000528 if (!Comdat.empty())
529 Comdats[Comdat].emplace_back(
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000530 ComdatEntry{WASM_COMDAT_FUNCTION, F->getFunctionIndex()});
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000531 }
532 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000533 const auto &InputSegments = Segments[I]->InputSegments;
534 if (InputSegments.empty())
535 continue;
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000536 StringRef Comdat = InputSegments[0]->getComdatName();
Sam Clegga697df522018-01-13 15:59:53 +0000537#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000538 for (const InputSegment *IS : InputSegments)
Nicholas Wilsonc4d9aa12018-03-14 15:45:11 +0000539 assert(IS->getComdatName() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000540#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000541 if (!Comdat.empty())
542 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
543 }
544
545 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000546 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000547 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000548 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000549 writeStr(Sub.OS, C.first, "comdat name");
550 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
551 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000552 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000553 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000554 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000555 }
556 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000557 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000558 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000559}
560
561// Create the custom "name" section containing debug symbol names.
562void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000563 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000564 for (const InputFunction *F : InputFunctions)
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000565 if (!F->getName().empty() || !F->getDebugName().empty())
Sam Clegg1963d712018-01-17 20:19:04 +0000566 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000567
Sam Clegg1963d712018-01-17 20:19:04 +0000568 if (NumNames == 0)
569 return;
Sam Clegg50686852018-01-12 18:35:13 +0000570
Sam Cleggc94d3932017-11-17 18:14:09 +0000571 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
572
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000573 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000574 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000575
Sam Clegg93102972018-02-23 05:08:53 +0000576 // Names must appear in function index order. As it happens ImportedSymbols
577 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000578 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000579 for (const Symbol *S : ImportedSymbols) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000580 if (auto *F = dyn_cast<FunctionSymbol>(S)) {
581 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Sam Clegg37125f02018-11-09 16:57:41 +0000582 writeStr(Sub.OS, toString(*S), "symbol name");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000583 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000584 }
Sam Clegg9f934222018-02-21 18:29:23 +0000585 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000586 if (!F->getName().empty()) {
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000587 writeUleb128(Sub.OS, F->getFunctionIndex(), "func index");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000588 if (!F->getDebugName().empty()) {
589 writeStr(Sub.OS, F->getDebugName(), "symbol name");
590 } else {
Sam Clegg37125f02018-11-09 16:57:41 +0000591 writeStr(Sub.OS, maybeDemangleSymbol(F->getName()), "symbol name");
Nicholas Wilson6c7fe302018-04-20 17:09:18 +0000592 }
Sam Clegg1963d712018-01-17 20:19:04 +0000593 }
594 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000595
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000596 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000597}
598
599void Writer::writeHeader() {
600 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
601}
602
603void Writer::writeSections() {
604 uint8_t *Buf = Buffer->getBufferStart();
605 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
606}
607
608// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000609// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000610// The default memory layout is as follows, from low to high.
611//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000612// - initialized data (starting at Config->GlobalBase)
613// - BSS data (not currently implemented in llvm)
614// - explicit stack (Config->ZStackSize)
615// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000616//
617// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000618// This can be useful since it means that stack overflow traps immediately
619// rather than overwriting global data, but also increases code size since all
620// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000621void Writer::layoutMemory() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000622 createOutputSegments();
623
Sam Clegga0f095e2018-05-03 17:21:53 +0000624 uint32_t MemoryPtr = 0;
625
626 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000627 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000628 return;
629 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
630 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
631 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
632 log("mem: stack size = " + Twine(Config->ZStackSize));
633 log("mem: stack base = " + Twine(MemoryPtr));
634 MemoryPtr += Config->ZStackSize;
635 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
636 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 Clegga0f095e2018-05-03 17:21:53 +0000669 if (!Config->StackFirst)
670 PlaceStack();
671
672 // Set `__heap_base` to directly follow the end of the stack or global data.
673 // The fact that this comes last means that a malloc/brk implementation
674 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000675 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000676 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000677 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000678 }
679
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000680 if (Config->InitialMemory != 0) {
681 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
682 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
683 if (MemoryPtr > Config->InitialMemory)
684 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
685 else
686 MemoryPtr = Config->InitialMemory;
687 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000688 MemSize = MemoryPtr;
689 NumMemoryPages = alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000690 log("mem: total pages = " + Twine(NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000691
692 if (Config->MaxMemory != 0) {
693 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
694 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
695 if (MemoryPtr > Config->MaxMemory)
696 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
697 MaxMemoryPages = Config->MaxMemory / WasmPageSize;
698 log("mem: max pages = " + Twine(MaxMemoryPages));
699 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000700}
701
702SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000703 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000704 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000705 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000706 OutputSections.push_back(Sec);
707 return Sec;
708}
709
710void Writer::createSections() {
711 // Known sections
Sam Cleggbfb75342018-11-15 00:37:21 +0000712 if (Config->Pic)
713 createDylinkSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000714 createTypeSection();
715 createImportSection();
716 createFunctionSection();
717 createTableSection();
718 createMemorySection();
719 createGlobalSection();
720 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000721 createElemSection();
722 createCodeSection();
723 createDataSection();
Sam Clegg80ba4382018-04-10 16:12:49 +0000724 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000725
726 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000727 if (Config->Relocatable) {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000728 createLinkingSection();
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000729 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000730 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000731 if (!Config->StripDebug && !Config->StripAll)
732 createNameSection();
733
734 for (OutputSection *S : OutputSections) {
735 S->setOffset(FileSize);
736 S->finalizeContents();
737 FileSize += S->getSize();
738 }
739}
740
Sam Cleggc94d3932017-11-17 18:14:09 +0000741void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000742 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000743 if (!Sym->isUndefined())
744 continue;
745 if (isa<DataSymbol>(Sym))
746 continue;
747 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000748 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000749 if (!Sym->isLive())
750 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000751 if (!Sym->IsUsedInRegularObj)
752 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000753
Nicola Zaghene7245b42018-05-15 13:36:20 +0000754 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000755 ImportedSymbols.emplace_back(Sym);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000756 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
757 F->setFunctionIndex(NumImportedFunctions++);
Sam Clegg93102972018-02-23 05:08:53 +0000758 else
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000759 cast<GlobalSymbol>(Sym)->setGlobalIndex(NumImportedGlobals++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000760 }
761}
762
Sam Cleggd3052d52018-01-18 23:40:49 +0000763void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000764 if (Config->Relocatable)
765 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000766
Sam Cleggd6beb322018-05-10 18:10:34 +0000767 if (!Config->Relocatable && !Config->ImportMemory)
768 Exports.push_back(WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
769
770 if (!Config->Relocatable && Config->ExportTable)
771 Exports.push_back(WasmExport{kFunctionTableName, WASM_EXTERNAL_TABLE, 0});
772
773 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
774
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000775 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000776 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000777 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000778 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000779 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000780
Sam Cleggd6beb322018-05-10 18:10:34 +0000781 StringRef Name = Sym->getName();
782 WasmExport Export;
783 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
784 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
785 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000786 // TODO(sbc): Remove this check once to mutable global proposal is
787 // implement in all major browsers.
788 // See: https://github.com/WebAssembly/mutable-global
789 if (G->getGlobalType()->Mutable) {
790 // Only the __stack_pointer should ever be create as mutable.
791 assert(G == WasmSym::StackPointer);
792 continue;
793 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000794 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
795 } else {
796 auto *D = cast<DefinedData>(Sym);
Sam Clegg93102972018-02-23 05:08:53 +0000797 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000798 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
799 }
800
Nicola Zaghene7245b42018-05-15 13:36:20 +0000801 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Cleggd6beb322018-05-10 18:10:34 +0000802 Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000803 }
Sam Clegg93102972018-02-23 05:08:53 +0000804}
805
806void Writer::assignSymtab() {
807 if (!Config->Relocatable)
808 return;
809
Sam Cleggd177ab22018-05-04 23:14:42 +0000810 StringMap<uint32_t> SectionSymbolIndices;
811
Sam Clegg93102972018-02-23 05:08:53 +0000812 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000813 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000814 LLVM_DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000815 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000816 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000817 continue;
Sam Cleggd177ab22018-05-04 23:14:42 +0000818
819 if (auto *S = dyn_cast<SectionSymbol>(Sym)) {
820 StringRef Name = S->getName();
821 if (CustomSectionMapping.count(Name) == 0)
822 continue;
823
824 auto SSI = SectionSymbolIndices.find(Name);
825 if (SSI != SectionSymbolIndices.end()) {
826 Sym->setOutputSymbolIndex(SSI->second);
827 continue;
828 }
829
830 SectionSymbolIndices[Name] = SymbolIndex;
831 CustomSectionSymbols[Name] = cast<SectionSymbol>(Sym);
832
833 Sym->markLive();
834 }
835
Nicholas Wilson06e0d172018-03-07 11:15:47 +0000836 // (Since this is relocatable output, GC is not performed so symbols must
837 // be live.)
838 assert(Sym->isLive());
Sam Clegg93102972018-02-23 05:08:53 +0000839 Sym->setOutputSymbolIndex(SymbolIndex++);
840 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000841 }
842 }
843
Sam Clegg93102972018-02-23 05:08:53 +0000844 // For the moment, relocatable output doesn't contain any synthetic functions,
845 // so no need to look through the Symtab for symbols not referenced by
846 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000847}
848
Sam Cleggc375e4e2018-01-10 19:18:22 +0000849uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000850 auto It = TypeIndices.find(Sig);
851 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000852 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000853 return 0;
854 }
855 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000856}
857
858uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000859 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000860 if (Pair.second) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000861 LLVM_DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000862 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000863 }
Sam Cleggb8621592017-11-30 01:40:08 +0000864 return Pair.first->second;
865}
866
Sam Cleggc94d3932017-11-17 18:14:09 +0000867void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000868 // The output type section is the union of the following sets:
869 // 1. Any signature used in the TYPE relocation
870 // 2. The signatures of all imported functions
871 // 3. The signatures of all defined functions
872
Sam Cleggc94d3932017-11-17 18:14:09 +0000873 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000874 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
875 for (uint32_t I = 0; I < Types.size(); I++)
876 if (File->TypeIsUsed[I])
877 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000878 }
Sam Clegg50686852018-01-12 18:35:13 +0000879
Sam Clegg93102972018-02-23 05:08:53 +0000880 for (const Symbol *Sym : ImportedSymbols)
881 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Cleggcefbf9a2018-06-28 16:53:53 +0000882 registerType(*F->FunctionType);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000883
Sam Clegg9f934222018-02-21 18:29:23 +0000884 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000885 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000886}
887
Sam Clegg8d146bb2018-01-09 23:56:44 +0000888void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000889 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000890 auto AddDefinedFunction = [&](InputFunction *Func) {
891 if (!Func->Live)
892 return;
893 InputFunctions.emplace_back(Func);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000894 Func->setFunctionIndex(FunctionIndex++);
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000895 };
896
Nicholas Wilson5639da82018-03-12 15:44:07 +0000897 for (InputFunction *Func : Symtab->SyntheticFunctions)
898 AddDefinedFunction(Func);
899
Sam Clegg87e61922018-01-08 23:39:11 +0000900 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000901 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000902 for (InputFunction *Func : File->Functions)
903 AddDefinedFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000904 }
905
Sam Cleggbfb75342018-11-15 00:37:21 +0000906 uint32_t TableIndex = TableBase;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000907 auto HandleRelocs = [&](InputChunk *Chunk) {
908 if (!Chunk->Live)
909 return;
910 ObjFile *File = Chunk->File;
911 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000912 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000913 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
914 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
915 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000916 if (Sym->hasTableIndex() || !Sym->hasFunctionIndex())
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000917 continue;
918 Sym->setTableIndex(TableIndex++);
919 IndirectFunctions.emplace_back(Sym);
920 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000921 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000922 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
923 File->TypeIsUsed[Reloc.Index] = true;
924 }
925 }
926 };
927
Sam Clegg8d146bb2018-01-09 23:56:44 +0000928 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000929 LLVM_DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000930 for (InputChunk *Chunk : File->Functions)
931 HandleRelocs(Chunk);
932 for (InputChunk *Chunk : File->Segments)
933 HandleRelocs(Chunk);
Sam Cleggd177ab22018-05-04 23:14:42 +0000934 for (auto &P : File->CustomSections)
935 HandleRelocs(P);
Sam Clegg93102972018-02-23 05:08:53 +0000936 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000937
Sam Clegg93102972018-02-23 05:08:53 +0000938 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
939 auto AddDefinedGlobal = [&](InputGlobal *Global) {
940 if (Global->Live) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000941 LLVM_DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000942 Global->setGlobalIndex(GlobalIndex++);
Sam Clegg93102972018-02-23 05:08:53 +0000943 InputGlobals.push_back(Global);
944 }
945 };
946
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000947 for (InputGlobal *Global : Symtab->SyntheticGlobals)
948 AddDefinedGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000949
950 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000951 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000952 for (InputGlobal *Global : File->Globals)
953 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000954 }
955}
956
957static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000958 // With PIC code we currently only support a single data segment since
959 // we only have a single __memory_base to use as our base address.
960 if (Config->Pic)
961 return "data";
Sam Clegg66844762018-05-10 18:23:51 +0000962 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000963 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000964 if (Name.startswith(".text."))
965 return ".text";
966 if (Name.startswith(".data."))
967 return ".data";
968 if (Name.startswith(".bss."))
969 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000970 if (Name.startswith(".rodata."))
971 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000972 return Name;
973}
974
975void Writer::createOutputSegments() {
976 for (ObjFile *File : Symtab->ObjectFiles) {
977 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000978 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000979 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000980 StringRef Name = getOutputDataSegmentName(Segment->getName());
981 OutputSegment *&S = SegmentMap[Name];
982 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000983 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000984 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000985 Segments.push_back(S);
986 }
987 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000988 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000989 }
990 }
991}
992
Sam Clegg50686852018-01-12 18:35:13 +0000993static const int OPCODE_CALL = 0x10;
994static const int OPCODE_END = 0xb;
995
996// Create synthetic "__wasm_call_ctors" function based on ctor functions
997// in input object.
998void Writer::createCtorFunction() {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000999 // First write the body's contents to a string.
1000 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +00001001 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001002 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +00001003 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +00001004 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +00001005 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +00001006 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +00001007 }
1008 writeU8(OS, OPCODE_END, "END");
1009 }
1010
1011 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +00001012 std::string FunctionBody;
1013 {
1014 raw_string_ostream OS(FunctionBody);
1015 writeUleb128(OS, BodyContent.size(), "function size");
1016 OS << BodyContent;
1017 }
Rui Ueyama29abfe42018-02-28 17:43:15 +00001018
Sam Cleggea656472018-10-22 08:35:39 +00001019 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +00001020 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +00001021}
1022
1023// Populate InitFunctions vector with init functions from all input objects.
1024// This is then used either when creating the output linking section or to
1025// synthesize the "__wasm_call_ctors" function.
1026void Writer::calculateInitFunctions() {
1027 for (ObjFile *File : Symtab->ObjectFiles) {
1028 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001029 for (const WasmInitFunc &F : L.InitFunctions) {
1030 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Derek Schuff371842b2018-10-03 22:25:32 +00001031 if (*Sym->FunctionType != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +00001032 error("invalid signature for init func: " + toString(*Sym));
1033 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
1034 }
Sam Clegg50686852018-01-12 18:35:13 +00001035 }
Rui Ueyamada69b712018-02-28 00:15:59 +00001036
Sam Clegg50686852018-01-12 18:35:13 +00001037 // Sort in order of priority (lowest first) so that they are called
1038 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +00001039 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +00001040 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +00001041 return L.Priority < R.Priority;
1042 });
Sam Clegg50686852018-01-12 18:35:13 +00001043}
1044
Sam Cleggc94d3932017-11-17 18:14:09 +00001045void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +00001046 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +00001047 Config->GlobalBase = 0;
1048
Sam Cleggbfb75342018-11-15 00:37:21 +00001049 // For PIC code the table base is assigned dynamically by the loader.
1050 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
1051 if (!Config->Pic)
1052 TableBase = 1;
1053
Sam Cleggc94d3932017-11-17 18:14:09 +00001054 log("-- calculateImports");
1055 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +00001056 log("-- assignIndexes");
1057 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +00001058 log("-- calculateInitFunctions");
1059 calculateInitFunctions();
1060 if (!Config->Relocatable)
1061 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +00001062 log("-- calculateTypes");
1063 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001064 log("-- layoutMemory");
1065 layoutMemory();
1066 log("-- calculateExports");
1067 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001068 log("-- calculateCustomSections");
1069 calculateCustomSections();
Sam Clegg93102972018-02-23 05:08:53 +00001070 log("-- assignSymtab");
1071 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +00001072
1073 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +00001074 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +00001075 log("Defined Globals : " + Twine(InputGlobals.size()));
1076 log("Function Imports : " + Twine(NumImportedFunctions));
1077 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +00001078 for (ObjFile *File : Symtab->ObjectFiles)
1079 File->dumpInfo();
1080 }
1081
Sam Cleggc94d3932017-11-17 18:14:09 +00001082 createHeader();
1083 log("-- createSections");
1084 createSections();
1085
1086 log("-- openFile");
1087 openFile();
1088 if (errorCount())
1089 return;
1090
1091 writeHeader();
1092
1093 log("-- writeSections");
1094 writeSections();
1095 if (errorCount())
1096 return;
1097
1098 if (Error E = Buffer->commit())
1099 fatal("failed to write the output file: " + toString(std::move(E)));
1100}
1101
1102// Open a result file.
1103void Writer::openFile() {
1104 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001105
1106 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1107 FileOutputBuffer::create(Config->OutputFile, FileSize,
1108 FileOutputBuffer::F_executable);
1109
1110 if (!BufferOrErr)
1111 error("failed to open " + Config->OutputFile + ": " +
1112 toString(BufferOrErr.takeError()));
1113 else
1114 Buffer = std::move(*BufferOrErr);
1115}
1116
1117void Writer::createHeader() {
1118 raw_string_ostream OS(Header);
1119 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
1120 writeU32(OS, WasmVersion, "wasm version");
1121 OS.flush();
1122 FileSize += Header.size();
1123}
1124
1125void lld::wasm::writeResult() { Writer().run(); }