summaryrefslogtreecommitdiffstats
path: root/llvm/lib/ExecutionEngine/JITLink/MachOAtomGraphBuilder.cpp
blob: 92c7e49039a9d3c8af5370b7fffa0e827f172dbe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//=--------- MachOAtomGraphBuilder.cpp - MachO AtomGraph builder ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Generic MachO AtomGraph buliding code.
//
//===----------------------------------------------------------------------===//

#include "MachOAtomGraphBuilder.h"

#define DEBUG_TYPE "jitlink"

namespace llvm {
namespace jitlink {

MachOAtomGraphBuilder::~MachOAtomGraphBuilder() {}

Expected<std::unique_ptr<AtomGraph>> MachOAtomGraphBuilder::buildGraph() {
  if (auto Err = parseSections())
    return std::move(Err);

  if (auto Err = addAtoms())
    return std::move(Err);

  if (auto Err = addRelocations())
    return std::move(Err);

  return std::move(G);
}

MachOAtomGraphBuilder::MachOAtomGraphBuilder(const object::MachOObjectFile &Obj)
    : Obj(Obj),
      G(llvm::make_unique<AtomGraph>(Obj.getFileName(), getPointerSize(Obj),
                                     getEndianness(Obj))) {}

void MachOAtomGraphBuilder::addCustomAtomizer(StringRef SectionName,
                                              CustomAtomizeFunction Atomizer) {
  assert(!CustomAtomizeFunctions.count(SectionName) &&
         "Custom atomizer for this section already exists");
  CustomAtomizeFunctions[SectionName] = std::move(Atomizer);
}

bool MachOAtomGraphBuilder::areLayoutLocked(const Atom &A, const Atom &B) {
  // If these atoms are the same then they're trivially "locked".
  if (&A == &B)
    return true;

  // If A and B are different, check whether either is undefined. (in which
  // case they are not locked).
  if (!A.isDefined() || !B.isDefined())
    return false;

  // A and B are different, but they're both defined atoms. We need to check
  // whether they're part of the same alt_entry chain.
  auto &DA = static_cast<const DefinedAtom &>(A);
  auto &DB = static_cast<const DefinedAtom &>(B);

  auto AStartItr = AltEntryStarts.find(&DA);
  if (AStartItr == AltEntryStarts.end()) // If A is not in a chain bail out.
    return false;

  auto BStartItr = AltEntryStarts.find(&DB);
  if (BStartItr == AltEntryStarts.end()) // If B is not in a chain bail out.
    return false;

  // A and B are layout locked if they're in the same chain.
  return AStartItr->second == BStartItr->second;
}

unsigned
MachOAtomGraphBuilder::getPointerSize(const object::MachOObjectFile &Obj) {
  return Obj.is64Bit() ? 8 : 4;
}

support::endianness
MachOAtomGraphBuilder::getEndianness(const object::MachOObjectFile &Obj) {
  return Obj.isLittleEndian() ? support::little : support::big;
}

MachOAtomGraphBuilder::MachOSection &MachOAtomGraphBuilder::getCommonSection() {
  if (!CommonSymbolsSection) {
    auto Prot = static_cast<sys::Memory::ProtectionFlags>(
        sys::Memory::MF_READ | sys::Memory::MF_WRITE);
    auto &GenericSection = G->createSection("<common>", 1, Prot, true);
    CommonSymbolsSection = MachOSection(GenericSection);
  }
  return *CommonSymbolsSection;
}

Error MachOAtomGraphBuilder::parseSections() {
  for (auto &SecRef : Obj.sections()) {
    assert((SecRef.getAlignment() <= std::numeric_limits<uint32_t>::max()) &&
           "Section alignment does not fit in 32 bits");

    Expected<StringRef> NameOrErr = SecRef.getName();
    if (!NameOrErr)
      return NameOrErr.takeError();
    StringRef Name = *NameOrErr;

    unsigned SectionIndex = SecRef.getIndex() + 1;

    uint32_t Align = SecRef.getAlignment();
    if (!isPowerOf2_32(Align))
      return make_error<JITLinkError>("Section " + Name +
                                      " has non-power-of-2 "
                                      "alignment");

    // FIXME: Get real section permissions
    // How, exactly, on MachO?
    sys::Memory::ProtectionFlags Prot;
    if (SecRef.isText())
      Prot = static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
                                                       sys::Memory::MF_EXEC);
    else
      Prot = static_cast<sys::Memory::ProtectionFlags>(sys::Memory::MF_READ |
                                                       sys::Memory::MF_WRITE);

    auto &GenericSection = G->createSection(Name, Align, Prot, SecRef.isBSS());

    LLVM_DEBUG({
      dbgs() << "Adding section " << Name << ": "
             << format("0x%016" PRIx64, SecRef.getAddress())
             << ", align: " << SecRef.getAlignment() << "\n";
    });

    assert(!Sections.count(SectionIndex) && "Section index already in use");

    auto &MachOSec =
        Sections
            .try_emplace(SectionIndex, GenericSection, SecRef.getAddress(),
                         SecRef.getAlignment())
            .first->second;

    if (!SecRef.isVirtual()) {
      // If this section has content then record it.
      Expected<StringRef> Content = SecRef.getContents();
      if (!Content)
        return Content.takeError();
      if (Content->size() != SecRef.getSize())
        return make_error<JITLinkError>("Section content size does not match "
                                        "declared size for " +
                                        Name);
      MachOSec.setContent(*Content);
    } else {
      // If this is a zero-fill section then just record the size.
      MachOSec.setZeroFill(SecRef.getSize());
    }

    uint32_t SectionFlags =
        Obj.is64Bit() ? Obj.getSection64(SecRef.getRawDataRefImpl()).flags
                      : Obj.getSection(SecRef.getRawDataRefImpl()).flags;

    MachOSec.setNoDeadStrip(SectionFlags & MachO::S_ATTR_NO_DEAD_STRIP);
  }

