blob: 4cefe3a473e461d6467d4de73207af9bcbdf3e99 [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"
11
Sam Clegg50686852018-01-12 18:35:13 +000012#include "llvm/ADT/DenseSet.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000013#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000014#include "InputChunks.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000015#include "OutputSections.h"
16#include "OutputSegment.h"
17#include "SymbolTable.h"
18#include "WriterUtils.h"
19#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000020#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000021#include "lld/Common/Threads.h"
22#include "llvm/Support/FileOutputBuffer.h"
23#include "llvm/Support/Format.h"
24#include "llvm/Support/FormatVariadic.h"
25#include "llvm/Support/LEB128.h"
26
27#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000028#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000029
30#define DEBUG_TYPE "lld"
31
32using namespace llvm;
33using namespace llvm::wasm;
34using namespace lld;
35using namespace lld::wasm;
36
37static constexpr int kStackAlignment = 16;
38
39namespace {
40
Sam Cleggc94d3932017-11-17 18:14:09 +000041// Traits for using WasmSignature in a DenseMap.
42struct WasmSignatureDenseMapInfo {
43 static WasmSignature getEmptyKey() {
44 WasmSignature Sig;
45 Sig.ReturnType = 1;
46 return Sig;
47 }
48 static WasmSignature getTombstoneKey() {
49 WasmSignature Sig;
50 Sig.ReturnType = 2;
51 return Sig;
52 }
53 static unsigned getHashValue(const WasmSignature &Sig) {
54 uintptr_t Value = 0;
55 Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType);
56 for (int32_t Param : Sig.ParamTypes)
57 Value += DenseMapInfo<int32_t>::getHashValue(Param);
58 return Value;
59 }
60 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
61 return LHS == RHS;
62 }
63};
64
Sam Cleggd3052d52018-01-18 23:40:49 +000065// A Wasm export to be written into the export section.
66struct WasmExportEntry {
67 const Symbol *Symbol;
68 StringRef FieldName; // may not match the Symbol name
69};
70
Sam Cleggc94d3932017-11-17 18:14:09 +000071// The writer writes a SymbolTable result to a file.
72class Writer {
73public:
74 void run();
75
76private:
77 void openFile();
78
Sam Cleggc375e4e2018-01-10 19:18:22 +000079 uint32_t lookupType(const WasmSignature &Sig);
80 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg50686852018-01-12 18:35:13 +000081 void createCtorFunction();
82 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000083 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000084 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000085 void calculateExports();
Sam Cleggc94d3932017-11-17 18:14:09 +000086 void calculateTypes();
87 void createOutputSegments();
88 void layoutMemory();
89 void createHeader();
90 void createSections();
91 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000092 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000093
94 // Builtin sections
95 void createTypeSection();
96 void createFunctionSection();
97 void createTableSection();
98 void createGlobalSection();
99 void createExportSection();
100 void createImportSection();
101 void createMemorySection();
102 void createElemSection();
103 void createStartSection();
104 void createCodeSection();
105 void createDataSection();
106
107 // Custom sections
108 void createRelocSections();
109 void createLinkingSection();
110 void createNameSection();
111
112 void writeHeader();
113 void writeSections();
114
115 uint64_t FileSize = 0;
116 uint32_t DataSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000117 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000118 uint32_t InitialTableOffset = 0;
119
120 std::vector<const WasmSignature *> Types;
121 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000122 std::vector<const Symbol *> ImportedFunctions;
123 std::vector<const Symbol *> ImportedGlobals;
Sam Cleggd3052d52018-01-18 23:40:49 +0000124 std::vector<WasmExportEntry> ExportedSymbols;
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000125 std::vector<const Symbol *> DefinedGlobals;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000126 std::vector<InputFunction *> DefinedFunctions;
Sam Cleggfc1a9122017-12-11 22:00:56 +0000127 std::vector<const Symbol *> IndirectFunctions;
Sam Clegg50686852018-01-12 18:35:13 +0000128 std::vector<WasmInitFunc> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000129
130 // Elements that are used to construct the final output
131 std::string Header;
132 std::vector<OutputSection *> OutputSections;
133
134 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000135 std::unique_ptr<SyntheticFunction> CtorFunction;
136 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000137
138 std::vector<OutputSegment *> Segments;
139 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
140};
141
142} // anonymous namespace
143
144static void debugPrint(const char *fmt, ...) {
145 if (!errorHandler().Verbose)
146 return;
147 fprintf(stderr, "lld: ");
148 va_list ap;
149 va_start(ap, fmt);
150 vfprintf(stderr, fmt, ap);
151 va_end(ap);
152}
153
154void Writer::createImportSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000155 uint32_t NumImports = ImportedFunctions.size() + ImportedGlobals.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000156 if (Config->ImportMemory)
157 ++NumImports;
158
159 if (NumImports == 0)
160 return;
161
162 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
163 raw_ostream &OS = Section->getStream();
164
165 writeUleb128(OS, NumImports, "import count");
166
Sam Clegg8d146bb2018-01-09 23:56:44 +0000167 for (const Symbol *Sym : ImportedFunctions) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 WasmImport Import;
169 Import.Module = "env";
170 Import.Field = Sym->getName();
171 Import.Kind = WASM_EXTERNAL_FUNCTION;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000172 Import.SigIndex = lookupType(Sym->getFunctionType());
Sam Cleggc94d3932017-11-17 18:14:09 +0000173 writeImport(OS, Import);
174 }
175
176 if (Config->ImportMemory) {
177 WasmImport Import;
178 Import.Module = "env";
179 Import.Field = "memory";
180 Import.Kind = WASM_EXTERNAL_MEMORY;
181 Import.Memory.Flags = 0;
182 Import.Memory.Initial = NumMemoryPages;
183 writeImport(OS, Import);
184 }
185
Sam Clegg8d146bb2018-01-09 23:56:44 +0000186 for (const Symbol *Sym : ImportedGlobals) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000187 WasmImport Import;
188 Import.Module = "env";
189 Import.Field = Sym->getName();
190 Import.Kind = WASM_EXTERNAL_GLOBAL;
191 Import.Global.Mutable = false;
Sam Cleggd451da12017-12-19 19:56:27 +0000192 Import.Global.Type = WASM_TYPE_I32;
Sam Cleggc94d3932017-11-17 18:14:09 +0000193 writeImport(OS, Import);
194 }
195}
196
197void Writer::createTypeSection() {
198 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
199 raw_ostream &OS = Section->getStream();
200 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000201 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000202 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000203}
204
205void Writer::createFunctionSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000206 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000207 return;
208
209 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
210 raw_ostream &OS = Section->getStream();
211
Sam Clegg8d146bb2018-01-09 23:56:44 +0000212 writeUleb128(OS, DefinedFunctions.size(), "function count");
213 for (const InputFunction *Func : DefinedFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000214 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000215}
216
217void Writer::createMemorySection() {
218 if (Config->ImportMemory)
219 return;
220
221 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
222 raw_ostream &OS = Section->getStream();
223
224 writeUleb128(OS, 1, "memory count");
225 writeUleb128(OS, 0, "memory limits flags");
226 writeUleb128(OS, NumMemoryPages, "initial pages");
227}
228
229void Writer::createGlobalSection() {
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000230 if (DefinedGlobals.empty())
231 return;
232
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
234 raw_ostream &OS = Section->getStream();
235
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000236 writeUleb128(OS, DefinedGlobals.size(), "global count");
237 for (const Symbol *Sym : DefinedGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000238 WasmGlobal Global;
239 Global.Type = WASM_TYPE_I32;
240 Global.Mutable = Sym == Config->StackPointerSymbol;
241 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
242 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 writeGlobal(OS, Global);
244 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000245}
246
247void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000248 // Always output a table section, even if there are no indirect calls.
249 // There are two reasons for this:
250 // 1. For executables it is useful to have an empty table slot at 0
251 // which can be filled with a null function call handler.
252 // 2. If we don't do this, any program that contains a call_indirect but
253 // no address-taken function will fail at validation time since it is
254 // a validation error to include a call_indirect instruction if there
255 // is not table.
256 uint32_t TableSize = InitialTableOffset + IndirectFunctions.size();
257
Sam Cleggc94d3932017-11-17 18:14:09 +0000258 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
259 raw_ostream &OS = Section->getStream();
260
261 writeUleb128(OS, 1, "table count");
262 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
263 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000264 writeUleb128(OS, TableSize, "table initial size");
265 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000266}
267
268void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000269 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000270
Sam Cleggd3052d52018-01-18 23:40:49 +0000271 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000272 if (!NumExports)
273 return;
274
275 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
276 raw_ostream &OS = Section->getStream();
277
278 writeUleb128(OS, NumExports, "export count");
279
280 if (ExportMemory) {
281 WasmExport MemoryExport;
282 MemoryExport.Name = "memory";
283 MemoryExport.Kind = WASM_EXTERNAL_MEMORY;
284 MemoryExport.Index = 0;
285 writeExport(OS, MemoryExport);
286 }
287
Sam Cleggd3052d52018-01-18 23:40:49 +0000288 for (const WasmExportEntry &E : ExportedSymbols) {
289 DEBUG(dbgs() << "Export: " << E.Symbol->getName() << "\n");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000290 WasmExport Export;
Sam Cleggd3052d52018-01-18 23:40:49 +0000291 Export.Name = E.FieldName;
292 Export.Index = E.Symbol->getOutputIndex();
293 if (E.Symbol->isFunction())
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000294 Export.Kind = WASM_EXTERNAL_FUNCTION;
295 else
296 Export.Kind = WASM_EXTERNAL_GLOBAL;
297 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000298 }
299}
300
301void Writer::createStartSection() {}
302
303void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000304 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000305 return;
306
307 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
308 raw_ostream &OS = Section->getStream();
309
310 writeUleb128(OS, 1, "segment count");
311 writeUleb128(OS, 0, "table index");
312 WasmInitExpr InitExpr;
313 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
314 InitExpr.Value.Int32 = InitialTableOffset;
315 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000316 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000317
Sam Cleggfc1a9122017-12-11 22:00:56 +0000318 uint32_t TableIndex = InitialTableOffset;
319 for (const Symbol *Sym : IndirectFunctions) {
320 assert(Sym->getTableIndex() == TableIndex);
321 writeUleb128(OS, Sym->getOutputIndex(), "function index");
322 ++TableIndex;
323 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000324}
325
326void Writer::createCodeSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000327 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000328 return;
329
330 log("createCodeSection");
331
Sam Clegg8d146bb2018-01-09 23:56:44 +0000332 auto Section = make<CodeSection>(DefinedFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000333 OutputSections.push_back(Section);
334}
335
336void Writer::createDataSection() {
337 if (!Segments.size())
338 return;
339
340 log("createDataSection");
341 auto Section = make<DataSection>(Segments);
342 OutputSections.push_back(Section);
343}
344
Sam Cleggd451da12017-12-19 19:56:27 +0000345// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000346// These are only created when relocatable output is requested.
347void Writer::createRelocSections() {
348 log("createRelocSections");
349 // Don't use iterator here since we are adding to OutputSection
350 size_t OrigSize = OutputSections.size();
351 for (size_t i = 0; i < OrigSize; i++) {
352 OutputSection *S = OutputSections[i];
353 const char *name;
354 uint32_t Count = S->numRelocations();
355 if (!Count)
356 continue;
357
358 if (S->Type == WASM_SEC_DATA)
359 name = "reloc.DATA";
360 else if (S->Type == WASM_SEC_CODE)
361 name = "reloc.CODE";
362 else
Sam Cleggd451da12017-12-19 19:56:27 +0000363 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000364
365 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, name);
366 raw_ostream &OS = Section->getStream();
367 writeUleb128(OS, S->Type, "reloc section");
368 writeUleb128(OS, Count, "reloc count");
369 S->writeRelocations(OS);
370 }
371}
372
Sam Clegg49ed9262017-12-01 00:53:21 +0000373// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000374// This is only created when relocatable output is requested.
375void Writer::createLinkingSection() {
376 SyntheticSection *Section =
377 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
378 raw_ostream &OS = Section->getStream();
379
380 SubSection DataSizeSubSection(WASM_DATA_SIZE);
381 writeUleb128(DataSizeSubSection.getStream(), DataSize, "data size");
382 DataSizeSubSection.finalizeContents();
383 DataSizeSubSection.writeToStream(OS);
384
Sam Clegg0d0dd392017-12-19 17:09:45 +0000385 if (!Config->Relocatable)
386 return;
387
Sam Cleggd3052d52018-01-18 23:40:49 +0000388 std::vector<std::pair<StringRef, uint32_t>> SymbolInfo;
389 for (const WasmExportEntry &E : ExportedSymbols) {
390 uint32_t Flags =
391 (E.Symbol->isLocal() ? WASM_SYMBOL_BINDING_LOCAL :
392 E.Symbol->isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0) |
393 (E.Symbol->isHidden() ? WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
394 if (Flags)
395 SymbolInfo.emplace_back(E.FieldName, Flags);
396 }
397 if (!SymbolInfo.empty()) {
398 SubSection SubSection(WASM_SYMBOL_INFO);
399 writeUleb128(SubSection.getStream(), SymbolInfo.size(), "num sym info");
400 for (auto Pair: SymbolInfo) {
401 writeStr(SubSection.getStream(), Pair.first, "sym name");
402 writeUleb128(SubSection.getStream(), Pair.second, "sym flags");
403 }
404 SubSection.finalizeContents();
405 SubSection.writeToStream(OS);
406 }
407
Sam Clegg0d0dd392017-12-19 17:09:45 +0000408 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000409 SubSection SubSection(WASM_SEGMENT_INFO);
410 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
411 for (const OutputSegment *S : Segments) {
412 writeStr(SubSection.getStream(), S->Name, "segment name");
413 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
414 writeUleb128(SubSection.getStream(), 0, "flags");
415 }
416 SubSection.finalizeContents();
417 SubSection.writeToStream(OS);
418 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000419
Sam Clegg0d0dd392017-12-19 17:09:45 +0000420 if (!InitFunctions.empty()) {
421 SubSection SubSection(WASM_INIT_FUNCS);
422 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000423 "num init functions");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000424 for (const WasmInitFunc &F : InitFunctions) {
425 writeUleb128(SubSection.getStream(), F.Priority, "priority");
426 writeUleb128(SubSection.getStream(), F.FunctionIndex, "function index");
427 }
428 SubSection.finalizeContents();
429 SubSection.writeToStream(OS);
430 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000431
432 struct ComdatEntry { unsigned Kind; uint32_t Index; };
433 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
434
435 for (const InputFunction *F : DefinedFunctions) {
436 StringRef Comdat = F->getComdat();
437 if (!Comdat.empty())
438 Comdats[Comdat].emplace_back(
439 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
440 }
441 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000442 const auto &InputSegments = Segments[I]->InputSegments;
443 if (InputSegments.empty())
444 continue;
445 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000446#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000447 for (const InputSegment *IS : InputSegments)
448 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000449#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000450 if (!Comdat.empty())
451 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
452 }
453
454 if (!Comdats.empty()) {
455 SubSection SubSection(WASM_COMDAT_INFO);
456 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
457 for (const auto &C : Comdats) {
458 writeStr(SubSection.getStream(), C.first, "comdat name");
459 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
460 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
461 for (const ComdatEntry &Entry : C.second) {
462 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
463 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
464 }
465 }
466 SubSection.finalizeContents();
467 SubSection.writeToStream(OS);
468 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000469}
470
471// Create the custom "name" section containing debug symbol names.
472void Writer::createNameSection() {
Sam Clegg1963d712018-01-17 20:19:04 +0000473 unsigned NumNames = ImportedFunctions.size();
474 for (const InputFunction *F : DefinedFunctions)
475 if (!F->getName().empty())
476 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000477
Sam Clegg1963d712018-01-17 20:19:04 +0000478 if (NumNames == 0)
479 return;
Sam Clegg50686852018-01-12 18:35:13 +0000480
Sam Cleggc94d3932017-11-17 18:14:09 +0000481 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
482
Sam Cleggc94d3932017-11-17 18:14:09 +0000483 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
484 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000485 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000486
Sam Clegg1963d712018-01-17 20:19:04 +0000487 // Names must appear in function index order. As it happens ImportedFunctions
488 // and DefinedFunctions are numbers in order with imported functions coming
489 // first.
490 for (const Symbol *S : ImportedFunctions) {
491 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000492 writeStr(OS, S->getName(), "symbol name");
493 }
Sam Clegg1963d712018-01-17 20:19:04 +0000494 for (const InputFunction *F : DefinedFunctions) {
495 if (!F->getName().empty()) {
496 writeUleb128(OS, F->getOutputIndex(), "func index");
497 writeStr(OS, F->getName(), "symbol name");
498 }
499 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000500
501 FunctionSubsection.finalizeContents();
502 FunctionSubsection.writeToStream(Section->getStream());
503}
504
505void Writer::writeHeader() {
506 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
507}
508
509void Writer::writeSections() {
510 uint8_t *Buf = Buffer->getBufferStart();
511 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
512}
513
514// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000515// to each of the input data sections as well as the explicit stack region.
Sam Cleggc94d3932017-11-17 18:14:09 +0000516void Writer::layoutMemory() {
517 uint32_t MemoryPtr = 0;
518 if (!Config->Relocatable) {
519 MemoryPtr = Config->GlobalBase;
520 debugPrint("mem: global base = %d\n", Config->GlobalBase);
521 }
522
523 createOutputSegments();
524
525 // Static data comes first
526 for (OutputSegment *Seg : Segments) {
527 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
528 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000529 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000530 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
531 MemoryPtr += Seg->Size;
532 }
533
534 DataSize = MemoryPtr;
535 if (!Config->Relocatable)
536 DataSize -= Config->GlobalBase;
537 debugPrint("mem: static data = %d\n", DataSize);
538
539 // Stack comes after static data
540 if (!Config->Relocatable) {
541 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
542 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
543 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
544 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
545 debugPrint("mem: stack base = %d\n", MemoryPtr);
546 MemoryPtr += Config->ZStackSize;
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000547 Config->StackPointerSymbol->setVirtualAddress(MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000548 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000549 // Set `__heap_base` to directly follow the end of the stack. We don't
550 // allocate any heap memory up front, but instead really on the malloc/brk
551 // implementation growing the memory at runtime.
552 Config->HeapBaseSymbol->setVirtualAddress(MemoryPtr);
553 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000554 }
555
556 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
557 NumMemoryPages = MemSize / WasmPageSize;
558 debugPrint("mem: total pages = %d\n", NumMemoryPages);
559}
560
561SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000562 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000563 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000564 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000565 OutputSections.push_back(Sec);
566 return Sec;
567}
568
569void Writer::createSections() {
570 // Known sections
571 createTypeSection();
572 createImportSection();
573 createFunctionSection();
574 createTableSection();
575 createMemorySection();
576 createGlobalSection();
577 createExportSection();
578 createStartSection();
579 createElemSection();
580 createCodeSection();
581 createDataSection();
582
583 // Custom sections
Sam Clegg22cfe522017-12-05 16:53:25 +0000584 if (Config->EmitRelocs)
Sam Cleggc94d3932017-11-17 18:14:09 +0000585 createRelocSections();
586 createLinkingSection();
587 if (!Config->StripDebug && !Config->StripAll)
588 createNameSection();
589
590 for (OutputSection *S : OutputSections) {
591 S->setOffset(FileSize);
592 S->finalizeContents();
593 FileSize += S->getSize();
594 }
595}
596
Sam Cleggc94d3932017-11-17 18:14:09 +0000597void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000598 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggc0181152017-12-15 22:17:15 +0000599 if (!Sym->isUndefined() || Sym->isWeak())
Sam Clegg574d7ce2017-12-15 19:23:49 +0000600 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000601
Sam Clegg574d7ce2017-12-15 19:23:49 +0000602 if (Sym->isFunction()) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000603 Sym->setOutputIndex(ImportedFunctions.size());
604 ImportedFunctions.push_back(Sym);
Sam Clegg574d7ce2017-12-15 19:23:49 +0000605 } else {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000606 Sym->setOutputIndex(ImportedGlobals.size());
607 ImportedGlobals.push_back(Sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000608 }
609 }
610}
611
Sam Cleggd3052d52018-01-18 23:40:49 +0000612void Writer::calculateExports() {
613 Symbol *EntrySym = Symtab->find(Config->Entry);
614 bool ExportEntry = !Config->Relocatable && EntrySym && EntrySym->isDefined();
615 bool ExportHidden = Config->EmitRelocs;
616 StringSet<> UsedNames;
617 auto BudgeLocalName = [&](const Symbol *Sym) {
618 StringRef SymName = Sym->getName();
619 // We can't budge non-local names.
620 if (!Sym->isLocal())
621 return SymName;
622 // We must budge local names that have a collision with a symbol that we
623 // haven't yet processed.
624 if (!Symtab->find(SymName) && UsedNames.insert(SymName).second)
625 return SymName;
626 for (unsigned I = 1; ; ++I) {
627 std::string NameBuf = (SymName + "." + Twine(I)).str();
628 if (!UsedNames.count(NameBuf)) {
629 StringRef Name = Saver.save(NameBuf);
630 UsedNames.insert(Name); // Insert must use safe StringRef from save()
631 return Name;
632 }
633 }
634 };
635
636 if (ExportEntry)
637 ExportedSymbols.emplace_back(WasmExportEntry{EntrySym, EntrySym->getName()});
638
639 if (Config->CtorSymbol && ExportHidden &&
640 !(ExportEntry && Config->CtorSymbol == EntrySym))
641 ExportedSymbols.emplace_back(
642 WasmExportEntry{Config->CtorSymbol, Config->CtorSymbol->getName()});
643
644 for (ObjFile *File : Symtab->ObjectFiles) {
645 for (Symbol *Sym : File->getSymbols()) {
646 if (!Sym->isDefined() || File != Sym->getFile())
647 continue;
648 if (Sym->isGlobal())
649 continue;
650 if (Sym->getFunction()->Discarded)
651 continue;
652
653 if ((Sym->isHidden() || Sym->isLocal()) && !ExportHidden)
654 continue;
655 if (ExportEntry && Sym == EntrySym)
656 continue;
657 ExportedSymbols.emplace_back(WasmExportEntry{Sym, BudgeLocalName(Sym)});
658 }
659 }
660
661 for (const Symbol *Sym : DefinedGlobals) {
662 // Can't export the SP right now because it's mutable and mutable globals
663 // cannot be exported.
664 if (Sym == Config->StackPointerSymbol)
665 continue;
666 ExportedSymbols.emplace_back(WasmExportEntry{Sym, BudgeLocalName(Sym)});
667 }
668}
669
Sam Cleggc375e4e2018-01-10 19:18:22 +0000670uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000671 auto It = TypeIndices.find(Sig);
672 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000673 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000674 return 0;
675 }
676 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000677}
678
679uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000680 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000681 if (Pair.second) {
682 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000683 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000684 }
Sam Cleggb8621592017-11-30 01:40:08 +0000685 return Pair.first->second;
686}
687
Sam Cleggc94d3932017-11-17 18:14:09 +0000688void Writer::calculateTypes() {
689 for (ObjFile *File : Symtab->ObjectFiles) {
690 File->TypeMap.reserve(File->getWasmObj()->types().size());
Sam Cleggb8621592017-11-30 01:40:08 +0000691 for (const WasmSignature &Sig : File->getWasmObj()->types())
Sam Cleggc375e4e2018-01-10 19:18:22 +0000692 File->TypeMap.push_back(registerType(Sig));
Sam Cleggc94d3932017-11-17 18:14:09 +0000693 }
Sam Clegg50686852018-01-12 18:35:13 +0000694
695 for (Symbol *Sym : Symtab->getSymbols())
696 if (Sym->isFunction())
697 registerType(Sym->getFunctionType());
Sam Cleggc94d3932017-11-17 18:14:09 +0000698}
699
Sam Clegg8d146bb2018-01-09 23:56:44 +0000700void Writer::assignIndexes() {
Sam Clegg50686852018-01-12 18:35:13 +0000701 uint32_t GlobalIndex = ImportedGlobals.size() + DefinedGlobals.size();
702 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000703
704 if (Config->StackPointerSymbol) {
705 DefinedGlobals.emplace_back(Config->StackPointerSymbol);
706 Config->StackPointerSymbol->setOutputIndex(GlobalIndex++);
707 }
708
Sam Clegg51bcdc22018-01-17 01:34:31 +0000709 if (Config->HeapBaseSymbol) {
710 DefinedGlobals.emplace_back(Config->HeapBaseSymbol);
711 Config->HeapBaseSymbol->setOutputIndex(GlobalIndex++);
712 }
713
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000714 if (Config->EmitRelocs)
715 DefinedGlobals.reserve(Symtab->getSymbols().size());
716
Sam Cleggfc1a9122017-12-11 22:00:56 +0000717 uint32_t TableIndex = InitialTableOffset;
718
Sam Cleggc94d3932017-11-17 18:14:09 +0000719 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000720 if (Config->EmitRelocs) {
721 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
722 for (Symbol *Sym : File->getSymbols()) {
723 // Create wasm globals for data symbols defined in this file
724 if (!Sym->isDefined() || File != Sym->getFile())
725 continue;
726 if (Sym->isFunction())
727 continue;
Sam Cleggfc1a9122017-12-11 22:00:56 +0000728
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000729 DefinedGlobals.emplace_back(Sym);
730 Sym->setOutputIndex(GlobalIndex++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000731 }
732 }
Sam Clegg87e61922018-01-08 23:39:11 +0000733 }
Sam Cleggfc1a9122017-12-11 22:00:56 +0000734
Sam Clegg87e61922018-01-08 23:39:11 +0000735 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000736 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
737 for (InputFunction *Func : File->Functions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000738 if (Func->Discarded)
739 continue;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000740 DefinedFunctions.emplace_back(Func);
741 Func->setOutputIndex(FunctionIndex++);
742 }
743 }
744
745 for (ObjFile *File : Symtab->ObjectFiles) {
746 DEBUG(dbgs() << "Table Indexes: " << File->getName() << "\n");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000747 for (Symbol *Sym : File->getTableSymbols()) {
Sam Clegg87e61922018-01-08 23:39:11 +0000748 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
749 continue;
750 Sym->setTableIndex(TableIndex++);
751 IndirectFunctions.emplace_back(Sym);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000752 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000753 }
754}
755
756static StringRef getOutputDataSegmentName(StringRef Name) {
757 if (Config->Relocatable)
758 return Name;
759
760 for (StringRef V :
761 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
762 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
763 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
764 StringRef Prefix = V.drop_back();
765 if (Name.startswith(V) || Name == Prefix)
766 return Prefix;
767 }
768
769 return Name;
770}
771
772void Writer::createOutputSegments() {
773 for (ObjFile *File : Symtab->ObjectFiles) {
774 for (InputSegment *Segment : File->Segments) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000775 if (Segment->Discarded)
776 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000777 StringRef Name = getOutputDataSegmentName(Segment->getName());
778 OutputSegment *&S = SegmentMap[Name];
779 if (S == nullptr) {
780 DEBUG(dbgs() << "new segment: " << Name << "\n");
781 S = make<OutputSegment>(Name);
782 Segments.push_back(S);
783 }
784 S->addInputSegment(Segment);
785 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000786 }
787 }
788}
789
Sam Clegg50686852018-01-12 18:35:13 +0000790static const int OPCODE_CALL = 0x10;
791static const int OPCODE_END = 0xb;
792
793// Create synthetic "__wasm_call_ctors" function based on ctor functions
794// in input object.
795void Writer::createCtorFunction() {
796 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
797 Config->CtorSymbol->setOutputIndex(FunctionIndex);
798
799 // First write the body bytes to a string.
800 std::string FunctionBody;
801 static WasmSignature Signature = {{}, WASM_TYPE_NORESULT};
802 {
803 raw_string_ostream OS(FunctionBody);
804 writeUleb128(OS, 0, "num locals");
805 for (const WasmInitFunc &F : InitFunctions) {
806 writeU8(OS, OPCODE_CALL, "CALL");
807 writeUleb128(OS, F.FunctionIndex, "function index");
808 }
809 writeU8(OS, OPCODE_END, "END");
810 }
811
812 // Once we know the size of the body we can create the final function body
813 raw_string_ostream OS(CtorFunctionBody);
814 writeUleb128(OS, FunctionBody.size(), "function size");
815 OS.flush();
816 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000817 ArrayRef<uint8_t> BodyArray(
818 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
819 CtorFunctionBody.size());
Sam Clegg1963d712018-01-17 20:19:04 +0000820 CtorFunction = llvm::make_unique<SyntheticFunction>(
821 Signature, BodyArray, Config->CtorSymbol->getName());
822 CtorFunction->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000823 DefinedFunctions.emplace_back(CtorFunction.get());
824}
825
826// Populate InitFunctions vector with init functions from all input objects.
827// This is then used either when creating the output linking section or to
828// synthesize the "__wasm_call_ctors" function.
829void Writer::calculateInitFunctions() {
830 for (ObjFile *File : Symtab->ObjectFiles) {
831 const WasmLinkingData &L = File->getWasmObj()->linkingData();
832 InitFunctions.reserve(InitFunctions.size() + L.InitFunctions.size());
833 for (const WasmInitFunc &F : L.InitFunctions)
834 InitFunctions.emplace_back(WasmInitFunc{
835 F.Priority, File->relocateFunctionIndex(F.FunctionIndex)});
836 }
837 // Sort in order of priority (lowest first) so that they are called
838 // in the correct order.
839 std::sort(InitFunctions.begin(), InitFunctions.end(),
840 [](const WasmInitFunc &L, const WasmInitFunc &R) {
841 return L.Priority < R.Priority;
842 });
843}
844
Sam Cleggc94d3932017-11-17 18:14:09 +0000845void Writer::run() {
846 if (!Config->Relocatable)
847 InitialTableOffset = 1;
848
849 log("-- calculateTypes");
850 calculateTypes();
851 log("-- calculateImports");
852 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000853 log("-- assignIndexes");
854 assignIndexes();
Sam Cleggd3052d52018-01-18 23:40:49 +0000855 log("-- calculateExports");
856 calculateExports();
Sam Clegg50686852018-01-12 18:35:13 +0000857 log("-- calculateInitFunctions");
858 calculateInitFunctions();
859 if (!Config->Relocatable)
860 createCtorFunction();
Sam Cleggc94d3932017-11-17 18:14:09 +0000861
862 if (errorHandler().Verbose) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000863 log("Defined Functions: " + Twine(DefinedFunctions.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000864 log("Defined Globals : " + Twine(DefinedGlobals.size()));
Sam Clegg8d146bb2018-01-09 23:56:44 +0000865 log("Function Imports : " + Twine(ImportedFunctions.size()));
866 log("Global Imports : " + Twine(ImportedGlobals.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000867 log("Total Imports : " +
Sam Clegg8d146bb2018-01-09 23:56:44 +0000868 Twine(ImportedFunctions.size() + ImportedGlobals.size()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000869 for (ObjFile *File : Symtab->ObjectFiles)
870 File->dumpInfo();
871 }
872
Sam Cleggc94d3932017-11-17 18:14:09 +0000873 log("-- layoutMemory");
874 layoutMemory();
875
876 createHeader();
877 log("-- createSections");
878 createSections();
879
880 log("-- openFile");
881 openFile();
882 if (errorCount())
883 return;
884
885 writeHeader();
886
887 log("-- writeSections");
888 writeSections();
889 if (errorCount())
890 return;
891
892 if (Error E = Buffer->commit())
893 fatal("failed to write the output file: " + toString(std::move(E)));
894}
895
896// Open a result file.
897void Writer::openFile() {
898 log("writing: " + Config->OutputFile);
899 ::remove(Config->OutputFile.str().c_str());
900
901 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
902 FileOutputBuffer::create(Config->OutputFile, FileSize,
903 FileOutputBuffer::F_executable);
904
905 if (!BufferOrErr)
906 error("failed to open " + Config->OutputFile + ": " +
907 toString(BufferOrErr.takeError()));
908 else
909 Buffer = std::move(*BufferOrErr);
910}
911
912void Writer::createHeader() {
913 raw_string_ostream OS(Header);
914 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
915 writeU32(OS, WasmVersion, "wasm version");
916 OS.flush();
917 FileSize += Header.size();
918}
919
920void lld::wasm::writeResult() { Writer().run(); }