1//===- OutputSections.cpp -------------------------------------------------===//
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#include "OutputSections.h"
10#include "InputChunks.h"
11#include "InputElement.h"
12#include "InputFiles.h"
13#include "OutputSegment.h"
14#include "WriterUtils.h"
15#include "lld/Common/ErrorHandler.h"
16#include "lld/Common/Memory.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Support/LEB128.h"
19
20#define DEBUG_TYPE "lld"
21
22using namespace llvm;
23using namespace llvm::wasm;
24
25namespace lld {
26
27// Returns a string, e.g. "FUNCTION(.text)".
28std::string toString(const wasm::OutputSection &sec) {
29 if (!sec.name.empty())
30 return (sec.getSectionName() + "(" + sec.name + ")").str();
31 return std::string(sec.getSectionName());
32}
33
34namespace wasm {
35StringRef OutputSection::getSectionName() const {
36 return sectionTypeToString(type);
37}
38
39void OutputSection::createHeader(size_t bodySize) {
40 raw_string_ostream os(header);
41 debugWrite(offset: os.tell(), msg: "section type [" + getSectionName() + "]");
42 encodeULEB128(Value: type, OS&: os);
43 writeUleb128(os, number: bodySize, msg: "section size");
44 log(msg: "createHeader: " + toString(sec: *this) + " body=" + Twine(bodySize) +
45 " total=" + Twine(getSize()));
46}
47
48void CodeSection::finalizeContents() {
49 raw_string_ostream os(codeSectionHeader);
50 writeUleb128(os, number: functions.size(), msg: "function count");
51 bodySize = codeSectionHeader.size();
52
53 for (InputFunction *func : functions) {
54 func->outputSec = this;
55 func->outSecOff = bodySize;
56 func->calculateSize();
57 // All functions should have a non-empty body at this point
58 assert(func->getSize());
59 bodySize += func->getSize();
60 }
61
62 if (bodySize > UINT32_MAX) {
63 error(msg: "section too large to encode: " + Twine(bodySize) + " bytes");
64 }
65
66 createHeader(bodySize);
67}
68
69void CodeSection::writeTo(uint8_t *buf) {
70 log(msg: "writing " + toString(sec: *this) + " offset=" + Twine(offset) +
71 " size=" + Twine(getSize()));
72 log(msg: " headersize=" + Twine(header.size()));
73 log(msg: " codeheadersize=" + Twine(codeSectionHeader.size()));
74 buf += offset;
75
76 // Write section header
77 memcpy(dest: buf, src: header.data(), n: header.size());
78 buf += header.size();
79
80 // Write code section headers
81 memcpy(dest: buf, src: codeSectionHeader.data(), n: codeSectionHeader.size());
82
83 // Write code section bodies
84 for (const InputChunk *chunk : functions)
85 chunk->writeTo(buf);
86}
87
88uint32_t CodeSection::getNumRelocations() const {
89 uint32_t count = 0;
90 for (const InputChunk *func : functions)
91 count += func->getNumRelocations();
92 return count;
93}
94
95void CodeSection::writeRelocations(raw_ostream &os) const {
96 for (const InputChunk *c : functions)
97 c->writeRelocations(os);
98}
99
100void DataSection::finalizeContents() {
101 raw_string_ostream os(dataSectionHeader);
102 unsigned segmentCount = llvm::count_if(Range&: segments, P: [](OutputSegment *segment) {
103 return segment->requiredInBinary();
104 });
105#ifndef NDEBUG
106 unsigned activeCount = llvm::count_if(segments, [](OutputSegment *segment) {
107 return segment->requiredInBinary() &&
108 (segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE) == 0;
109 });
110#endif
111
112 assert((ctx.arg.sharedMemory || !ctx.isPic || ctx.arg.extendedConst ||
113 activeCount <= 1) &&
114 "output segments should have been combined by now");
115
116 writeUleb128(os, number: segmentCount, msg: "data segment count");
117 bodySize = dataSectionHeader.size();
118 bool is64 = ctx.arg.is64.value_or(u: false);
119
120 for (OutputSegment *segment : segments) {
121 if (!segment->requiredInBinary())
122 continue;
123 raw_string_ostream os(segment->header);
124 writeUleb128(os, number: segment->initFlags, msg: "init flags");
125 if (segment->initFlags & WASM_DATA_SEGMENT_HAS_MEMINDEX)
126 writeUleb128(os, number: 0, msg: "memory index");
127 if ((segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
128 if (ctx.isPic && ctx.arg.extendedConst) {
129 writeU8(os, byte: WASM_OPCODE_GLOBAL_GET, msg: "global get");
130 writeUleb128(os, number: ctx.sym.memoryBase->getGlobalIndex(),
131 msg: "literal (global index)");
132 if (segment->startVA) {
133 writePtrConst(os, number: segment->startVA, is64, msg: "offset");
134 writeU8(os, byte: is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, msg: "add");
135 }
136 writeU8(os, byte: WASM_OPCODE_END, msg: "opcode:end");
137 } else {
138 WasmInitExpr initExpr;
139 initExpr.Extended = false;
140 if (ctx.isPic) {
141 assert(segment->startVA == 0);
142 initExpr.Inst.Opcode = WASM_OPCODE_GLOBAL_GET;
143 initExpr.Inst.Value.Global = ctx.sym.memoryBase->getGlobalIndex();
144 } else {
145 initExpr = intConst(value: segment->startVA, is64);
146 }
147 writeInitExpr(os, initExpr);
148 }
149 }
150 writeUleb128(os, number: segment->size, msg: "segment size");
151
152 segment->sectionOffset = bodySize;
153 bodySize += segment->header.size() + segment->size;
154 log(msg: "Data segment: size=" + Twine(segment->size) + ", startVA=" +
155 Twine::utohexstr(Val: segment->startVA) + ", name=" + segment->name);
156
157 for (InputChunk *inputSeg : segment->inputSegments) {
158 inputSeg->outputSec = this;
159 inputSeg->outSecOff = segment->sectionOffset + segment->header.size() +
160 inputSeg->outputSegmentOffset;
161 }
162 }
163
164 if (bodySize > UINT32_MAX) {
165 error(msg: "section too large to encode: " + Twine(bodySize) + " bytes");
166 }
167
168 createHeader(bodySize);
169}
170
171void DataSection::writeTo(uint8_t *buf) {
172 log(msg: "writing " + toString(sec: *this) + " offset=" + Twine(offset) +
173 " size=" + Twine(getSize()) + " body=" + Twine(bodySize));
174 buf += offset;
175
176 // Write section header
177 memcpy(dest: buf, src: header.data(), n: header.size());
178 buf += header.size();
179
180 // Write data section headers
181 memcpy(dest: buf, src: dataSectionHeader.data(), n: dataSectionHeader.size());
182
183 for (const OutputSegment *segment : segments) {
184 if (!segment->requiredInBinary())
185 continue;
186 // Write data segment header
187 uint8_t *segStart = buf + segment->sectionOffset;
188 memcpy(dest: segStart, src: segment->header.data(), n: segment->header.size());
189
190 // Write segment data payload
191 for (const InputChunk *chunk : segment->inputSegments)
192 chunk->writeTo(buf);
193 }
194}
195
196uint32_t DataSection::getNumRelocations() const {
197 uint32_t count = 0;
198 for (const OutputSegment *seg : segments)
199 for (const InputChunk *inputSeg : seg->inputSegments)
200 count += inputSeg->getNumRelocations();
201 return count;
202}
203
204void DataSection::writeRelocations(raw_ostream &os) const {
205 for (const OutputSegment *seg : segments)
206 for (const InputChunk *c : seg->inputSegments)
207 c->writeRelocations(os);
208}
209
210bool DataSection::isNeeded() const {
211 for (const OutputSegment *seg : segments)
212 if (seg->requiredInBinary())
213 return true;
214 return false;
215}
216
217// Lots of duplication here with OutputSegment::finalizeInputSegments
218void CustomSection::finalizeInputSections() {
219 SyntheticMergedChunk *mergedSection = nullptr;
220 std::vector<InputChunk *> newSections;
221
222 for (InputChunk *s : inputSections) {
223 s->outputSec = this;
224 MergeInputChunk *ms = dyn_cast<MergeInputChunk>(Val: s);
225 if (!ms) {
226 newSections.push_back(x: s);
227 continue;
228 }
229
230 if (!mergedSection) {
231 mergedSection =
232 make<SyntheticMergedChunk>(args&: name, args: 0, args: WASM_SEG_FLAG_STRINGS);
233 newSections.push_back(x: mergedSection);
234 mergedSection->outputSec = this;
235 }
236 mergedSection->addMergeChunk(ms);
237 }
238
239 if (!mergedSection)
240 return;
241
242 mergedSection->finalizeContents();
243 inputSections = std::move(newSections);
244}
245
246void CustomSection::finalizeContents() {
247 finalizeInputSections();
248
249 raw_string_ostream os(nameData);
250 encodeULEB128(Value: name.size(), OS&: os);
251 os << name;
252
253 for (InputChunk *section : inputSections) {
254 assert(!section->discarded);
255 payloadSize = alignTo(Value: payloadSize, Align: section->alignment);
256 section->outSecOff = payloadSize;
257 payloadSize += section->getSize();
258 }
259
260 if (payloadSize > UINT32_MAX) {
261 error(msg: "section '" + name + "' too large to encode: " + Twine(payloadSize) +
262 " bytes");
263 }
264
265 createHeader(bodySize: payloadSize + nameData.size());
266}
267
268void CustomSection::writeTo(uint8_t *buf) {
269 log(msg: "writing " + toString(sec: *this) + " offset=" + Twine(offset) +
270 " size=" + Twine(getSize()) + " chunks=" + Twine(inputSections.size()));
271
272 assert(offset);
273 buf += offset;
274
275 // Write section header
276 memcpy(dest: buf, src: header.data(), n: header.size());
277 buf += header.size();
278 memcpy(dest: buf, src: nameData.data(), n: nameData.size());
279 buf += nameData.size();
280
281 // Write custom sections payload
282 for (const InputChunk *section : inputSections)
283 section->writeTo(buf);
284}
285
286uint32_t CustomSection::getNumRelocations() const {
287 uint32_t count = 0;
288 for (const InputChunk *inputSect : inputSections)
289 count += inputSect->getNumLiveRelocations();
290 return count;
291}
292
293void CustomSection::writeRelocations(raw_ostream &os) const {
294 for (const InputChunk *s : inputSections)
295 s->writeRelocations(os);
296}
297
298} // namespace wasm
299} // namespace lld
300