LLVM 18.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
14
15#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/StringSet.h"
21
22#include <chrono>
23
24#define DEBUG_TYPE "orc"
25
26using namespace llvm;
27using namespace llvm::jitlink;
28using namespace llvm::orc;
29
30static const char *SynthDebugSectionName = "__jitlink_synth_debug_object";
31
32namespace {
33
34class MachODebugObjectSynthesizerBase
36public:
37 static bool isDebugSection(Section &Sec) {
38 return Sec.getName().startswith("__DWARF,");
39 }
40
41 MachODebugObjectSynthesizerBase(LinkGraph &G, ExecutorAddr RegisterActionAddr)
42 : G(G), RegisterActionAddr(RegisterActionAddr) {}
43 virtual ~MachODebugObjectSynthesizerBase() = default;
44
46 if (G.findSectionByName(SynthDebugSectionName)) {
48 dbgs() << "MachODebugObjectSynthesizer skipping graph " << G.getName()
49 << " which contains an unexpected existing "
50 << SynthDebugSectionName << " section.\n";
51 });
52 return Error::success();
53 }
54
56 dbgs() << "MachODebugObjectSynthesizer visiting graph " << G.getName()
57 << "\n";
58 });
59 for (auto &Sec : G.sections()) {
60 if (!isDebugSection(Sec))
61 continue;
62 // Preserve blocks in this debug section by marking one existing symbol
63 // live for each block, and introducing a new live, anonymous symbol for
64 // each currently unreferenced block.
66 dbgs() << " Preserving debug section " << Sec.getName() << "\n";
67 });
68 SmallSet<Block *, 8> PreservedBlocks;
69 for (auto *Sym : Sec.symbols()) {
70 bool NewPreservedBlock =
71 PreservedBlocks.insert(&Sym->getBlock()).second;
72 if (NewPreservedBlock)
73 Sym->setLive(true);
74 }
75 for (auto *B : Sec.blocks())
76 if (!PreservedBlocks.count(B))
77 G.addAnonymousSymbol(*B, 0, 0, false, true);
78 }
79
80 return Error::success();
81 }
82
83protected:
84 LinkGraph &G;
85 ExecutorAddr RegisterActionAddr;
86};
87
88template <typename MachOTraits>
89class MachODebugObjectSynthesizer : public MachODebugObjectSynthesizerBase {
90public:
91 MachODebugObjectSynthesizer(ExecutionSession &ES, LinkGraph &G,
92 ExecutorAddr RegisterActionAddr)
93 : MachODebugObjectSynthesizerBase(G, RegisterActionAddr),
94 Builder(ES.getPageSize()) {}
95
96 using MachODebugObjectSynthesizerBase::MachODebugObjectSynthesizerBase;
97
98 Error startSynthesis() override {
100 dbgs() << "Creating " << SynthDebugSectionName << " for " << G.getName()
101 << "\n";
102 });
103
104 for (auto &Sec : G.sections()) {
105 if (Sec.blocks().empty())
106 continue;
107
108 // Skip sections whose name's don't fit the MachO standard.
109 if (Sec.getName().empty() || Sec.getName().size() > 33 ||
110 Sec.getName().find(',') > 16)
111 continue;
112
113 if (isDebugSection(Sec))
114 DebugSections.push_back({&Sec, nullptr});
115 else if (Sec.getMemLifetime() != MemLifetime::NoAlloc)
116 NonDebugSections.push_back({&Sec, nullptr});
117 }
118
119 // Bail out early if no debug sections.
120 if (DebugSections.empty())
121 return Error::success();
122
123 // Write MachO header and debug section load commands.
124 Builder.Header.filetype = MachO::MH_OBJECT;
125 switch (G.getTargetTriple().getArch()) {
126 case Triple::x86_64:
127 Builder.Header.cputype = MachO::CPU_TYPE_X86_64;
128 Builder.Header.cpusubtype = MachO::CPU_SUBTYPE_X86_64_ALL;
129 break;
130 case Triple::aarch64:
131 Builder.Header.cputype = MachO::CPU_TYPE_ARM64;
132 Builder.Header.cpusubtype = MachO::CPU_SUBTYPE_ARM64_ALL;
133 break;
134 default:
135 llvm_unreachable("Unsupported architecture");
136 }
137
138 Seg = &Builder.addSegment("");
139
141 StringRef DebugLineSectionData;
142 for (auto &DSec : DebugSections) {
143 auto [SegName, SecName] = DSec.GraphSec->getName().split(',');
144 DSec.BuilderSec = &Seg->addSection(SecName, SegName);
145
146 SectionRange SR(*DSec.GraphSec);
147 DSec.BuilderSec->Content.Size = SR.getSize();
148 if (!SR.empty()) {
149 DSec.BuilderSec->align = Log2_64(SR.getFirstBlock()->getAlignment());
150 StringRef SectionData(SR.getFirstBlock()->getContent().data(),
151 SR.getFirstBlock()->getSize());
152 DebugSectionMap[SecName] =
153 MemoryBuffer::getMemBuffer(SectionData, G.getName(), false);
154 if (SecName == "__debug_line")
155 DebugLineSectionData = SectionData;
156 }
157 }
158
159 std::optional<StringRef> FileName;
160 if (!DebugLineSectionData.empty()) {
161 auto DWARFCtx = DWARFContext::create(DebugSectionMap, G.getPointerSize(),
162 G.getEndianness());
163 DWARFDataExtractor DebugLineData(
164 DebugLineSectionData,
165 G.getEndianness() == support::endianness::little, G.getPointerSize());
166 uint64_t Offset = 0;
168
169 // Try to parse line data. Consume error on failure.
170 if (auto Err = LineTable.parse(DebugLineData, &Offset, *DWARFCtx, nullptr,
171 consumeError)) {
172 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
173 LLVM_DEBUG({
174 dbgs() << "Cannot parse line table for \"" << G.getName() << "\": ";
175 EIB.log(dbgs());
176 dbgs() << "\n";
177 });
178 });
179 } else {
180 if (!LineTable.Prologue.FileNames.empty())
181 FileName = *dwarf::toString(LineTable.Prologue.FileNames[0].Name);
182 }
183 }
184
185 // If no line table (or unable to use) then use graph name.
186 // FIXME: There are probably other debug sections we should look in first.
187 if (!FileName)
188 FileName = StringRef(G.getName());
189
190 Builder.addSymbol("", MachO::N_SO, 0, 0, 0);
191 Builder.addSymbol(*FileName, MachO::N_SO, 0, 0, 0);
192 auto TimeStamp = std::chrono::duration_cast<std::chrono::seconds>(
193 std::chrono::system_clock::now().time_since_epoch())
194 .count();
195 Builder.addSymbol("", MachO::N_OSO, 3, 1, TimeStamp);
196
197 for (auto &NDSP : NonDebugSections) {
198 auto [SegName, SecName] = NDSP.GraphSec->getName().split(',');
199 NDSP.BuilderSec = &Seg->addSection(SecName, SegName);
200 SectionRange SR(*NDSP.GraphSec);
201 if (!SR.empty())
202 NDSP.BuilderSec->align = Log2_64(SR.getFirstBlock()->getAlignment());
203
204 // Add stabs.
205 for (auto *Sym : NDSP.GraphSec->symbols()) {
206 // Skip anonymous symbols.
207 if (!Sym->hasName())
208 continue;
209
210 uint8_t SymType = Sym->isCallable() ? MachO::N_FUN : MachO::N_GSYM;
211
212 Builder.addSymbol("", MachO::N_BNSYM, 1, 0, 0);
213 StabSymbols.push_back(
214 {*Sym, Builder.addSymbol(Sym->getName(), SymType, 1, 0, 0),
215 Builder.addSymbol(Sym->getName(), SymType, 0, 0, 0)});
216 Builder.addSymbol("", MachO::N_ENSYM, 1, 0, 0);
217 }
218 }
219
220 Builder.addSymbol("", MachO::N_SO, 1, 0, 0);
221
222 // Lay out the debug object, create a section and block for it.
223 size_t DebugObjectSize = Builder.layout();
224
225 auto &SDOSec = G.createSection(SynthDebugSectionName, MemProt::Read);
226 MachOContainerBlock = &G.createMutableContentBlock(
227 SDOSec, G.allocateBuffer(DebugObjectSize), orc::ExecutorAddr(), 8, 0);
228
229 return Error::success();
230 }
231
232 Error completeSynthesisAndRegister() override {
233 if (!MachOContainerBlock) {
234 LLVM_DEBUG({
235 dbgs() << "Not writing MachO debug object header for " << G.getName()
236 << " since createDebugSection failed\n";
237 });
238
239 return Error::success();
240 }
241 ExecutorAddr MaxAddr;
242 for (auto &NDSec : NonDebugSections) {
243 SectionRange SR(*NDSec.GraphSec);
244 NDSec.BuilderSec->addr = SR.getStart().getValue();
245 NDSec.BuilderSec->size = SR.getSize();
246 NDSec.BuilderSec->offset = SR.getStart().getValue();
247 if (SR.getEnd() > MaxAddr)
248 MaxAddr = SR.getEnd();
249 }
250
251 for (auto &DSec : DebugSections) {
252 if (DSec.GraphSec->blocks_size() != 1)
253 return make_error<StringError>(
254 "Unexpected number of blocks in debug info section",
256
257 if (ExecutorAddr(DSec.BuilderSec->addr) + DSec.BuilderSec->size > MaxAddr)
258 MaxAddr = ExecutorAddr(DSec.BuilderSec->addr) + DSec.BuilderSec->size;
259
260 auto &B = **DSec.GraphSec->blocks().begin();
261 DSec.BuilderSec->Content.Data = B.getContent().data();
262 DSec.BuilderSec->Content.Size = B.getContent().size();
263 DSec.BuilderSec->flags |= MachO::S_ATTR_DEBUG;
264 }
265
266 LLVM_DEBUG({
267 dbgs() << "Writing MachO debug object header for " << G.getName() << "\n";
268 });
269
270 // Update stab symbol addresses.
271 for (auto &SS : StabSymbols) {
272 SS.StartStab.nlist().n_value = SS.Sym.getAddress().getValue();
273 SS.EndStab.nlist().n_value = SS.Sym.getSize();
274 }
275
276 Builder.write(MachOContainerBlock->getAlreadyMutableContent());
277
278 static constexpr bool AutoRegisterCode = true;
279 SectionRange R(MachOContainerBlock->getSection());
280 G.allocActions().push_back(
283 RegisterActionAddr, R.getRange(), AutoRegisterCode)),
284 {}});
285
286 return Error::success();
287 }
288
289private:
290 struct SectionPair {
291 Section *GraphSec = nullptr;
292 typename MachOBuilder<MachOTraits>::Section *BuilderSec = nullptr;
293 };
294
295 struct StabSymbolsEntry {
296 using RelocTarget = typename MachOBuilder<MachOTraits>::RelocTarget;
297
298 StabSymbolsEntry(Symbol &Sym, RelocTarget StartStab, RelocTarget EndStab)
299 : Sym(Sym), StartStab(StartStab), EndStab(EndStab) {}
300
301 Symbol &Sym;
302 RelocTarget StartStab, EndStab;
303 };
304
305 using BuilderType = MachOBuilder<MachOTraits>;
306
307 Block *MachOContainerBlock = nullptr;
309 typename MachOBuilder<MachOTraits>::Segment *Seg = nullptr;
310 std::vector<StabSymbolsEntry> StabSymbols;
311 SmallVector<SectionPair, 16> DebugSections;
312 SmallVector<SectionPair, 16> NonDebugSections;
313};
314
315} // end anonymous namespace
316
317namespace llvm {
318namespace orc {
319
322 JITDylib &ProcessJD,
323 const Triple &TT) {
324 auto RegisterActionAddr =
325 TT.isOSBinFormatMachO()
326 ? ES.intern("_llvm_orc_registerJITLoaderGDBAllocAction")
327 : ES.intern("llvm_orc_registerJITLoaderGDBAllocAction");
328
329 if (auto RegisterSym = ES.lookup({&ProcessJD}, RegisterActionAddr))
330 return std::make_unique<GDBJITDebugInfoRegistrationPlugin>(
331 RegisterSym->getAddress());
332 else
333 return RegisterSym.takeError();
334}
335
338 return Error::success();
339}
340
342 JITDylib &JD, ResourceKey K) {
343 return Error::success();
344}
345
347 JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) {}
348
351 PassConfiguration &PassConfig) {
352
354 modifyPassConfigForMachO(MR, LG, PassConfig);
355 else {
356 LLVM_DEBUG({
357 dbgs() << "GDBJITDebugInfoRegistrationPlugin skipping unspported graph "
358 << LG.getName() << "(triple = " << LG.getTargetTriple().str()
359 << "\n";
360 });
361 }
362}
363
364void GDBJITDebugInfoRegistrationPlugin::modifyPassConfigForMachO(
366 jitlink::PassConfiguration &PassConfig) {
367
368 switch (LG.getTargetTriple().getArch()) {
369 case Triple::x86_64:
370 case Triple::aarch64:
371 // Supported, continue.
372 assert(LG.getPointerSize() == 8 && "Graph has incorrect pointer size");
374 "Graph has incorrect endianness");
375 break;
376 default:
377 // Unsupported.
378 LLVM_DEBUG({
379 dbgs() << "GDBJITDebugInfoRegistrationPlugin skipping unsupported "
380 << "MachO graph " << LG.getName()
381 << "(triple = " << LG.getTargetTriple().str()
382 << ", pointer size = " << LG.getPointerSize() << ", endianness = "
383 << (LG.getEndianness() == support::big ? "big" : "little")
384 << ")\n";
385 });
386 return;
387 }
388
389 // Scan for debug sections. If we find one then install passes.
390 bool HasDebugSections = false;
391 for (auto &Sec : LG.sections())
392 if (MachODebugObjectSynthesizerBase::isDebugSection(Sec)) {
393 HasDebugSections = true;
394 break;
395 }
396
397 if (HasDebugSections) {
398 LLVM_DEBUG({
399 dbgs() << "GDBJITDebugInfoRegistrationPlugin: Graph " << LG.getName()
400 << " contains debug info. Installing debugger support passes.\n";
401 });
402
403 auto MDOS = std::make_shared<MachODebugObjectSynthesizer<MachO64LE>>(
404 MR.getTargetJITDylib().getExecutionSession(), LG, RegisterActionAddr);
405 PassConfig.PrePrunePasses.push_back(
406 [=](LinkGraph &G) { return MDOS->preserveDebugSections(); });
407 PassConfig.PostPrunePasses.push_back(
408 [=](LinkGraph &G) { return MDOS->startSynthesis(); });
409 PassConfig.PostFixupPasses.push_back(
410 [=](LinkGraph &G) { return MDOS->completeSynthesisAndRegister(); });
411 } else {
412 LLVM_DEBUG({
413 dbgs() << "GDBJITDebugInfoRegistrationPlugin: Graph " << LG.getName()
414 << " contains no debug info. Skipping.\n";
415 });
416 }
417}
418
419} // namespace orc
420} // namespace llvm
assume Assume Builder
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DEBUG(X)
Definition: Debug.h:101
static const char * SynthDebugSectionName
static bool isDebugSection(const SectionBase &Sec)
Definition: ELFObjcopy.cpp:54
Symbol * Sym
Definition: ELF_riscv.cpp:468
#define G(x, y, z)
Definition: MD5.cpp:56
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallSet class.
This file defines the SmallVector class.
StringSet - A set-like wrapper for the StringMap.
const T * data() const
Definition: ArrayRef.h:162
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 DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
Base class for error info classes.
Definition: Error.h:45
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:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:135
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition: SmallSet.h:179
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:112
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:704
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
bool startswith(StringRef Prefix) const
Definition: StringRef.h:261
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ObjectFormatType getObjectFormat() const
Get the object format for this triple.
Definition: Triple.h:381
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:355
const std::string & str() const
Definition: Triple.h:414
An ExecutionSession represents a running JIT program.
Definition: Core.h:1389
SymbolStringPtr intern(StringRef SymName)
Add a symbol name to the SymbolStringPool and return a pointer to it.
Definition: Core.h:1446
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:2121
size_t getPageSize() const
Definition: Core.h:1438
Represents an address in the executor process.
void modifyPassConfig(MaterializationResponsibility &MR, jitlink::LinkGraph &LG, jitlink::PassConfiguration &PassConfig) override
static Expected< std::unique_ptr< GDBJITDebugInfoRegistrationPlugin > > Create(ExecutionSession &ES, JITDylib &ProcessJD, const Triple &TT)
void notifyTransferringResources(JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) override
Error notifyRemovingResources(JITDylib &JD, ResourceKey K) override
Error notifyFailed(MaterializationResponsibility &MR) override
Represents a JIT'd dynamic library.
Definition: Core.h:958
ExecutionSession & getExecutionSession() const
Get a reference to the ExecutionSession for this JITDylib.
Definition: Core.h:977
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:527
JITDylib & getTargetJITDylib() const
Returns the target JITDylib that these symbols are being materialized into.
Definition: Core.h:549
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ N_ENSYM
Definition: MachO.h:372
@ N_GSYM
Definition: MachO.h:361
@ N_BNSYM
Definition: MachO.h:366
@ CPU_SUBTYPE_ARM64_ALL
Definition: MachO.h:1647
@ MH_OBJECT
Definition: MachO.h:43
@ S_ATTR_DEBUG
S_ATTR_DEBUG - A debug section.
Definition: MachO.h:207
@ CPU_SUBTYPE_X86_64_ALL
Definition: MachO.h:1617
@ CPU_TYPE_ARM64
Definition: MachO.h:1576
@ CPU_TYPE_X86_64
Definition: MachO.h:1572
@ SS
Definition: X86.h:208
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
Error preserveDebugSections(jitlink::LinkGraph &G)
uintptr_t ResourceKey
Definition: Core.h:53
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
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:970
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:90
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:319
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:749
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
Error parse(DWARFDataExtractor &DebugLineData, uint64_t *OffsetPtr, const DWARFContext &Ctx, const DWARFUnit *U, function_ref< void(Error)> RecoverableErrorHandler, raw_ostream *OS=nullptr, bool Verbose=false)
Parse prologue and all rows.
std::vector< FileNameEntry > FileNames