blob: 11c4b913fd3723d817cacde15492d4334ff0b4c5 [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam Cleggc94d3932017-11-17 18:14:09 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000010#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000011#include "InputChunks.h"
Heejin Ahne915a712018-12-08 06:17:43 +000012#include "InputEvent.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"
Sam Clegg8fcf0122019-05-21 09:13:09 +000016#include "Relocations.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000017#include "SymbolTable.h"
Sam Clegg8fcf0122019-05-21 09:13:09 +000018#include "SyntheticSections.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000019#include "WriterUtils.h"
20#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000021#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000022#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000023#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000024#include "llvm/ADT/DenseSet.h"
Thomas Livelyf6f4f842019-03-20 20:26:45 +000025#include "llvm/ADT/SmallSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000026#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000027#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000028#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000029#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000030#include "llvm/Support/FileOutputBuffer.h"
31#include "llvm/Support/Format.h"
32#include "llvm/Support/FormatVariadic.h"
33#include "llvm/Support/LEB128.h"
34
35#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000036#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000037
38#define DEBUG_TYPE "lld"
39
40using namespace llvm;
41using namespace llvm::wasm;
42using namespace lld;
43using namespace lld::wasm;
44
Rui Ueyama136d27a2019-07-11 05:40:30 +000045static constexpr int stackAlignment = 16;
Sam Cleggc94d3932017-11-17 18:14:09 +000046
47namespace {
48
Sam Cleggc94d3932017-11-17 18:14:09 +000049// The writer writes a SymbolTable result to a file.
50class Writer {
51public:
52 void run();
53
54private:
55 void openFile();
56
Thomas Lively6004d9a2019-07-03 22:04:54 +000057 void createInitMemoryFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000058 void createApplyRelocationsFunction();
59 void createCallCtorsFunction();
60
Sam Clegg8d146bb2018-01-09 23:56:44 +000061 void assignIndexes();
Sam Clegg8fcf0122019-05-21 09:13:09 +000062 void populateSymtab();
63 void populateProducers();
64 void populateTargetFeatures();
65 void calculateInitFunctions();
Sam Cleggc94d3932017-11-17 18:14:09 +000066 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000067 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000068 void calculateCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000069 void calculateTypes();
70 void createOutputSegments();
71 void layoutMemory();
72 void createHeader();
Sam Cleggc94d3932017-11-17 18:14:09 +000073
Rui Ueyama136d27a2019-07-11 05:40:30 +000074 void addSection(OutputSection *sec);
Sam Clegg8fcf0122019-05-21 09:13:09 +000075
76 void addSections();
Sam Clegg4bce63a2019-05-23 10:06:03 +000077
Sam Clegg80ba4382018-04-10 16:12:49 +000078 void createCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +000079 void createSyntheticSections();
80 void finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000081
82 // Custom sections
83 void createRelocSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000084
85 void writeHeader();
86 void writeSections();
87
Rui Ueyama136d27a2019-07-11 05:40:30 +000088 uint64_t fileSize = 0;
89 uint32_t tableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000090
Rui Ueyama136d27a2019-07-11 05:40:30 +000091 std::vector<WasmInitEntry> initFunctions;
92 llvm::StringMap<std::vector<InputSection *>> customSectionMapping;
Sam Clegg80ba4382018-04-10 16:12:49 +000093
Sam Cleggc94d3932017-11-17 18:14:09 +000094 // Elements that are used to construct the final output
Rui Ueyama136d27a2019-07-11 05:40:30 +000095 std::string header;
96 std::vector<OutputSection *> outputSections;
Sam Cleggc94d3932017-11-17 18:14:09 +000097
Rui Ueyama136d27a2019-07-11 05:40:30 +000098 std::unique_ptr<FileOutputBuffer> buffer;
Sam Cleggc94d3932017-11-17 18:14:09 +000099
Rui Ueyama136d27a2019-07-11 05:40:30 +0000100 std::vector<OutputSegment *> segments;
101 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
Sam Cleggc94d3932017-11-17 18:14:09 +0000102};
103
104} // anonymous namespace
105
Sam Cleggd177ab22018-05-04 23:14:42 +0000106void Writer::calculateCustomSections() {
107 log("calculateCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000108 bool stripDebug = config->stripDebug || config->stripAll;
109 for (ObjFile *file : symtab->objectFiles) {
110 for (InputSection *section : file->customSections) {
111 StringRef name = section->getName();
Sam Cleggd177ab22018-05-04 23:14:42 +0000112 // These custom sections are known the linker and synthesized rather than
113 // blindly copied
Rui Ueyama136d27a2019-07-11 05:40:30 +0000114 if (name == "linking" || name == "name" || name == "producers" ||
115 name == "target_features" || name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000116 continue;
117 // .. or it is a debug section
Rui Ueyama136d27a2019-07-11 05:40:30 +0000118 if (stripDebug && name.startswith(".debug_"))
Sam Cleggd177ab22018-05-04 23:14:42 +0000119 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000120 customSectionMapping[name].push_back(section);
Sam Cleggd177ab22018-05-04 23:14:42 +0000121 }
122 }
123}
124
Sam Clegg80ba4382018-04-10 16:12:49 +0000125void Writer::createCustomSections() {
126 log("createCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000127 for (auto &pair : customSectionMapping) {
128 StringRef name = pair.first();
129 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000130
Rui Ueyama136d27a2019-07-11 05:40:30 +0000131 OutputSection *sec = make<CustomSection>(name, pair.second);
132 if (config->relocatable || config->emitRelocs) {
133 auto *sym = make<OutputSectionSymbol>(sec);
134 out.linkingSec->addToSymtab(sym);
135 sec->sectionSym = sym;
Sam Clegg8fcf0122019-05-21 09:13:09 +0000136 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000137 addSection(sec);
Sam Clegg80ba4382018-04-10 16:12:49 +0000138 }
139}
140
Sam Cleggd451da12017-12-19 19:56:27 +0000141// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000142// These are only created when relocatable output is requested.
143void Writer::createRelocSections() {
144 log("createRelocSections");
145 // Don't use iterator here since we are adding to OutputSection
Rui Ueyama136d27a2019-07-11 05:40:30 +0000146 size_t origSize = outputSections.size();
147 for (size_t i = 0; i < origSize; i++) {
148 LLVM_DEBUG(dbgs() << "check section " << i << "\n");
149 OutputSection *sec = outputSections[i];
Sam Clegg8fcf0122019-05-21 09:13:09 +0000150
151 // Count the number of needed sections.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000152 uint32_t count = sec->getNumRelocations();
153 if (!count)
Sam Cleggc94d3932017-11-17 18:14:09 +0000154 continue;
155
Rui Ueyama136d27a2019-07-11 05:40:30 +0000156 StringRef name;
157 if (sec->type == WASM_SEC_DATA)
158 name = "reloc.DATA";
159 else if (sec->type == WASM_SEC_CODE)
160 name = "reloc.CODE";
161 else if (sec->type == WASM_SEC_CUSTOM)
162 name = saver.save("reloc." + sec->name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000163 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000164 llvm_unreachable(
165 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000166
Rui Ueyama136d27a2019-07-11 05:40:30 +0000167 addSection(make<RelocSection>(name, sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 }
169}
170
Sam Clegg8fcf0122019-05-21 09:13:09 +0000171void Writer::populateProducers() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000172 for (ObjFile *file : symtab->objectFiles) {
173 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
174 out.producersSec->addInfo(info);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000175 }
176}
177
Sam Cleggc94d3932017-11-17 18:14:09 +0000178void Writer::writeHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000179 memcpy(buffer->getBufferStart(), header.data(), header.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000180}
181
182void Writer::writeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000183 uint8_t *buf = buffer->getBufferStart();
184 parallelForEach(outputSections, [buf](OutputSection *s) {
185 assert(s->isNeeded());
186 s->writeTo(buf);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000187 });
Sam Cleggc94d3932017-11-17 18:14:09 +0000188}
189
190// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000191// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000192// The default memory layout is as follows, from low to high.
193//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000194// - initialized data (starting at Config->GlobalBase)
195// - BSS data (not currently implemented in llvm)
196// - explicit stack (Config->ZStackSize)
197// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000198//
199// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000200// This can be useful since it means that stack overflow traps immediately
201// rather than overwriting global data, but also increases code size since all
202// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000203void Writer::layoutMemory() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000204 uint32_t memoryPtr = 0;
Sam Clegga0f095e2018-05-03 17:21:53 +0000205
Rui Ueyama136d27a2019-07-11 05:40:30 +0000206 auto placeStack = [&]() {
207 if (config->relocatable || config->shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000208 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000209 memoryPtr = alignTo(memoryPtr, stackAlignment);
210 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
211 error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
212 log("mem: stack size = " + Twine(config->zStackSize));
213 log("mem: stack base = " + Twine(memoryPtr));
214 memoryPtr += config->zStackSize;
215 auto *sp = cast<DefinedGlobal>(WasmSym::stackPointer);
216 sp->global->global.InitExpr.Value.Int32 = memoryPtr;
217 log("mem: stack top = " + Twine(memoryPtr));
Sam Clegga0f095e2018-05-03 17:21:53 +0000218 };
219
Rui Ueyama136d27a2019-07-11 05:40:30 +0000220 if (config->stackFirst) {
221 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000222 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000223 memoryPtr = config->globalBase;
224 log("mem: global base = " + Twine(config->globalBase));
Sam Clegga0f095e2018-05-03 17:21:53 +0000225 }
226
Rui Ueyama136d27a2019-07-11 05:40:30 +0000227 if (WasmSym::globalBase)
228 WasmSym::globalBase->setVirtualAddress(config->globalBase);
Guanzhong Chene15dc952019-06-26 20:12:33 +0000229
Rui Ueyama136d27a2019-07-11 05:40:30 +0000230 uint32_t dataStart = memoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000231
Sam Cleggf0d433d2018-02-02 22:59:56 +0000232 // Arbitrarily set __dso_handle handle to point to the start of the data
233 // segments.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000234 if (WasmSym::dsoHandle)
235 WasmSym::dsoHandle->setVirtualAddress(dataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000236
Rui Ueyama136d27a2019-07-11 05:40:30 +0000237 out.dylinkSec->memAlign = 0;
238 for (OutputSegment *seg : segments) {
239 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
240 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
241 seg->startVA = memoryPtr;
242 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
243 memoryPtr, seg->size, seg->alignment));
244 memoryPtr += seg->size;
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 }
246
Sam Cleggf0d433d2018-02-02 22:59:56 +0000247 // TODO: Add .bss space here.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000248 if (WasmSym::dataEnd)
249 WasmSym::dataEnd->setVirtualAddress(memoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000250
Rui Ueyama136d27a2019-07-11 05:40:30 +0000251 log("mem: static data = " + Twine(memoryPtr - dataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000252
Rui Ueyama136d27a2019-07-11 05:40:30 +0000253 if (config->shared) {
254 out.dylinkSec->memSize = memoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000255 return;
256 }
257
Rui Ueyama136d27a2019-07-11 05:40:30 +0000258 if (!config->stackFirst)
259 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000260
261 // Set `__heap_base` to directly follow the end of the stack or global data.
262 // The fact that this comes last means that a malloc/brk implementation
263 // can grow the heap at runtime.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000264 log("mem: heap base = " + Twine(memoryPtr));
265 if (WasmSym::heapBase)
266 WasmSym::heapBase->setVirtualAddress(memoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000267
Rui Ueyama136d27a2019-07-11 05:40:30 +0000268 if (config->initialMemory != 0) {
269 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000270 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000271 if (memoryPtr > config->initialMemory)
272 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000273 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000274 memoryPtr = config->initialMemory;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000275 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000276 out.dylinkSec->memSize = memoryPtr;
277 out.memorySec->numMemoryPages =
278 alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
279 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000280
Thomas Lively06391f32019-03-29 20:43:49 +0000281 // Check max if explicitly supplied or required by shared memory
Rui Ueyama136d27a2019-07-11 05:40:30 +0000282 if (config->maxMemory != 0 || config->sharedMemory) {
283 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000284 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000285 if (memoryPtr > config->maxMemory)
286 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
287 out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
288 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000289 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000290}
291
Rui Ueyama136d27a2019-07-11 05:40:30 +0000292void Writer::addSection(OutputSection *sec) {
293 if (!sec->isNeeded())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000294 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000295 log("addSection: " + toString(*sec));
296 sec->sectionIndex = outputSections.size();
297 outputSections.push_back(sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000298}
299
Sam Clegg4bce63a2019-05-23 10:06:03 +0000300// If a section name is valid as a C identifier (which is rare because of
301// the leading '.'), linkers are expected to define __start_<secname> and
302// __stop_<secname> symbols. They are at beginning and end of the section,
303// respectively. This is not requested by the ELF standard, but GNU ld and
304// gold provide the feature, and used by many programs.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000305static void addStartStopSymbols(const OutputSegment *seg) {
306 StringRef name = seg->name;
307 if (!isValidCIdentifier(name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000308 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000309 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
310 uint32_t start = seg->startVA;
311 uint32_t stop = start + seg->size;
312 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
313 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000314}
315
Sam Clegg8fcf0122019-05-21 09:13:09 +0000316void Writer::addSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000317 addSection(out.dylinkSec);
318 addSection(out.typeSec);
319 addSection(out.importSec);
320 addSection(out.functionSec);
321 addSection(out.tableSec);
322 addSection(out.memorySec);
323 addSection(out.globalSec);
324 addSection(out.eventSec);
325 addSection(out.exportSec);
326 addSection(out.elemSec);
327 addSection(out.dataCountSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000328
Rui Ueyama136d27a2019-07-11 05:40:30 +0000329 addSection(make<CodeSection>(out.functionSec->inputFunctions));
330 addSection(make<DataSection>(segments));
Sam Clegg8fcf0122019-05-21 09:13:09 +0000331
Sam Clegg80ba4382018-04-10 16:12:49 +0000332 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000333
Rui Ueyama136d27a2019-07-11 05:40:30 +0000334 addSection(out.linkingSec);
335 if (config->emitRelocs || config->relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000336 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000337 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000338
Rui Ueyama136d27a2019-07-11 05:40:30 +0000339 addSection(out.nameSec);
340 addSection(out.producersSec);
341 addSection(out.targetFeaturesSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000342}
Sam Cleggc94d3932017-11-17 18:14:09 +0000343
Sam Clegg8fcf0122019-05-21 09:13:09 +0000344void Writer::finalizeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000345 for (OutputSection *s : outputSections) {
346 s->setOffset(fileSize);
347 s->finalizeContents();
348 fileSize += s->getSize();
Sam Cleggc94d3932017-11-17 18:14:09 +0000349 }
350}
351
Sam Clegg8fcf0122019-05-21 09:13:09 +0000352void Writer::populateTargetFeatures() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000353 StringMap<std::string> used;
354 StringMap<std::string> required;
355 StringMap<std::string> disallowed;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000356
Thomas Lively82de51a2019-03-26 04:11:05 +0000357 // Only infer used features if user did not specify features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000358 bool inferFeatures = !config->features.hasValue();
Thomas Lively82de51a2019-03-26 04:11:05 +0000359
Rui Ueyama136d27a2019-07-11 05:40:30 +0000360 if (!inferFeatures) {
361 for (auto &feature : config->features.getValue())
362 out.targetFeaturesSec->features.insert(feature);
Thomas Lively82de51a2019-03-26 04:11:05 +0000363 // No need to read or check features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000364 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000365 return;
366 }
367
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000368 // Find the sets of used, required, and disallowed features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000369 for (ObjFile *file : symtab->objectFiles) {
370 StringRef fileName(file->getName());
371 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
372 switch (feature.Prefix) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000373 case WASM_FEATURE_PREFIX_USED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000374 used.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000375 break;
376 case WASM_FEATURE_PREFIX_REQUIRED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000377 used.insert({feature.Name, fileName});
378 required.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000379 break;
380 case WASM_FEATURE_PREFIX_DISALLOWED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000381 disallowed.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000382 break;
383 default:
384 error("Unrecognized feature policy prefix " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000385 std::to_string(feature.Prefix));
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000386 }
387 }
388 }
389
Rui Ueyama136d27a2019-07-11 05:40:30 +0000390 if (inferFeatures)
391 out.targetFeaturesSec->features.insert(used.keys().begin(),
392 used.keys().end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000393
Rui Ueyama136d27a2019-07-11 05:40:30 +0000394 if (out.targetFeaturesSec->features.count("atomics") &&
395 !config->sharedMemory) {
396 if (inferFeatures)
397 error(Twine("'atomics' feature is used by ") + used["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000398 ", so --shared-memory must be used");
399 else
400 error("'atomics' feature is used, so --shared-memory must be used");
401 }
Thomas Lively06391f32019-03-29 20:43:49 +0000402
Rui Ueyama136d27a2019-07-11 05:40:30 +0000403 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000404 return;
405
Rui Ueyama136d27a2019-07-11 05:40:30 +0000406 if (disallowed.count("atomics") && config->sharedMemory)
407 error("'atomics' feature is disallowed by " + disallowed["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000408 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000409
Rui Ueyama136d27a2019-07-11 05:40:30 +0000410 if (!used.count("bulk-memory") && config->passiveSegments)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000411 error("'bulk-memory' feature must be used in order to emit passive "
412 "segments");
413
Thomas Lively82de51a2019-03-26 04:11:05 +0000414 // Validate that used features are allowed in output
Rui Ueyama136d27a2019-07-11 05:40:30 +0000415 if (!inferFeatures) {
416 for (auto &feature : used.keys()) {
417 if (!out.targetFeaturesSec->features.count(feature))
418 error(Twine("Target feature '") + feature + "' used by " +
419 used[feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000420 }
421 }
422
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000423 // Validate the required and disallowed constraints for each file
Rui Ueyama136d27a2019-07-11 05:40:30 +0000424 for (ObjFile *file : symtab->objectFiles) {
425 StringRef fileName(file->getName());
426 SmallSet<std::string, 8> objectFeatures;
427 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
428 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000429 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000430 objectFeatures.insert(feature.Name);
431 if (disallowed.count(feature.Name))
432 error(Twine("Target feature '") + feature.Name + "' used in " +
433 fileName + " is disallowed by " + disallowed[feature.Name] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000434 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000435 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000436 for (auto &feature : required.keys()) {
437 if (!objectFeatures.count(feature))
438 error(Twine("Missing target feature '") + feature + "' in " + fileName +
439 ", required by " + required[feature] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000440 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000441 }
442 }
443}
444
Sam Cleggc94d3932017-11-17 18:14:09 +0000445void Writer::calculateImports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000446 for (Symbol *sym : symtab->getSymbols()) {
447 if (!sym->isUndefined())
Sam Clegg93102972018-02-23 05:08:53 +0000448 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000449 if (sym->isWeak() && !config->relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000450 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000451 if (!sym->isLive())
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000452 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000453 if (!sym->isUsedInRegularObj)
Sam Cleggc729c1b2018-05-30 18:07:52 +0000454 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000455 // We don't generate imports for data symbols. They however can be imported
456 // as GOT entries.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000457 if (isa<DataSymbol>(sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000458 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000459
Rui Ueyama136d27a2019-07-11 05:40:30 +0000460 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
461 out.importSec->addImport(sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
463}
464
Sam Cleggd3052d52018-01-18 23:40:49 +0000465void Writer::calculateExports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000466 if (config->relocatable)
Sam Clegg93102972018-02-23 05:08:53 +0000467 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000468
Rui Ueyama136d27a2019-07-11 05:40:30 +0000469 if (!config->relocatable && !config->importMemory)
470 out.exportSec->exports.push_back(
Sam Clegg8fcf0122019-05-21 09:13:09 +0000471 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000472
Rui Ueyama136d27a2019-07-11 05:40:30 +0000473 if (!config->relocatable && config->exportTable)
474 out.exportSec->exports.push_back(
475 WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000476
Rui Ueyama136d27a2019-07-11 05:40:30 +0000477 unsigned fakeGlobalIndex = out.importSec->getNumImportedGlobals() +
478 out.globalSec->inputGlobals.size();
Sam Cleggd6beb322018-05-10 18:10:34 +0000479
Rui Ueyama136d27a2019-07-11 05:40:30 +0000480 for (Symbol *sym : symtab->getSymbols()) {
481 if (!sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000482 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000483 if (!sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000484 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000485
Rui Ueyama136d27a2019-07-11 05:40:30 +0000486 StringRef name = sym->getName();
487 WasmExport export_;
488 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
489 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
490 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000491 // TODO(sbc): Remove this check once to mutable global proposal is
492 // implement in all major browsers.
493 // See: https://github.com/WebAssembly/mutable-global
Rui Ueyama136d27a2019-07-11 05:40:30 +0000494 if (g->getGlobalType()->Mutable) {
Sam Clegg177b4582018-06-07 01:27:07 +0000495 // Only the __stack_pointer should ever be create as mutable.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000496 assert(g == WasmSym::stackPointer);
Sam Clegg177b4582018-06-07 01:27:07 +0000497 continue;
498 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000499 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
500 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
501 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000502 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000503 auto *d = cast<DefinedData>(sym);
504 out.globalSec->definedFakeGlobals.emplace_back(d);
505 export_ = {name, WASM_EXTERNAL_GLOBAL, fakeGlobalIndex++};
Sam Cleggd6beb322018-05-10 18:10:34 +0000506 }
507
Rui Ueyama136d27a2019-07-11 05:40:30 +0000508 LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
509 out.exportSec->exports.push_back(export_);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000510 }
Sam Clegg93102972018-02-23 05:08:53 +0000511}
512
Sam Clegg8fcf0122019-05-21 09:13:09 +0000513void Writer::populateSymtab() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000514 if (!config->relocatable && !config->emitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000515 return;
516
Rui Ueyama136d27a2019-07-11 05:40:30 +0000517 for (Symbol *sym : symtab->getSymbols())
518 if (sym->isUsedInRegularObj && sym->isLive())
519 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000520
Rui Ueyama136d27a2019-07-11 05:40:30 +0000521 for (ObjFile *file : symtab->objectFiles) {
522 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
523 for (Symbol *sym : file->getSymbols())
524 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
525 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000526 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000527}
528
Sam Cleggc94d3932017-11-17 18:14:09 +0000529void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000530 // The output type section is the union of the following sets:
531 // 1. Any signature used in the TYPE relocation
532 // 2. The signatures of all imported functions
533 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000534 // 4. The signatures of all imported events
535 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000536
Rui Ueyama136d27a2019-07-11 05:40:30 +0000537 for (ObjFile *file : symtab->objectFiles) {
538 ArrayRef<WasmSignature> types = file->getWasmObj()->types();
539 for (uint32_t i = 0; i < types.size(); i++)
540 if (file->typeIsUsed[i])
541 file->typeMap[i] = out.typeSec->registerType(types[i]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000542 }
Sam Clegg50686852018-01-12 18:35:13 +0000543
Rui Ueyama136d27a2019-07-11 05:40:30 +0000544 for (const Symbol *sym : out.importSec->importedSymbols) {
545 if (auto *f = dyn_cast<FunctionSymbol>(sym))
546 out.typeSec->registerType(*f->signature);
547 else if (auto *e = dyn_cast<EventSymbol>(sym))
548 out.typeSec->registerType(*e->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000549 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000550
Rui Ueyama136d27a2019-07-11 05:40:30 +0000551 for (const InputFunction *f : out.functionSec->inputFunctions)
552 out.typeSec->registerType(f->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000553
Rui Ueyama136d27a2019-07-11 05:40:30 +0000554 for (const InputEvent *e : out.eventSec->inputEvents)
555 out.typeSec->registerType(e->signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000556}
557
Sam Clegg8fcf0122019-05-21 09:13:09 +0000558static void scanRelocations() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000559 for (ObjFile *file : symtab->objectFiles) {
560 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
561 for (InputChunk *chunk : file->functions)
562 scanRelocations(chunk);
563 for (InputChunk *chunk : file->segments)
564 scanRelocations(chunk);
565 for (auto &p : file->customSections)
566 scanRelocations(p);
Sam Clegg632c21792019-03-16 01:18:12 +0000567 }
568}
569
Sam Clegg8d146bb2018-01-09 23:56:44 +0000570void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000571 // Seal the import section, since other index spaces such as function and
572 // global are effected by the number of imports.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000573 out.importSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000574
Rui Ueyama136d27a2019-07-11 05:40:30 +0000575 for (InputFunction *func : symtab->syntheticFunctions)
576 out.functionSec->addFunction(func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000577
Rui Ueyama136d27a2019-07-11 05:40:30 +0000578 for (ObjFile *file : symtab->objectFiles) {
579 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
580 for (InputFunction *func : file->functions)
581 out.functionSec->addFunction(func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000582 }
583
Rui Ueyama136d27a2019-07-11 05:40:30 +0000584 for (InputGlobal *global : symtab->syntheticGlobals)
585 out.globalSec->addGlobal(global);
Sam Clegg93102972018-02-23 05:08:53 +0000586
Rui Ueyama136d27a2019-07-11 05:40:30 +0000587 for (ObjFile *file : symtab->objectFiles) {
588 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
589 for (InputGlobal *global : file->globals)
590 out.globalSec->addGlobal(global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 }
Heejin Ahne915a712018-12-08 06:17:43 +0000592
Rui Ueyama136d27a2019-07-11 05:40:30 +0000593 for (ObjFile *file : symtab->objectFiles) {
594 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
595 for (InputEvent *event : file->events)
596 out.eventSec->addEvent(event);
Heejin Ahne915a712018-12-08 06:17:43 +0000597 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000598}
599
Rui Ueyama136d27a2019-07-11 05:40:30 +0000600static StringRef getOutputDataSegmentName(StringRef name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000601 // With PIC code we currently only support a single data segment since
602 // we only have a single __memory_base to use as our base address.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000603 if (config->isPic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000604 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000605 if (!config->mergeDataSegments)
606 return name;
607 if (name.startswith(".text."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000608 return ".text";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000609 if (name.startswith(".data."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000610 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000611 if (name.startswith(".bss."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000612 return ".bss";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000613 if (name.startswith(".rodata."))
Sam Clegg57694c52018-08-08 18:02:55 +0000614 return ".rodata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000615 return name;
Sam Cleggc94d3932017-11-17 18:14:09 +0000616}
617
618void Writer::createOutputSegments() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000619 for (ObjFile *file : symtab->objectFiles) {
620 for (InputSegment *segment : file->segments) {
621 if (!segment->live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000622 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000623 StringRef name = getOutputDataSegmentName(segment->getName());
624 OutputSegment *&s = segmentMap[name];
625 if (s == nullptr) {
626 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
627 s = make<OutputSegment>(name, segments.size());
628 if (config->passiveSegments)
629 s->initFlags = WASM_SEGMENT_IS_PASSIVE;
630 segments.push_back(s);
Sam Cleggc94d3932017-11-17 18:14:09 +0000631 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000632 s->addInputSegment(segment);
633 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 }
635 }
636}
637
Rui Ueyama136d27a2019-07-11 05:40:30 +0000638static void createFunction(DefinedFunction *func, StringRef bodyContent) {
639 std::string functionBody;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000640 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000641 raw_string_ostream os(functionBody);
642 writeUleb128(os, bodyContent.size(), "function size");
643 os << bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000644 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000645 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
646 cast<SyntheticFunction>(func->function)->setBody(body);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000647}
648
649void Writer::createInitMemoryFunction() {
650 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000651 std::string bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000652 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000653 raw_string_ostream os(bodyContent);
654 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000655
656 // initialize passive data segments
Rui Ueyama136d27a2019-07-11 05:40:30 +0000657 for (const OutputSegment *s : segments) {
658 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE) {
Thomas Lively6004d9a2019-07-03 22:04:54 +0000659 // destination address
Rui Ueyama136d27a2019-07-11 05:40:30 +0000660 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
661 writeUleb128(os, s->startVA, "destination address");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000662 // source segment offset
Rui Ueyama136d27a2019-07-11 05:40:30 +0000663 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
664 writeUleb128(os, 0, "segment offset");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000665 // memory region size
Rui Ueyama136d27a2019-07-11 05:40:30 +0000666 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
667 writeUleb128(os, s->size, "memory region size");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000668 // memory.init instruction
Rui Ueyama136d27a2019-07-11 05:40:30 +0000669 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
670 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
671 writeUleb128(os, s->index, "segment index immediate");
672 writeU8(os, 0, "memory index immediate");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000673 // data.drop instruction
Rui Ueyama136d27a2019-07-11 05:40:30 +0000674 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
675 writeUleb128(os, WASM_OPCODE_DATA_DROP, "DATA.DROP");
676 writeUleb128(os, s->index, "segment index immediate");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000677 }
678 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000679 writeU8(os, WASM_OPCODE_END, "END");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000680 }
681
Rui Ueyama136d27a2019-07-11 05:40:30 +0000682 createFunction(WasmSym::initMemory, bodyContent);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000683}
684
Sam Clegg09137be2019-04-04 18:40:51 +0000685// For -shared (PIC) output, we create create a synthetic function which will
686// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000687// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
688// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000689void Writer::createApplyRelocationsFunction() {
690 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
691 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000692 std::string bodyContent;
Sam Clegg09137be2019-04-04 18:40:51 +0000693 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000694 raw_string_ostream os(bodyContent);
695 writeUleb128(os, 0, "num locals");
696 for (const OutputSegment *seg : segments)
697 for (const InputSegment *inSeg : seg->inputSegments)
698 inSeg->generateRelocationCode(os);
699 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg09137be2019-04-04 18:40:51 +0000700 }
701
Rui Ueyama136d27a2019-07-11 05:40:30 +0000702 createFunction(WasmSym::applyRelocs, bodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000703}
Sam Clegg50686852018-01-12 18:35:13 +0000704
705// Create synthetic "__wasm_call_ctors" function based on ctor functions
706// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000707void Writer::createCallCtorsFunction() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000708 if (!WasmSym::callCtors->isLive())
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000709 return;
710
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000711 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000712 std::string bodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000713 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000714 raw_string_ostream os(bodyContent);
715 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000716
Rui Ueyama136d27a2019-07-11 05:40:30 +0000717 if (config->passiveSegments) {
718 writeU8(os, WASM_OPCODE_CALL, "CALL");
719 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
Thomas Lively6004d9a2019-07-03 22:04:54 +0000720 "function index");
721 }
722
Rui Ueyama136d27a2019-07-11 05:40:30 +0000723 if (config->isPic) {
724 writeU8(os, WASM_OPCODE_CALL, "CALL");
725 writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
Sam Clegg09137be2019-04-04 18:40:51 +0000726 "function index");
727 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000728
729 // Call constructors
Rui Ueyama136d27a2019-07-11 05:40:30 +0000730 for (const WasmInitEntry &f : initFunctions) {
731 writeU8(os, WASM_OPCODE_CALL, "CALL");
732 writeUleb128(os, f.sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000733 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000734 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000735 }
736
Rui Ueyama136d27a2019-07-11 05:40:30 +0000737 createFunction(WasmSym::callCtors, bodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000738}
739
740// Populate InitFunctions vector with init functions from all input objects.
741// This is then used either when creating the output linking section or to
742// synthesize the "__wasm_call_ctors" function.
743void Writer::calculateInitFunctions() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000744 if (!config->relocatable && !WasmSym::callCtors->isLive())
Sam Clegg61f13b32019-03-02 04:55:02 +0000745 return;
746
Rui Ueyama136d27a2019-07-11 05:40:30 +0000747 for (ObjFile *file : symtab->objectFiles) {
748 const WasmLinkingData &l = file->getWasmObj()->linkingData();
749 for (const WasmInitFunc &f : l.InitFunctions) {
750 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000751 // comdat exclusions can cause init functions be discarded.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000752 if (sym->isDiscarded())
Sam Cleggfd54fa52019-06-07 06:00:46 +0000753 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000754 assert(sym->isLive());
755 if (*sym->signature != WasmSignature{{}, {}})
756 error("invalid signature for init func: " + toString(*sym));
757 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000758 }
Sam Clegg50686852018-01-12 18:35:13 +0000759 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000760
Sam Clegg50686852018-01-12 18:35:13 +0000761 // Sort in order of priority (lowest first) so that they are called
762 // in the correct order.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000763 llvm::stable_sort(initFunctions,
764 [](const WasmInitEntry &l, const WasmInitEntry &r) {
765 return l.priority < r.priority;
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000766 });
Sam Clegg50686852018-01-12 18:35:13 +0000767}
768
Sam Clegg8fcf0122019-05-21 09:13:09 +0000769void Writer::createSyntheticSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000770 out.dylinkSec = make<DylinkSection>();
771 out.typeSec = make<TypeSection>();
772 out.importSec = make<ImportSection>();
773 out.functionSec = make<FunctionSection>();
774 out.tableSec = make<TableSection>();
775 out.memorySec = make<MemorySection>();
776 out.globalSec = make<GlobalSection>();
777 out.eventSec = make<EventSection>();
778 out.exportSec = make<ExportSection>();
779 out.elemSec = make<ElemSection>(tableBase);
780 out.dataCountSec = make<DataCountSection>(segments.size());
781 out.linkingSec = make<LinkingSection>(initFunctions, segments);
782 out.nameSec = make<NameSection>();
783 out.producersSec = make<ProducersSection>();
784 out.targetFeaturesSec = make<TargetFeaturesSection>();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000785}
786
Sam Cleggc94d3932017-11-17 18:14:09 +0000787void Writer::run() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000788 if (config->relocatable || config->isPic)
789 config->globalBase = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000790
Sam Cleggbfb75342018-11-15 00:37:21 +0000791 // For PIC code the table base is assigned dynamically by the loader.
792 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000793 if (!config->isPic)
794 tableBase = 1;
Sam Cleggbfb75342018-11-15 00:37:21 +0000795
Sam Clegg8fcf0122019-05-21 09:13:09 +0000796 log("-- createOutputSegments");
797 createOutputSegments();
798 log("-- createSyntheticSections");
799 createSyntheticSections();
800 log("-- populateProducers");
801 populateProducers();
802 log("-- populateTargetFeatures");
803 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000804 log("-- calculateImports");
805 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000806 log("-- layoutMemory");
807 layoutMemory();
808
Rui Ueyama136d27a2019-07-11 05:40:30 +0000809 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000810 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
811 // This has to be done after memory layout is performed.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000812 for (const OutputSegment *seg : segments)
813 addStartStopSymbols(seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000814 }
815
Sam Cleggb9889bb2019-05-23 09:41:03 +0000816 log("-- scanRelocations");
817 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000818 log("-- assignIndexes");
819 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000820 log("-- calculateInitFunctions");
821 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000822
Rui Ueyama136d27a2019-07-11 05:40:30 +0000823 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000824 // Create linker synthesized functions
Rui Ueyama136d27a2019-07-11 05:40:30 +0000825 if (config->passiveSegments)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000826 createInitMemoryFunction();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000827 if (config->isPic)
Sam Clegg09137be2019-04-04 18:40:51 +0000828 createApplyRelocationsFunction();
829 createCallCtorsFunction();
830 }
Sam Clegg4bce63a2019-05-23 10:06:03 +0000831
832 log("-- calculateTypes");
833 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000834 log("-- calculateExports");
835 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +0000836 log("-- calculateCustomSections");
837 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000838 log("-- populateSymtab");
839 populateSymtab();
840 log("-- addSections");
841 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000842
Rui Ueyama136d27a2019-07-11 05:40:30 +0000843 if (errorHandler().verbose) {
844 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
845 log("Defined Globals : " + Twine(out.globalSec->inputGlobals.size()));
846 log("Defined Events : " + Twine(out.eventSec->inputEvents.size()));
Rui Ueyama7e296ad2019-07-10 09:10:01 +0000847 log("Function Imports : " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000848 Twine(out.importSec->getNumImportedFunctions()));
849 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals()));
850 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents()));
851 for (ObjFile *file : symtab->objectFiles)
852 file->dumpInfo();
Sam Cleggc94d3932017-11-17 18:14:09 +0000853 }
854
Sam Cleggc94d3932017-11-17 18:14:09 +0000855 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000856 log("-- finalizeSections");
857 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000858
859 log("-- openFile");
860 openFile();
861 if (errorCount())
862 return;
863
864 writeHeader();
865
866 log("-- writeSections");
867 writeSections();
868 if (errorCount())
869 return;
870
Rui Ueyama136d27a2019-07-11 05:40:30 +0000871 if (Error e = buffer->commit())
872 fatal("failed to write the output file: " + toString(std::move(e)));
Sam Cleggc94d3932017-11-17 18:14:09 +0000873}
874
875// Open a result file.
876void Writer::openFile() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000877 log("writing: " + config->outputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000878
Rui Ueyama136d27a2019-07-11 05:40:30 +0000879 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
880 FileOutputBuffer::create(config->outputFile, fileSize,
Sam Cleggc94d3932017-11-17 18:14:09 +0000881 FileOutputBuffer::F_executable);
882
Rui Ueyama136d27a2019-07-11 05:40:30 +0000883 if (!bufferOrErr)
884 error("failed to open " + config->outputFile + ": " +
885 toString(bufferOrErr.takeError()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000886 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000887 buffer = std::move(*bufferOrErr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000888}
889
890void Writer::createHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000891 raw_string_ostream os(header);
892 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
893 writeU32(os, WasmVersion, "wasm version");
894 os.flush();
895 fileSize += header.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000896}
897
898void lld::wasm::writeResult() { Writer().run(); }