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