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/Object/Wasm.h"
28 
29 namespace lld {
30 namespace wasm {
31 
32 class ObjFile;
33 class OutputSegment;
34 class OutputSection;
35 
36 class InputChunk {
37 public:
38   enum Kind { DataSegment, Function, SyntheticFunction, Section };
39 
40   Kind kind() const { return sectionKind; }
41 
42   virtual uint32_t getSize() const { return data().size(); }
43   virtual uint32_t getInputSize() const { return getSize(); };
44 
45   virtual void writeTo(uint8_t *buf) const;
46 
47   ArrayRef<WasmRelocation> getRelocations() const { return relocations; }
48   void setRelocations(ArrayRef<WasmRelocation> rs) { relocations = rs; }
49 
50   uint64_t getOffset(uint64_t offset) const { return outSecOff + offset; }
51   virtual StringRef getName() const = 0;
52   virtual StringRef getDebugName() const = 0;
53   virtual uint32_t getComdat() const = 0;
54   StringRef getComdatName() const;
55   virtual uint32_t getInputSectionOffset() const = 0;
56 
57   size_t getNumRelocations() const { return relocations.size(); }
58   void writeRelocations(llvm::raw_ostream &os) const;
59 
60   ObjFile *file;
61   OutputSection *outputSec = nullptr;
62 
63   // After assignAddresses is called, this represents the offset from
64   // the beginning of the output section this chunk was assigned to.
65   int32_t outSecOff = 0;
66 
67   // Signals that the section is part of the output.  The garbage collector,
68   // and COMDAT handling can set a sections' Live bit.
69   // If GC is disabled, all sections start out as live by default.
70   unsigned live : 1;
71 
72   // Signals the chunk was discarded by COMDAT handling.
73   unsigned discarded : 1;
74 
75 protected:
76   InputChunk(ObjFile *f, Kind k)
77       : file(f), live(!config->gcSections), discarded(false), sectionKind(k) {}
78   virtual ~InputChunk() = default;
79   virtual ArrayRef<uint8_t> data() const = 0;
80   virtual uint64_t getTombstone() const { return 0; }
81 
82   // Verifies the existing data at relocation targets matches our expectations.
83   // This is performed only debug builds as an extra sanity check.
84   void verifyRelocTargets() const;
85 
86   ArrayRef<WasmRelocation> relocations;
87   Kind sectionKind;
88 };
89 
90 // Represents a WebAssembly data segment which can be included as part of
91 // an output data segments.  Note that in WebAssembly, unlike ELF and other
92 // formats, used the term "data segment" to refer to the continuous regions of
93 // memory that make on the data section. See:
94 // https://webassembly.github.io/spec/syntax/modules.html#syntax-data
95 //
96 // For example, by default, clang will produce a separate data section for
97 // each global variable.
98 class InputSegment : public InputChunk {
99 public:
100   InputSegment(const WasmSegment &seg, ObjFile *f)
101       : InputChunk(f, InputChunk::DataSegment), segment(seg) {
102     alignment = segment.Data.Alignment;
103   }
104 
105   static bool classof(const InputChunk *c) { return c->kind() == DataSegment; }
106 
107   void generateRelocationCode(raw_ostream &os) const;
108 
109   StringRef getName() const override { return segment.Data.Name; }
110   StringRef getDebugName() const override { return StringRef(); }
111   uint32_t getComdat() const override { return segment.Data.Comdat; }
112   uint32_t getInputSectionOffset() const override {
113     return segment.SectionOffset;
114   }
115   uint64_t getVA(uint64_t offset = 0) const;
116 
117   const OutputSegment *outputSeg = nullptr;
118   uint32_t outputSegmentOffset = 0;
119   uint32_t alignment = 0;
120 
121 protected:
122   ArrayRef<uint8_t> data() const override { return segment.Data.Content; }
123 
124   const WasmSegment &segment;
125 };
126 
127 // Represents a single wasm function within and input file.  These are
128 // combined to create the final output CODE section.
129 class InputFunction : public InputChunk {
130 public:
131   InputFunction(const WasmSignature &s, const WasmFunction *func, ObjFile *f)
132       : InputChunk(f, InputChunk::Function), signature(s), function(func),
133         exportName(func && func->ExportName.hasValue()
134                        ? (*func->ExportName).str()
135                        : llvm::Optional<std::string>()) {}
136 
137   static bool classof(const InputChunk *c) {
138     return c->kind() == InputChunk::Function ||
139            c->kind() == InputChunk::SyntheticFunction;
140   }
141 
142   void writeTo(uint8_t *buf) const override;
143   StringRef getName() const override { return function->SymbolName; }
144   StringRef getDebugName() const override { return function->DebugName; }
145   llvm::Optional<StringRef> getExportName() const {
146     return exportName.hasValue() ? llvm::Optional<StringRef>(*exportName)
147                                  : llvm::Optional<StringRef>();
148   }
149   void setExportName(std::string exportName) { this->exportName = exportName; }
150   uint32_t getComdat() const override { return function->Comdat; }
151   uint32_t getFunctionInputOffset() const { return getInputSectionOffset(); }
152   uint32_t getFunctionCodeOffset() const { return function->CodeOffset; }
153   uint32_t getSize() const override {
154     if (config->compressRelocations && file) {
155       assert(compressedSize);
156       return compressedSize;
157     }
158     return data().size();
159   }
160   uint32_t getInputSize() const override { return function->Size; }
161   uint32_t getFunctionIndex() const { return functionIndex.getValue(); }
162   bool hasFunctionIndex() const { return functionIndex.hasValue(); }
163   void setFunctionIndex(uint32_t index);
164   uint32_t getInputSectionOffset() const override {
165     return function->CodeSectionOffset;
166   }
167   uint32_t getTableIndex() const { return tableIndex.getValue(); }
168   bool hasTableIndex() const { return tableIndex.hasValue(); }
169   void setTableIndex(uint32_t index);
170 
171   // The size of a given input function can depend on the values of the
172   // LEB relocations within it.  This finalizeContents method is called after
173   // all the symbol values have be calculated but before getSize() is ever
174   // called.
175   void calculateSize();
176 
177   const WasmSignature &signature;
178 
179 protected:
180   ArrayRef<uint8_t> data() const override {
181     assert(!config->compressRelocations);
182     return file->codeSection->Content.slice(getInputSectionOffset(),
183                                             function->Size);
184   }
185 
186   const WasmFunction *function;
187   llvm::Optional<std::string> exportName;
188   llvm::Optional<uint32_t> functionIndex;
189   llvm::Optional<uint32_t> tableIndex;
190   uint32_t compressedFuncSize = 0;
191   uint32_t compressedSize = 0;
192 };
193 
194 class SyntheticFunction : public InputFunction {
195 public:
196   SyntheticFunction(const WasmSignature &s, StringRef name,
197                     StringRef debugName = {})
198       : InputFunction(s, nullptr, nullptr), name(name), debugName(debugName) {
199     sectionKind = InputChunk::SyntheticFunction;
200   }
201 
202   static bool classof(const InputChunk *c) {
203     return c->kind() == InputChunk::SyntheticFunction;
204   }
205 
206   StringRef getName() const override { return name; }
207   StringRef getDebugName() const override { return debugName; }
208   uint32_t getComdat() const override { return UINT32_MAX; }
209 
210   void setBody(ArrayRef<uint8_t> body_) { body = body_; }
211 
212 protected:
213   ArrayRef<uint8_t> data() const override { return body; }
214 
215   StringRef name;
216   StringRef debugName;
217   ArrayRef<uint8_t> body;
218 };
219 
220 // Represents a single Wasm Section within an input file.
221 class InputSection : public InputChunk {
222 public:
223   InputSection(const WasmSection &s, ObjFile *f)
224       : InputChunk(f, InputChunk::Section), section(s), tombstoneValue(getTombstoneForSection(s.Name)) {
225     assert(section.Type == llvm::wasm::WASM_SEC_CUSTOM);
226   }
227 
228   StringRef getName() const override { return section.Name; }
229   StringRef getDebugName() const override { return StringRef(); }
230   uint32_t getComdat() const override { return section.Comdat; }
231 
232 protected:
233   ArrayRef<uint8_t> data() const override { return section.Content; }
234 
235   // Offset within the input section.  This is only zero since this chunk
236   // type represents an entire input section, not part of one.
237   uint32_t getInputSectionOffset() const override { return 0; }
238   uint64_t getTombstone() const override { return tombstoneValue; }
239   static uint64_t getTombstoneForSection(StringRef name);
240 
241   const WasmSection &section;
242   const uint64_t tombstoneValue;
243 };
244 
245 } // namespace wasm
246 
247 std::string toString(const wasm::InputChunk *);
248 StringRef relocTypeToString(uint8_t relocType);
249 
250 } // namespace lld
251 
252 #endif // LLD_WASM_INPUT_CHUNKS_H
253