blob: 5df3ae68e307cdab37c34d70640a28fa512bd6af [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;
Sam Cleggc94d3932017-11-17 18:14:09 +000042
Fangrui Song33c59ab2019-10-10 05:25:39 +000043namespace lld {
44namespace wasm {
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();
Guanzhong Chen42bba4b2019-07-16 22:00:45 +000060 void createInitTLSFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000061
Sam Clegg8d146bb2018-01-09 23:56:44 +000062 void assignIndexes();
Sam Clegg8fcf0122019-05-21 09:13:09 +000063 void populateSymtab();
64 void populateProducers();
65 void populateTargetFeatures();
66 void calculateInitFunctions();
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 Cleggc94d3932017-11-17 18:14:09 +000070 void calculateTypes();
71 void createOutputSegments();
72 void layoutMemory();
73 void createHeader();
Sam Cleggc94d3932017-11-17 18:14:09 +000074
Rui Ueyama136d27a2019-07-11 05:40:30 +000075 void addSection(OutputSection *sec);
Sam Clegg8fcf0122019-05-21 09:13:09 +000076
77 void addSections();
Sam Clegg4bce63a2019-05-23 10:06:03 +000078
Sam Clegg80ba4382018-04-10 16:12:49 +000079 void createCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +000080 void createSyntheticSections();
81 void finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000082
83 // Custom sections
84 void createRelocSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000085
86 void writeHeader();
87 void writeSections();
88
Rui Ueyama136d27a2019-07-11 05:40:30 +000089 uint64_t fileSize = 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//
Fangrui Song33fdf822019-07-16 08:08:17 +0000194// - initialized data (starting at Config->globalBase)
Sam Cleggf0d433d2018-02-02 22:59:56 +0000195// - 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 = [&]() {
Sam Cleggfd11ce32019-07-11 13:13:25 +0000207 if (config->relocatable || config->isPic)
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)
Sam Clegg7185a732019-08-13 17:02:02 +0000228 WasmSym::globalBase->setVirtualAddress(memoryPtr);
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;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000245
246 if (WasmSym::tlsSize && seg->name == ".tdata") {
247 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
248 tlsSize->global->global.InitExpr.Value.Int32 = seg->size;
Guanzhong Chen5204f762019-07-19 23:34:16 +0000249
250 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
251 tlsAlign->global->global.InitExpr.Value.Int32 = 1U << seg->alignment;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000252 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000253 }
254
Thomas Lively09768c52019-09-04 19:50:39 +0000255 // Make space for the memory initialization flag
256 if (WasmSym::initMemoryFlag) {
257 memoryPtr = alignTo(memoryPtr, 4);
258 WasmSym::initMemoryFlag->setVirtualAddress(memoryPtr);
259 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}",
260 "__wasm_init_memory_flag", memoryPtr, 4, 4));
261 memoryPtr += 4;
262 }
263
Rui Ueyama136d27a2019-07-11 05:40:30 +0000264 if (WasmSym::dataEnd)
265 WasmSym::dataEnd->setVirtualAddress(memoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000266
Rui Ueyama136d27a2019-07-11 05:40:30 +0000267 log("mem: static data = " + Twine(memoryPtr - dataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000268
Rui Ueyama136d27a2019-07-11 05:40:30 +0000269 if (config->shared) {
270 out.dylinkSec->memSize = memoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000271 return;
272 }
273
Rui Ueyama136d27a2019-07-11 05:40:30 +0000274 if (!config->stackFirst)
275 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000276
277 // Set `__heap_base` to directly follow the end of the stack or global data.
278 // The fact that this comes last means that a malloc/brk implementation
279 // can grow the heap at runtime.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000280 log("mem: heap base = " + Twine(memoryPtr));
281 if (WasmSym::heapBase)
282 WasmSym::heapBase->setVirtualAddress(memoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000283
Rui Ueyama136d27a2019-07-11 05:40:30 +0000284 if (config->initialMemory != 0) {
285 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000286 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000287 if (memoryPtr > config->initialMemory)
288 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000289 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000290 memoryPtr = config->initialMemory;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000291 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000292 out.dylinkSec->memSize = memoryPtr;
293 out.memorySec->numMemoryPages =
294 alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
295 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000296
Thomas Lively06391f32019-03-29 20:43:49 +0000297 // Check max if explicitly supplied or required by shared memory
Rui Ueyama136d27a2019-07-11 05:40:30 +0000298 if (config->maxMemory != 0 || config->sharedMemory) {
299 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000300 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000301 if (memoryPtr > config->maxMemory)
302 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
303 out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
304 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000305 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000306}
307
Rui Ueyama136d27a2019-07-11 05:40:30 +0000308void Writer::addSection(OutputSection *sec) {
309 if (!sec->isNeeded())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000310 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000311 log("addSection: " + toString(*sec));
312 sec->sectionIndex = outputSections.size();
313 outputSections.push_back(sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000314}
315
Sam Clegg4bce63a2019-05-23 10:06:03 +0000316// If a section name is valid as a C identifier (which is rare because of
317// the leading '.'), linkers are expected to define __start_<secname> and
318// __stop_<secname> symbols. They are at beginning and end of the section,
319// respectively. This is not requested by the ELF standard, but GNU ld and
320// gold provide the feature, and used by many programs.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000321static void addStartStopSymbols(const OutputSegment *seg) {
322 StringRef name = seg->name;
323 if (!isValidCIdentifier(name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000324 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000325 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
326 uint32_t start = seg->startVA;
327 uint32_t stop = start + seg->size;
328 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
329 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000330}
331
Sam Clegg8fcf0122019-05-21 09:13:09 +0000332void Writer::addSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000333 addSection(out.dylinkSec);
334 addSection(out.typeSec);
335 addSection(out.importSec);
336 addSection(out.functionSec);
337 addSection(out.tableSec);
338 addSection(out.memorySec);
339 addSection(out.globalSec);
340 addSection(out.eventSec);
341 addSection(out.exportSec);
Thomas Lively09768c52019-09-04 19:50:39 +0000342 addSection(out.startSec);
Rui Ueyama136d27a2019-07-11 05:40:30 +0000343 addSection(out.elemSec);
344 addSection(out.dataCountSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000345
Rui Ueyama136d27a2019-07-11 05:40:30 +0000346 addSection(make<CodeSection>(out.functionSec->inputFunctions));
347 addSection(make<DataSection>(segments));
Sam Clegg8fcf0122019-05-21 09:13:09 +0000348
Sam Clegg80ba4382018-04-10 16:12:49 +0000349 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000350
Rui Ueyama136d27a2019-07-11 05:40:30 +0000351 addSection(out.linkingSec);
352 if (config->emitRelocs || config->relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000353 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000354 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000355
Rui Ueyama136d27a2019-07-11 05:40:30 +0000356 addSection(out.nameSec);
357 addSection(out.producersSec);
358 addSection(out.targetFeaturesSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000359}
Sam Cleggc94d3932017-11-17 18:14:09 +0000360
Sam Clegg8fcf0122019-05-21 09:13:09 +0000361void Writer::finalizeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000362 for (OutputSection *s : outputSections) {
363 s->setOffset(fileSize);
364 s->finalizeContents();
365 fileSize += s->getSize();
Sam Cleggc94d3932017-11-17 18:14:09 +0000366 }
367}
368
Sam Clegg8fcf0122019-05-21 09:13:09 +0000369void Writer::populateTargetFeatures() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000370 StringMap<std::string> used;
371 StringMap<std::string> required;
372 StringMap<std::string> disallowed;
Thomas Lively09768c52019-09-04 19:50:39 +0000373 SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000374 bool tlsUsed = false;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000375
Thomas Lively82de51a2019-03-26 04:11:05 +0000376 // Only infer used features if user did not specify features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000377 bool inferFeatures = !config->features.hasValue();
Thomas Lively82de51a2019-03-26 04:11:05 +0000378
Rui Ueyama136d27a2019-07-11 05:40:30 +0000379 if (!inferFeatures) {
Thomas Lively09768c52019-09-04 19:50:39 +0000380 auto &explicitFeatures = config->features.getValue();
381 allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
Rui Ueyama136d27a2019-07-11 05:40:30 +0000382 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000383 return;
384 }
385
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000386 // Find the sets of used, required, and disallowed features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000387 for (ObjFile *file : symtab->objectFiles) {
388 StringRef fileName(file->getName());
389 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
390 switch (feature.Prefix) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000391 case WASM_FEATURE_PREFIX_USED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000392 used.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000393 break;
394 case WASM_FEATURE_PREFIX_REQUIRED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000395 used.insert({feature.Name, fileName});
396 required.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000397 break;
398 case WASM_FEATURE_PREFIX_DISALLOWED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000399 disallowed.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000400 break;
401 default:
402 error("Unrecognized feature policy prefix " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000403 std::to_string(feature.Prefix));
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000404 }
405 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000406
Thomas Lively09768c52019-09-04 19:50:39 +0000407 // Find TLS data segments
408 auto isTLS = [](InputSegment *segment) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000409 StringRef name = segment->getName();
Thomas Lively09768c52019-09-04 19:50:39 +0000410 return segment->live &&
411 (name.startswith(".tdata") || name.startswith(".tbss"));
412 };
413 tlsUsed = tlsUsed ||
414 std::any_of(file->segments.begin(), file->segments.end(), isTLS);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000415 }
416
Rui Ueyama136d27a2019-07-11 05:40:30 +0000417 if (inferFeatures)
Thomas Lively09768c52019-09-04 19:50:39 +0000418 allowed.insert(used.keys().begin(), used.keys().end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000419
Thomas Lively09768c52019-09-04 19:50:39 +0000420 if (allowed.count("atomics") && !config->sharedMemory) {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000421 if (inferFeatures)
422 error(Twine("'atomics' feature is used by ") + used["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000423 ", so --shared-memory must be used");
424 else
425 error("'atomics' feature is used, so --shared-memory must be used");
426 }
Thomas Lively06391f32019-03-29 20:43:49 +0000427
Rui Ueyama136d27a2019-07-11 05:40:30 +0000428 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000429 return;
430
Rui Ueyama136d27a2019-07-11 05:40:30 +0000431 if (disallowed.count("atomics") && config->sharedMemory)
432 error("'atomics' feature is disallowed by " + disallowed["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000433 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000434
Thomas Lively09768c52019-09-04 19:50:39 +0000435 if (!allowed.count("atomics") && config->sharedMemory)
436 error("'atomics' feature must be used in order to use shared "
437 "memory");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000438
Thomas Lively09768c52019-09-04 19:50:39 +0000439 if (!allowed.count("bulk-memory") && config->sharedMemory)
440 error("'bulk-memory' feature must be used in order to use shared "
441 "memory");
442
443 if (!allowed.count("bulk-memory") && tlsUsed)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000444 error("'bulk-memory' feature must be used in order to use thread-local "
445 "storage");
446
Thomas Lively82de51a2019-03-26 04:11:05 +0000447 // Validate that used features are allowed in output
Rui Ueyama136d27a2019-07-11 05:40:30 +0000448 if (!inferFeatures) {
449 for (auto &feature : used.keys()) {
Thomas Lively09768c52019-09-04 19:50:39 +0000450 if (!allowed.count(feature))
Rui Ueyama136d27a2019-07-11 05:40:30 +0000451 error(Twine("Target feature '") + feature + "' used by " +
452 used[feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000453 }
454 }
455
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000456 // Validate the required and disallowed constraints for each file
Rui Ueyama136d27a2019-07-11 05:40:30 +0000457 for (ObjFile *file : symtab->objectFiles) {
458 StringRef fileName(file->getName());
459 SmallSet<std::string, 8> objectFeatures;
460 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
461 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000462 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000463 objectFeatures.insert(feature.Name);
464 if (disallowed.count(feature.Name))
465 error(Twine("Target feature '") + feature.Name + "' used in " +
466 fileName + " is disallowed by " + disallowed[feature.Name] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000467 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000468 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000469 for (auto &feature : required.keys()) {
470 if (!objectFeatures.count(feature))
471 error(Twine("Missing target feature '") + feature + "' in " + fileName +
472 ", required by " + required[feature] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000473 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000474 }
475 }
476}
477
Sam Cleggc94d3932017-11-17 18:14:09 +0000478void Writer::calculateImports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000479 for (Symbol *sym : symtab->getSymbols()) {
480 if (!sym->isUndefined())
Sam Clegg93102972018-02-23 05:08:53 +0000481 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000482 if (sym->isWeak() && !config->relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000483 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000484 if (!sym->isLive())
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000485 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000486 if (!sym->isUsedInRegularObj)
Sam Cleggc729c1b2018-05-30 18:07:52 +0000487 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000488 // We don't generate imports for data symbols. They however can be imported
489 // as GOT entries.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000490 if (isa<DataSymbol>(sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000491 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000492
Rui Ueyama136d27a2019-07-11 05:40:30 +0000493 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
494 out.importSec->addImport(sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000495 }
496}
497
Sam Cleggd3052d52018-01-18 23:40:49 +0000498void Writer::calculateExports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000499 if (config->relocatable)
Sam Clegg93102972018-02-23 05:08:53 +0000500 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000501
Rui Ueyama136d27a2019-07-11 05:40:30 +0000502 if (!config->relocatable && !config->importMemory)
503 out.exportSec->exports.push_back(
Sam Clegg8fcf0122019-05-21 09:13:09 +0000504 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000505
Rui Ueyama136d27a2019-07-11 05:40:30 +0000506 if (!config->relocatable && config->exportTable)
507 out.exportSec->exports.push_back(
508 WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000509
Sam Clegg937b9552019-09-24 20:52:12 +0000510 unsigned globalIndex =
511 out.importSec->getNumImportedGlobals() + out.globalSec->numGlobals();
Sam Cleggd6beb322018-05-10 18:10:34 +0000512
Rui Ueyama136d27a2019-07-11 05:40:30 +0000513 for (Symbol *sym : symtab->getSymbols()) {
514 if (!sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000515 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000516 if (!sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000517 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000518
Rui Ueyama136d27a2019-07-11 05:40:30 +0000519 StringRef name = sym->getName();
520 WasmExport export_;
521 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
522 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
523 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000524 // TODO(sbc): Remove this check once to mutable global proposal is
525 // implement in all major browsers.
526 // See: https://github.com/WebAssembly/mutable-global
Rui Ueyama136d27a2019-07-11 05:40:30 +0000527 if (g->getGlobalType()->Mutable) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000528 // Only __stack_pointer and __tls_base should ever be create as mutable.
529 assert(g == WasmSym::stackPointer || g == WasmSym::tlsBase);
Sam Clegg177b4582018-06-07 01:27:07 +0000530 continue;
531 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000532 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
533 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
534 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000535 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000536 auto *d = cast<DefinedData>(sym);
Sam Clegg937b9552019-09-24 20:52:12 +0000537 out.globalSec->dataAddressGlobals.push_back(d);
538 export_ = {name, WASM_EXTERNAL_GLOBAL, globalIndex++};
Sam Cleggd6beb322018-05-10 18:10:34 +0000539 }
540
Rui Ueyama136d27a2019-07-11 05:40:30 +0000541 LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
542 out.exportSec->exports.push_back(export_);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000543 }
Sam Clegg93102972018-02-23 05:08:53 +0000544}
545
Sam Clegg8fcf0122019-05-21 09:13:09 +0000546void Writer::populateSymtab() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000547 if (!config->relocatable && !config->emitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000548 return;
549
Rui Ueyama136d27a2019-07-11 05:40:30 +0000550 for (Symbol *sym : symtab->getSymbols())
551 if (sym->isUsedInRegularObj && sym->isLive())
552 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000553
Rui Ueyama136d27a2019-07-11 05:40:30 +0000554 for (ObjFile *file : symtab->objectFiles) {
555 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
556 for (Symbol *sym : file->getSymbols())
557 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
558 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000559 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000560}
561
Sam Cleggc94d3932017-11-17 18:14:09 +0000562void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000563 // The output type section is the union of the following sets:
564 // 1. Any signature used in the TYPE relocation
565 // 2. The signatures of all imported functions
566 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000567 // 4. The signatures of all imported events
568 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000569
Rui Ueyama136d27a2019-07-11 05:40:30 +0000570 for (ObjFile *file : symtab->objectFiles) {
571 ArrayRef<WasmSignature> types = file->getWasmObj()->types();
572 for (uint32_t i = 0; i < types.size(); i++)
573 if (file->typeIsUsed[i])
574 file->typeMap[i] = out.typeSec->registerType(types[i]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000575 }
Sam Clegg50686852018-01-12 18:35:13 +0000576
Rui Ueyama136d27a2019-07-11 05:40:30 +0000577 for (const Symbol *sym : out.importSec->importedSymbols) {
578 if (auto *f = dyn_cast<FunctionSymbol>(sym))
579 out.typeSec->registerType(*f->signature);
580 else if (auto *e = dyn_cast<EventSymbol>(sym))
581 out.typeSec->registerType(*e->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000582 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000583
Rui Ueyama136d27a2019-07-11 05:40:30 +0000584 for (const InputFunction *f : out.functionSec->inputFunctions)
585 out.typeSec->registerType(f->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000586
Rui Ueyama136d27a2019-07-11 05:40:30 +0000587 for (const InputEvent *e : out.eventSec->inputEvents)
588 out.typeSec->registerType(e->signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000589}
590
Sam Clegg8fcf0122019-05-21 09:13:09 +0000591static void scanRelocations() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000592 for (ObjFile *file : symtab->objectFiles) {
593 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
594 for (InputChunk *chunk : file->functions)
595 scanRelocations(chunk);
596 for (InputChunk *chunk : file->segments)
597 scanRelocations(chunk);
598 for (auto &p : file->customSections)
599 scanRelocations(p);
Sam Clegg632c21792019-03-16 01:18:12 +0000600 }
601}
602
Sam Clegg8d146bb2018-01-09 23:56:44 +0000603void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000604 // Seal the import section, since other index spaces such as function and
605 // global are effected by the number of imports.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000606 out.importSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000607
Rui Ueyama136d27a2019-07-11 05:40:30 +0000608 for (InputFunction *func : symtab->syntheticFunctions)
609 out.functionSec->addFunction(func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000610
Rui Ueyama136d27a2019-07-11 05:40:30 +0000611 for (ObjFile *file : symtab->objectFiles) {
612 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
613 for (InputFunction *func : file->functions)
614 out.functionSec->addFunction(func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000615 }
616
Rui Ueyama136d27a2019-07-11 05:40:30 +0000617 for (InputGlobal *global : symtab->syntheticGlobals)
618 out.globalSec->addGlobal(global);
Sam Clegg93102972018-02-23 05:08:53 +0000619
Rui Ueyama136d27a2019-07-11 05:40:30 +0000620 for (ObjFile *file : symtab->objectFiles) {
621 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
622 for (InputGlobal *global : file->globals)
623 out.globalSec->addGlobal(global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000624 }
Heejin Ahne915a712018-12-08 06:17:43 +0000625
Rui Ueyama136d27a2019-07-11 05:40:30 +0000626 for (ObjFile *file : symtab->objectFiles) {
627 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
628 for (InputEvent *event : file->events)
629 out.eventSec->addEvent(event);
Heejin Ahne915a712018-12-08 06:17:43 +0000630 }
Sam Clegg7185a732019-08-13 17:02:02 +0000631
632 out.globalSec->assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +0000633}
634
Rui Ueyama136d27a2019-07-11 05:40:30 +0000635static StringRef getOutputDataSegmentName(StringRef name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000636 // With PIC code we currently only support a single data segment since
637 // we only have a single __memory_base to use as our base address.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000638 if (config->isPic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000639 return ".data";
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000640 // We only support one thread-local segment, so we must merge the segments
641 // despite --no-merge-data-segments.
642 // We also need to merge .tbss into .tdata so they share the same offsets.
643 if (name.startswith(".tdata") || name.startswith(".tbss"))
644 return ".tdata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000645 if (!config->mergeDataSegments)
646 return name;
647 if (name.startswith(".text."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000648 return ".text";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000649 if (name.startswith(".data."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000650 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000651 if (name.startswith(".bss."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000652 return ".bss";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000653 if (name.startswith(".rodata."))
Sam Clegg57694c52018-08-08 18:02:55 +0000654 return ".rodata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000655 return name;
Sam Cleggc94d3932017-11-17 18:14:09 +0000656}
657
658void Writer::createOutputSegments() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000659 for (ObjFile *file : symtab->objectFiles) {
660 for (InputSegment *segment : file->segments) {
661 if (!segment->live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000662 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000663 StringRef name = getOutputDataSegmentName(segment->getName());
664 OutputSegment *&s = segmentMap[name];
665 if (s == nullptr) {
666 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
Thomas Lively21143b92019-09-19 01:14:59 +0000667 s = make<OutputSegment>(name);
Thomas Lively09768c52019-09-04 19:50:39 +0000668 if (config->sharedMemory || name == ".tdata")
Rui Ueyama136d27a2019-07-11 05:40:30 +0000669 s->initFlags = WASM_SEGMENT_IS_PASSIVE;
Thomas Lively190dacc2019-10-15 19:05:11 +0000670 // Exported memories are guaranteed to be zero-initialized, so no need
671 // to emit data segments for bss sections.
672 // TODO: consider initializing bss sections with memory.fill
673 // instructions when memory is imported and bulk-memory is available.
674 if (!config->importMemory && !config->relocatable &&
675 name.startswith(".bss"))
676 s->isBss = true;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000677 segments.push_back(s);
Sam Cleggc94d3932017-11-17 18:14:09 +0000678 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000679 s->addInputSegment(segment);
680 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000681 }
682 }
Thomas Lively21143b92019-09-19 01:14:59 +0000683
684 // Sort segments by type, placing .bss last
685 std::stable_sort(segments.begin(), segments.end(),
686 [](const OutputSegment *a, const OutputSegment *b) {
687 auto order = [](StringRef name) {
688 return StringSwitch<int>(name)
689 .StartsWith(".rodata", 0)
690 .StartsWith(".data", 1)
691 .StartsWith(".tdata", 2)
692 .StartsWith(".bss", 4)
693 .Default(3);
694 };
695 return order(a->name) < order(b->name);
696 });
697
Thomas Lively0c3d4cf2019-09-19 21:51:52 +0000698 for (size_t i = 0; i < segments.size(); ++i)
Thomas Lively21143b92019-09-19 01:14:59 +0000699 segments[i]->index = i;
Sam Cleggc94d3932017-11-17 18:14:09 +0000700}
701
Rui Ueyama136d27a2019-07-11 05:40:30 +0000702static void createFunction(DefinedFunction *func, StringRef bodyContent) {
703 std::string functionBody;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000704 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000705 raw_string_ostream os(functionBody);
706 writeUleb128(os, bodyContent.size(), "function size");
707 os << bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000708 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000709 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
710 cast<SyntheticFunction>(func->function)->setBody(body);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000711}
712
713void Writer::createInitMemoryFunction() {
714 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
Thomas Lively09768c52019-09-04 19:50:39 +0000715 assert(WasmSym::initMemoryFlag);
716 uint32_t flagAddress = WasmSym::initMemoryFlag->getVirtualAddress();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000717 std::string bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000718 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000719 raw_string_ostream os(bodyContent);
720 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000721
Thomas Lively09768c52019-09-04 19:50:39 +0000722 if (segments.size()) {
723 // Initialize memory in a thread-safe manner. The thread that successfully
724 // increments the flag from 0 to 1 is is responsible for performing the
725 // memory initialization. Other threads go sleep on the flag until the
726 // first thread finishing initializing memory, increments the flag to 2,
727 // and wakes all the other threads. Once the flag has been set to 2,
728 // subsequently started threads will skip the sleep. All threads
729 // unconditionally drop their passive data segments once memory has been
730 // initialized. The generated code is as follows:
731 //
732 // (func $__wasm_init_memory
733 // (if
734 // (i32.atomic.rmw.cmpxchg align=2 offset=0
735 // (i32.const $__init_memory_flag)
736 // (i32.const 0)
737 // (i32.const 1)
738 // )
739 // (then
740 // (drop
741 // (i32.atomic.wait align=2 offset=0
742 // (i32.const $__init_memory_flag)
743 // (i32.const 1)
744 // (i32.const -1)
745 // )
746 // )
747 // )
748 // (else
749 // ( ... initialize data segments ... )
750 // (i32.atomic.store align=2 offset=0
751 // (i32.const $__init_memory_flag)
752 // (i32.const 2)
753 // )
754 // (drop
755 // (i32.atomic.notify align=2 offset=0
756 // (i32.const $__init_memory_flag)
757 // (i32.const -1u)
758 // )
759 // )
760 // )
761 // )
762 // ( ... drop data segments ... )
763 // )
764
765 // Atomically check whether this is the main thread.
766 writeI32Const(os, flagAddress, "flag address");
767 writeI32Const(os, 0, "expected flag value");
768 writeI32Const(os, 1, "flag value");
769 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
770 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
771 writeMemArg(os, 2, 0);
772 writeU8(os, WASM_OPCODE_IF, "IF");
773 writeU8(os, WASM_TYPE_NORESULT, "blocktype");
774
775 // Did not increment 0, so wait for main thread to initialize memory
776 writeI32Const(os, flagAddress, "flag address");
777 writeI32Const(os, 1, "expected flag value");
778 writeI64Const(os, -1, "timeout");
779 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
780 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
781 writeMemArg(os, 2, 0);
782 writeU8(os, WASM_OPCODE_DROP, "drop");
783
784 writeU8(os, WASM_OPCODE_ELSE, "ELSE");
785
786 // Did increment 0, so conditionally initialize passive data segments
787 for (const OutputSegment *s : segments) {
788 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
789 // destination address
790 writeI32Const(os, s->startVA, "destination address");
791 // source segment offset
792 writeI32Const(os, 0, "segment offset");
793 // memory region size
794 writeI32Const(os, s->size, "memory region size");
795 // memory.init instruction
796 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
797 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
798 writeUleb128(os, s->index, "segment index immediate");
799 writeU8(os, 0, "memory index immediate");
800 }
801 }
802
803 // Set flag to 2 to mark end of initialization
804 writeI32Const(os, flagAddress, "flag address");
805 writeI32Const(os, 2, "flag value");
806 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
807 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
808 writeMemArg(os, 2, 0);
809
810 // Notify any waiters that memory initialization is complete
811 writeI32Const(os, flagAddress, "flag address");
812 writeI32Const(os, -1, "number of waiters");
813 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
814 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
815 writeMemArg(os, 2, 0);
816 writeU8(os, WASM_OPCODE_DROP, "drop");
817
818 writeU8(os, WASM_OPCODE_END, "END");
819
820 // Unconditionally drop passive data segments
821 for (const OutputSegment *s : segments) {
822 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
823 // data.drop instruction
824 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
825 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
826 writeUleb128(os, s->index, "segment index immediate");
827 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000828 }
829 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000830 writeU8(os, WASM_OPCODE_END, "END");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000831 }
832
Rui Ueyama136d27a2019-07-11 05:40:30 +0000833 createFunction(WasmSym::initMemory, bodyContent);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000834}
835
Sam Clegg09137be2019-04-04 18:40:51 +0000836// For -shared (PIC) output, we create create a synthetic function which will
837// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000838// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
839// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000840void Writer::createApplyRelocationsFunction() {
841 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
842 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000843 std::string bodyContent;
Sam Clegg09137be2019-04-04 18:40:51 +0000844 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000845 raw_string_ostream os(bodyContent);
846 writeUleb128(os, 0, "num locals");
847 for (const OutputSegment *seg : segments)
848 for (const InputSegment *inSeg : seg->inputSegments)
849 inSeg->generateRelocationCode(os);
850 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg09137be2019-04-04 18:40:51 +0000851 }
852
Rui Ueyama136d27a2019-07-11 05:40:30 +0000853 createFunction(WasmSym::applyRelocs, bodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000854}
Sam Clegg50686852018-01-12 18:35:13 +0000855
856// Create synthetic "__wasm_call_ctors" function based on ctor functions
857// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000858void Writer::createCallCtorsFunction() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000859 if (!WasmSym::callCtors->isLive())
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000860 return;
861
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000862 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000863 std::string bodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000864 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000865 raw_string_ostream os(bodyContent);
866 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000867
Rui Ueyama136d27a2019-07-11 05:40:30 +0000868 if (config->isPic) {
869 writeU8(os, WASM_OPCODE_CALL, "CALL");
870 writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
Sam Clegg09137be2019-04-04 18:40:51 +0000871 "function index");
872 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000873
874 // Call constructors
Rui Ueyama136d27a2019-07-11 05:40:30 +0000875 for (const WasmInitEntry &f : initFunctions) {
876 writeU8(os, WASM_OPCODE_CALL, "CALL");
877 writeUleb128(os, f.sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000878 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000879 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000880 }
881
Rui Ueyama136d27a2019-07-11 05:40:30 +0000882 createFunction(WasmSym::callCtors, bodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000883}
884
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000885void Writer::createInitTLSFunction() {
886 if (!WasmSym::initTLS->isLive())
887 return;
888
889 std::string bodyContent;
890 {
891 raw_string_ostream os(bodyContent);
892
893 OutputSegment *tlsSeg = nullptr;
894 for (auto *seg : segments) {
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000895 if (seg->name == ".tdata") {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000896 tlsSeg = seg;
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000897 break;
898 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000899 }
900
901 writeUleb128(os, 0, "num locals");
902 if (tlsSeg) {
903 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
904 writeUleb128(os, 0, "local index");
905
906 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
907 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
908
909 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
910 writeUleb128(os, 0, "local index");
911
Thomas Lively09768c52019-09-04 19:50:39 +0000912 writeI32Const(os, 0, "segment offset");
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000913
Thomas Lively09768c52019-09-04 19:50:39 +0000914 writeI32Const(os, tlsSeg->size, "memory region size");
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000915
916 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
917 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
918 writeUleb128(os, tlsSeg->index, "segment index immediate");
919 writeU8(os, 0, "memory index immediate");
920 }
921 writeU8(os, WASM_OPCODE_END, "end function");
922 }
923
924 createFunction(WasmSym::initTLS, bodyContent);
925}
926
Sam Clegg50686852018-01-12 18:35:13 +0000927// Populate InitFunctions vector with init functions from all input objects.
928// This is then used either when creating the output linking section or to
929// synthesize the "__wasm_call_ctors" function.
930void Writer::calculateInitFunctions() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000931 if (!config->relocatable && !WasmSym::callCtors->isLive())
Sam Clegg61f13b32019-03-02 04:55:02 +0000932 return;
933
Rui Ueyama136d27a2019-07-11 05:40:30 +0000934 for (ObjFile *file : symtab->objectFiles) {
935 const WasmLinkingData &l = file->getWasmObj()->linkingData();
936 for (const WasmInitFunc &f : l.InitFunctions) {
937 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000938 // comdat exclusions can cause init functions be discarded.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000939 if (sym->isDiscarded())
Sam Cleggfd54fa52019-06-07 06:00:46 +0000940 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000941 assert(sym->isLive());
942 if (*sym->signature != WasmSignature{{}, {}})
943 error("invalid signature for init func: " + toString(*sym));
Sam Cleggaccad762019-07-17 18:43:36 +0000944 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000945 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000946 }
Sam Clegg50686852018-01-12 18:35:13 +0000947 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000948
Sam Clegg50686852018-01-12 18:35:13 +0000949 // Sort in order of priority (lowest first) so that they are called
950 // in the correct order.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000951 llvm::stable_sort(initFunctions,
952 [](const WasmInitEntry &l, const WasmInitEntry &r) {
953 return l.priority < r.priority;
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000954 });
Sam Clegg50686852018-01-12 18:35:13 +0000955}
956
Sam Clegg8fcf0122019-05-21 09:13:09 +0000957void Writer::createSyntheticSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000958 out.dylinkSec = make<DylinkSection>();
959 out.typeSec = make<TypeSection>();
960 out.importSec = make<ImportSection>();
961 out.functionSec = make<FunctionSection>();
962 out.tableSec = make<TableSection>();
963 out.memorySec = make<MemorySection>();
964 out.globalSec = make<GlobalSection>();
965 out.eventSec = make<EventSection>();
966 out.exportSec = make<ExportSection>();
Thomas Lively09768c52019-09-04 19:50:39 +0000967 out.startSec = make<StartSection>(segments.size());
Sam Clegg1a1df722019-08-27 04:19:34 +0000968 out.elemSec = make<ElemSection>();
Thomas Lively190dacc2019-10-15 19:05:11 +0000969 out.dataCountSec = make<DataCountSection>(segments);
Rui Ueyama136d27a2019-07-11 05:40:30 +0000970 out.linkingSec = make<LinkingSection>(initFunctions, segments);
971 out.nameSec = make<NameSection>();
972 out.producersSec = make<ProducersSection>();
973 out.targetFeaturesSec = make<TargetFeaturesSection>();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000974}
975
Sam Cleggc94d3932017-11-17 18:14:09 +0000976void Writer::run() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000977 if (config->relocatable || config->isPic)
978 config->globalBase = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000979
Sam Cleggbfb75342018-11-15 00:37:21 +0000980 // For PIC code the table base is assigned dynamically by the loader.
981 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
Sam Clegg7185a732019-08-13 17:02:02 +0000982 if (!config->isPic) {
Sam Clegg1a1df722019-08-27 04:19:34 +0000983 config->tableBase = 1;
Sam Clegg7185a732019-08-13 17:02:02 +0000984 if (WasmSym::definedTableBase)
Sam Clegg1a1df722019-08-27 04:19:34 +0000985 WasmSym::definedTableBase->setVirtualAddress(config->tableBase);
Sam Clegg7185a732019-08-13 17:02:02 +0000986 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000987
Sam Clegg8fcf0122019-05-21 09:13:09 +0000988 log("-- createOutputSegments");
989 createOutputSegments();
990 log("-- createSyntheticSections");
991 createSyntheticSections();
992 log("-- populateProducers");
993 populateProducers();
994 log("-- populateTargetFeatures");
995 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000996 log("-- calculateImports");
997 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000998 log("-- layoutMemory");
999 layoutMemory();
1000
Rui Ueyama136d27a2019-07-11 05:40:30 +00001001 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +00001002 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
1003 // This has to be done after memory layout is performed.
Rui Ueyama136d27a2019-07-11 05:40:30 +00001004 for (const OutputSegment *seg : segments)
1005 addStartStopSymbols(seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +00001006 }
1007
Sam Cleggb9889bb2019-05-23 09:41:03 +00001008 log("-- scanRelocations");
1009 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +00001010 log("-- assignIndexes");
1011 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +00001012 log("-- calculateInitFunctions");
1013 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +00001014
Rui Ueyama136d27a2019-07-11 05:40:30 +00001015 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +00001016 // Create linker synthesized functions
Thomas Lively09768c52019-09-04 19:50:39 +00001017 if (config->sharedMemory)
Thomas Lively6004d9a2019-07-03 22:04:54 +00001018 createInitMemoryFunction();
Rui Ueyama136d27a2019-07-11 05:40:30 +00001019 if (config->isPic)
Sam Clegg09137be2019-04-04 18:40:51 +00001020 createApplyRelocationsFunction();
1021 createCallCtorsFunction();
1022 }
Sam Clegg4bce63a2019-05-23 10:06:03 +00001023
Guanzhong Chen0cb776e2019-08-06 20:09:04 +00001024 if (!config->relocatable && config->sharedMemory && !config->shared)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +00001025 createInitTLSFunction();
1026
1027 if (errorCount())
1028 return;
1029
Sam Clegg4bce63a2019-05-23 10:06:03 +00001030 log("-- calculateTypes");
1031 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001032 log("-- calculateExports");
1033 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001034 log("-- calculateCustomSections");
1035 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +00001036 log("-- populateSymtab");
1037 populateSymtab();
1038 log("-- addSections");
1039 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +00001040
Rui Ueyama136d27a2019-07-11 05:40:30 +00001041 if (errorHandler().verbose) {
1042 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
Sam Clegg937b9552019-09-24 20:52:12 +00001043 log("Defined Globals : " + Twine(out.globalSec->numGlobals()));
Rui Ueyama136d27a2019-07-11 05:40:30 +00001044 log("Defined Events : " + Twine(out.eventSec->inputEvents.size()));
Rui Ueyama7e296ad2019-07-10 09:10:01 +00001045 log("Function Imports : " +
Rui Ueyama136d27a2019-07-11 05:40:30 +00001046 Twine(out.importSec->getNumImportedFunctions()));
1047 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals()));
1048 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents()));
1049 for (ObjFile *file : symtab->objectFiles)
1050 file->dumpInfo();
Sam Cleggc94d3932017-11-17 18:14:09 +00001051 }
1052
Sam Cleggc94d3932017-11-17 18:14:09 +00001053 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +00001054 log("-- finalizeSections");
1055 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +00001056
1057 log("-- openFile");
1058 openFile();
1059 if (errorCount())
1060 return;
1061
1062 writeHeader();
1063
1064 log("-- writeSections");
1065 writeSections();
1066 if (errorCount())
1067 return;
1068
Rui Ueyama136d27a2019-07-11 05:40:30 +00001069 if (Error e = buffer->commit())
1070 fatal("failed to write the output file: " + toString(std::move(e)));
Sam Cleggc94d3932017-11-17 18:14:09 +00001071}
1072
1073// Open a result file.
1074void Writer::openFile() {
Rui Ueyama136d27a2019-07-11 05:40:30 +00001075 log("writing: " + config->outputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001076
Rui Ueyama136d27a2019-07-11 05:40:30 +00001077 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1078 FileOutputBuffer::create(config->outputFile, fileSize,
Sam Cleggc94d3932017-11-17 18:14:09 +00001079 FileOutputBuffer::F_executable);
1080
Rui Ueyama136d27a2019-07-11 05:40:30 +00001081 if (!bufferOrErr)
1082 error("failed to open " + config->outputFile + ": " +
1083 toString(bufferOrErr.takeError()));
Sam Cleggc94d3932017-11-17 18:14:09 +00001084 else
Rui Ueyama136d27a2019-07-11 05:40:30 +00001085 buffer = std::move(*bufferOrErr);
Sam Cleggc94d3932017-11-17 18:14:09 +00001086}
1087
1088void Writer::createHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +00001089 raw_string_ostream os(header);
1090 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1091 writeU32(os, WasmVersion, "wasm version");
1092 os.flush();
1093 fileSize += header.size();
Sam Cleggc94d3932017-11-17 18:14:09 +00001094}
1095
Fangrui Song33c59ab2019-10-10 05:25:39 +00001096void writeResult() { Writer().run(); }
1097
1098} // namespace wasm
1099} // namespace lld