[lldb] Make Process::ReadMemory non-virtual #217148
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-lldb
Author: Augusto Noronha (augusto2112)
<details>
<summary>Changes</summary>
...and defensively clear it in Process::ReadMemory subclasses
Target::ReadMemory might've tried to read memory from the filecache, which could've failed, and set error. Some subclasses of process were not clearing the error in their ReadMemory implementations. This patch both clears the error in Target::ReadMemory, because of the issue above, and defensively in the subclasses of Process that didn't do it defensively already.
Assisted-by: Claude
rdar://185250410
---
Full diff: https://github.com/llvm/llvm-project/pull/217148.diff
6 Files Affected:
````````````diff --git a/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp b/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp
index 1b3617c90e3e7..a2e339e2fa3ac 100644
--- a/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp
+++ b/lldb/source/Plugins/Process/elf-core/ProcessElfCore.cpp
@@ -526,6 +526,8 @@ bool ProcessElfCore::IsAlive() { return true; }
// Process Memory
size_t ProcessElfCore::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
Status &error) {
+ error.Clear();
+
if (lldb::ABISP abi_sp = GetABI())
addr = abi_sp->FixAnyAddress(addr);
diff --git a/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp b/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp
index 91a977bb69bdc..bf799ee0ee4cb 100644
--- a/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp
+++ b/lldb/source/Plugins/Process/mach-core/ProcessMachCore.cpp
@@ -723,6 +723,7 @@ bool ProcessMachCore::WarnBeforeDetach() const { return false; }
// Process Memory
size_t ProcessMachCore::ReadMemory(addr_t addr, void *buf, size_t size,
Status &error) {
+ error.Clear();
// Don't allow the caching that lldb_private::Process::ReadMemory does since
// in core files we have it all cached our our core file anyway.
return DoReadMemory(FixAnyAddress(addr), buf, size, error);
diff --git a/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp b/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
index 7b3c090286349..98b1939a2b020 100644
--- a/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
+++ b/lldb/source/Plugins/Process/minidump/ProcessMinidump.cpp
@@ -316,6 +316,7 @@ bool ProcessMinidump::WarnBeforeDetach() const { return false; }
size_t ProcessMinidump::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
Status &error) {
+ error.Clear();
// Don't allow the caching that lldb_private::Process::ReadMemory does since
// we have it all cached in our dump file anyway.
return DoReadMemory(addr, buf, size, error);
diff --git a/lldb/source/Plugins/Process/wasm/ProcessWasm.cpp b/lldb/source/Plugins/Process/wasm/ProcessWasm.cpp
index f7d744c967ea0..11e04ebc3b21b 100644
--- a/lldb/source/Plugins/Process/wasm/ProcessWasm.cpp
+++ b/lldb/source/Plugins/Process/wasm/ProcessWasm.cpp
@@ -129,6 +129,8 @@ size_t ProcessWasm::ReadGlobal(uint32_t module_id, uint32_t index, void *buf,
size_t ProcessWasm::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size,
Status &error) {
+ error.Clear();
+
wasm_addr_t wasm_addr(vm_addr);
switch (wasm_addr.GetType()) {
diff --git a/lldb/source/Target/Target.cpp b/lldb/source/Target/Target.cpp
index 6d4e200ea2241..8d82b43dff383 100644
--- a/lldb/source/Target/Target.cpp
+++ b/lldb/source/Target/Target.cpp
@@ -2176,6 +2176,7 @@ size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
error = Status::FromErrorStringWithFormat(
"0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
} else {
+ error.Clear();
bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
if (bytes_read != dst_len) {
if (error.Success()) {
diff --git a/lldb/unittests/Target/MemoryTest.cpp b/lldb/unittests/Target/MemoryTest.cpp
index f9d3dc1fee72f..f1b5cfe78dc72 100644
--- a/lldb/unittests/Target/MemoryTest.cpp
+++ b/lldb/unittests/Target/MemoryTest.cpp
@@ -922,3 +922,132 @@ TEST_F(MemoryTest, TestReadMemoryClearsStaleError) {
12u);
EXPECT_TRUE(short_error.Fail());
}
+
+// A process that does not clear the Status it is handed
+class StatusPreservingProcess : public Process {
+public:
+ StatusPreservingProcess(lldb::TargetSP target_sp,
+ lldb::ListenerSP listener_sp)
+ : Process(target_sp, listener_sp) {}
+
+ // Doesn't clear error.
+ size_t ReadMemory(lldb::addr_t, void *buf, size_t size, Status &) override {
+ if (!m_can_read)
+ return 0;
+ memset(buf, 'B', size);
+ return size;
+ }
+
+ void SetCanRead(bool can_read) { m_can_read = can_read; }
+
+ // Boilerplate.
+ bool CanDebug(lldb::TargetSP, bool) override { return true; }
+ Status DoDestroy() override { return {}; }
+ void RefreshStateAfterStop() override {}
+ bool IsAlive() override { return true; }
+ bool DoUpdateThreadList(ThreadList &, ThreadList &) override { return false; }
+ llvm::StringRef GetPluginName() override { return "status-preserving"; }
+ size_t DoReadMemory(lldb::addr_t, void *, size_t, Status &) override {
+ llvm_unreachable("don't call this");
+ }
+
+private:
+ bool m_can_read = true;
+};
+
+// Test that a filecache read that sets the error is cleared when reading from
+// the process.
+TEST_F(MemoryTest, TestReadMemoryClearsStaleFileCacheError) {
+ SubsystemRAII<ObjectFileMachO> subsystems;
+
+ ArchSpec arch("x86_64-apple-macosx-");
+ Platform::SetHostPlatform(PlatformRemoteMacOSX::CreateInstance(true, &arch));
+
+ DebuggerSP debugger_sp = Debugger::CreateInstance();
+ ASSERT_TRUE(debugger_sp);
+
+ TargetSP target_sp = CreateTarget(debugger_sp, arch);
+ ASSERT_TRUE(target_sp);
+
+ ListenerSP listener_sp(Listener::MakeListener("dummy"));
+ auto process_sp =
+ std::make_shared<StatusPreservingProcess>(target_sp, listener_sp);
+ struct TargetHack : public Target {
+ void SetProcess(lldb::ProcessSP process) { m_process_sp = process; }
+ };
+ static_cast<TargetHack *>(target_sp.get())->SetProcess(process_sp);
+
+ // A read-only section whose file contents are absen, so the file cache cannot
+ // read from it.
+ auto expected_file = TestFile::fromYaml(R"(
+--- !mach-o
+FileHeader:
+ magic: 0xFEEDFACF
+ cputype: 0x1000007
+ cpusubtype: 0x3
+ filetype: 0x2
+ ncmds: 1
+ sizeofcmds: 152
+ flags: 0x200085
+ reserved: 0x0
+LoadCommands:
+ - cmd: LC_SEGMENT_64
+ cmdsize: 152
+ segname: __TEXT
+ vmaddr: 0x100001000
+ vmsize: 0xC
+ fileoff: 0x0
+ filesize: 0x0
+ maxprot: 5
+ initprot: 5
+ nsects: 1
+ flags: 0
+ Sections:
+ - sectname: __const
+ segname: __TEXT
+ addr: 0x100001000
+ size: 12
+ offset: 0x0
+ align: 0
+ reloff: 0x0
+ nreloc: 0
+ flags: 0x0
+ reserved1: 0x0
+ reserved2: 0x0
+ reserved3: 0x0
+...
+)");
+ ASSERT_THAT_EXPECTED(expected_file, llvm::Succeeded());
+
+ ModuleSP module_sp = std::make_shared<Module>(expected_file->moduleSpec());
+ target_sp->GetImages().Append(module_sp, /*notify=*/false);
+
+ SectionList *sections = module_sp->GetSectionList();
+ ASSERT_TRUE(sections);
+ SectionSP section_sp = sections->FindSectionByName(ConstString("__const"));
+ ASSERT_TRUE(section_sp);
+ // The file-cache path only runs for a read-only section.
+ ASSERT_FALSE(Flags(section_sp->GetPermissions()).Test(ePermissionsWritable));
+ target_sp->SetSectionLoadAddress(section_sp, section_sp->GetFileAddress());
+
+ Address addr;
+ ASSERT_TRUE(
+ target_sp->ResolveLoadAddress(section_sp->GetFileAddress(), addr));
+
+ // force_live_memory defaults to false, so the read-only file-cache path runs
+ // first and fails, leaving an error for the live read to supersede.
+ char buf[5] = {};
+ Status error;
+ EXPECT_EQ(target_sp->ReadMemory(addr, buf, sizeof(buf), error), sizeof(buf));
+ EXPECT_TRUE(error.Success()) << error.AsCString();
+ // The filler proves the bytes came from the process, not the file.
+ EXPECT_EQ(llvm::StringRef(buf, sizeof(buf)), "BBBBB");
+
+ // Clearing the stale error must not mask a genuine failure.
+ process_sp->SetCanRead(false);
+ char unread[5] = {};
+ Status fail_error;
+ EXPECT_EQ(target_sp->ReadMemory(addr, unread, sizeof(unread), fail_error),
+ 0u);
+ EXPECT_TRUE(fail_error.Fail());
+}
</details>
Why is this necessary. If you are going to make it so you can trust that ReadMemory clears the error, you should trust it... Otherwise this is confusing.
It's a little ugly that a few of the Process classes override ReadMemory and not DoReadMemory, so you had to set this is a handful of places. I don't see why you need to do this in Target::ReadMemory now, but otherwise this looks ok.
As a "defensive" clear in case new implementations pop up and don't clear it. Idk if this is the best solution, but from Target we don't know whether the subclasses of Process do clear the status or not.
<!--PREMERGE ADVISOR COMMENT: Linux-->
:penguin: Linux x64 Test Results
34212 tests passed
511 tests skipped
:white_check_mark: The build succeeded and all tests passed.
If I were writing new code should I do this? Or should we go auditing all the uses of ReadMemory to see if they need to also defensively clear this? That just seems awkward.
Document in Process::ReadMemory that any classes that override ReadMemory (and not DoReadMemory) have to clear the error, and if somebody doesn't do that, they will eventually find out.
typo absen.
error should be cleared here as well, otherwise partial file-cache data is returned with the live read's error attached.
The PR looks good to me, some comments,
Add error clear in ProcessTrace::ReadMemory too.
It's a little ugly that a few of the Process classes override ReadMemory and not DoReadMemory,
Is it too late for us to make only _one_ of these methods virtual?
> It's a little ugly that a few of the Process classes override ReadMemory and not DoReadMemory,
> Is it too late for us to make only _one_ of these methods virtual?
I don't know whether it was the original intent but it looks like Process::DoReadMemory is the implementation if you are using the memory cache, and process plugins that don't use the memory cache override ReadMemory.
We can change any of this since it's all lldb_private. But if we're going to, we should have process ReadMemory check whether the plugin uses the memory cache and skip directly to DoReadMemory if the answer is no. Then all the plugins could switch to DoReadMemory.
I've changed the title and description to better reflect that the patch is now about clearing the error in Process::ReadMemory subclasses. It still one error clear in Target::ReadMemory because Process::ReadMemory might fail.
<!--PREMERGE ADVISOR COMMENT: Windows-->
:window: Windows x64 Test Results
33488 tests passed
907 tests skipped
:white_check_mark: The build succeeded and all tests passed.
Looks like Process::ReadMemory was not meant to be overridden:
/// This function is not meant to be overridden by Process subclasses, the
/// subclasses should implement Process::DoReadMemory(const ProcessAddress &,
/// void *, size_t, Status &).
Looks like Process::ReadMemory was not meant to be overridden:
>> /// This function is not meant to be overridden by Process subclasses, the > /// subclasses should implement Process::DoReadMemory(const ProcessAddress &, > /// void *, size_t, Status &). >
It was silly to both say that and keep the method virtual...
It does look like we override that one just to disable memory caching:
size_t ProcessMachCore::ReadMemory(const ProcessAddress &process_addr,
void *buf, size_t size, Status &error) {
lldb::addr_t addr = process_addr.GetValue();
// Don't allow the caching that lldb_private::Process::ReadMemory does since
// in core files we have it all cached our our core file anyway.
return DoReadMemory(FixAnyAddress(addr), buf, size, error);
}
So I think we could fix this by adding
virtual bool Process::ShouldUseMemoryCache();
and then have Process::ReadMemory check this and skip over the caching part straight to DoReadMemory if it return false. Then we should be able to make ReadMemory non-virtual
@jimingham @felipepiovezan I've refactored this to make Process::ReadMemory non-virtual
This introduces one non-obvious difference between Process Plugins that say they use the memory cache and ones that don't. If you don't use the memory cache, we call DoReadMemory directly. But if you say you do we actually call ReadMemoryFromInferior. Most of that is chunking up for the memory cache, but it also does:
if (ABISP abi_sp = GetABI())
addr = abi_sp->FixAnyAddress(addr);
before using the address. And that is what gets passed to DoReadMemory. If you don't use the memory cache you get handed the unfixed address. That's not at all obvious.
It looks like all the other ReadMemory overloads call Process::FixAnyAddress before using the address (that's identical to the code inlined in ReadMemoryFromInferior above). So maybe we should define DoReadMemory to pass the fixed address? Or if we don't want to do that, we should pass the DoReadMemory calls in ReadMemoryFromInferior that unfixed value so everyone gets unfixed values.
BTW, other than that side-effect, this is a good change IMO.
This introduces one non-obvious difference between Process Plugins that say they use the memory cache and ones that don't. If you don't use the memory cache, we call DoReadMemory directly. But if you say you do we actually call ReadMemoryFromInferior. Most of that is chunking up for the memory cache, but it also does:
> if (ABISP abi_sp = GetABI()) addr = abi_sp->FixAnyAddress(addr);
> before using the address. And that is what gets passed to DoReadMemory. If you don't use the memory cache you get handed the unfixed address. That's not at all obvious.
Process::ReadMemory already calls
lldb::addr_t addr = process_addr.GetValue();
if (ABISP abi_sp = GetABI())
addr = abi_sp->FixAnyAddress(addr);
So address fixing happens twice, but we always pass the fixed address to both functions.
...although we are passing process_addr to ShouldUseMemoryCache, but the fixed address to the ReadMemory functions, so I have to fix that
The parameter name: vm_addr is wrong now, but that wasn't your doing...
But now that you are calling FixAnyAddress in Process::ReadMemory before calling DoReadMemory, you should note here that this is a "fixed virtual load address" to distinguish this from ReadMemory's vm_addr parameter.
This name is now wrong though you didn't do that... Calling it a virtual load address rather than a ProcessAddress is a bit odd.
The only reason to mention this in this PR is that I thought you should make a distinction between the address passed to ReadMemory - which might not be "fixed" and the one to DoReadMemory - which is now always fixed.
Okay, this looks good.
I think it would be useful to document Process::DoReadMemory as always receiving a fixed address, whereas ReadMemory doesn't require that. Other than that this LGTM.
LGTM too, happy to see us getting rid of one of the virtual methods
Sorry this fell off my radar. I've rebased this plus applied @jimingham's suggestions.
qiyao
augusto2112
Add Process::ShouldUseMemoryCache so a plugin can keep its reads out of
the memory cache instead of overriding ReadMemory. The plugins that
overrode ReadMemory now implement DoReadMemory, and ReadMemory clears
the error once for all of them.
Assisted-by: Claude