1//===- lib/MC/MCSectionMachO.cpp - MachO Code Section Representation ------===//
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 "llvm/MC/MCSectionMachO.h"
10#include "llvm/MC/SectionKind.h"
11#include "llvm/Support/raw_ostream.h"
12
13namespace llvm {
14class MCAsmInfo;
15class MCExpr;
16class MCSymbol;
17class Triple;
18} // namespace llvm
19
20using namespace llvm;
21
22/// SectionTypeDescriptors - These are strings that describe the various section
23/// types. This *must* be kept in order with and stay synchronized with the
24/// section type list.
25static constexpr struct {
26 StringLiteral AssemblerName, EnumName;
27} SectionTypeDescriptors[MachO::LAST_KNOWN_SECTION_TYPE + 1] = {
28 {.AssemblerName: StringLiteral("regular"), .EnumName: StringLiteral("S_REGULAR")}, // 0x00
29 {.AssemblerName: StringLiteral("zerofill"), .EnumName: StringLiteral("S_ZEROFILL")}, // 0x01
30 {.AssemblerName: StringLiteral("cstring_literals"),
31 .EnumName: StringLiteral("S_CSTRING_LITERALS")}, // 0x02
32 {.AssemblerName: StringLiteral("4byte_literals"),
33 .EnumName: StringLiteral("S_4BYTE_LITERALS")}, // 0x03
34 {.AssemblerName: StringLiteral("8byte_literals"),
35 .EnumName: StringLiteral("S_8BYTE_LITERALS")}, // 0x04
36 {.AssemblerName: StringLiteral("literal_pointers"),
37 .EnumName: StringLiteral("S_LITERAL_POINTERS")}, // 0x05
38 {.AssemblerName: StringLiteral("non_lazy_symbol_pointers"),
39 .EnumName: StringLiteral("S_NON_LAZY_SYMBOL_POINTERS")}, // 0x06
40 {.AssemblerName: StringLiteral("lazy_symbol_pointers"),
41 .EnumName: StringLiteral("S_LAZY_SYMBOL_POINTERS")}, // 0x07
42 {.AssemblerName: StringLiteral("symbol_stubs"), .EnumName: StringLiteral("S_SYMBOL_STUBS")}, // 0x08
43 {.AssemblerName: StringLiteral("mod_init_funcs"),
44 .EnumName: StringLiteral("S_MOD_INIT_FUNC_POINTERS")}, // 0x09
45 {.AssemblerName: StringLiteral("mod_term_funcs"),
46 .EnumName: StringLiteral("S_MOD_TERM_FUNC_POINTERS")}, // 0x0A
47 {.AssemblerName: StringLiteral("coalesced"), .EnumName: StringLiteral("S_COALESCED")}, // 0x0B
48 {.AssemblerName: StringLiteral("") /*FIXME??*/, .EnumName: StringLiteral("S_GB_ZEROFILL")}, // 0x0C
49 {.AssemblerName: StringLiteral("interposing"), .EnumName: StringLiteral("S_INTERPOSING")}, // 0x0D
50 {.AssemblerName: StringLiteral("16byte_literals"),
51 .EnumName: StringLiteral("S_16BYTE_LITERALS")}, // 0x0E
52 {.AssemblerName: StringLiteral("") /*FIXME??*/, .EnumName: StringLiteral("S_DTRACE_DOF")}, // 0x0F
53 {.AssemblerName: StringLiteral("") /*FIXME??*/,
54 .EnumName: StringLiteral("S_LAZY_DYLIB_SYMBOL_POINTERS")}, // 0x10
55 {.AssemblerName: StringLiteral("thread_local_regular"),
56 .EnumName: StringLiteral("S_THREAD_LOCAL_REGULAR")}, // 0x11
57 {.AssemblerName: StringLiteral("thread_local_zerofill"),
58 .EnumName: StringLiteral("S_THREAD_LOCAL_ZEROFILL")}, // 0x12
59 {.AssemblerName: StringLiteral("thread_local_variables"),
60 .EnumName: StringLiteral("S_THREAD_LOCAL_VARIABLES")}, // 0x13
61 {.AssemblerName: StringLiteral("thread_local_variable_pointers"),
62 .EnumName: StringLiteral("S_THREAD_LOCAL_VARIABLE_POINTERS")}, // 0x14
63 {.AssemblerName: StringLiteral("thread_local_init_function_pointers"),
64 .EnumName: StringLiteral("S_THREAD_LOCAL_INIT_FUNCTION_POINTERS")}, // 0x15
65 {.AssemblerName: StringLiteral("") /* linker-synthesized */,
66 .EnumName: StringLiteral("S_INIT_FUNC_OFFSETS")}, // 0x16
67};
68
69/// SectionAttrDescriptors - This is an array of descriptors for section
70/// attributes. Unlike the SectionTypeDescriptors, this is not directly indexed
71/// by attribute, instead it is searched.
72static constexpr struct {
73 unsigned AttrFlag;
74 StringLiteral AssemblerName, EnumName;
75} SectionAttrDescriptors[] = {
76#define ENTRY(ASMNAME, ENUM) \
77 { MachO::ENUM, StringLiteral(ASMNAME), StringLiteral(#ENUM) },
78ENTRY("pure_instructions", S_ATTR_PURE_INSTRUCTIONS)
79ENTRY("no_toc", S_ATTR_NO_TOC)
80ENTRY("strip_static_syms", S_ATTR_STRIP_STATIC_SYMS)
81ENTRY("no_dead_strip", S_ATTR_NO_DEAD_STRIP)
82ENTRY("live_support", S_ATTR_LIVE_SUPPORT)
83ENTRY("self_modifying_code", S_ATTR_SELF_MODIFYING_CODE)
84ENTRY("debug", S_ATTR_DEBUG)
85ENTRY("" /*FIXME*/, S_ATTR_SOME_INSTRUCTIONS)
86ENTRY("" /*FIXME*/, S_ATTR_EXT_RELOC)
87ENTRY("" /*FIXME*/, S_ATTR_LOC_RELOC)
88#undef ENTRY
89 { .AttrFlag: 0, .AssemblerName: StringLiteral("none"), .EnumName: StringLiteral("") }, // used if section has no attributes but has a stub size
90};
91
92MCSectionMachO::MCSectionMachO(StringRef Segment, StringRef Section,
93 unsigned TAA, unsigned reserved2, SectionKind K,
94 MCSymbol *Begin)
95 : MCSection(SV_MachO, Section, K.isText(),
96 MachO::isVirtualSection(type: TAA & MachO::SECTION_TYPE), Begin),
97 TypeAndAttributes(TAA), Reserved2(reserved2) {
98 assert(Segment.size() <= 16 && Section.size() <= 16 &&
99 "Segment or section string too long");
100 for (unsigned i = 0; i != 16; ++i) {
101 if (i < Segment.size())
102 SegmentName[i] = Segment[i];
103 else
104 SegmentName[i] = 0;
105 }
106}
107
108void MCSectionMachO::printSwitchToSection(const MCAsmInfo &MAI, const Triple &T,
109 raw_ostream &OS,
110 uint32_t Subsection) const {
111 OS << "\t.section\t" << getSegmentName() << ',' << getName();
112
113 // Get the section type and attributes.
114 unsigned TAA = getTypeAndAttributes();
115 if (TAA == 0) {
116 OS << '\n';
117 return;
118 }
119
120 MachO::SectionType SectionType = getType();
121 assert(SectionType <= MachO::LAST_KNOWN_SECTION_TYPE &&
122 "Invalid SectionType specified!");
123
124 if (!SectionTypeDescriptors[SectionType].AssemblerName.empty()) {
125 OS << ',';
126 OS << SectionTypeDescriptors[SectionType].AssemblerName;
127 } else {
128 // If we have no name for the attribute, stop here.
129 OS << '\n';
130 return;
131 }
132
133 // If we don't have any attributes, we're done.
134 unsigned SectionAttrs = TAA & MachO::SECTION_ATTRIBUTES;
135 if (SectionAttrs == 0) {
136 // If we have a S_SYMBOL_STUBS size specified, print it along with 'none' as
137 // the attribute specifier.
138 if (Reserved2 != 0)
139 OS << ",none," << Reserved2;
140 OS << '\n';
141 return;
142 }
143
144 // Check each attribute to see if we have it.
145 char Separator = ',';
146 for (unsigned i = 0;
147 SectionAttrs != 0 && SectionAttrDescriptors[i].AttrFlag;
148 ++i) {
149 // Check to see if we have this attribute.
150 if ((SectionAttrDescriptors[i].AttrFlag & SectionAttrs) == 0)
151 continue;
152
153 // Yep, clear it and print it.
154 SectionAttrs &= ~SectionAttrDescriptors[i].AttrFlag;
155
156 OS << Separator;
157 if (!SectionAttrDescriptors[i].AssemblerName.empty())
158 OS << SectionAttrDescriptors[i].AssemblerName;
159 else
160 OS << "<<" << SectionAttrDescriptors[i].EnumName << ">>";
161 Separator = '+';
162 }
163
164 assert(SectionAttrs == 0 && "Unknown section attributes!");
165
166 // If we have a S_SYMBOL_STUBS size specified, print it.
167 if (Reserved2 != 0)
168 OS << ',' << Reserved2;
169 OS << '\n';
170}
171
172bool MCSectionMachO::useCodeAlign() const {
173 return hasAttribute(Value: MachO::S_ATTR_PURE_INSTRUCTIONS);
174}
175
176/// ParseSectionSpecifier - Parse the section specifier indicated by "Spec".
177/// This is a string that can appear after a .section directive in a mach-o
178/// flavored .s file. If successful, this fills in the specified Out
179/// parameters and returns an empty string. When an invalid section
180/// specifier is present, this returns a string indicating the problem.
181Error MCSectionMachO::ParseSectionSpecifier(StringRef Spec, // In.
182 StringRef &Segment, // Out.
183 StringRef &Section, // Out.
184 unsigned &TAA, // Out.
185 bool &TAAParsed, // Out.
186 unsigned &StubSize) { // Out.
187 TAAParsed = false;
188
189 SmallVector<StringRef, 5> SplitSpec;
190 Spec.split(A&: SplitSpec, Separator: ',');
191 // Remove leading and trailing whitespace.
192 auto GetEmptyOrTrim = [&SplitSpec](size_t Idx) -> StringRef {
193 return SplitSpec.size() > Idx ? SplitSpec[Idx].trim() : StringRef();
194 };
195 Segment = GetEmptyOrTrim(0);
196 Section = GetEmptyOrTrim(1);
197 StringRef SectionType = GetEmptyOrTrim(2);
198 StringRef Attrs = GetEmptyOrTrim(3);
199 StringRef StubSizeStr = GetEmptyOrTrim(4);
200
201 // Verify that the section is present.
202 if (Section.empty())
203 return createStringError(EC: inconvertibleErrorCode(),
204 S: "mach-o section specifier requires a segment "
205 "and section separated by a comma");
206
207 // Verify that the section is not too long.
208 if (Section.size() > 16)
209 return createStringError(EC: inconvertibleErrorCode(),
210 S: "mach-o section specifier requires a section "
211 "whose length is between 1 and 16 characters");
212
213 // If there is no comma after the section, we're done.
214 TAA = 0;
215 StubSize = 0;
216 if (SectionType.empty())
217 return Error::success();
218
219 // Figure out which section type it is.
220 auto TypeDescriptor =
221 llvm::find_if(Range: SectionTypeDescriptors,
222 P: [&](decltype(*SectionTypeDescriptors) &Descriptor) {
223 return SectionType == Descriptor.AssemblerName;
224 });
225
226 // If we didn't find the section type, reject it.
227 if (TypeDescriptor == std::end(arr: SectionTypeDescriptors))
228 return createStringError(EC: inconvertibleErrorCode(),
229 S: "mach-o section specifier uses an unknown "
230 "section type");
231
232 // Remember the TypeID.
233 TAA = TypeDescriptor - std::begin(arr: SectionTypeDescriptors);
234 TAAParsed = true;
235
236 // If we have no comma after the section type, there are no attributes.
237 if (Attrs.empty()) {
238 // S_SYMBOL_STUBS always require a symbol stub size specifier.
239 if (TAA == MachO::S_SYMBOL_STUBS)
240 return createStringError(EC: inconvertibleErrorCode(),
241 S: "mach-o section specifier of type "
242 "'symbol_stubs' requires a size specifier");
243 return Error::success();
244 }
245
246 // The attribute list is a '+' separated list of attributes.
247 SmallVector<StringRef, 1> SectionAttrs;
248 Attrs.split(A&: SectionAttrs, Separator: '+', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
249
250 for (StringRef &SectionAttr : SectionAttrs) {
251 auto AttrDescriptorI =
252 llvm::find_if(Range: SectionAttrDescriptors,
253 P: [&](decltype(*SectionAttrDescriptors) &Descriptor) {
254 return SectionAttr.trim() == Descriptor.AssemblerName;
255 });
256 if (AttrDescriptorI == std::end(arr: SectionAttrDescriptors))
257 return createStringError(EC: inconvertibleErrorCode(),
258 S: "mach-o section specifier has invalid "
259 "attribute");
260
261 TAA |= AttrDescriptorI->AttrFlag;
262 }
263
264 // Okay, we've parsed the section attributes, see if we have a stub size spec.
265 if (StubSizeStr.empty()) {
266 // S_SYMBOL_STUBS always require a symbol stub size specifier.
267 if (TAA == MachO::S_SYMBOL_STUBS)
268 return createStringError(EC: inconvertibleErrorCode(),
269 S: "mach-o section specifier of type "
270 "'symbol_stubs' requires a size specifier");
271 return Error::success();
272 }
273
274 // If we have a stub size spec, we must have a sectiontype of S_SYMBOL_STUBS.
275 if ((TAA & MachO::SECTION_TYPE) != MachO::S_SYMBOL_STUBS)
276 return createStringError(EC: inconvertibleErrorCode(),
277 S: "mach-o section specifier cannot have a stub "
278 "size specified because it does not have type "
279 "'symbol_stubs'");
280
281 // Convert the stub size from a string to an integer.
282 if (StubSizeStr.getAsInteger(Radix: 0, Result&: StubSize))
283 return createStringError(EC: inconvertibleErrorCode(),
284 S: "mach-o section specifier has a malformed "
285 "stub size");
286
287 return Error::success();
288}
289
290void MCSectionMachO::allocAtoms() {
291 auto *L = curFragList();
292 if (L->Tail)
293 Atoms.resize(N: L->Tail->getLayoutOrder() + 1);
294}
295
296const MCSymbol *MCSectionMachO::getAtom(size_t I) const {
297 return I < Atoms.size() ? Atoms[I] : nullptr;
298}
299
300void MCSectionMachO::setAtom(size_t I, const MCSymbol *Sym) { Atoms[I] = Sym; }
301