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