1//===- InputChunks.h --------------------------------------------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// An InputChunks represents an indivisible opaque region of a input wasm file.
10// i.e. a single wasm data segment or a single wasm function.
11//
12// They are written directly to the mmap'd output file after which relocations
13// are applied. Because each Chunk is independent they can be written in
14// parallel.
15//
16// Chunks are also unit on which garbage collection (--gc-sections) operates.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLD_WASM_INPUT_CHUNKS_H
21#define LLD_WASM_INPUT_CHUNKS_H
22
23#include "Config.h"
24#include "InputFiles.h"
25#include "lld/Common/ErrorHandler.h"
26#include "lld/Common/LLVM.h"
27#include "llvm/ADT/CachedHashString.h"
28#include "llvm/MC/StringTableBuilder.h"
29#include "llvm/Object/Wasm.h"
30#include <optional>
31
32namespace lld {
33namespace wasm {
34
35class ObjFile;
36class OutputSegment;
37class OutputSection;
38
39class InputChunk {
40public:
41 enum Kind {
42 DataSegment,
43 Merge,
44 MergedChunk,
45 Function,
46 SyntheticFunction,
47 Section,
48 };
49
50 StringRef name;
51 StringRef debugName;
52
53 Kind kind() const { return (Kind)sectionKind; }
54
55 uint32_t getSize() const;
56 uint32_t getInputSize() const;
57
58 void writeTo(uint8_t *buf) const;
59 void relocate(uint8_t *buf) const;
60
61 ArrayRef<WasmRelocation> getRelocations() const { return relocations; }
62 void setRelocations(ArrayRef<WasmRelocation> rs) { relocations = rs; }
63
64 // Translate an offset into the input chunk to an offset in the output
65 // section.
66 uint64_t getOffset(uint64_t offset) const;
67 // Translate an offset into the input chunk into an offset into the output
68 // chunk. For data segments (InputSegment) this will return and offset into
69 // the output segment. For MergeInputChunk, this will return an offset into
70 // the parent merged chunk. For other chunk types this is no-op and we just
71 // return unmodified offset.
72 uint64_t getChunkOffset(uint64_t offset) const;
73 uint64_t getVA(uint64_t offset = 0) const;
74
75 uint32_t getComdat() const { return comdat; }
76 StringRef getComdatName() const;
77 uint32_t getInputSectionOffset() const { return inputSectionOffset; }
78
79 size_t getNumRelocations() const { return relocations.size(); }
80 size_t getNumLiveRelocations() const;
81 void writeRelocations(llvm::raw_ostream &os) const;
82 bool generateRelocationCode(raw_ostream &os) const;
83
84 bool isTLS() const { return flags & llvm::wasm::WASM_SEG_FLAG_TLS; }
85 bool isRetained() const { return flags & llvm::wasm::WASM_SEG_FLAG_RETAIN; }
86
87 ObjFile *file;
88 OutputSection *outputSec = nullptr;
89 uint32_t comdat = UINT32_MAX;
90 uint32_t inputSectionOffset = 0;
91 uint32_t alignment;
92 uint32_t flags;
93
94 // Only applies to data segments.
95 uint32_t outputSegmentOffset = 0;
96 const OutputSegment *outputSeg = nullptr;
97
98 // After assignAddresses is called, this represents the offset from
99 // the beginning of the output section this chunk was assigned to.
100 //
101 // WASM sections can be up to 4GB. We use a larger, signed integer here to
102 // be able to detect section size overflow instead of a silent wrap-around
103 // and corrupted output sections.
104 int64_t outSecOff = 0;
105
106 uint8_t sectionKind : 3;
107
108 // Signals that the section is part of the output. The garbage collector,
109 // and COMDAT handling can set a sections' Live bit.
110 // If GC is disabled, all sections start out as live by default.
111 unsigned live : 1;
112
113 // Signals the chunk was discarded by COMDAT handling.
114 unsigned discarded : 1;
115
116protected:
117 InputChunk(ObjFile *f, Kind k, StringRef name, uint32_t alignment = 0,
118 uint32_t flags = 0)
119 : name(name), file(f), alignment(alignment), flags(flags), sectionKind(k),
120 live(!ctx.arg.gcSections), discarded(false) {}
121 ArrayRef<uint8_t> data() const { return rawData; }
122 uint64_t getTombstone() const;
123
124 ArrayRef<WasmRelocation> relocations;
125 ArrayRef<uint8_t> rawData;
126};
127
128// Represents a WebAssembly data segment which can be included as part of
129// an output data segments. Note that in WebAssembly, unlike ELF and other
130// formats, used the term "data segment" to refer to the continuous regions of
131// memory that make on the data section. See:
132// https://webassembly.github.io/spec/syntax/modules.html#syntax-data
133//
134// For example, by default, clang will produce a separate data section for
135// each global variable.
136class InputSegment : public InputChunk {
137public:
138 InputSegment(const WasmSegment &seg, ObjFile *f)
139 : InputChunk(f, InputChunk::DataSegment, seg.Data.Name,
140 seg.Data.Alignment, seg.Data.LinkingFlags),
141 segment(seg) {
142 rawData = segment.Data.Content;
143 comdat = segment.Data.Comdat;
144 inputSectionOffset = segment.SectionOffset;
145 }
146
147 static bool classof(const InputChunk *c) { return c->kind() == DataSegment; }
148
149protected:
150 const WasmSegment &segment;
151};
152
153class SyntheticMergedChunk;
154
155// Merge segment handling copied from lld/ELF/InputSection.h. Keep in sync
156// where possible.
157
158// SectionPiece represents a piece of splittable segment contents.
159// We allocate a lot of these and binary search on them. This means that they
160// have to be as compact as possible, which is why we don't store the size (can
161// be found by looking at the next one).
162struct SectionPiece {
163 SectionPiece(size_t off, uint32_t hash, bool live)
164 : inputOff(off), live(live || !ctx.arg.gcSections), hash(hash >> 1) {}
165
166 uint32_t inputOff;
167 uint32_t live : 1;
168 uint32_t hash : 31;
169 uint64_t outputOff = 0;
170};
171
172static_assert(sizeof(SectionPiece) == 16, "SectionPiece is too big");
173
174// This corresponds segments marked as WASM_SEG_FLAG_STRINGS.
175class MergeInputChunk : public InputChunk {
176public:
177 MergeInputChunk(const WasmSegment &seg, ObjFile *f)
178 : InputChunk(f, Merge, seg.Data.Name, seg.Data.Alignment,
179 seg.Data.LinkingFlags) {
180 rawData = seg.Data.Content;
181 comdat = seg.Data.Comdat;
182 inputSectionOffset = seg.SectionOffset;
183 }
184
185 MergeInputChunk(const WasmSection &s, ObjFile *f, uint32_t alignment)
186 : InputChunk(f, Merge, s.Name, alignment,
187 llvm::wasm::WASM_SEG_FLAG_STRINGS) {
188 assert(s.Type == llvm::wasm::WASM_SEC_CUSTOM);
189 comdat = s.Comdat;
190 rawData = s.Content;
191 }
192
193 static bool classof(const InputChunk *s) { return s->kind() == Merge; }
194 void splitIntoPieces();
195
196 // Translate an offset in the input section to an offset in the parent
197 // MergeSyntheticSection.
198 uint64_t getParentOffset(uint64_t offset) const;
199
200 // Splittable sections are handled as a sequence of data
201 // rather than a single large blob of data.
202 std::vector<SectionPiece> pieces;
203
204 // Returns I'th piece's data. This function is very hot when
205 // string merging is enabled, so we want to inline.
206 LLVM_ATTRIBUTE_ALWAYS_INLINE
207 llvm::CachedHashStringRef getData(size_t i) const {
208 size_t begin = pieces[i].inputOff;
209 size_t end =
210 (pieces.size() - 1 == i) ? data().size() : pieces[i + 1].inputOff;
211 return {toStringRef(Input: data().slice(N: begin, M: end - begin)), pieces[i].hash};
212 }
213
214 // Returns the SectionPiece at a given input section offset.
215 SectionPiece *getSectionPiece(uint64_t offset);
216 const SectionPiece *getSectionPiece(uint64_t offset) const {
217 return const_cast<MergeInputChunk *>(this)->getSectionPiece(offset);
218 }
219
220 SyntheticMergedChunk *parent = nullptr;
221
222private:
223 void splitStrings(ArrayRef<uint8_t> a);
224};
225
226// SyntheticMergedChunk is a class that allows us to put mergeable
227// sections with different attributes in a single output sections. To do that we
228// put them into SyntheticMergedChunk synthetic input sections which are
229// attached to regular output sections.
230class SyntheticMergedChunk : public InputChunk {
231public:
232 SyntheticMergedChunk(StringRef name, uint32_t alignment, uint32_t flags)
233 : InputChunk(nullptr, InputChunk::MergedChunk, name, alignment, flags),
234 builder(llvm::StringTableBuilder::RAW, llvm::Align(1ULL << alignment)) {
235 }
236
237 static bool classof(const InputChunk *c) {
238 return c->kind() == InputChunk::MergedChunk;
239 }
240
241 void addMergeChunk(MergeInputChunk *ms) {
242 comdat = ms->getComdat();
243 alignment = std::max(a: alignment, b: ms->alignment);
244 ms->parent = this;
245 chunks.push_back(x: ms);
246 }
247
248 void finalizeContents();
249
250 llvm::StringTableBuilder builder;
251
252protected:
253 std::vector<MergeInputChunk *> chunks;
254};
255
256// Represents a single wasm function within and input file. These are
257// combined to create the final output CODE section.
258class InputFunction : public InputChunk {
259public:
260 InputFunction(const WasmSignature &s, const WasmFunction *func, ObjFile *f)
261 : InputChunk(f, InputChunk::Function, func->SymbolName), signature(s),
262 function(func),
263 exportName(func && func->ExportName ? (*func->ExportName).str()
264 : std::optional<std::string>()) {
265 inputSectionOffset = function->CodeSectionOffset;
266 rawData =
267 file->codeSection->Content.slice(N: inputSectionOffset, M: function->Size);
268 debugName = function->DebugName;
269 comdat = function->Comdat;
270 assert(s.Kind != WasmSignature::Placeholder);
271 }
272
273 InputFunction(StringRef name, const WasmSignature &s)
274 : InputChunk(nullptr, InputChunk::Function, name), signature(s) {
275 assert(s.Kind == WasmSignature::Function);
276 }
277
278 static bool classof(const InputChunk *c) {
279 return c->kind() == InputChunk::Function ||
280 c->kind() == InputChunk::SyntheticFunction;
281 }
282
283 std::optional<StringRef> getExportName() const {
284 return exportName ? std::optional<StringRef>(*exportName)
285 : std::optional<StringRef>();
286 }
287 void setExportName(std::string exportName) { this->exportName = exportName; }
288 uint32_t getFunctionInputOffset() const { return getInputSectionOffset(); }
289 uint32_t getFunctionCodeOffset() const {
290 // For generated synthetic functions, such as unreachable stubs generated
291 // for signature mismatches, 'function' reference does not exist. This
292 // function is used to get function offsets for .debug_info section, and for
293 // those generated stubs function offsets are not meaningful anyway. So just
294 // return 0 in those cases.
295 return function ? function->CodeOffset : 0;
296 }
297 uint32_t getFunctionIndex() const { return *functionIndex; }
298 bool hasFunctionIndex() const { return functionIndex.has_value(); }
299 void setFunctionIndex(uint32_t index);
300 uint32_t getTableIndex() const { return *tableIndex; }
301 bool hasTableIndex() const { return tableIndex.has_value(); }
302 void setTableIndex(uint32_t index);
303 void writeCompressed(uint8_t *buf) const;
304
305 // The size of a given input function can depend on the values of the
306 // LEB relocations within it. This finalizeContents method is called after
307 // all the symbol values have be calculated but before getSize() is ever
308 // called.
309 void calculateSize();
310
311 const WasmSignature &signature;
312
313 uint32_t getCompressedSize() const {
314 assert(compressedSize);
315 return compressedSize;
316 }
317
318 const WasmFunction *function = nullptr;
319
320protected:
321 std::optional<std::string> exportName;
322 std::optional<uint32_t> functionIndex;
323 std::optional<uint32_t> tableIndex;
324 uint32_t compressedFuncSize = 0;
325 uint32_t compressedSize = 0;
326};
327
328class SyntheticFunction : public InputFunction {
329public:
330 SyntheticFunction(const WasmSignature &s, StringRef name,
331 StringRef debugName = {})
332 : InputFunction(name, s) {
333 sectionKind = InputChunk::SyntheticFunction;
334 this->debugName = debugName;
335 }
336
337 static bool classof(const InputChunk *c) {
338 return c->kind() == InputChunk::SyntheticFunction;
339 }
340
341 void setBody(ArrayRef<uint8_t> body) { rawData = body; }
342};
343
344// Represents a single Wasm Section within an input file.
345class InputSection : public InputChunk {
346public:
347 InputSection(const WasmSection &s, ObjFile *f, uint32_t alignment)
348 : InputChunk(f, InputChunk::Section, s.Name, alignment),
349 tombstoneValue(getTombstoneForSection(name: s.Name)), section(s) {
350 assert(section.Type == llvm::wasm::WASM_SEC_CUSTOM);
351 comdat = section.Comdat;
352 rawData = section.Content;
353 }
354
355 static bool classof(const InputChunk *c) {
356 return c->kind() == InputChunk::Section;
357 }
358
359 const uint64_t tombstoneValue;
360
361protected:
362 static uint64_t getTombstoneForSection(StringRef name);
363 const WasmSection &section;
364};
365
366} // namespace wasm
367
368std::string toString(const wasm::InputChunk *);
369StringRef relocTypeToString(uint8_t relocType);
370
371} // namespace lld
372
373#endif // LLD_WASM_INPUT_CHUNKS_H
374