LLVM 20.0.0git
MCSectionMachO.cpp
Go to the documentation of this file.
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
10#include "llvm/MC/SectionKind.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 {
28 {StringLiteral("regular"), StringLiteral("S_REGULAR")}, // 0x00
29 {StringLiteral("zerofill"), StringLiteral("S_ZEROFILL")}, // 0x01
30 {StringLiteral("cstring_literals"),
31 StringLiteral("S_CSTRING_LITERALS")}, // 0x02
32 {StringLiteral("4byte_literals"),
33 StringLiteral("S_4BYTE_LITERALS")}, // 0x03
34 {StringLiteral("8byte_literals"),
35 StringLiteral("S_8BYTE_LITERALS")}, // 0x04
36 {StringLiteral("literal_pointers"),
37 StringLiteral("S_LITERAL_POINTERS")}, // 0x05
38 {StringLiteral("non_lazy_symbol_pointers"),
39 StringLiteral("S_NON_LAZY_SYMBOL_POINTERS")}, // 0x06
40 {StringLiteral("lazy_symbol_pointers"),
41 StringLiteral("S_LAZY_SYMBOL_POINTERS")}, // 0x07
42 {StringLiteral("symbol_stubs"), StringLiteral("S_SYMBOL_STUBS")}, // 0x08
43 {StringLiteral("mod_init_funcs"),
44 StringLiteral("S_MOD_INIT_FUNC_POINTERS")}, // 0x09
45 {StringLiteral("mod_term_funcs"),
46 StringLiteral("S_MOD_TERM_FUNC_POINTERS")}, // 0x0A
47 {StringLiteral("coalesced"), StringLiteral("S_COALESCED")}, // 0x0B
48 {StringLiteral("") /*FIXME??*/, StringLiteral("S_GB_ZEROFILL")}, // 0x0C
49 {StringLiteral("interposing"), StringLiteral("S_INTERPOSING")}, // 0x0D
50 {StringLiteral("16byte_literals"),
51 StringLiteral("S_16BYTE_LITERALS")}, // 0x0E
52 {StringLiteral("") /*FIXME??*/, StringLiteral("S_DTRACE_DOF")}, // 0x0F
53 {StringLiteral("") /*FIXME??*/,
54 StringLiteral("S_LAZY_DYLIB_SYMBOL_POINTERS")}, // 0x10
55 {StringLiteral("thread_local_regular"),
56 StringLiteral("S_THREAD_LOCAL_REGULAR")}, // 0x11
57 {StringLiteral("thread_local_zerofill"),
58 StringLiteral("S_THREAD_LOCAL_ZEROFILL")}, // 0x12
59 {StringLiteral("thread_local_variables"),
60 StringLiteral("S_THREAD_LOCAL_VARIABLES")}, // 0x13
61 {StringLiteral("thread_local_variable_pointers"),
62 StringLiteral("S_THREAD_LOCAL_VARIABLE_POINTERS")}, // 0x14
63 {StringLiteral("thread_local_init_function_pointers"),
64 StringLiteral("S_THREAD_LOCAL_INIT_FUNCTION_POINTERS")}, // 0x15
65 {StringLiteral("") /* linker-synthesized */,
66 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;
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)
86ENTRY("" /*FIXME*/, S_ATTR_EXT_RELOC)
87ENTRY("" /*FIXME*/, S_ATTR_LOC_RELOC)
88#undef ENTRY
89 { 0, StringLiteral("none"), 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(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
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;
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
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.
182 StringRef &Segment, // Out.
183 StringRef &Section, // Out.
184 unsigned &TAA, // Out.
185 bool &TAAParsed, // Out.
186 unsigned &StubSize) { // Out.
187 TAAParsed = false;
188
190 Spec.split(SplitSpec, ',');
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())
204 "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)
210 "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 =
222 [&](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(SectionTypeDescriptors))
229 "mach-o section specifier uses an unknown "
230 "section type");
231
232 // Remember the TypeID.
233 TAA = TypeDescriptor - std::begin(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)
241 "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(SectionAttrs, '+', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
249
250 for (StringRef &SectionAttr : SectionAttrs) {
251 auto AttrDescriptorI =
253 [&](decltype(*SectionAttrDescriptors) &Descriptor) {
254 return SectionAttr.trim() == Descriptor.AssemblerName;
255 });
256 if (AttrDescriptorI == std::end(SectionAttrDescriptors))
258 "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)
269 "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.
277 "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(0, StubSize))
284 "mach-o section specifier has a malformed "
285 "stub size");
286
287 return Error::success();
288}
289
291 auto *L = curFragList();
292 if (L->Tail)
293 Atoms.resize(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; }
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
Symbol * Sym
Definition: ELF_riscv.cpp:479
static constexpr struct @488 SectionAttrDescriptors[]
SectionAttrDescriptors - This is an array of descriptors for section attributes.
unsigned AttrFlag
static constexpr struct @487 SectionTypeDescriptors[MachO::LAST_KNOWN_SECTION_TYPE+1]
SectionTypeDescriptors - These are strings that describe the various section types.
#define ENTRY(ASMNAME, ENUM)
StringLiteral EnumName
StringLiteral AssemblerName
#define I(x, y, z)
Definition: MD5.cpp:58
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
static Error ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
MachO::SectionType getType() const
void setAtom(size_t I, const MCSymbol *Sym)
StringRef getSegmentName() const
const MCSymbol * getAtom(size_t I) const
bool useCodeAlign() const override
Return true if a .align directive should use "optimized nops" to fill instead of 0s.
unsigned getTypeAndAttributes() const
bool hasAttribute(unsigned Value) const
void printSwitchToSection(const MCAsmInfo &MAI, const Triple &T, raw_ostream &OS, uint32_t Subsection) const override
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
StringRef getName() const
Definition: MCSection.h:130
FragList * curFragList() const
Definition: MCSection.h:181
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
size_t size() const
Definition: SmallVector.h:91
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:838
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:455
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
@ SECTION_ATTRIBUTES
Definition: MachO.h:115
@ SECTION_TYPE
Definition: MachO.h:114
@ S_ATTR_SOME_INSTRUCTIONS
S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions.
Definition: MachO.h:213
@ S_ATTR_EXT_RELOC
S_ATTR_EXT_RELOC - Section has external relocation entries.
Definition: MachO.h:215
@ S_ATTR_DEBUG
S_ATTR_DEBUG - A debug section.
Definition: MachO.h:207
@ S_ATTR_NO_DEAD_STRIP
S_ATTR_NO_DEAD_STRIP - No dead stripping.
Definition: MachO.h:200
@ S_ATTR_LOC_RELOC
S_ATTR_LOC_RELOC - Section has local relocation entries.
Definition: MachO.h:217
@ S_ATTR_NO_TOC
S_ATTR_NO_TOC - Section contains coalesced symbols that are not to be in a ranlib table of contents.
Definition: MachO.h:195
@ S_ATTR_LIVE_SUPPORT
S_ATTR_LIVE_SUPPORT - Blocks are live if they reference live blocks.
Definition: MachO.h:202
@ S_ATTR_PURE_INSTRUCTIONS
S_ATTR_PURE_INSTRUCTIONS - Section contains only true machine instructions.
Definition: MachO.h:192
@ S_ATTR_SELF_MODIFYING_CODE
S_ATTR_SELF_MODIFYING_CODE - Used with i386 code stubs written on by dyld.
Definition: MachO.h:205
@ S_ATTR_STRIP_STATIC_SYMS
S_ATTR_STRIP_STATIC_SYMS - Ok to strip static symbols in this section in files with the MY_DYLDLINK f...
Definition: MachO.h:198
bool isVirtualSection(uint8_t type)
Definition: MachO.h:595
SectionType
These are the section type and attributes fields.
Definition: MachO.h:122
@ LAST_KNOWN_SECTION_TYPE
Definition: MachO.h:183
@ S_SYMBOL_STUBS
S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in the Reserved2 field.
Definition: MachO.h:144
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1286
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749