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