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::numRelocations() const {
117   uint32_t Count = 0;
118   for (const InputChunk *Func : Functions)
119     Count += Func->NumRelocations();
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->Pic ||
136          Segments.size() <= 1 &&
137              "Currenly only a single data segment is supported in PIC mode");
138 
139   for (OutputSegment *Segment : Segments) {
140     raw_string_ostream OS(Segment->Header);
141     writeUleb128(OS, Segment->InitFlags, "init flags");
142     if (Segment->InitFlags & WASM_SEGMENT_HAS_MEMINDEX)
143       writeUleb128(OS, 0, "memory index");
144     if ((Segment->InitFlags & WASM_SEGMENT_IS_PASSIVE) == 0) {
145       WasmInitExpr InitExpr;
146       if (Config->Pic) {
147         InitExpr.Opcode = WASM_OPCODE_GLOBAL_GET;
148         InitExpr.Value.Global = WasmSym::MemoryBase->getGlobalIndex();
149       } else {
150         InitExpr.Opcode = WASM_OPCODE_I32_CONST;
151         InitExpr.Value.Int32 = Segment->StartVA;
152       }
153       writeInitExpr(OS, InitExpr);
154     }
155     writeUleb128(OS, Segment->Size, "segment size");
156     OS.flush();
157 
158     Segment->SectionOffset = BodySize;
159     BodySize += Segment->Header.size() + Segment->Size;
160     log("Data segment: size=" + Twine(Segment->Size) + ", startVA=" +
161         Twine::utohexstr(Segment->StartVA) + ", name=" + Segment->Name);
162 
163     for (InputSegment *InputSeg : Segment->InputSegments)
164       InputSeg->OutputOffset = Segment->SectionOffset + Segment->Header.size() +
165                                InputSeg->OutputSegmentOffset;
166   }
167 
168   createHeader(BodySize);
169 }
170 
171 void DataSection::writeTo(uint8_t *Buf) {
172   log("writing " + toString(*this) + " size=" + Twine(getSize()) +
173       " body=" + Twine(BodySize));
174   Buf += Offset;
175 
176   // Write section header
177   memcpy(Buf, Header.data(), Header.size());
178   Buf += Header.size();
179 
180   // Write data section headers
181   memcpy(Buf, DataSectionHeader.data(), DataSectionHeader.size());
182 
183   for (const OutputSegment *Segment : Segments) {
184     // Write data segment header
185     uint8_t *SegStart = Buf + Segment->SectionOffset;
186     memcpy(SegStart, Segment->Header.data(), Segment->Header.size());
187 
188     // Write segment data payload
189     for (const InputChunk *Chunk : Segment->InputSegments)
190       Chunk->writeTo(Buf);
191   }
192 }
193 
194 uint32_t DataSection::numRelocations() const {
195   uint32_t Count = 0;
196   for (const OutputSegment *Seg : Segments)
197     for (const InputChunk *InputSeg : Seg->InputSegments)
198       Count += InputSeg->NumRelocations();
199   return Count;
200 }
201 
202 void 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 
208 void CustomSection::finalizeContents() {
209   raw_string_ostream OS(NameData);
210   encodeULEB128(Name.size(), OS);
211   OS << Name;
212   OS.flush();
213 
214   for (InputSection *Section : InputSections) {
215     Section->OutputOffset = PayloadSize;
216     Section->OutputSec = this;
217     PayloadSize += Section->getSize();
218   }
219 
220   createHeader(PayloadSize + NameData.size());
221 }
222 
223 void CustomSection::writeTo(uint8_t *Buf) {
224   log("writing " + toString(*this) + " size=" + Twine(getSize()) +
225       " chunks=" + Twine(InputSections.size()));
226 
227   assert(Offset);
228   Buf += Offset;
229 
230   // Write section header
231   memcpy(Buf, Header.data(), Header.size());
232   Buf += Header.size();
233   memcpy(Buf, NameData.data(), NameData.size());
234   Buf += NameData.size();
235 
236   // Write custom sections payload
237   for (const InputSection *Section : InputSections)
238     Section->writeTo(Buf);
239 }
240 
241 uint32_t CustomSection::numRelocations() const {
242   uint32_t Count = 0;
243   for (const InputSection *InputSect : InputSections)
244     Count += InputSect->NumRelocations();
245   return Count;
246 }
247 
248 void CustomSection::writeRelocations(raw_ostream &OS) const {
249   for (const InputSection *S : InputSections)
250     S->writeRelocations(OS);
251 }
252