  return Error::success();
}

// Adds atoms with identified start addresses (but not lengths) for all named
// atoms.
// Also, for every section that contains named atoms, but does not have an
// atom at offset zero of that section, constructs an anonymous atom covering
// that range.
Error MachOAtomGraphBuilder::addNonCustomAtoms() {
  using AddrToAtomMap = std::map<JITTargetAddress, DefinedAtom *>;
  DenseMap<MachOSection *, AddrToAtomMap> SecToAtoms;

  DenseMap<MachOSection *, unsigned> FirstOrdinal;
  std::vector<DefinedAtom *> AltEntryAtoms;

  DenseSet<StringRef> ProcessedSymbols; // Used to check for duplicate defs.

  for (auto SymI = Obj.symbol_begin(), SymE = Obj.symbol_end(); SymI != SymE;
       ++SymI) {
    object::SymbolRef Sym(SymI->getRawDataRefImpl(), &Obj);

    auto Name = Sym.getName();
    if (!Name)
      return Name.takeError();

    // Bail out on duplicate definitions: There should never be more than one
    // definition for a symbol in a given object file.
    if (ProcessedSymbols.count(*Name))
      return make_error<JITLinkError>("Duplicate definition within object: " +
                                      *Name);
    else
      ProcessedSymbols.insert(*Name);

    auto Addr = Sym.getAddress();
    if (!Addr)
      return Addr.takeError();

    auto SymType = Sym.getType();
    if (!SymType)
      return SymType.takeError();

    auto Flags = Sym.getFlags();

    if (Flags & object::SymbolRef::SF_Undefined) {
      LLVM_DEBUG(dbgs() << "Adding undef atom \"" << *Name << "\"\n");
      G->addExternalAtom(*Name);
      continue;
    } else if (Flags & object::SymbolRef::SF_Absolute) {
      LLVM_DEBUG(dbgs() << "Adding absolute \"" << *Name << "\" addr: "
                        << format("0x%016" PRIx64, *Addr) << "\n");
      auto &A = G->addAbsoluteAtom(*Name, *Addr);
      A.setGlobal(Flags & object::SymbolRef::SF_Global);
      A.setExported(Flags & object::SymbolRef::SF_Exported);
      A.setWeak(Flags & object::SymbolRef::SF_Weak);
      continue;
    } else if (Flags & object::SymbolRef::SF_Common) {
      LLVM_DEBUG({
        dbgs() << "Adding common \"" << *Name
               << "\" addr: " << format("0x%016" PRIx64, *Addr) << "\n";
      });
      auto &A =
          G->addCommonAtom(getCommonSection().getGenericSection(), *Name, *Addr,
                           std::max(Sym.getAlignment(), 1U),
                           Obj.getCommonSymbolSize(Sym.getRawDataRefImpl()));
      A.setGlobal(Flags & object::SymbolRef::SF_Global);
      A.setExported(Flags & object::SymbolRef::SF_Exported);
      continue;
    }

    LLVM_DEBUG(dbgs() << "Adding defined atom \"" << *Name << "\"\n");

    // This atom is neither undefined nor absolute, so it must be defined in
    // this object. Get its section index.
    auto SecItr = Sym.getSection();
    if (!SecItr)
      return SecItr.takeError();

    uint64_t SectionIndex = (*SecItr)->getIndex() + 1;

    LLVM_DEBUG(dbgs() << "  to section index " << SectionIndex << "\n");

    auto SecByIndexItr = Sections.find(SectionIndex);
    if (SecByIndexItr == Sections.end())
      return make_error<JITLinkError>("Unrecognized section index in macho");

    auto &Sec = SecByIndexItr->second;

    auto &DA = G->addDefinedAtom(Sec.getGenericSection(), *Name, *Addr,
                                 std::max(Sym.getAlignment(), 1U));

    DA.setGlobal(Flags & object::SymbolRef::SF_Global);
    DA.setExported(Flags & object::SymbolRef::SF_Exported);
    DA.setWeak(Flags & object::SymbolRef::SF_Weak);

    DA.setCallable(*SymType & object::SymbolRef::ST_Function);

    // Check NDesc flags.
    {
      uint16_t NDesc = 0;
      if (Obj.is64Bit())
        NDesc = Obj.getSymbol64TableEntry(SymI->getRawDataRefImpl()).n_desc;
      else
        NDesc = Obj.getSymbolTableEntry(SymI->getRawDataRefImpl()).n_desc;

      // Record atom for alt-entry post-processing (where the layout-next
      // constraints will be added).
      if (NDesc & MachO::N_ALT_ENTRY)
        AltEntryAtoms.push_back(&DA);

      // If this atom has a no-dead-strip attr attached then mark it live.
      if (NDesc & MachO::N_NO_DEAD_STRIP)
        DA.setLive(true);
    }

    LLVM_DEBUG({
      dbgs() << "  Added " << *Name
             << " addr: " << format("0x%016" PRIx64, *Addr)
             << ", align: " << DA.getAlignment()
             << ", section: " << Sec.getGenericSection().getName() << "\n";
    });

    auto &SecAtoms = SecToAtoms[&Sec];
    SecAtoms[DA.getAddress() - Sec.getAddress()] = &DA;
  }

  // Add anonymous atoms.
  for (auto &KV : Sections) {
    auto &S = KV.second;

    // Skip empty sections.
    if (S.empty())
      continue;

    // Skip sections with custom handling.
    if (CustomAtomizeFunctions.count(S.getName()))
      continue;

    auto SAI = SecToAtoms.find(&S);

    // If S is not in the SecToAtoms map then it contained no named atom. Add
    // one anonymous atom to cover the whole section.
    if (SAI == SecToAtoms.end()) {
      SecToAtoms[&S][0] = &G->addAnonymousAtom(
          S.getGenericSection(), S.getAddress(), S.getAlignment());
      continue;
    }

    // Otherwise, check whether this section had an atom covering offset zero.
    // If not, add one.
    auto &SecAtoms = SAI->second;
    if (!SecAtoms.count(0))
      SecAtoms[0] = &G->addAnonymousAtom(S.getGenericSection(), S.getAddress(),
                                         S.getAlignment());
  }

  LLVM_DEBUG(dbgs() << "MachOGraphBuilder setting atom content\n");

  // Set atom contents and any section-based flags.
  for (auto &KV : SecToAtoms) {
    auto &S = *KV.first;
    auto &SecAtoms = KV.second;

    // Iterate the atoms in reverse order and set up their contents.
    JITTargetAddress LastAtomAddr = S.getSize();
    for (auto I = SecAtoms.rbegin(), E = SecAtoms.rend(); I != E; ++I) {
      auto Offset = I->first;
      auto &A = *I->second;
      LLVM_DEBUG({
        dbgs() << "  " << A << " to [ " << S.getAddress() + Offset << " .. "
               << S.getAddress() + LastAtomAddr << " ]\n";
      });

      if (S.isZeroFill())
        A.setZeroFill(LastAtomAddr - Offset);
      else
        A.setContent(S.getContent().substr(Offset, LastAtomAddr - Offset));

      // If the section has no-dead-strip set then mark the atom as live.
      if (S.isNoDeadStrip())
        A.setLive(true);

      LastAtomAddr = Offset;
    }
  }

  LLVM_DEBUG(dbgs() << "Adding alt-entry starts\n");

  // Sort alt-entry atoms by address in ascending order.
  llvm::sort(AltEntryAtoms.begin(), AltEntryAtoms.end(),
             [](const DefinedAtom *LHS, const DefinedAtom *RHS) {
               return LHS->getAddress() < RHS->getAddress();
             });

  // Process alt-entry atoms in address order to build the table of alt-entry
  // atoms to alt-entry chain starts.
  for (auto *DA : AltEntryAtoms) {
    assert(!AltEntryStarts.count(DA) && "Duplicate entry in AltEntryStarts");

    // DA is an alt-entry atom. Look for the predecessor atom that it is locked
    // to, bailing out if we do not find one.
    auto AltEntryPred = G->findAtomByAddress(DA->getAddress() - 1);
    if (!AltEntryPred)
      return AltEntryPred.takeError();

    // Add a LayoutNext edge from the predecessor to this atom.
    AltEntryPred->setLayoutNext(*DA);

    // Check to see whether the predecessor itself is an alt-entry atom.
    auto AltEntryStartItr = AltEntryStarts.find(&*AltEntryPred);
    if (AltEntryStartItr != AltEntryStarts.end()) {
      // If the predecessor was an alt-entry atom then re-use its value.
      LLVM_DEBUG({
        dbgs() << "  " << *DA << " -> " << *AltEntryStartItr->second
               << " (based on existing entry for " << *AltEntryPred << ")\n";
      });
      AltEntryStarts[DA] = AltEntryStartItr->second;
    } else {
      // If the predecessor does not have an entry then add an entry for this
      // atom (i.e. the alt_entry atom) and a self-reference entry for the
      /// predecessory atom that is the start of this chain.
      LLVM_DEBUG({
        dbgs() << "  " << *AltEntryPred << " -> " << *AltEntryPred << "\n"
               << "  " << *DA << " -> " << *AltEntryPred << "\n";
      });
      AltEntryStarts[&*AltEntryPred] = &*AltEntryPred;
      AltEntryStarts[DA] = &*AltEntryPred;
    }
  }

  return Error::success();
}

Error MachOAtomGraphBuilder::addAtoms() {
  // Add all named atoms.
  if (auto Err = addNonCustomAtoms())
    return Err;

  // Process special sections.
  for (auto &KV : Sections) {
    auto &S = KV.second;
    auto HI = CustomAtomizeFunctions.find(S.getGenericSection().getName());
    if (HI != CustomAtomizeFunctions.end()) {
      auto &Atomize = HI->second;
      if (auto Err = Atomize(S))
        return Err;
    }
  }

  return Error::success();
}

} // end namespace jitlink
} // end namespace llvm
OpenPOWER on IntegriCloud