[Lldb-commits] [lldb] [lldb] Cache the symbol table for memory-read modules by default (PR #229305)
Jason Molenda via lldb-commits
lldb-commits at lists.llvm.org
Tue Oct 6 15:50:35 PDT 2026
https://github.com/jasonmolenda updated https://github.com/llvm/llvm-project/pull/229305
>From 9368741b019d896ed8f400cfefc0be6058f2b767 Mon Sep 17 00:00:00 2001
From: Jason Molenda <jmolenda at apple.com>
Date: Mon, 5 Oct 2026 20:51:13 -0700
Subject: [PATCH 1/2] [lldb] Cache the symbol table for memory-read modules by
default
When lldb debugs a process on a remote system/device, there may be
binaries loaded in the process that it cannot find on the debug
host. It will read the object file header / load commands (mach-o
terminology) and symbol table out of memory at ObjectFile/Module
creation time. The symbol table may involve many separate reads
to complete, and can be a serious performance issue. We've
traditionally worked hard to always have binaries for the remote
target present on the host computer, because it was such a poor
user experience, but in practice it's never perfect.
This PR adds a new setting, symbols.enable-lldb-index-cache-memory-modules,
which is defaulted to on, and I also increase the default value in
symbols.lldb-index-cache-expiration-days from 7 to 31. With this
change, when lldb reads a remote binary out of memory, it will
create a DataFileCache symtab serialization of its symbol table on
the host computer, and keep it around for 31 days, by default.
I'm open to discussions about changing the expiration-days default.
I know DataFileCache was a significant performance improvement for
first-debug-session and I'm sure it was in active use originally.
But since we've switched to creating Modules in parallel, I'm not
sure it's as load bearing as it once was, unless people have one
very large binary that they're linked against. For instance, the
difference to attach to the macOS Mail.app process with 1350 binaries,
with parallel Module creation on an M5 Pro notebook, goes from 2.4
seconds to 2.1 seconds if lldb-index-cache is enabled (for the first
launch in an lldb session; none of this is relevant for subsequent
launches with the same lldb execution)
When discussing this change with Jonas, he wants DynamicLoaderDarwin
to use a sentinel library -- something like libobjc.A.dylib -- and
if we are reading that from memory, we are probably dealing with a
situation where NONE of the binaries from the remote target are
present. Jonas thinks we should not enable this cacheing behavior
in that sitaution, because attaching to a modern macOS UI app can
yield 2GB of DataFileCache symtabs for all the binaries that are
loaded in the process, and that's a lot of disk space because someone
didn't have their DeviceSupport directory populated for the remote
device. We're really trying to address the situation where a SMALL
NUMBER of binaries are missing from the debug host, not all of them.
I want to handle that policy choice in a separate PR for simplicity,
but I'm open to doing it here if there's disagreement.
I wrote a test for a while(1)sleep() test program that removes its
binary and touches a signal file. The API test waits for the signal
file, attaches once to popular the DataFileCache directory with
the memory module symbol table, detaches, deletes the target, flushes
the global module cache. Then attaches a second time and collects
a packet log during the attach; it checks that no memory reads were
sent for the symbol table VM region of the binary -- that lldb read
it out of the DataFileCache symtab.
I don't think the code details of the PR are particularly interesting,
but the policy decisions here are moreso and I'm open to discussions.
rdar://188327429
---
lldb/include/lldb/Core/Module.h | 12 +-
lldb/include/lldb/Core/ModuleList.h | 2 +
lldb/source/Core/CoreProperties.td | 6 +-
lldb/source/Core/Module.cpp | 10 +-
lldb/source/Core/ModuleList.cpp | 12 ++
.../SymbolFile/DWARF/ManualDWARFIndex.cpp | 12 +-
lldb/source/Symbol/Symtab.cpp | 4 +-
.../macosx/memory-read-module-symtab/Makefile | 3 +
.../TestMemoryReadModuleSymtab.py | 154 ++++++++++++++++++
.../macosx/memory-read-module-symtab/main.c | 56 +++++++
10 files changed, 256 insertions(+), 15 deletions(-)
create mode 100644 lldb/test/API/macosx/memory-read-module-symtab/Makefile
create mode 100644 lldb/test/API/macosx/memory-read-module-symtab/TestMemoryReadModuleSymtab.py
create mode 100644 lldb/test/API/macosx/memory-read-module-symtab/main.c
diff --git a/lldb/include/lldb/Core/Module.h b/lldb/include/lldb/Core/Module.h
index 6fc9ca834c5281..e71a29e3e413b9 100644
--- a/lldb/include/lldb/Core/Module.h
+++ b/lldb/include/lldb/Core/Module.h
@@ -1040,14 +1040,18 @@ class Module : public std::enable_shared_from_this<Module>,
/// Get the global index file cache.
///
/// LLDB can cache data for a module between runs. This cache directory can be
- /// used to stored data that previously was manually created each time you debug.
- /// Examples include debug information indexes, symbol tables, symbol table
- /// indexes, and more.
+ /// used to stored data that previously was manually created each time you
+ /// debug. Examples include debug information indexes, symbol tables, symbol
+ /// table indexes, and more.
+ ///
+ /// \param[in] memory_module
+ /// True if this binary exists only in memory.
///
/// \returns
/// If caching is enabled in the lldb settings, return a pointer to the data
/// file cache. If caching is not enabled, return NULL.
- static DataFileCache *GetIndexCache();
+ static DataFileCache *GetIndexCache(bool memory_module);
+
protected:
// Member Variables
mutable std::recursive_mutex m_mutex; ///< A mutex to keep this object happy
diff --git a/lldb/include/lldb/Core/ModuleList.h b/lldb/include/lldb/Core/ModuleList.h
index aa0e7c674c1d28..f35be86798ebef 100644
--- a/lldb/include/lldb/Core/ModuleList.h
+++ b/lldb/include/lldb/Core/ModuleList.h
@@ -107,6 +107,8 @@ class ModuleListProperties : public Properties {
lldb::SymbolSharedCacheUse GetSharedCacheBinaryLoading() const;
bool GetEnableLLDBIndexCache() const;
bool SetEnableLLDBIndexCache(bool new_value);
+ bool GetEnableLLDBIndexCacheMemoryModules() const;
+ bool SetEnableLLDBIndexCacheMemoryModules(bool new_value);
uint64_t GetLLDBIndexCacheMaxByteSize();
uint64_t GetLLDBIndexCacheMaxPercent();
uint64_t GetLLDBIndexCacheExpirationDays();
diff --git a/lldb/source/Core/CoreProperties.td b/lldb/source/Core/CoreProperties.td
index 268d5da19fadda..c36347e1b2394a 100644
--- a/lldb/source/Core/CoreProperties.td
+++ b/lldb/source/Core/CoreProperties.td
@@ -31,6 +31,10 @@ let Definition = "modulelist", Path = "symbols" in {
Global,
DefaultFalse,
Desc<"Enable caching for debug sessions in LLDB. LLDB can cache data for each module for improved performance in subsequent debug sessions.">;
+ def EnableLLDBIndexCacheMemoryModules: Property<"enable-lldb-index-cache-memory-modules", "Boolean">,
+ Global,
+ DefaultTrue,
+ Desc<"Enable symbol table caching for memory-read binaries. LLDB can cache the symbol table memory-read binaries, for improved performance in subsequent debug sessions.">;
def LLDBIndexCachePath: Property<"lldb-index-cache-path", "FileSpec">,
Global,
DefaultStringValue<"">,
@@ -45,7 +49,7 @@ let Definition = "modulelist", Path = "symbols" in {
Desc<"The maximum size for the cache directory in terms of percentage of the available space on the disk. Set to 100 to indicate no limit, 50 to indicate that the cache size will not be left over half the available disk space. A value over 100 will be reduced to 100. A value of 0 disables the percentage size-based pruning.">;
def LLDBIndexCacheExpirationDays: Property<"lldb-index-cache-expiration-days", "UInt64">,
Global,
- DefaultUnsignedValue<7>,
+ DefaultUnsignedValue<31>,
Desc<"The expiration time in days for a file. When a file hasn't been accessed for the specified amount of days, it is removed from the cache. A value of 0 disables the expiration-based pruning.">;
def LoadSymbolOnDemand: Property<"load-on-demand", "Boolean">,
Global,
diff --git a/lldb/source/Core/Module.cpp b/lldb/source/Core/Module.cpp
index 2d7cffb7b43984..4191e9652f586c 100644
--- a/lldb/source/Core/Module.cpp
+++ b/lldb/source/Core/Module.cpp
@@ -1660,8 +1660,14 @@ std::string Module::GetCacheKey() {
return key;
}
-DataFileCache *Module::GetIndexCache() {
- if (!ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
+DataFileCache *Module::GetIndexCache(bool memory_module) {
+ bool lldb_index_enabled = false;
+ if (ModuleList::GetGlobalModuleListProperties().GetEnableLLDBIndexCache())
+ lldb_index_enabled = true;
+ if (memory_module && ModuleList::GetGlobalModuleListProperties()
+ .GetEnableLLDBIndexCacheMemoryModules())
+ lldb_index_enabled = true;
+ if (!lldb_index_enabled)
return nullptr;
// NOTE: intentional leak so we don't crash if global destructor chain gets
// called as other threads still use the result of this function
diff --git a/lldb/source/Core/ModuleList.cpp b/lldb/source/Core/ModuleList.cpp
index 5b7e15f71c26c1..ae2b8747efd27e 100644
--- a/lldb/source/Core/ModuleList.cpp
+++ b/lldb/source/Core/ModuleList.cpp
@@ -155,6 +155,18 @@ bool ModuleListProperties::SetEnableLLDBIndexCache(bool new_value) {
return SetPropertyAtIndex(ePropertyEnableLLDBIndexCache, new_value);
}
+bool ModuleListProperties::GetEnableLLDBIndexCacheMemoryModules() const {
+ const uint32_t idx = ePropertyEnableLLDBIndexCacheMemoryModules;
+ return GetPropertyAtIndexAs<bool>(
+ idx, g_modulelist_properties[idx].default_uint_value != 0);
+}
+
+bool ModuleListProperties::SetEnableLLDBIndexCacheMemoryModules(
+ bool new_value) {
+ return SetPropertyAtIndex(ePropertyEnableLLDBIndexCacheMemoryModules,
+ new_value);
+}
+
uint64_t ModuleListProperties::GetLLDBIndexCacheMaxByteSize() {
const uint32_t idx = ePropertyLLDBIndexCacheMaxByteSize;
return GetPropertyAtIndexAs<uint64_t>(
diff --git a/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp b/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp
index 0971e66df86aed..c3fff3d3d1486c 100644
--- a/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp
+++ b/lldb/source/Plugins/SymbolFile/DWARF/ManualDWARFIndex.cpp
@@ -617,12 +617,12 @@ std::string ManualDWARFIndex::GetCacheKey() {
}
bool ManualDWARFIndex::LoadFromCache() {
- DataFileCache *cache = Module::GetIndexCache();
- if (!cache)
- return false;
ObjectFile *objfile = m_dwarf->GetObjectFile();
if (!objfile)
return false;
+ DataFileCache *cache = Module::GetIndexCache(objfile->IsInMemory());
+ if (!cache)
+ return false;
std::unique_ptr<llvm::MemoryBuffer> mem_buffer_up =
cache->GetCachedData(GetCacheKey());
if (!mem_buffer_up)
@@ -640,12 +640,12 @@ bool ManualDWARFIndex::LoadFromCache() {
}
void ManualDWARFIndex::SaveToCache() {
- DataFileCache *cache = Module::GetIndexCache();
- if (!cache)
- return; // Caching is not enabled.
ObjectFile *objfile = m_dwarf->GetObjectFile();
if (!objfile)
return;
+ DataFileCache *cache = Module::GetIndexCache(objfile->IsInMemory());
+ if (!cache)
+ return; // Caching is not enabled.
DataEncoder file(endian::InlHostByteOrder(), objfile->GetAddressByteSize());
// Encode will return false if the object file doesn't have anything to make
// a signature from.
diff --git a/lldb/source/Symbol/Symtab.cpp b/lldb/source/Symbol/Symtab.cpp
index 0b151d7497f3a9..81179212136d17 100644
--- a/lldb/source/Symbol/Symtab.cpp
+++ b/lldb/source/Symbol/Symtab.cpp
@@ -1167,7 +1167,7 @@ std::string Symtab::GetCacheKey() {
}
void Symtab::SaveToCache() {
- DataFileCache *cache = Module::GetIndexCache();
+ DataFileCache *cache = Module::GetIndexCache(m_objfile->IsInMemory());
if (!cache)
return; // Caching is not enabled.
@@ -1346,7 +1346,7 @@ bool Symtab::Decode(const DataExtractor &data, lldb::offset_t *offset_ptr,
}
bool Symtab::LoadFromCache() {
- DataFileCache *cache = Module::GetIndexCache();
+ DataFileCache *cache = Module::GetIndexCache(m_objfile->IsInMemory());
if (!cache)
return false;
diff --git a/lldb/test/API/macosx/memory-read-module-symtab/Makefile b/lldb/test/API/macosx/memory-read-module-symtab/Makefile
new file mode 100644
index 00000000000000..10495940055b63
--- /dev/null
+++ b/lldb/test/API/macosx/memory-read-module-symtab/Makefile
@@ -0,0 +1,3 @@
+C_SOURCES := main.c
+
+include Makefile.rules
diff --git a/lldb/test/API/macosx/memory-read-module-symtab/TestMemoryReadModuleSymtab.py b/lldb/test/API/macosx/memory-read-module-symtab/TestMemoryReadModuleSymtab.py
new file mode 100644
index 00000000000000..7a428c45003fb1
--- /dev/null
+++ b/lldb/test/API/macosx/memory-read-module-symtab/TestMemoryReadModuleSymtab.py
@@ -0,0 +1,154 @@
+import time
+import lldb
+import glob
+import re
+from lldbsuite.test.decorators import *
+from lldbsuite.test.lldbtest import *
+from lldbsuite.test import lldbutil
+
+
+class MemoryReadModuleSymtabTestCase(TestBase):
+ NO_DEBUG_INFO_TESTCASE = True
+ SHARED_BUILD_TESTCASE = False
+
+ def packet_log(self, name):
+ """Enable packet logging to a scratch file, removed on teardown."""
+ logfile = os.path.join(
+ self.getBuildDir(), "%s-%s.txt" % (name, self.getArchitecture())
+ )
+ self.runCmd("log enable -f %s gdb-remote packets" % logfile)
+
+ def cleanup():
+ self.runCmd("log disable gdb-remote packets")
+ if os.path.exists(logfile):
+ os.unlink(logfile)
+
+ self.addTearDownHook(cleanup)
+ return logfile
+
+ def memory_read_requests(self, logfile):
+ """Scan a gdb-remote packet log for memory read requests,
+ return an array of [start-address, end-address] entries."""
+ self.assertTrue(os.path.exists(logfile), "packet log was created")
+ log_text = [s.rstrip() for s in open(logfile).readlines()]
+ read_lines = [line for line in log_text if "send packet: $x" in line]
+
+ results = list()
+ for l in read_lines:
+ pattern = r"send packet: [$]x([0-9a-f]+),([0-9a-f]+)#"
+ match = re.search(pattern, l)
+ if match:
+ start = int(match.group(1), 16)
+ end = start + int(match.group(2), 16)
+ entry = [start, end]
+ results.append(entry)
+
+ print(results)
+ return results
+
+ def confirm_datafilecache_dir_contents(self, cache_dir):
+ # Check that we have a symtab created for a.out.
+ module_file_glob = os.path.join(cache_dir, "llvmcache-*a.out*-symtab-*")
+ self.assertEqual(len(glob.glob(module_file_glob)), 1)
+
+ # Check that we don't have a symtab for a system library.
+ module_file_glob = os.path.join(
+ cache_dir, "llvmcache-*libsystem_c.dylib*-symtab-*"
+ )
+ self.assertEqual(len(glob.glob(module_file_glob)), 0)
+
+ def attach_to_process(self, pid):
+ target = self.dbg.CreateTarget(None)
+ self.assertTrue(target.IsValid(), "Got a vaid empty target.")
+ error = lldb.SBError()
+ attach_info = lldb.SBAttachInfo()
+ attach_info.SetProcessID(pid)
+ attach_info.SetIgnoreExisting(False)
+ process = target.Attach(attach_info, error)
+ self.assertSuccess(error, "Didn't attach successfully to %d" % (pid))
+ return target, process
+
+ @requireDarwin
+ def test_memory_read_module_symtab(self):
+ """Attach to a process where no on-disk copy of the binary exists.
+ On first attach, we create a DataFileCache SymbolTable for the
+ binary.
+ Detach, delete the target, flush the module cache.
+ On second attach, we turn on packet communication logging,
+ attach to the process again, and should get the symbol table
+ from the DataFileCache.
+ Check the packet log to ensure that no reads were made of the
+ binary's symbol table."""
+ self.build()
+ exe = self.getBuildArtifact("a.out")
+
+ # Use a file as a synchronization point between test and inferior: the
+ # inferior writes its pid only after it has called PT_DENY_ATTACH.
+ pid_file_path = lldbutil.append_to_process_working_directory(
+ self, "pid_file_%d" % (int(time.time()))
+ )
+ self.addTearDownHook(
+ lambda: self.run_platform_command("rm %s" % (pid_file_path))
+ )
+
+ cache_dir = os.path.join(self.getBuildDir(), "lldb-module-cache")
+ self.runCmd('settings set -g symbols.lldb-index-cache-path "%s"' % (cache_dir))
+ self.runCmd("settings set -g symbols.enable-lldb-index-cache false")
+ self.runCmd(
+ "settings set -g symbols.enable-lldb-index-cache-memory-modules true"
+ )
+
+ # Launch the process, so it can remove the binary before
+ # lldb attaches.
+ popen = self.spawnSubprocess(exe, [pid_file_path])
+ pid = int(lldbutil.wait_for_file_on_target(self, pid_file_path))
+
+ # First attach: Create the DataFileCache for the MemoryModule.
+ target, process = self.attach_to_process(pid)
+ self.confirm_datafilecache_dir_contents(cache_dir)
+ process.Detach()
+
+ # Delete the target, flush the Module we've created, so
+ # we'll need to re-create it.
+ self.dbg.DeleteTarget(target)
+ self.assertEqual(self.dbg.GetNumTargets(), 0)
+ self.dbg.MemoryPressureDetected()
+
+ # Enable logging of gdb-remote packets, to look for any
+ # reads of a.out's __LINKEDIT in this second attach.
+ logfile = self.packet_log("packets")
+
+ # Second attach: Read the DataFileCache for the MemoryModule.
+ target, process = self.attach_to_process(pid)
+ self.confirm_datafilecache_dir_contents(cache_dir)
+
+ # Ensure we've parsed the a.out Module.
+ self.runCmd("bt")
+
+ exe_filespec = lldb.SBFileSpec("a.out")
+ exe_module = target.FindModule(exe_filespec)
+ print(exe_module)
+ exe_linkedit = exe_module.FindSection("__LINKEDIT")
+ print(exe_linkedit)
+ self.assertTrue(exe_linkedit.IsValid())
+ linkedit_startaddr = exe_linkedit.GetLoadAddress(target)
+ linkedit_endaddr = linkedit_startaddr + exe_linkedit.GetByteSize()
+
+ memory_read_addrs = self.memory_read_requests(logfile)
+ self.assertGreater(len(memory_read_addrs), 0)
+
+ # Iterate through the start & end address of every memory
+ # read packet, and confirm that none of them are within
+ # the VM range of a.out's __LINKEDIT. The SymbolTable for
+ # a.out should be gotten from the DataFileCache, not memory.
+ for addrs in memory_read_addrs:
+ for addr in addrs:
+ if addr >= linkedit_startaddr and addr < linkedit_endaddr:
+ print(
+ "Address 0x%x was read from a.out's __LINKEDIT; all symbol table information should have been retrieved from DataFileCache of it."
+ % addr
+ )
+ if self.TraceOn():
+ self.runCmd("target modules dump sections a.out")
+ print("Read of address 0x%x is within LINKEDIT" % addr)
+ self.assertFalse(addr >= linkedit_startaddr and addr < linkedit_endaddr)
diff --git a/lldb/test/API/macosx/memory-read-module-symtab/main.c b/lldb/test/API/macosx/memory-read-module-symtab/main.c
new file mode 100644
index 00000000000000..75cdb7692473e3
--- /dev/null
+++ b/lldb/test/API/macosx/memory-read-module-symtab/main.c
@@ -0,0 +1,56 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/ptrace.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+// Write our pid into file_name atomically (write to a temp file, then rename)
+// so the test never observes a partially written pid.
+static int write_pid(const char *file_name) {
+ char tmp_name[1024];
+ snprintf(tmp_name, sizeof(tmp_name), "%s_tmp", file_name);
+
+ int fd = open(tmp_name, O_CREAT | O_WRONLY | O_TRUNC, S_IRUSR | S_IWUSR);
+ if (fd == -1) {
+ fprintf(stderr, "open(%s) failed: %s\n", tmp_name, strerror(errno));
+ return 1;
+ }
+
+ char buffer[64];
+ int len = snprintf(buffer, sizeof(buffer), "%ld", (long)getpid());
+ int result = 0;
+ if (write(fd, buffer, len) == -1) {
+ fprintf(stderr, "write failed: %s\n", strerror(errno));
+ result = 1;
+ }
+ close(fd);
+
+ if (rename(tmp_name, file_name) == -1) {
+ fprintf(stderr, "rename failed: %s\n", strerror(errno));
+ result = 1;
+ }
+ return result;
+}
+
+int main(int argc, char const *argv[]) {
+ if (argc < 2) {
+ fprintf(stderr, "invalid number of command line arguments\n");
+ return 1;
+ }
+
+ // Remove the binary so lldb must read it from memory.
+ if (unlink(argv[0]))
+ return 1;
+
+ if (write_pid(argv[1]) != 0)
+ return 2;
+
+ // Wait for the debugger to try (and fail) to attach.
+ while (1)
+ sleep(60);
+
+ return 0;
+}
>From ce8c9e0b241b6d853b93fd9dd01fb3bf1e3526be Mon Sep 17 00:00:00 2001
From: Jason Molenda <jmolenda at apple.com>
Date: Tue, 6 Oct 2026 15:50:07 -0700
Subject: [PATCH 2/2] revert change to 31-day expiration change part of my PR.
---
lldb/source/Core/CoreProperties.td | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lldb/source/Core/CoreProperties.td b/lldb/source/Core/CoreProperties.td
index c36347e1b2394a..d18ccc73bee584 100644
--- a/lldb/source/Core/CoreProperties.td
+++ b/lldb/source/Core/CoreProperties.td
@@ -49,7 +49,7 @@ let Definition = "modulelist", Path = "symbols" in {
Desc<"The maximum size for the cache directory in terms of percentage of the available space on the disk. Set to 100 to indicate no limit, 50 to indicate that the cache size will not be left over half the available disk space. A value over 100 will be reduced to 100. A value of 0 disables the percentage size-based pruning.">;
def LLDBIndexCacheExpirationDays: Property<"lldb-index-cache-expiration-days", "UInt64">,
Global,
- DefaultUnsignedValue<31>,
+ DefaultUnsignedValue<7>,
Desc<"The expiration time in days for a file. When a file hasn't been accessed for the specified amount of days, it is removed from the cache. A value of 0 disables the expiration-based pruning.">;
def LoadSymbolOnDemand: Property<"load-on-demand", "Boolean">,
Global,
More information about the lldb-commits
mailing list