LLVM 24.0.0git
DebuggerSupportPlugin.cpp
Go to the documentation of this file.
1//===------- DebuggerSupportPlugin.cpp - Utils for debugger support -------===//
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//
10//===----------------------------------------------------------------------===//
11
15
20
21#include <chrono>
22
23#define DEBUG_TYPE "orc"
24
25using namespace llvm;
26using namespace llvm::jitlink;
27using namespace llvm::orc;
28
29static const char *SynthDebugSectionName = "__jitlink_synth_debug_object";
30
31namespace {
32
33class MachODebugObjectSynthesizerBase
35public:
36 static bool isDebugSection(Section &Sec) {
37 return Sec.getName().starts_with("__DWARF,");
38 }
39
40 MachODebugObjectSynthesizerBase(LinkGraph &G, ExecutorAddr RegisterActionAddr)
41 : G(G), RegisterActionAddr(RegisterActionAddr) {}
42 ~MachODebugObjectSynthesizerBase() override = default;
43
45 if (G.findSectionByName(SynthDebugSectionName)) {
47 dbgs() << "MachODebugObjectSynthesizer skipping graph " << G.getName()
48 << " which contains an unexpected existing "
49 << SynthDebugSectionName << " section.\n";
50 });
51 return Error::success();
52 }
53
55 dbgs() << "MachODebugObjectSynthesizer visiting graph " << G.getName()
56 << "\n";
57 });
58 for (auto &Sec : G.sections()) {
59 if (!isDebugSection(Sec))
60 continue;
61 // Preserve blocks in this debug section by marking one existing symbol
62 // live for each block, and introducing a new live, anonymous symbol for
63 // each currently unreferenced block.
65 dbgs() << " Preserving debug section " << Sec.getName() << "\n";
66 });
67 SmallPtrSet<Block *, 8> PreservedBlocks;
68 for (auto *Sym : Sec.symbols()) {
69 bool NewPreservedBlock =
70 PreservedBlocks.insert(&Sym->getBlock()).second;
71 if (NewPreservedBlock)
72 Sym->setLive(true);
73 }
74 for (auto *B : Sec.blocks())
75 if (!PreservedBlocks.count(B))
76 G.addAnonymousSymbol(*B, 0, 0, false, true);
77 }
78
79 return Error::success();
80 }
81
82protected:
83 LinkGraph &G;
84 ExecutorAddr RegisterActionAddr;
85};
86
87template <typename MachOTraits>
88class MachODebugObjectSynthesizer : public MachODebugObjectSynthesizerBase {
89public:
90 MachODebugObjectSynthesizer(ExecutionSession &ES, LinkGraph &G,
91 ExecutorAddr RegisterActionAddr)
92 : MachODebugObjectSynthesizerBase(G, RegisterActionAddr),
93 Builder(ES.getPageSize()) {}
94
95 using MachODebugObjectSynthesizerBase::MachODebugObjectSynthesizerBase;
96
97 Error startSynthesis() override {
99 dbgs() << "Creating " << SynthDebugSectionName << " for " << G.getName()
100 << "\n";
101 });
102
103 for (auto &Sec : G.sections()) {
104 if (Sec.blocks().empty())
105 continue;
106
107 // Skip sections whose name's don't fit the MachO standard.
108 if (Sec.getName().empty() || Sec.getName().size() > 33 ||
109 Sec.getName().find(',') > 16)
110 continue;
111
112 if (isDebugSection(Sec))
113 DebugSections.push_back({&Sec, nullptr});
114 else if (Sec.getMemLifetime() != MemLifetime::NoAlloc)
115 NonDebugSections.push_back({&Sec, nullptr});
116 }
117
118 // Bail out early if no debug sections.
119 if (DebugSections.empty())
120 return Error::success();
121
122 // Write MachO header and debug section load commands.
123 Builder.Header.filetype = MachO::MH_OBJECT;
124 if (auto CPUType = MachO::getCPUType(G.getTargetTriple()))
125 Builder.Header.cputype = *CPUType;
126 else
127 return CPUType.takeError();
128 if (auto CPUSubType = MachO::getCPUSubType(G.getTargetTriple()))
129 Builder.Header.cpusubtype = *CPUSubType;
130 else
131 return CPUSubType.takeError();
132
133 Seg = &Builder.addSegment("");
134
136 StringRef DebugLineSectionData;
137 for (auto &DSec : DebugSections) {
138 auto [SegName, SecName] = DSec.GraphSec->getName().split(',');
139 DSec.BuilderSec = &Seg->addSection(SecName, SegName);
140
141 SectionRange SR(*DSec.GraphSec);
142 DSec.BuilderSec->Content.Size = SR.getSize();
143 if (!SR.empty()) {
144 DSec.BuilderSec->align = Log2_64(SR.getFirstBlock()->getAlignment());
145 StringRef SectionData(SR.getFirstBlock()->getContent().data(),
146 SR.getFirstBlock()->getSize());
147 DebugSectionMap[SecName.drop_front(2)] = // drop "__" prefix.
148 MemoryBuffer::getMemBuffer(SectionData, G.getName(), false);
149 if (SecName == "__debug_line")
150 DebugLineSectionData = SectionData;
151 }
152 }
153
154 std::optional<StringRef> FileName;
155 if (!DebugLineSectionData.empty()) {
156 assert((G.getEndianness() == llvm::endianness::big ||
157 G.getEndianness() == llvm::endianness::little) &&
158 "G.getEndianness() must be either big or little");
159 auto DWARFCtx =
160 DWARFContext::create(DebugSectionMap, G.getPointerSize(),
161 G.getEndianness() == llvm::endianness::little);
162 DWARFDataExtractor DebugLineData(
163 DebugLineSectionData, G.getEndianness() == llvm::endianness::little,
164 G.getPointerSize());
165 uint64_t Offset = 0;
167
168 // Try to parse line data. Consume error on failure.
169 if (auto Err = P.parse(DebugLineData, &Offset, consumeError, *DWARFCtx)) {
170 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
171 LLVM_DEBUG({
172 dbgs() << "Cannot parse line table for \"" << G.getName() << "\": ";
173 EIB.log(dbgs());
174 dbgs() << "\n";
175 });
176 });
177 } else {
178 for (auto &FN : P.FileNames)
179 if ((FileName = dwarf::toString(FN.Name))) {
180 LLVM_DEBUG({
181 dbgs() << "Using FileName = \"" << *FileName
182 << "\" from DWARF line table\n";
183 });
184 break;
185 }
186 }
187 }
188
189 // If no line table (or unable to use) then use graph name.
190 // FIXME: There are probably other debug sections we should look in first.
191 if (!FileName) {
192 LLVM_DEBUG({
193 dbgs() << "Could not find source name from DWARF line table. "
194 "Using FileName = \"\"\n";
195 });
196 FileName = "";
197 }
198
199 Builder.addSymbol("", MachO::N_SO, 0, 0, 0);
200 Builder.addSymbol(*FileName, MachO::N_SO, 0, 0, 0);
201 auto TimeStamp = std::chrono::duration_cast<std::chrono::seconds>(
202 std::chrono::system_clock::now().time_since_epoch())
203 .count();
204 Builder.addSymbol("", MachO::N_OSO, 3, 1, TimeStamp);
205
206 for (auto &NDSP : NonDebugSections) {
207 auto [SegName, SecName] = NDSP.GraphSec->getName().split(',');
208 NDSP.BuilderSec = &Seg->addSection(SecName, SegName);
209 SectionRange SR(*NDSP.GraphSec);
210 if (!SR.empty())
211 NDSP.BuilderSec->align = Log2_64(SR.getFirstBlock()->getAlignment());
212
213 // Add stabs.
214 for (auto *Sym : NDSP.GraphSec->symbols()) {
215 // Skip anonymous symbols.
216 if (!Sym->hasName())
217 continue;
218
219 uint8_t SymType = Sym->isCallable() ? MachO::N_FUN : MachO::N_GSYM;
220
221 Builder.addSymbol("", MachO::N_BNSYM, 1, 0, 0);
222 StabSymbols.push_back(
223 {*Sym, Builder.addSymbol(*Sym->getName(), SymType, 1, 0, 0),
224 Builder.addSymbol(*Sym->getName(), SymType, 0, 0, 0)});
225 Builder.addSymbol("", MachO::N_ENSYM, 1, 0, 0);
226 }
227 }
228
229 Builder.addSymbol("", MachO::N_SO, 1, 0, 0);
230
231 // Lay out the debug object, create a section and block for it.
232 size_t DebugObjectSize = Builder.layout();
233
234 auto &SDOSec = G.createSection(SynthDebugSectionName, MemProt::Read);
235 MachOContainerBlock = &G.createMutableContentBlock(
236 SDOSec, G.allocateBuffer(DebugObjectSize), orc::ExecutorAddr(), 8, 0);
237
238 return Error::success();
239 }
240
241 Error completeSynthesisAndRegister() override {
242 if (!MachOContainerBlock) {
243 LLVM_DEBUG({
244 dbgs() << "Not writing MachO debug object header for " << G.getName()
245 << " since createDebugSection failed\n";
246 });
247
248 return Error::success();
249 }
250 ExecutorAddr MaxAddr;
251 for (auto &NDSec : NonDebugSections) {
252 SectionRange SR(*NDSec.GraphSec);
253 NDSec.BuilderSec->addr = SR.getStart().getValue();
254 NDSec.BuilderSec->size = SR.getSize();
255 NDSec.BuilderSec->offset = SR.getStart().getValue();
256 if (SR.getEnd() > MaxAddr)
257 MaxAddr = SR.getEnd();
258 }
259
260 for (auto &DSec : DebugSections) {
261 if (DSec.GraphSec->blocks_size() != 1)
263 "Unexpected number of blocks in debug info section",
265
266 if (ExecutorAddr(DSec.BuilderSec->addr) + DSec.BuilderSec->size > MaxAddr)
267 MaxAddr = ExecutorAddr(DSec.BuilderSec->addr) + DSec.BuilderSec->size;
268
269 auto &B = **DSec.GraphSec->blocks().begin();
270 DSec.BuilderSec->Content.Data = B.getContent().data();
271 DSec.BuilderSec->Content.Size = B.getContent().size();
272 DSec.BuilderSec->flags |= MachO::S_ATTR_DEBUG;
273 }
274
275 LLVM_DEBUG({
276 dbgs() << "Writing MachO debug object header for " << G.getName() << "\n";
277 });
278
279 // Update stab symbol addresses.
280 for (auto &SS : StabSymbols) {
281 SS.StartStab.nlist().n_value = SS.Sym.getAddress().getValue();
282 SS.EndStab.nlist().n_value = SS.Sym.getSize();
283 }
284
285 Builder.write(MachOContainerBlock->getAlreadyMutableContent());
286
287 SectionRange R(MachOContainerBlock->getSection());
288 G.allocActions().push_back(
291 RegisterActionAddr, R.getRange())),
292 {}});
293
294 return Error::success();
295 }
296
297private:
298 struct SectionPair {
299 Section *GraphSec = nullptr;
300 typename MachOBuilder<MachOTraits>::Section *BuilderSec = nullptr;
301 };
302
303 struct StabSymbolsEntry {
304 using RelocTarget = typename MachOBuilder<MachOTraits>::RelocTarget;
305
306 StabSymbolsEntry(Symbol &Sym, RelocTarget StartStab, RelocTarget EndStab)
307 : Sym(Sym), StartStab(StartStab), EndStab(EndStab) {}
308
309 Symbol &Sym;
310 RelocTarget StartStab, EndStab;
311 };
312
313 using BuilderType = MachOBuilder<MachOTraits>;
314
315 Block *MachOContainerBlock = nullptr;
317 typename MachOBuilder<MachOTraits>::Segment *Seg = nullptr;
318 std::vector<StabSymbolsEntry> StabSymbols;
319 SmallVector<SectionPair, 16> DebugSections;
320 SmallVector<SectionPair, 16> NonDebugSections;
321};
322
323} // end anonymous namespace
324
325namespace llvm {
326namespace orc {
327
328Expected<std::unique_ptr<GDBJITDebugInfoRegistrationPlugin>>
330 JITDylib &BootstrapJD) {
331 auto RegisterActionName = ES.intern(rt::RegisterJITLoaderGDBAllocActionName);
332
333 if (auto RegisterSym = ES.lookup({&BootstrapJD}, RegisterActionName))
334 return std::make_unique<GDBJITDebugInfoRegistrationPlugin>(
335 RegisterSym->getAddress());
336 else
337 return RegisterSym.takeError();
338}
339
344
349
352
355 PassConfiguration &PassConfig) {
356
358 modifyPassConfigForMachO(MR, LG, PassConfig);
359 else {
360 LLVM_DEBUG({
361 dbgs() << "GDBJITDebugInfoRegistrationPlugin skipping unspported graph "
362 << LG.getName() << "(triple = " << LG.getTargetTriple().str()
363 << "\n";
364 });
365 }
366}
367
368void GDBJITDebugInfoRegistrationPlugin::modifyPassConfigForMachO(
370 jitlink::PassConfiguration &PassConfig) {
371
372 switch (LG.getTargetTriple().getArch()) {
373 case Triple::x86_64:
374 case Triple::aarch64:
375 // Supported, continue.
376 assert(LG.getPointerSize() == 8 && "Graph has incorrect pointer size");
378 "Graph has incorrect endianness");
379 break;
380 default:
381 // Unsupported.
382 LLVM_DEBUG({
383 dbgs() << "GDBJITDebugInfoRegistrationPlugin skipping unsupported "
384 << "MachO graph " << LG.getName()
385 << "(triple = " << LG.getTargetTriple().str()
386 << ", pointer size = " << LG.getPointerSize() << ", endianness = "
387 << (LG.getEndianness() == llvm::endianness::big ? "big" : "little")
388 << ")\n";
389 });
390 return;
391 }
392
393 // Scan for debug sections. If we find one then install passes.
394 bool HasDebugSections = false;
395 for (auto &Sec : LG.sections())
396 if (MachODebugObjectSynthesizerBase::isDebugSection(Sec)) {
397 HasDebugSections = true;
398 break;
399 }
400
401 if (HasDebugSections) {
402 LLVM_DEBUG({
403 dbgs() << "GDBJITDebugInfoRegistrationPlugin: Graph " << LG.getName()
404 << " contains debug info. Installing debugger support passes.\n";
405 });
406
407 auto MDOS = std::make_shared<MachODebugObjectSynthesizer<MachO64LE>>(
408 MR.getTargetJITDylib().getExecutionSession(), LG, RegisterActionAddr);
409 PassConfig.PrePrunePasses.push_back(
410 [=](LinkGraph &G) { return MDOS->preserveDebugSections(); });
411 PassConfig.PostPrunePasses.push_back(
412 [=](LinkGraph &G) { return MDOS->startSynthesis(); });
413 PassConfig.PostFixupPasses.push_back(
414 [=](LinkGraph &G) { return MDOS->completeSynthesisAndRegister(); });
415 } else {
416 LLVM_DEBUG({
417 dbgs() << "GDBJITDebugInfoRegistrationPlugin: Graph " << LG.getName()
418 << " contains no debug info. Skipping.\n";
419 });
420 }
421}
422
423} // namespace orc
424} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static const char * SynthDebugSectionName
static bool isDebugSection(const SectionBase &Sec)
#define G(x, y, z)
Definition MD5.cpp:55
#define P(N)
This file defines the SmallVector class.
#define LLVM_DEBUG(...)
Definition Debug.h:119
const T * data() const
Definition ArrayRef.h:138
static std::unique_ptr< DWARFContext > create(const object::ObjectFile &Obj, ProcessDebugRelocations RelocAction=ProcessDebugRelocations::Process, const LoadedObjectInfo *L=nullptr, std::string DWPName="", std::function< void(Error)> RecoverableErrorHandler=WithColor::defaultErrorHandler, std::function< void(Error)> WarningHandler=WithColor::defaultWarningHandler, bool ThreadSafe=false)
A DWARFDataExtractor (typically for an in-memory copy of an object-file section) plus a relocation ma...
Base class for error info classes.
Definition Error.h:44
virtual void log(raw_ostream &OS) const =0
Print an error message to an output stream.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:128
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
size_t count(char C) const
Return the number of occurrences of C in the string.
Definition StringRef.h:471
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition Triple.h:536
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:512
const std::string & str() const
Definition Triple.h:577
An ExecutionSession represents a running JIT program.
Definition Core.h:1111
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition Core.h:1170
LLVM_ABI void lookup(LookupKind K, const JITDylibSearchOrder &SearchOrder, SymbolLookupSet Symbols, SymbolState RequiredState, SymbolsResolvedCallback NotifyComplete, RegisterDependenciesFunction RegisterDependencies)
Search the given JITDylibs for the given symbols.
Definition Core.cpp:1764
size_t getPageSize() const
Definition Core.h:1162
Represents an address in the executor process.
uint64_t getValue() const
void modifyPassConfig(MaterializationResponsibility &MR, jitlink::LinkGraph &LG, jitlink::PassConfiguration &PassConfig) override
void notifyTransferringResources(JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) override
static Expected< std::unique_ptr< GDBJITDebugInfoRegistrationPlugin > > Create(ExecutionSession &ES, JITDylib &BootstrapJD)
Error notifyRemovingResources(JITDylib &JD, ResourceKey K) override
Error notifyFailed(MaterializationResponsibility &MR) override
Represents a JIT'd dynamic library.
Definition Core.h:675
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition Core.h:349
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition Core.h:374
A utility class for serializing to a blob from a variadic list.
static Expected< WrapperFunctionCall > Create(ExecutorAddr FnAddr, const ArgTs &...Args)
Create a WrapperFunctionCall using the given SPS serializer to serialize the arguments.
LLVM_ABI Expected< uint32_t > getCPUSubType(const Triple &T)
Definition MachO.cpp:107
@ MH_OBJECT
Definition MachO.h:43
LLVM_ABI Expected< uint32_t > getCPUType(const Triple &T)
Definition MachO.cpp:87
@ S_ATTR_DEBUG
S_ATTR_DEBUG - A debug section.
Definition MachO.h:207
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
LLVM_ABI const char * RegisterJITLoaderGDBAllocActionName
LLVM_ABI Error preserveDebugSections(jitlink::LinkGraph &G)
uintptr_t ResourceKey
Definition Core.h:60
@ NoAlloc
NoAlloc memory should not be allocated by the JITLinkMemoryManager at all.
Definition MemoryFlags.h:88
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:338
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition Error.h:769
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106