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 "InputFiles.h"
12 #include "OutputSegment.h"
13 #include "WriterUtils.h"
14 #include "lld/Common/ErrorHandler.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/Support/LEB128.h"
17 #include "llvm/Support/Parallel.h"
18 
19 #define DEBUG_TYPE "lld"
20 
21 using namespace llvm;
22 using namespace llvm::wasm;
23 
24 namespace lld {
25 
26 // Returns a string, e.g. "FUNCTION(.text)".
27 std::string toString(const wasm::OutputSection &sec) {
28   if (!sec.name.empty())
29     return (sec.getSectionName() + "(" + sec.name + ")").str();
30   return std::string(sec.getSectionName());
31 }
32 
33 namespace wasm {
34 static StringRef sectionTypeToString(uint32_t sectionType) {
35   switch (sectionType) {
36   case WASM_SEC_CUSTOM:
37     return "CUSTOM";
38   case WASM_SEC_TYPE:
39     return "TYPE";
40   case WASM_SEC_IMPORT:
41     return "IMPORT";
42   case WASM_SEC_FUNCTION:
43     return "FUNCTION";
44   case WASM_SEC_TABLE:
45     return "TABLE";
46   case WASM_SEC_MEMORY:
47     return "MEMORY";
48   case WASM_SEC_GLOBAL:
49     return "GLOBAL";
50   case WASM_SEC_EVENT:
51     return "EVENT";
52   case WASM_SEC_EXPORT:
53     return "EXPORT";
54   case WASM_SEC_START:
55     return "START";
56   case WASM_SEC_ELEM:
57     return "ELEM";
58   case WASM_SEC_CODE:
59     return "CODE";
60   case WASM_SEC_DATA:
61     return "DATA";
62   case WASM_SEC_DATACOUNT:
63     return "DATACOUNT";
64   default:
65     fatal("invalid section type");
66   }
67 }
68 
69 StringRef OutputSection::getSectionName() const {
70   return sectionTypeToString(type);
71 }
72 
73 void OutputSection::createHeader(size_t bodySize) {
74   raw_string_ostream os(header);
75   debugWrite(os.tell(), "section type [" + getSectionName() + "]");
76   encodeULEB128(type, os);
77   writeUleb128(os, bodySize, "section size");
78   os.flush();
79   log("createHeader: " + toString(*this) + " body=" + Twine(bodySize) +
80       " total=" + Twine(getSize()));
81 }
82 
83 void CodeSection::finalizeContents() {
84   raw_string_ostream os(codeSectionHeader);
85   writeUleb128(os, functions.size(), "function count");
86   os.flush();
87   bodySize = codeSectionHeader.size();
88 
89   for (InputFunction *func : functions) {
90     func->outputSec = this;
91     func->outSecOff = bodySize;
92     func->calculateSize();
93     // All functions should have a non-empty body at this point
94     assert(func->getSize());
95     bodySize += func->getSize();
96   }
97 
98   createHeader(bodySize);
99 }
100 
101 void CodeSection::writeTo(uint8_t *buf) {
102   log("writing " + toString(*this));
103   log(" size=" + Twine(getSize()));
104   log(" headersize=" + Twine(header.size()));
105   log(" codeheadersize=" + Twine(codeSectionHeader.size()));
106   buf += offset;
107 
108   // Write section header
109   memcpy(buf, header.data(), header.size());
110   buf += header.size();
111 
112   // Write code section headers
113   memcpy(buf, codeSectionHeader.data(), codeSectionHeader.size());
114 
115   // Write code section bodies
116   for (const InputChunk *chunk : functions)
117     chunk->writeTo(buf);
118 }
119 
120 uint32_t CodeSection::getNumRelocations() const {
121   uint32_t count = 0;
122   for (const InputChunk *func : functions)
123     count += func->getNumRelocations();
124   return count;
125 }
126 
127 void CodeSection::writeRelocations(raw_ostream &os) const {
128   for (const InputChunk *c : functions)
129     c->writeRelocations(os);
130 }
131 
132 void DataSection::finalizeContents() {
133   raw_string_ostream os(dataSectionHeader);
134   unsigned segmentCount =
135       std::count_if(segments.begin(), segments.end(),
136                     [](OutputSegment *segment) { return !segment->isBss; });
137 
138 #ifndef NDEBUG
139   unsigned activeCount = std::count_if(
140       segments.begin(), segments.end(), [](OutputSegment *segment) {
141         return (segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE) == 0;
142       });
143 #endif
144 
145   assert((!config->isPic || activeCount <= 1) &&
146          "Currenly only a single data segment is supported in PIC mode");
147 
148   writeUleb128(os, segmentCount, "data segment count");
149   os.flush();
150   bodySize = dataSectionHeader.size();
151 
152   for (OutputSegment *segment : segments) {
153     if (segment->isBss)
154       continue;
155     raw_string_ostream os(segment->header);
156     writeUleb128(os, segment->initFlags, "init flags");
157     if (segment->initFlags & WASM_DATA_SEGMENT_HAS_MEMINDEX)
158       writeUleb128(os, 0, "memory index");
159     if ((segment->initFlags & WASM_DATA_SEGMENT_IS_PASSIVE) == 0) {
160       WasmInitExpr initExpr;
161       if (config->isPic) {
162         initExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
163         initExpr.Value.Global = WasmSym::memoryBase->getGlobalIndex();
164       } else if (config->is64.getValueOr(false)) {
165         initExpr.Opcode = WASM_OPCODE_I64_CONST;
166         initExpr.Value.Int64 = static_cast<int64_t>(segment->startVA);
167       } else {
168         initExpr.Opcode = WASM_OPCODE_I32_CONST;
169         initExpr.Value.Int32 = static_cast<int32_t>(segment->startVA);
170       }
171       writeInitExpr(os, initExpr);
172     }
173     writeUleb128(os, segment->size, "segment size");
174     os.flush();
175 
176     segment->sectionOffset = bodySize;
177     bodySize += segment->header.size() + segment->size;
178     log("Data segment: size=" + Twine(segment->size) + ", startVA=" +
179         Twine::utohexstr(segment->startVA) + ", name=" + segment->name);
180 
181     for (InputSegment *inputSeg : segment->inputSegments) {
182       inputSeg->outputSec = this;
183       inputSeg->outSecOff = segment->sectionOffset + segment->header.size() +
184                             inputSeg->outputSegmentOffset;
185     }
186   }
187 
188   createHeader(bodySize);
189 }
190 
191 void DataSection::writeTo(uint8_t *buf) {
192   log("writing " + toString(*this) + " size=" + Twine(getSize()) +
193       " body=" + Twine(bodySize));
194   buf += offset;
195 
196   // Write section header
197   memcpy(buf, header.data(), header.size());
198   buf += header.size();
199 
200   // Write data section headers
201   memcpy(buf, dataSectionHeader.data(), dataSectionHeader.size());
202 
203   for (const OutputSegment *segment : segments) {
204     if (segment->isBss)
205       continue;
206     // Write data segment header
207     uint8_t *segStart = buf + segment->sectionOffset;
208     memcpy(segStart, segment->header.data(), segment->header.size());
209 
210     // Write segment data payload
211     for (const InputChunk *chunk : segment->inputSegments)
212       chunk->writeTo(buf);
213   }
214 }
215 
216 uint32_t DataSection::getNumRelocations() const {
217   uint32_t count = 0;
218   for (const OutputSegment *seg : segments)
219     for (const InputChunk *inputSeg : seg->inputSegments)
220       count += inputSeg->getNumRelocations();
221   return count;
222 }
223 
224 void DataSection::writeRelocations(raw_ostream &os) const {
225   for (const OutputSegment *seg : segments)
226     for (const InputChunk *c : seg->inputSegments)
227       c->writeRelocations(os);
228 }
229 
230 bool DataSection::isNeeded() const {
231   for (const OutputSegment *seg : segments)
232     if (!seg->isBss)
233       return true;
234   return false;
235 }
236 
237 void CustomSection::finalizeContents() {
238   raw_string_ostream os(nameData);
239   encodeULEB128(name.size(), os);
240   os << name;
241   os.flush();
242 
243   for (InputSection *section : inputSections) {
244     assert(!section->discarded);
245     section->outputSec = this;
246     section->outSecOff = payloadSize;
247     payloadSize += section->getSize();
248   }
249 
250   createHeader(payloadSize + nameData.size());
251 }
252 
253 void CustomSection::writeTo(uint8_t *buf) {
254   log("writing " + toString(*this) + " size=" + Twine(getSize()) +
255       " chunks=" + Twine(inputSections.size()));
256 
257   assert(offset);
258   buf += offset;
259 
260   // Write section header
261   memcpy(buf, header.data(), header.size());
262   buf += header.size();
263   memcpy(buf, nameData.data(), nameData.size());
264   buf += nameData.size();
265 
266   // Write custom sections payload
267   for (const InputSection *section : inputSections)
268     section->writeTo(buf);
269 }
270 
271 uint32_t CustomSection::getNumRelocations() const {
272   uint32_t count = 0;
273   for (const InputSection *inputSect : inputSections)
274     count += inputSect->getNumRelocations();
275   return count;
276 }
277 
278 void CustomSection::writeRelocations(raw_ostream &os) const {
279   for (const InputSection *s : inputSections)
280     s->writeRelocations(os);
281 }
282 
283 } // namespace wasm
284 } // namespace lld
285