xref: /freebsd/contrib/llvm-project/llvm/lib/MC/MCSectionMachO.cpp (revision ebacd8013fe5f7fdf9f6a5b286f6680dd2891036)
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 
13 namespace llvm {
14 class MCAsmInfo;
15 class MCExpr;
16 class MCSymbol;
17 class Triple;
18 } // namespace llvm
19 
20 using 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.
25 static constexpr struct {
26   StringLiteral AssemblerName, EnumName;
27 } SectionTypeDescriptors[MachO::LAST_KNOWN_SECTION_TYPE + 1] = {
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 };
66 
67 /// SectionAttrDescriptors - This is an array of descriptors for section
68 /// attributes.  Unlike the SectionTypeDescriptors, this is not directly indexed
69 /// by attribute, instead it is searched.
70 static constexpr struct {
71   unsigned AttrFlag;
72   StringLiteral AssemblerName, EnumName;
73 } SectionAttrDescriptors[] = {
74 #define ENTRY(ASMNAME, ENUM) \
75   { MachO::ENUM, StringLiteral(ASMNAME), StringLiteral(#ENUM) },
76 ENTRY("pure_instructions",   S_ATTR_PURE_INSTRUCTIONS)
77 ENTRY("no_toc",              S_ATTR_NO_TOC)
78 ENTRY("strip_static_syms",   S_ATTR_STRIP_STATIC_SYMS)
79 ENTRY("no_dead_strip",       S_ATTR_NO_DEAD_STRIP)
80 ENTRY("live_support",        S_ATTR_LIVE_SUPPORT)
81 ENTRY("self_modifying_code", S_ATTR_SELF_MODIFYING_CODE)
82 ENTRY("debug",               S_ATTR_DEBUG)
83 ENTRY("" /*FIXME*/,          S_ATTR_SOME_INSTRUCTIONS)
84 ENTRY("" /*FIXME*/,          S_ATTR_EXT_RELOC)
85 ENTRY("" /*FIXME*/,          S_ATTR_LOC_RELOC)
86 #undef ENTRY
87   { 0, StringLiteral("none"), StringLiteral("") }, // used if section has no attributes but has a stub size
88 };
89 
90 MCSectionMachO::MCSectionMachO(StringRef Segment, StringRef Section,
91                                unsigned TAA, unsigned reserved2, SectionKind K,
92                                MCSymbol *Begin)
93     : MCSection(SV_MachO, Section, K, Begin), TypeAndAttributes(TAA),
94       Reserved2(reserved2) {
95   assert(Segment.size() <= 16 && Section.size() <= 16 &&
96          "Segment or section string too long");
97   for (unsigned i = 0; i != 16; ++i) {
98     if (i < Segment.size())
99       SegmentName[i] = Segment[i];
100     else
101       SegmentName[i] = 0;
102   }
103 }
104 
105 void MCSectionMachO::printSwitchToSection(const MCAsmInfo &MAI, const Triple &T,
106                                           raw_ostream &OS,
107                                           const MCExpr *Subsection) const {
108   OS << "\t.section\t" << getSegmentName() << ',' << getName();
109 
110   // Get the section type and attributes.
111   unsigned TAA = getTypeAndAttributes();
112   if (TAA == 0) {
113     OS << '\n';
114     return;
115   }
116 
117   MachO::SectionType SectionType = getType();
118   assert(SectionType <= MachO::LAST_KNOWN_SECTION_TYPE &&
119          "Invalid SectionType specified!");
120 
121   if (!SectionTypeDescriptors[SectionType].AssemblerName.empty()) {
122     OS << ',';
123     OS << SectionTypeDescriptors[SectionType].AssemblerName;
124   } else {
125     // If we have no name for the attribute, stop here.
126     OS << '\n';
127     return;
128   }
129 
130   // If we don't have any attributes, we're done.
131   unsigned SectionAttrs = TAA & MachO::SECTION_ATTRIBUTES;
132   if (SectionAttrs == 0) {
133     // If we have a S_SYMBOL_STUBS size specified, print it along with 'none' as
134     // the attribute specifier.
135     if (Reserved2 != 0)
136       OS << ",none," << Reserved2;
137     OS << '\n';
138     return;
139   }
140 
141   // Check each attribute to see if we have it.
142   char Separator = ',';
143   for (unsigned i = 0;
144        SectionAttrs != 0 && SectionAttrDescriptors[i].AttrFlag;
145        ++i) {
146     // Check to see if we have this attribute.
147     if ((SectionAttrDescriptors[i].AttrFlag & SectionAttrs) == 0)
148       continue;
149 
150     // Yep, clear it and print it.
151     SectionAttrs &= ~SectionAttrDescriptors[i].AttrFlag;
152 
153     OS << Separator;
154     if (!SectionAttrDescriptors[i].AssemblerName.empty())
155       OS << SectionAttrDescriptors[i].AssemblerName;
156     else
157       OS << "<<" << SectionAttrDescriptors[i].EnumName << ">>";
158     Separator = '+';
159   }
160 
161   assert(SectionAttrs == 0 && "Unknown section attributes!");
162 
163   // If we have a S_SYMBOL_STUBS size specified, print it.
164   if (Reserved2 != 0)
165     OS << ',' << Reserved2;
166   OS << '\n';
167 }
168 
169 bool MCSectionMachO::useCodeAlign() const {
170   return hasAttribute(MachO::S_ATTR_PURE_INSTRUCTIONS);
171 }
172 
173 bool MCSectionMachO::isVirtualSection() const {
174   return (getType() == MachO::S_ZEROFILL ||
175           getType() == MachO::S_GB_ZEROFILL ||
176           getType() == MachO::S_THREAD_LOCAL_ZEROFILL);
177 }
178 
179 /// ParseSectionSpecifier - Parse the section specifier indicated by "Spec".
180 /// This is a string that can appear after a .section directive in a mach-o
181 /// flavored .s file.  If successful, this fills in the specified Out
182 /// parameters and returns an empty string.  When an invalid section
183 /// specifier is present, this returns a string indicating the problem.
184 Error MCSectionMachO::ParseSectionSpecifier(StringRef Spec,       // In.
185                                             StringRef &Segment,   // Out.
186                                             StringRef &Section,   // Out.
187                                             unsigned &TAA,        // Out.
188                                             bool &TAAParsed,      // Out.
189                                             unsigned &StubSize) { // Out.
190   TAAParsed = false;
191 
192   SmallVector<StringRef, 5> SplitSpec;
193   Spec.split(SplitSpec, ',');
194   // Remove leading and trailing whitespace.
195   auto GetEmptyOrTrim = [&SplitSpec](size_t Idx) -> StringRef {
196     return SplitSpec.size() > Idx ? SplitSpec[Idx].trim() : StringRef();
197   };
198   Segment = GetEmptyOrTrim(0);
199   Section = GetEmptyOrTrim(1);
200   StringRef SectionType = GetEmptyOrTrim(2);
201   StringRef Attrs = GetEmptyOrTrim(3);
202   StringRef StubSizeStr = GetEmptyOrTrim(4);
203 
204   // Verify that the section is present.
205   if (Section.empty())
206     return createStringError(inconvertibleErrorCode(),
207                              "mach-o section specifier requires a segment "
208                              "and section separated by a comma");
209 
210   // Verify that the section is not too long.
211   if (Section.size() > 16)
212     return createStringError(inconvertibleErrorCode(),
213                              "mach-o section specifier requires a section "
214                              "whose length is between 1 and 16 characters");
215 
216   // If there is no comma after the section, we're done.
217   TAA = 0;
218   StubSize = 0;
219   if (SectionType.empty())
220     return Error::success();
221 
222   // Figure out which section type it is.
223   auto TypeDescriptor =
224       llvm::find_if(SectionTypeDescriptors,
225                     [&](decltype(*SectionTypeDescriptors) &Descriptor) {
226                       return SectionType == Descriptor.AssemblerName;
227                     });
228 
229   // If we didn't find the section type, reject it.
230   if (TypeDescriptor == std::end(SectionTypeDescriptors))
231     return createStringError(inconvertibleErrorCode(),
232                              "mach-o section specifier uses an unknown "
233                              "section type");
234 
235   // Remember the TypeID.
236   TAA = TypeDescriptor - std::begin(SectionTypeDescriptors);
237   TAAParsed = true;
238 
239   // If we have no comma after the section type, there are no attributes.
240   if (Attrs.empty()) {
241     // S_SYMBOL_STUBS always require a symbol stub size specifier.
242     if (TAA == MachO::S_SYMBOL_STUBS)
243       return createStringError(inconvertibleErrorCode(),
244                                "mach-o section specifier of type "
245                                "'symbol_stubs' requires a size specifier");
246     return Error::success();
247   }
248 
249   // The attribute list is a '+' separated list of attributes.
250   SmallVector<StringRef, 1> SectionAttrs;
251   Attrs.split(SectionAttrs, '+', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
252 
253   for (StringRef &SectionAttr : SectionAttrs) {
254     auto AttrDescriptorI =
255         llvm::find_if(SectionAttrDescriptors,
256                       [&](decltype(*SectionAttrDescriptors) &Descriptor) {
257                         return SectionAttr.trim() == Descriptor.AssemblerName;
258                       });
259     if (AttrDescriptorI == std::end(SectionAttrDescriptors))
260       return createStringError(inconvertibleErrorCode(),
261                                "mach-o section specifier has invalid "
262                                "attribute");
263 
264     TAA |= AttrDescriptorI->AttrFlag;
265   }
266 
267   // Okay, we've parsed the section attributes, see if we have a stub size spec.
268   if (StubSizeStr.empty()) {
269     // S_SYMBOL_STUBS always require a symbol stub size specifier.
270     if (TAA == MachO::S_SYMBOL_STUBS)
271       return createStringError(inconvertibleErrorCode(),
272                                "mach-o section specifier of type "
273                                "'symbol_stubs' requires a size specifier");
274     return Error::success();
275   }
276 
277   // If we have a stub size spec, we must have a sectiontype of S_SYMBOL_STUBS.
278   if ((TAA & MachO::SECTION_TYPE) != MachO::S_SYMBOL_STUBS)
279     return createStringError(inconvertibleErrorCode(),
280                              "mach-o section specifier cannot have a stub "
281                              "size specified because it does not have type "
282                              "'symbol_stubs'");
283 
284   // Convert the stub size from a string to an integer.
285   if (StubSizeStr.getAsInteger(0, StubSize))
286     return createStringError(inconvertibleErrorCode(),
287                              "mach-o section specifier has a malformed "
288                              "stub size");
289 
290   return Error::success();
291 }
292