LLVM 20.0.0git
DebugObjectManagerPlugin.cpp
Go to the documentation of this file.
1//===------- DebugObjectManagerPlugin.cpp - JITLink debug objects ---------===//
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// FIXME: Update Plugin to poke the debug object into a new JITLink section,
10// rather than creating a new allocation.
11//
12//===----------------------------------------------------------------------===//
13
15
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
23#include "llvm/Support/Errc.h"
28
29#include <set>
30
31#define DEBUG_TYPE "orc"
32
33using namespace llvm::jitlink;
34using namespace llvm::object;
35
36namespace llvm {
37namespace orc {
38
40public:
42 virtual void dump(raw_ostream &OS, StringRef Name) {}
43 virtual ~DebugObjectSection() = default;
44};
45
46template <typename ELFT>
48public:
49 // BinaryFormat ELF is not meant as a mutable format. We can only make changes
50 // that don't invalidate the file structure.
51 ELFDebugObjectSection(const typename ELFT::Shdr *Header)
52 : Header(const_cast<typename ELFT::Shdr *>(Header)) {}
53
55 void dump(raw_ostream &OS, StringRef Name) override;
56
57 Error validateInBounds(StringRef Buffer, const char *Name) const;
58
59private:
60 typename ELFT::Shdr *Header;
61};
62
63template <typename ELFT>
65 // All recorded sections are candidates for load-address patching.
66 Header->sh_addr =
67 static_cast<typename ELFT::uint>(Range.getStart().getValue());
68}
69
70template <typename ELFT>
72 const char *Name) const {
73 const uint8_t *Start = Buffer.bytes_begin();
74 const uint8_t *End = Buffer.bytes_end();
75 const uint8_t *HeaderPtr = reinterpret_cast<uint8_t *>(Header);
76 if (HeaderPtr < Start || HeaderPtr + sizeof(typename ELFT::Shdr) > End)
77 return make_error<StringError>(
78 formatv("{0} section header at {1:x16} not within bounds of the "
79 "given debug object buffer [{2:x16} - {3:x16}]",
80 Name, &Header->sh_addr, Start, End),
82 if (Header->sh_offset + Header->sh_size > Buffer.size())
83 return make_error<StringError>(
84 formatv("{0} section data [{1:x16} - {2:x16}] not within bounds of "
85 "the given debug object buffer [{3:x16} - {4:x16}]",
86 Name, Start + Header->sh_offset,
87 Start + Header->sh_offset + Header->sh_size, Start, End),
89 return Error::success();
90}
91
92template <typename ELFT>
94 if (uint64_t Addr = Header->sh_addr) {
95 OS << formatv(" {0:x16} {1}\n", Addr, Name);
96 } else {
97 OS << formatv(" {0}\n", Name);
98 }
99}
100
102 // Request final target memory load-addresses for all sections.
104
105 // We found sections with debug information when processing the input object.
107};
108
109/// The plugin creates a debug object from when JITLink starts processing the
110/// corresponding LinkGraph. It provides access to the pass configuration of
111/// the LinkGraph and calls the finalization function, once the resulting link
112/// artifact was emitted.
113///
115public:
118 : MemMgr(MemMgr), JD(JD), ES(ES), Flags(DebugObjectFlags{}) {}
119
120 bool hasFlags(DebugObjectFlags F) const { return Flags & F; }
122 Flags = static_cast<DebugObjectFlags>(Flags | F);
123 }
125 Flags = static_cast<DebugObjectFlags>(Flags & ~F);
126 }
127
129
130 void finalizeAsync(FinalizeContinuation OnFinalize);
131
132 virtual ~DebugObject() {
133 if (Alloc) {
134 std::vector<FinalizedAlloc> Allocs;
135 Allocs.push_back(std::move(Alloc));
136 if (Error Err = MemMgr.deallocate(std::move(Allocs)))
137 ES.reportError(std::move(Err));
138 }
139 }
140
142 SectionRange TargetMem) {}
143
144protected:
147
149
151 const JITLinkDylib *JD = nullptr;
153
154private:
155 DebugObjectFlags Flags;
156 FinalizedAlloc Alloc;
157};
158
159// Finalize working memory and take ownership of the resulting allocation. Start
160// copying memory over to the target and pass on the result once we're done.
161// Ownership of the allocation remains with us for the rest of our lifetime.
163 assert(!Alloc && "Cannot finalize more than once");
164
165 if (auto SimpleSegAlloc = finalizeWorkingMemory()) {
166 auto ROSeg = SimpleSegAlloc->getSegInfo(MemProt::Read);
167 ExecutorAddrRange DebugObjRange(ROSeg.Addr, ROSeg.WorkingMem.size());
168 SimpleSegAlloc->finalize(
169 [this, DebugObjRange,
170 OnFinalize = std::move(OnFinalize)](Expected<FinalizedAlloc> FA) {
171 if (FA) {
172 Alloc = std::move(*FA);
173 OnFinalize(DebugObjRange);
174 } else
175 OnFinalize(FA.takeError());
176 });
177 } else
178 OnFinalize(SimpleSegAlloc.takeError());
179}
180
181/// The current implementation of ELFDebugObject replicates the approach used in
182/// RuntimeDyld: It patches executable and data section headers in the given
183/// object buffer with load-addresses of their corresponding sections in target
184/// memory.
185///
187public:
190
192 SectionRange TargetMem) override;
193
194 StringRef getBuffer() const { return Buffer->getMemBufferRef().getBuffer(); }
195
196protected:
198
199 template <typename ELFT>
201 std::unique_ptr<ELFDebugObjectSection<ELFT>> Section);
203
204private:
205 template <typename ELFT>
207 CreateArchType(MemoryBufferRef Buffer, JITLinkMemoryManager &MemMgr,
209
210 static std::unique_ptr<WritableMemoryBuffer>
211 CopyBuffer(MemoryBufferRef Buffer, Error &Err);
212
213 ELFDebugObject(std::unique_ptr<WritableMemoryBuffer> Buffer,
216 : DebugObject(MemMgr, JD, ES), Buffer(std::move(Buffer)) {
218 }
219
220 std::unique_ptr<WritableMemoryBuffer> Buffer;
222};
223
224static const std::set<StringRef> DwarfSectionNames = {
225#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME, OPTION) \
226 ELF_NAME,
227#include "llvm/BinaryFormat/Dwarf.def"
228#undef HANDLE_DWARF_SECTION
229};
230
232 return DwarfSectionNames.count(SectionName) == 1;
233}
234
235std::unique_ptr<WritableMemoryBuffer>
236ELFDebugObject::CopyBuffer(MemoryBufferRef Buffer, Error &Err) {
238 size_t Size = Buffer.getBufferSize();
241 memcpy(Copy->getBufferStart(), Buffer.getBufferStart(), Size);
242 return Copy;
243 }
244
246 return nullptr;
247}
248
249template <typename ELFT>
251ELFDebugObject::CreateArchType(MemoryBufferRef Buffer,
252 JITLinkMemoryManager &MemMgr,
253 const JITLinkDylib *JD, ExecutionSession &ES) {
254 using SectionHeader = typename ELFT::Shdr;
255
256 Error Err = Error::success();
257 std::unique_ptr<ELFDebugObject> DebugObj(
258 new ELFDebugObject(CopyBuffer(Buffer, Err), MemMgr, JD, ES));
259 if (Err)
260 return std::move(Err);
261
262 Expected<ELFFile<ELFT>> ObjRef = ELFFile<ELFT>::create(DebugObj->getBuffer());
263 if (!ObjRef)
264 return ObjRef.takeError();
265
266 Expected<ArrayRef<SectionHeader>> Sections = ObjRef->sections();
267 if (!Sections)
268 return Sections.takeError();
269
270 for (const SectionHeader &Header : *Sections) {
271 Expected<StringRef> Name = ObjRef->getSectionName(Header);
272 if (!Name)
273 return Name.takeError();
274 if (Name->empty())
275 continue;
276 if (isDwarfSection(*Name))
277 DebugObj->setFlags(HasDebugSections);
278
279 // Only record text and data sections (i.e. no bss, comments, rel, etc.)
280 if (Header.sh_type != ELF::SHT_PROGBITS &&
281 Header.sh_type != ELF::SHT_X86_64_UNWIND)
282 continue;
283 if (!(Header.sh_flags & ELF::SHF_ALLOC))
284 continue;
285
286 auto Wrapped = std::make_unique<ELFDebugObjectSection<ELFT>>(&Header);
287 if (Error Err = DebugObj->recordSection(*Name, std::move(Wrapped)))
288 return std::move(Err);
289 }
290
291 return std::move(DebugObj);
292}
293
296 ExecutionSession &ES) {
297 unsigned char Class, Endian;
298 std::tie(Class, Endian) = getElfArchType(Buffer.getBuffer());
299
300 if (Class == ELF::ELFCLASS32) {
302 return CreateArchType<ELF32LE>(Buffer, Ctx.getMemoryManager(),
303 Ctx.getJITLinkDylib(), ES);
305 return CreateArchType<ELF32BE>(Buffer, Ctx.getMemoryManager(),
306 Ctx.getJITLinkDylib(), ES);
307 return nullptr;
308 }
309 if (Class == ELF::ELFCLASS64) {
311 return CreateArchType<ELF64LE>(Buffer, Ctx.getMemoryManager(),
312 Ctx.getJITLinkDylib(), ES);
314 return CreateArchType<ELF64BE>(Buffer, Ctx.getMemoryManager(),
315 Ctx.getJITLinkDylib(), ES);
316 return nullptr;
317 }
318 return nullptr;
319}
320
322 LLVM_DEBUG({
323 dbgs() << "Section load-addresses in debug object for \""
324 << Buffer->getBufferIdentifier() << "\":\n";
325 for (const auto &KV : Sections)
326 KV.second->dump(dbgs(), KV.first());
327 });
328
329 // TODO: This works, but what actual alignment requirements do we have?
331 size_t Size = Buffer->getBufferSize();
332
333 // Allocate working memory for debug object in read-only segment.
334 auto Alloc =
336 {{MemProt::Read, {Size, Align(PageSize)}}});
337 if (!Alloc)
338 return Alloc;
339
340 // Initialize working memory with a copy of our object buffer.
341 auto SegInfo = Alloc->getSegInfo(MemProt::Read);
342 memcpy(SegInfo.WorkingMem.data(), Buffer->getBufferStart(), Size);
343 Buffer.reset();
344
345 return Alloc;
346}
347
348void ELFDebugObject::reportSectionTargetMemoryRange(StringRef Name,
349 SectionRange TargetMem) {
350 if (auto *DebugObjSection = getSection(Name))
351 DebugObjSection->setTargetMemoryRange(TargetMem);
352}
353
354template <typename ELFT>
355Error ELFDebugObject::recordSection(
357 if (Error Err = Section->validateInBounds(this->getBuffer(), Name.data()))
358 return Err;
359 bool Inserted = Sections.try_emplace(Name, std::move(Section)).second;
360 if (!Inserted)
361 LLVM_DEBUG(dbgs() << "Skipping debug registration for section '" << Name
362 << "' in object " << Buffer->getBufferIdentifier()
363 << " (duplicate name)\n");
364 return Error::success();
365}
366
367DebugObjectSection *ELFDebugObject::getSection(StringRef Name) {
368 auto It = Sections.find(Name);
369 return It == Sections.end() ? nullptr : It->second.get();
370}
371
372/// Creates a debug object based on the input object file from
373/// ObjectLinkingLayerJITLinkContext.
374///
377 JITLinkContext &Ctx, MemoryBufferRef ObjBuffer) {
378 switch (G.getTargetTriple().getObjectFormat()) {
379 case Triple::ELF:
380 return ELFDebugObject::Create(ObjBuffer, Ctx, ES);
381
382 default:
383 // TODO: Once we add support for other formats, we might want to split this
384 // into multiple files.
385 return nullptr;
386 }
387}
388
389DebugObjectManagerPlugin::DebugObjectManagerPlugin(
390 ExecutionSession &ES, std::unique_ptr<DebugObjectRegistrar> Target,
391 bool RequireDebugSections, bool AutoRegisterCode)
392 : ES(ES), Target(std::move(Target)),
393 RequireDebugSections(RequireDebugSections),
394 AutoRegisterCode(AutoRegisterCode) {}
395
397 ExecutionSession &ES, std::unique_ptr<DebugObjectRegistrar> Target)
399
401
404 MemoryBufferRef ObjBuffer) {
405 std::lock_guard<std::mutex> Lock(PendingObjsLock);
406 assert(PendingObjs.count(&MR) == 0 &&
407 "Cannot have more than one pending debug object per "
408 "MaterializationResponsibility");
409
410 if (auto DebugObj = createDebugObjectFromBuffer(ES, G, Ctx, ObjBuffer)) {
411 // Not all link artifacts allow debugging.
412 if (*DebugObj == nullptr)
413 return;
414 if (RequireDebugSections && !(**DebugObj).hasFlags(HasDebugSections)) {
415 LLVM_DEBUG(dbgs() << "Skipping debug registration for LinkGraph '"
416 << G.getName() << "': no debug info\n");
417 return;
418 }
419 PendingObjs[&MR] = std::move(*DebugObj);
420 } else {
421 ES.reportError(DebugObj.takeError());
422 }
423}
424
427 PassConfiguration &PassConfig) {
428 // Not all link artifacts have associated debug objects.
429 std::lock_guard<std::mutex> Lock(PendingObjsLock);
430 auto It = PendingObjs.find(&MR);
431 if (It == PendingObjs.end())
432 return;
433
434 DebugObject &DebugObj = *It->second;
436 PassConfig.PostAllocationPasses.push_back(
437 [&DebugObj](LinkGraph &Graph) -> Error {
438 for (const Section &GraphSection : Graph.sections())
439 DebugObj.reportSectionTargetMemoryRange(GraphSection.getName(),
440 SectionRange(GraphSection));
441 return Error::success();
442 });
443 }
444}
445
448 std::lock_guard<std::mutex> Lock(PendingObjsLock);
449 auto It = PendingObjs.find(&MR);
450 if (It == PendingObjs.end())
451 return Error::success();
452
453 // During finalization the debug object is registered with the target.
454 // Materialization must wait for this process to finish. Otherwise we might
455 // start running code before the debugger processed the corresponding debug
456 // info.
457 std::promise<MSVCPError> FinalizePromise;
458 std::future<MSVCPError> FinalizeErr = FinalizePromise.get_future();
459
460 It->second->finalizeAsync(
461 [this, &FinalizePromise, &MR](Expected<ExecutorAddrRange> TargetMem) {
462 // Any failure here will fail materialization.
463 if (!TargetMem) {
464 FinalizePromise.set_value(TargetMem.takeError());
465 return;
466 }
467 if (Error Err =
468 Target->registerDebugObject(*TargetMem, AutoRegisterCode)) {
469 FinalizePromise.set_value(std::move(Err));
470 return;
471 }
472
473 // Once our tracking info is updated, notifyEmitted() can return and
474 // finish materialization.
475 FinalizePromise.set_value(MR.withResourceKeyDo([&](ResourceKey K) {
476 assert(PendingObjs.count(&MR) && "We still hold PendingObjsLock");
477 std::lock_guard<std::mutex> Lock(RegisteredObjsLock);
478 RegisteredObjs[K].push_back(std::move(PendingObjs[&MR]));
479 PendingObjs.erase(&MR);
480 }));
481 });
482
483 return FinalizeErr.get();
484}
485
488 std::lock_guard<std::mutex> Lock(PendingObjsLock);
489 PendingObjs.erase(&MR);
490 return Error::success();
491}
492
494 ResourceKey DstKey,
495 ResourceKey SrcKey) {
496 // Debug objects are stored by ResourceKey only after registration.
497 // Thus, pending objects don't need to be updated here.
498 std::lock_guard<std::mutex> Lock(RegisteredObjsLock);
499 auto SrcIt = RegisteredObjs.find(SrcKey);
500 if (SrcIt != RegisteredObjs.end()) {
501 // Resources from distinct MaterializationResponsibilitys can get merged
502 // after emission, so we can have multiple debug objects per resource key.
503 for (std::unique_ptr<DebugObject> &DebugObj : SrcIt->second)
504 RegisteredObjs[DstKey].push_back(std::move(DebugObj));
505 RegisteredObjs.erase(SrcIt);
506 }
507}
508
510 ResourceKey Key) {
511 // Removing the resource for a pending object fails materialization, so they
512 // get cleaned up in the notifyFailed() handler.
513 std::lock_guard<std::mutex> Lock(RegisteredObjsLock);
514 RegisteredObjs.erase(Key);
515
516 // TODO: Implement unregister notifications.
517 return Error::success();
518}
519
520} // namespace orc
521} // namespace llvm
This file defines the StringMap class.
basic Basic Alias true
#define LLVM_DEBUG(...)
Definition: Debug.h:106
Elf_Shdr Shdr
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
#define _
static cl::opt< int > PageSize("imp-null-check-page-size", cl::desc("The page size of the target in bytes"), cl::init(4096), cl::Hidden)
#define F(x, y, z)
Definition: MD5.cpp:55
#define G(x, y, z)
Definition: MD5.cpp:56
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
Provides a library for accessing information about this process and other processes on the operating ...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
endianness Endian
raw_pwrite_stream & OS
Helper for Errors used as out-parameters.
Definition: Error.h:1130
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
size_t getBufferSize() const
StringRef getBufferIdentifier() const
const char * getBufferStart() const
StringRef getBuffer() const
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:128
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
const unsigned char * bytes_end() const
Definition: StringRef.h:131
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:150
const unsigned char * bytes_begin() const
Definition: StringRef.h:128
Target - Wrapper for Target specific information.
static std::unique_ptr< WritableMemoryBuffer > getNewUninitMemBuffer(size_t Size, const Twine &BufferName="", std::optional< Align > Alignment=std::nullopt)
Allocate a new MemoryBuffer of the specified size that is not initialized.
static Expected< ELFFile > create(StringRef Object)
Definition: ELF.h:888
Creates and manages DebugObjects for JITLink artifacts.
Error notifyRemovingResources(JITDylib &JD, ResourceKey K) override
void notifyTransferringResources(JITDylib &JD, ResourceKey DstKey, ResourceKey SrcKey) override
Error notifyFailed(MaterializationResponsibility &MR) override
Error notifyEmitted(MaterializationResponsibility &MR) override
void notifyMaterializing(MaterializationResponsibility &MR, jitlink::LinkGraph &G, jitlink::JITLinkContext &Ctx, MemoryBufferRef InputObject) override
void modifyPassConfig(MaterializationResponsibility &MR, jitlink::LinkGraph &LG, jitlink::PassConfiguration &PassConfig) override
DebugObjectManagerPlugin(ExecutionSession &ES, std::unique_ptr< DebugObjectRegistrar > Target)
virtual void setTargetMemoryRange(SectionRange Range)=0
virtual void dump(raw_ostream &OS, StringRef Name)
virtual ~DebugObjectSection()=default
The plugin creates a debug object from when JITLink starts processing the corresponding LinkGraph.
bool hasFlags(DebugObjectFlags F) const
void finalizeAsync(FinalizeContinuation OnFinalize)
virtual Expected< SimpleSegmentAlloc > finalizeWorkingMemory()=0
std::function< void(Expected< ExecutorAddrRange >)> FinalizeContinuation
void clearFlags(DebugObjectFlags F)
virtual void reportSectionTargetMemoryRange(StringRef Name, SectionRange TargetMem)
void setFlags(DebugObjectFlags F)
DebugObject(JITLinkMemoryManager &MemMgr, const JITLinkDylib *JD, ExecutionSession &ES)
Error validateInBounds(StringRef Buffer, const char *Name) const
void setTargetMemoryRange(SectionRange Range) override
void dump(raw_ostream &OS, StringRef Name) override
ELFDebugObjectSection(const typename ELFT::Shdr *Header)
The current implementation of ELFDebugObject replicates the approach used in RuntimeDyld: It patches ...
Error recordSection(StringRef Name, std::unique_ptr< ELFDebugObjectSection< ELFT > > Section)
DebugObjectSection * getSection(StringRef Name)
Expected< SimpleSegmentAlloc > finalizeWorkingMemory() override
void reportSectionTargetMemoryRange(StringRef Name, SectionRange TargetMem) override
static Expected< std::unique_ptr< DebugObject > > Create(MemoryBufferRef Buffer, JITLinkContext &Ctx, ExecutionSession &ES)
An ExecutionSession represents a running JIT program.
Definition: Core.h:1339
void reportError(Error Err)
Report a error for this execution session.
Definition: Core.h:1474
std::shared_ptr< SymbolStringPool > getSymbolStringPool()
Get the SymbolStringPool for this instance.
Definition: Core.h:1388
Represents a JIT'd dynamic library.
Definition: Core.h:897
Tracks responsibility for materialization, and mediates interactions between MaterializationUnits and...
Definition: Core.h:571
Error withResourceKeyDo(Func &&F) const
Runs the given callback under the session lock, passing in the associated ResourceKey.
Definition: Core.h:590
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
static unsigned getPageSizeEstimate()
Get the process's estimated page size.
Definition: Process.h:61
@ ELFCLASS64
Definition: ELF.h:330
@ ELFCLASS32
Definition: ELF.h:329
@ SHT_PROGBITS
Definition: ELF.h:1090
@ SHT_X86_64_UNWIND
Definition: ELF.h:1162
@ SHF_ALLOC
Definition: ELF.h:1188
@ ELFDATA2MSB
Definition: ELF.h:337
@ ELFDATA2LSB
Definition: ELF.h:336
Expected< const typename ELFT::Shdr * > getSection(typename ELFT::ShdrRange Sections, uint32_t Index)
Definition: ELF.h:534
std::pair< unsigned char, unsigned char > getElfArchType(StringRef Object)
Definition: ELF.h:80
static const std::set< StringRef > DwarfSectionNames
static Expected< std::unique_ptr< DebugObject > > createDebugObjectFromBuffer(ExecutionSession &ES, LinkGraph &G, JITLinkContext &Ctx, MemoryBufferRef ObjBuffer)
Creates a debug object based on the input object file from ObjectLinkingLayerJITLinkContext.
static bool isDwarfSection(StringRef SectionName)
uintptr_t ResourceKey
Definition: Core.h:74
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code make_error_code(BitcodeError E)
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
Represents an address range in the exceutor process.