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() && segment->isActive();
108 });
109#endif
110
111 assert((!ctx.isPic || ctx.arg.extendedConst || activeCount <= 1) &&
112 "output segments should have been combined by now");
113
114 writeUleb128(os, number: segmentCount, msg: "data segment count");
115 bodySize = dataSectionHeader.size();
116 bool is64 = ctx.arg.is64.value_or(u: false);
117
118 for (OutputSegment *segment : segments) {
119 if (!segment->requiredInBinary())
120 continue;
121 raw_string_ostream os(segment->header);
122 writeUleb128(os, number: segment->initFlags, msg: "init flags");
123 if (segment->initFlags & WASM_DATA_SEGMENT_HAS_MEMINDEX)
124 writeUleb128(os, number: 0, msg: "memory index");
125 if (segment->isActive()) {
126 if (ctx.isPic && ctx.arg.extendedConst) {
127 writeU8(os, byte: WASM_OPCODE_GLOBAL_GET, msg: "global get");
128 writeUleb128(os, number: ctx.sym.memoryBase->getGlobalIndex(),
129 msg: "literal (global index)");
130 if (segment->startVA) {
131 writePtrConst(os, number: segment->startVA, is64, msg: "offset");
132 writeU8(os, byte: is64 ? WASM_OPCODE_I64_ADD : WASM_OPCODE_I32_ADD, msg: "add");
133 }
134 writeU8(os, byte: WASM_OPCODE_END, msg: "opcode:end");
135 } else {
136 WasmInitExpr initExpr;
137 initExpr.Extended = false;
138 if (ctx.isPic) {
139 assert(segment->startVA == 0);
140 initExpr.Inst.Opcode = WASM_OPCODE_GLOBAL_GET;
141 initExpr.Inst.Value.Global = ctx.sym.memoryBase->getGlobalIndex();
142 } else {
143 initExpr = intConst(value: segment->startVA, is64);
144 }
145 writeInitExpr(os, initExpr);
146 }
147 }
148 writeUleb128(os, number: segment->size, msg: "segment size");
149
150 segment->sectionOffset = bodySize;
151 bodySize += segment->header.size() + segment->size;
152 log(msg: "Data segment: size=" + Twine(segment->size) + ", startVA=" +
153 Twine::utohexstr(Val: segment->startVA) + ", name=" + segment->name);
154
155 for (InputChunk *inputSeg : segment->inputSegments) {
156 inputSeg->outputSec = this;
157 inputSeg->outSecOff = segment->sectionOffset + segment->header.size() +
158 inputSeg->outputSegmentOffset;
159 }
160 }
161
162 if (bodySize > UINT32_MAX) {
163 error(msg: "section too large to encode: " + Twine(bodySize) + " bytes");
164 }
165
166 createHeader(bodySize);
167}
168
169void DataSection::writeTo(uint8_t *buf) {
170 log(msg: "writing " + toString(sec: *this) + " offset=" + Twine(offset) +
171 " size=" + Twine(getSize()) + " body=" + Twine(bodySize));
172 buf += offset;
173
174 // Write section header
175 memcpy(dest: buf, src: header.data(), n: header.size());
176 buf += header.size();
177
178 // Write data section headers
179 memcpy(dest: buf, src: dataSectionHeader.data(), n: dataSectionHeader.size());
180
181 for (const OutputSegment *segment : segments) {
182 if (!segment->requiredInBinary())
183 continue;
184 // Write data segment header
185 uint8_t *segStart = buf + segment->sectionOffset;
186 memcpy(dest: segStart, src: segment->header.data(), n: segment->header.size());
187
188 // Write segment data payload
189 for (const InputChunk *chunk : segment->inputSegments)
190 chunk->writeTo(buf);
191 }
192}
193
194uint32_t DataSection::getNumRelocations() const {
195 uint32_t count = 0;
196 for (const OutputSegment *seg : segments)
197 for (const InputChunk *inputSeg : seg->inputSegments)
198 count += inputSeg->getNumRelocations();
199 return count;
200}
201
202void DataSection::writeRelocations(raw_ostream &os) const {
203 for (const OutputSegment *seg : segments)
204 for (const InputChunk *c : seg->inputSegments)
205 c->writeRelocations(os);
206}
207
208bool DataSection::isNeeded() const {
209 for (const OutputSegment *seg : segments)
210 if (seg->requiredInBinary())
211 return true;
212 return false;
213}
214
215// Lots of duplication here with OutputSegment::finalizeInputSegments
216void CustomSection::finalizeInputSections() {
217 SyntheticMergedChunk *mergedSection = nullptr;
218 std::vector<InputChunk *> newSections;
219
220 for (InputChunk *s : inputSections) {
221 s->outputSec = this;
222 MergeInputChunk *ms = dyn_cast<MergeInputChunk>(Val: s);
223 if (!ms) {
224 newSections.push_back(x: s);
225 continue;
226 }
227
228 if (!mergedSection) {
229 mergedSection =
230 make<SyntheticMergedChunk>(args&: name, args: 0, args: WASM_SEG_FLAG_STRINGS);
231 newSections.push_back(x: mergedSection);
232 mergedSection->outputSec = this;
233 }
234 mergedSection->addMergeChunk(ms);
235 }
236
237 if (!mergedSection)
238 return;
239
240 mergedSection->finalizeContents();
241 inputSections = std::move(newSections);
242}
243
244void CustomSection::finalizeContents() {
245 finalizeInputSections();
246
247 raw_string_ostream os(nameData);
248 encodeULEB128(Value: name.size(), OS&: os);
249 os << name;
250
251 for (InputChunk *section : inputSections) {
252 assert(!section->discarded);
253 payloadSize = alignTo(Value: payloadSize, Align: section->alignment);
254 section->outSecOff = payloadSize;
255 payloadSize += section->getSize();
256 }
257
258 if (payloadSize > UINT32_MAX) {
259 error(msg: "section '" + name + "' too large to encode: " + Twine(payloadSize) +
260 " bytes");
261 }
262
263 createHeader(bodySize: payloadSize + nameData.size());
264}
265
266void CustomSection::writeTo(uint8_t *buf) {
267 log(msg: "writing " + toString(sec: *this) + " offset=" + Twine(offset) +
268 " size=" + Twine(getSize()) + " chunks=" + Twine(inputSections.size()));
269
270 assert(offset);
271 buf += offset;
272
273 // Write section header
274 memcpy(dest: buf, src: header.data(), n: header.size());
275 buf += header.size();
276 memcpy(dest: buf, src: nameData.data(), n: nameData.size());
277 buf += nameData.size();
278
279 // Write custom sections payload
280 for (const InputChunk *section : inputSections)
281 section->writeTo(buf);
282}
283
284uint32_t CustomSection::getNumRelocations() const {
285 uint32_t count = 0;
286 for (const InputChunk *inputSect : inputSections)
287 count += inputSect->getNumLiveRelocations();
288 return count;
289}
290
291void CustomSection::writeRelocations(raw_ostream &os) const {
292 for (const InputChunk *s : inputSections)
293 s->writeRelocations(os);
294}
295
296} // namespace wasm
297} // namespace lld
298