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
16
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().starts_with("__DWARF,");
39 }
40
41 MachODebugObjectSynthesizerBase(LinkGraph &G, ExecutorAddr RegisterActionAddr)
42 : G(G), RegisterActionAddr(RegisterActionAddr) {}
43 ~MachODebugObjectSynthesizerBase() override = 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 SmallPtrSet<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 if (auto CPUType = MachO::getCPUType(G.getTargetTriple()))
126 Builder.Header.cputype = *CPUType;
127 else
128 return CPUType.takeError();
129 if (auto CPUSubType = MachO::getCPUSubType(G.getTargetTriple()))
130 Builder.Header.cpusubtype = *CPUSubType;
131 else
132 return CPUSubType.takeError();
133
134 Seg = &Builder.addSegment("");
135
137 StringRef DebugLineSectionData;
138 for (auto &DSec : DebugSections) {
139 auto [SegName, SecName] = DSec.GraphSec->getName().split(',');
140 DSec.BuilderSec = &Seg->addSection(SecName, SegName);
141
142 SectionRange SR(*DSec.GraphSec);
143 DSec.BuilderSec->Content.Size = SR.getSize();
144 if (!SR.empty()) {
145 DSec.BuilderSec->align = Log2_64(SR.getFirstBlock()->getAlignment());
146 StringRef SectionData(SR.getFirstBlock()->getContent().data(),
147 SR.getFirstBlock()->getSize());
148 DebugSectionMap[SecName.drop_front(2)] = // drop "__" prefix.
149 MemoryBuffer::getMemBuffer(SectionData, G.getName(), false);
150 if (SecName == "__debug_line")
151 DebugLineSectionData = SectionData;
152 }
153 }
154
155 std::optional<StringRef> FileName;
156 if (!DebugLineSectionData.empty()) {
157 assert((G.getEndianness() == llvm::endianness::big ||
158 G.getEndianness() == llvm::endianness::little) &&
159 "G.getEndianness() must be either big or little");
160 auto DWARFCtx =
161 DWARFContext::create(DebugSectionMap, G.getPointerSize(),
162 G.getEndianness() == llvm::endianness::little);
163 DWARFDataExtractor DebugLineData(
164 DebugLineSectionData, G.getEndianness() == llvm::endianness::little,
165 G.getPointerSize());
166 uint64_t Offset = 0;
168
169 // Try to parse line data. Consume error on failure.
170 if (auto Err = P.parse(DebugLineData, &Offset, consumeError, *DWARFCtx)) {
171 handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
172 LLVM_DEBUG({
173 dbgs() << "Cannot parse line table for \"" << G.getName() << "\": ";
174 EIB.log(dbgs());
175 dbgs() << "\n";
176 });
177 });
178 } else {
179 for (auto &FN : P.FileNames)
180 if ((FileName = dwarf::toString(FN.Name))) {
181 LLVM_DEBUG({
182 dbgs() << "Using FileName = \"" << *FileName
183 << "\" from DWARF line table\n";
184 });
185 break;
186 }
187 }
188 }
189
190 // If no line table (or unable to use) then use graph name.
191 // FIXME: There are probably other debug sections we should look in first.
192 if (!FileName) {
193 LLVM_DEBUG({
194 dbgs() << "Could not find source name from DWARF line table. "
195 "Using FileName = \"\"\n";
196 });
197 FileName = "";
198 }
199
200 Builder.addSymbol("", MachO::N_SO, 0, 0, 0);
201 Builder.addSymbol(*FileName, MachO::N_SO, 0, 0, 0);
202 auto TimeStamp = std::chrono::duration_cast<std::chrono::seconds>(
203 std::chrono::system_clock::now().time_since_epoch())
204 .count();
205 Builder.addSymbol("", MachO::N_OSO, 3, 1, TimeStamp);
206
207 for (auto &NDSP : NonDebugSections) {
208 auto [SegName, SecName] = NDSP.GraphSec->getName().split(',');
209 NDSP.BuilderSec = &Seg->addSection(SecName, SegName);
210 SectionRange SR(*NDSP.GraphSec);
211 if (!SR.empty())
212 NDSP.BuilderSec->align = Log2_64(SR.getFirstBlock()->getAlignment());
213
214 // Add stabs.
215 for (auto *Sym : NDSP.GraphSec->symbols()) {
216 // Skip anonymous symbols.
217 if (!Sym->hasName())
218 continue;
219
220 uint8_t SymType = Sym->isCallable() ? MachO::N_FUN : MachO::N_GSYM;
221
222 Builder.addSymbol("", MachO::N_BNSYM, 1, 0, 0);
223 StabSymbols.push_back(
224 {*Sym, Builder.addSymbol(*Sym->getName(), SymType, 1, 0, 0),
225 Builder.addSymbol(*Sym->getName(), SymType, 0, 0, 0)});
226 Builder.addSymbol("", MachO::N_ENSYM, 1, 0, 0);
227 }
228 }
229
230 Builder.addSymbol("", MachO::N_SO, 1, 0, 0);
231
232 // Lay out the debug object, create a section and block for it.
233 size_t DebugObjectSize = Builder.layout();
234
235 auto &SDOSec = G.createSection(SynthDebugSectionName, MemProt::Read);
236 MachOContainerBlock = &G.createMutableContentBlock(
237 SDOSec, G.allocateBuffer(DebugObjectSize), orc::ExecutorAddr(), 8, 0);
238
239 return Error::success();
240 }
241
242 Error completeSynthesisAndRegister() override {
243 if (!MachOContainerBlock) {
244 LLVM_DEBUG({
245 dbgs() << "Not writing MachO debug object header for " << G.getName()
246 << " since createDebugSection failed\n";
247 });
248
249 return Error::success();
250 }
251 ExecutorAddr MaxAddr;
252 for (auto &NDSec : NonDebugSections) {
253 SectionRange SR(*NDSec.GraphSec);
254 NDSec.BuilderSec->addr = SR.getStart().getValue();
255 NDSec.BuilderSec->size = SR.getSize();
256 NDSec.BuilderSec->offset = SR.getStart().getValue();
257 if (SR.getEnd() > MaxAddr)
258 MaxAddr = SR.getEnd();
259 }
260
261 for (auto &DSec : DebugSections) {
262 if (DSec.GraphSec->blocks_size() != 1)
264 "Unexpected number of blocks in debug info section",
266
267 if (ExecutorAddr(DSec.BuilderSec->addr) + DSec.BuilderSec->size > MaxAddr)
268 MaxAddr = ExecutorAddr(DSec.BuilderSec->addr) + DSec.BuilderSec->size;
269
270 auto &B = **DSec.GraphSec->blocks().begin();
271 DSec.BuilderSec->Content.Data = B.getContent().data();
272 DSec.BuilderSec->Content.Size = B.getContent().size();
273 DSec.BuilderSec->flags |= MachO::S_ATTR_DEBUG;
274 }
275
276 LLVM_DEBUG({
277 dbgs() << "Writing MachO debug object header for " << G.getName() << "\n";
278 });
279
280 // Update stab symbol addresses.
281 for (auto &SS : StabSymbols) {
282 SS.StartStab.nlist().n_value = SS.Sym.getAddress().getValue();
283 SS.EndStab.nlist().n_value = SS.Sym.getSize();
284 }
285
286 Builder.write(MachOContainerBlock->getAlreadyMutableContent());
287
288 SectionRange R(MachOContainerBlock->getSection());
289 G.allocActions().push_back(
292 RegisterActionAddr, R.getRange())),
293 {}});
294
295 return Error::success();
296 }
297
298private:
299 struct SectionPair {
300 Section *GraphSec = nullptr;
301 typename MachOBuilder<MachOTraits>::Section *BuilderSec = nullptr;
302 };
303
304 struct StabSymbolsEntry {
305 using RelocTarget = typename MachOBuilder<MachOTraits>::RelocTarget;
306
307 StabSymbolsEntry(Symbol &Sym, RelocTarget StartStab, RelocTarget EndStab)
308 : Sym(Sym), StartStab(StartStab), EndStab(EndStab) {}
309
310 Symbol &Sym;
311 RelocTarget StartStab, EndStab;
312 };
313
314 using BuilderType = MachOBuilder<MachOTraits>;
315
316 Block *MachOContainerBlock = nullptr;
318 typename MachOBuilder<MachOTraits>::Segment *Seg = nullptr;
319 std::vector<StabSymbolsEntry> StabSymbols;
320 SmallVector<SectionPair, 16> DebugSections;
321 SmallVector<SectionPair, 16> NonDebugSections;
322};
323
324} // end anonymous namespace
325
326namespace llvm {
327namespace orc {
328
329Expected<std::unique_ptr<GDBJITDebugInfoRegistrationPlugin>>
331 JITDylib &BootstrapJD) {
332 auto RegisterActionName =
334
335 if (auto RegisterSym = ES.lookup({&BootstrapJD}, RegisterActionName))
336 return std::make_unique<GDBJITDebugInfoRegistrationPlugin>(
337 RegisterSym->getAddress());
338 else
339 return RegisterSym.takeError();
340}
341
346
351
354
357 PassConfiguration &PassConfig) {
358
360 modifyPassConfigForMachO(MR, LG, PassConfig);
361 else {
362 LLVM_DEBUG({
363 dbgs() << "GDBJITDebugInfoRegistrationPlugin skipping unspported graph "
364 << LG.getName() << "(triple = " << LG.getTargetTriple().str()
365 << "\n";
366 });
367 }
368}
369
370void GDBJITDebugInfoRegistrationPlugin::modifyPassConfigForMachO(
372 jitlink::PassConfiguration &PassConfig) {
373
374 switch (LG.getTargetTriple().getArch()) {
375 case Triple::x86_64:
376 case Triple::aarch64:
377 // Supported, continue.
378 assert(LG.getPointerSize() == 8 && "Graph has incorrect pointer size");
380 "Graph has incorrect endianness");
381 break;
382 default:
383 // Unsupported.
384 LLVM_DEBUG({
385 dbgs() << "GDBJITDebugInfoRegistrationPlugin skipping unsupported "
386 << "MachO graph " << LG.getName()
387 << "(triple = " << LG.getTargetTriple().str()
388 << ", pointer size = " << LG.getPointerSize() << ", endianness = "
389 << (LG.getEndianness() == llvm::endianness::big ? "big" : "little")
390 << ")\n";
391 });
392 return;
393 }
394
395 // Scan for debug sections. If we find one then install passes.
396 bool HasDebugSections = false;
397 for (auto &Sec : LG.sections())
398 if (MachODebugObjectSynthesizerBase::isDebugSection(Sec)) {
399 HasDebugSections = true;
400 break;
401 }
402
403 if (HasDebugSections) {
404 LLVM_DEBUG({
405 dbgs() << "GDBJITDebugInfoRegistrationPlugin: Graph " << LG.getName()
406 << " contains debug info. Installing debugger support passes.\n";
407 });
408
409 auto MDOS = std::make_shared<MachODebugObjectSynthesizer<MachO64LE>>(
410 MR.getTargetJITDylib().getExecutionSession(), LG, RegisterActionAddr);
411 PassConfig.PrePrunePasses.push_back(
412 [=](LinkGraph &G) { return MDOS->preserveDebugSections(); });
413 PassConfig.PostPrunePasses.push_back(
414 [=](LinkGraph &G) { return MDOS->startSynthesis(); });
415 PassConfig.PostFixupPasses.push_back(
416 [=](LinkGraph &G) { return MDOS->completeSynthesisAndRegister(); });
417 } else {
418 LLVM_DEBUG({
419 dbgs() << "GDBJITDebugInfoRegistrationPlugin: Graph " << LG.getName()
420 << " contains no debug info. Skipping.\n";
421 });
422 }
423}
424
425} // namespace orc
426} // namespace llvm
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
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:129
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:538
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:514
const std::string & str() const
Definition Triple.h:579
An ExecutionSession represents a running JIT program.
Definition Core.h:1111
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
Mangles symbol names then uniques them in the context of an ExecutionSession.
Definition Mangling.h:28
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:109
@ MH_OBJECT
Definition MachO.h:43
LLVM_ABI Expected< uint32_t > getCPUType(const Triple &T)
Definition MachO.cpp:89
@ 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 SymbolNameSpec 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:577
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:332
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