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)".
toString(const wasm::OutputSection & sec)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 {
sectionTypeToString(uint32_t sectionType)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 
getSectionName() const69 StringRef OutputSection::getSectionName() const {
70   return sectionTypeToString(type);
71 }
72 
createHeader(size_t bodySize)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 
finalizeContents()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->outputOffset = bodySize;
92     func->calculateSize();
93     bodySize += func->getSize();
94   }
95 
96   createHeader(bodySize);
97 }
98 
writeTo(uint8_t * buf)99 void CodeSection::writeTo(uint8_t *buf) {
100   log("writing " + toString(*this));
101   log(" size=" + Twine(getSize()));
102   log(" headersize=" + Twine(header.size()));
103   log(" codeheadersize=" + Twine(codeSectionHeader.size()));
104   buf += offset;
105 
106   // Write section header
107   memcpy(buf, header.data(), header.size());
108   buf += header.size();
109 
110   // Write code section headers
111   memcpy(buf, codeSectionHeader.data(), codeSectionHeader.size());
112 
113   // Write code section bodies
114   for (const InputChunk *chunk : functions)
115     chunk->writeTo(buf);
116 }
117 
getNumRelocations() const118 uint32_t CodeSection::getNumRelocations() const {
119   uint32_t count = 0;
120   for (const InputChunk *func : functions)
121     count += func->getNumRelocations();
122   return count;
123 }
124 
writeRelocations(raw_ostream & os) const125 void CodeSection::writeRelocations(raw_ostream &os) const {
126   for (const InputChunk *c : functions)
127     c->writeRelocations(os);
128 }
129 
finalizeContents()130 void DataSection::finalizeContents() {
131   raw_string_ostream os(dataSectionHeader);
132   unsigned segmentCount =
133       std::count_if(segments.begin(), segments.end(),
134                     [](OutputSegment *segment) { return !segment->isBss; });
135 
136   writeUleb128(os, segmentCount, "data segment count");
137   os.flush();
138   bodySize = dataSectionHeader.size();
139 
140   assert((!config->isPic || segments.size() <= 1) &&
141          "Currenly only a single data segment is supported in PIC mode");
142 
143   for (OutputSegment *segment : segments) {
144     if (segment->isBss)
145       continue;
146     raw_string_ostream os(segment->header);
147     writeUleb128(os, segment->initFlags, "init flags");
148     if (segment->initFlags & WASM_SEGMENT_HAS_MEMINDEX)
149       writeUleb128(os, 0, "memory index");
150     if ((segment->initFlags & WASM_SEGMENT_IS_PASSIVE) == 0) {
151       WasmInitExpr initExpr;
152       if (config->isPic) {
153         initExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
154         initExpr.Value.Global = WasmSym::memoryBase->getGlobalIndex();
155       } else {
156         // FIXME(wvo): I64?
157         initExpr.Opcode = WASM_OPCODE_I32_CONST;
158         initExpr.Value.Int32 = segment->startVA;
159       }
160       writeInitExpr(os, initExpr);
161     }
162     writeUleb128(os, segment->size, "segment size");
163     os.flush();
164 
165     segment->sectionOffset = bodySize;
166     bodySize += segment->header.size() + segment->size;
167     log("Data segment: size=" + Twine(segment->size) + ", startVA=" +
168         Twine::utohexstr(segment->startVA) + ", name=" + segment->name);
169 
170     for (InputSegment *inputSeg : segment->inputSegments) {
171       inputSeg->outputSec = this;
172       inputSeg->outputOffset = segment->sectionOffset + segment->header.size() +
173                                inputSeg->outputSegmentOffset;
174     }
175   }
176 
177   createHeader(bodySize);
178 }
179 
writeTo(uint8_t * buf)180 void DataSection::writeTo(uint8_t *buf) {
181   log("writing " + toString(*this) + " size=" + Twine(getSize()) +
182       " body=" + Twine(bodySize));
183   buf += offset;
184 
185   // Write section header
186   memcpy(buf, header.data(), header.size());
187   buf += header.size();
188 
189   // Write data section headers
190   memcpy(buf, dataSectionHeader.data(), dataSectionHeader.size());
191 
192   for (const OutputSegment *segment : segments) {
193     if (segment->isBss)
194       continue;
195     // Write data segment header
196     uint8_t *segStart = buf + segment->sectionOffset;
197     memcpy(segStart, segment->header.data(), segment->header.size());
198 
199     // Write segment data payload
200     for (const InputChunk *chunk : segment->inputSegments)
201       chunk->writeTo(buf);
202   }
203 }
204 
getNumRelocations() const205 uint32_t DataSection::getNumRelocations() const {
206   uint32_t count = 0;
207   for (const OutputSegment *seg : segments)
208     for (const InputChunk *inputSeg : seg->inputSegments)
209       count += inputSeg->getNumRelocations();
210   return count;
211 }
212 
writeRelocations(raw_ostream & os) const213 void DataSection::writeRelocations(raw_ostream &os) const {
214   for (const OutputSegment *seg : segments)
215     for (const InputChunk *c : seg->inputSegments)
216       c->writeRelocations(os);
217 }
218 
isNeeded() const219 bool DataSection::isNeeded() const {
220   for (const OutputSegment *seg : segments)
221     if (!seg->isBss)
222       return true;
223   return false;
224 }
225 
finalizeContents()226 void CustomSection::finalizeContents() {
227   raw_string_ostream os(nameData);
228   encodeULEB128(name.size(), os);
229   os << name;
230   os.flush();
231 
232   for (InputSection *section : inputSections) {
233     section->outputSec = this;
234     section->outputOffset = payloadSize;
235     payloadSize += section->getSize();
236   }
237 
238   createHeader(payloadSize + nameData.size());
239 }
240 
writeTo(uint8_t * buf)241 void CustomSection::writeTo(uint8_t *buf) {
242   log("writing " + toString(*this) + " size=" + Twine(getSize()) +
243       " chunks=" + Twine(inputSections.size()));
244 
245   assert(offset);
246   buf += offset;
247 
248   // Write section header
249   memcpy(buf, header.data(), header.size());
250   buf += header.size();
251   memcpy(buf, nameData.data(), nameData.size());
252   buf += nameData.size();
253 
254   // Write custom sections payload
255   for (const InputSection *section : inputSections)
256     section->writeTo(buf);
257 }
258 
getNumRelocations() const259 uint32_t CustomSection::getNumRelocations() const {
260   uint32_t count = 0;
261   for (const InputSection *inputSect : inputSections)
262     count += inputSect->getNumRelocations();
263   return count;
264 }
265 
writeRelocations(raw_ostream & os) const266 void CustomSection::writeRelocations(raw_ostream &os) const {
267   for (const InputSection *s : inputSections)
268     s->writeRelocations(os);
269 }
270 
271 } // namespace wasm
272 } // namespace lld
273