From bebf5777576ebe7b0335bf2213e7072cede19bb4 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 11:33:46 -0800 Subject: [PATCH 01/91] Add heapmaplock_deadlock_test (deterministic g_heapMapLock deadlock) VLDGetLeaksCount holds g_heapMapLock, which every allocation hook takes, while it resolves leak call stacks with dbghelp. dbghelp loads a module's symbols on first use, and that load can need the loader lock (with a symbol server, symsrv/wininet load DLLs). A thread running DLL_THREAD_ATTACH holds the loader lock and blocks in VLD's allocation hook on g_heapMapLock, so the two threads deadlock. Seen in a dump of ignore_modules_getaddrinfo_test run with _NT_SYMBOL_PATH=srv*... The test makes that ordering deterministic without a symbol server: a dbghelp callback on the deferred symbol load of a helper DLL starts a thread whose DLL_THREAD_ATTACH in the helper allocates, waits until that thread is inside thread attach, then calls LoadLibrary. A watchdog prints where both threads are and terminates the process after 30 s (exit 3); ctest TIMEOUT is 60 s. It fails today in Debug and RelWithDebInfo (x64). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 41 +++++ .../heapmaplock_deadlock_dll.cpp | 44 +++++ .../heapmaplock_deadlock_test.cpp | 164 ++++++++++++++++++ src/tests/heapmaplock_deadlock_test/vld.ini | 15 ++ 4 files changed, 264 insertions(+) create mode 100644 src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_dll.cpp create mode 100644 src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp create mode 100644 src/tests/heapmaplock_deadlock_test/vld.ini diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 55624ce2..b5a269f4 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -505,6 +505,47 @@ add_custom_command(TARGET no_protect_to_read_test POST_BUILD COMMENT "Copying no_protect_to_read_test vld.ini, VLD DLL, and dbghelp.dll" ) +# ============================================================================ +# g_heapMapLock deadlock regression test +# +# VLD must not resolve symbols (dbghelp) while holding g_heapMapLock: a +# deferred symbol load that needs the loader lock deadlocks against a thread +# in DLL_THREAD_ATTACH whose allocation waits for g_heapMapLock. The test makes +# that ordering deterministic and fails via a watchdog instead of hanging. +# ============================================================================ +add_vld_test(heapmaplock_deadlock_dll + IS_DLL + SOURCES heapmaplock_deadlock_test/heapmaplock_deadlock_dll.cpp +) +add_vld_test(heapmaplock_deadlock_test + SOURCES heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp +) +add_dependencies(heapmaplock_deadlock_test heapmaplock_deadlock_dll) + +foreach(HEAPMAPLOCK_TARGET heapmaplock_deadlock_test heapmaplock_deadlock_dll) + set_target_properties(${HEAPMAPLOCK_TARGET} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$/heapmaplock_deadlock_test" + RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin/Debug/heapmaplock_deadlock_test" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin/Release/heapmaplock_deadlock_test" + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/bin/RelWithDebInfo/heapmaplock_deadlock_test" + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/bin/MinSizeRel/heapmaplock_deadlock_test" + ) +endforeach() + +add_custom_command(TARGET heapmaplock_deadlock_test POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_CURRENT_SOURCE_DIR}/heapmaplock_deadlock_test/vld.ini" + "$/vld.ini" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "$" + "$/$" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_SOURCE_DIR}/setup/dbghelp/${DBGHELP_ARCH}/dbghelp.dll" + "$/dbghelp.dll" + COMMENT "Copying heapmaplock_deadlock_test vld.ini, VLD DLL, and dbghelp.dll" +) +set_property(TEST heapmaplock_deadlock_test PROPERTY TIMEOUT 60) + # ============================================================================ # Deep Callstack Test - Tests for excessively long stack traces (PR #37) # ============================================================================ diff --git a/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_dll.cpp b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_dll.cpp new file mode 100644 index 00000000..53ad9d03 --- /dev/null +++ b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_dll.cpp @@ -0,0 +1,44 @@ +// heapmaplock_deadlock_dll.cpp - helper for heapmaplock_deadlock_test. +// +// Links VLD so that its allocations are tracked (VLD's allocation hooks take +// g_heapMapLock). Once armed, the next DLL_THREAD_ATTACH, which runs while +// the new thread holds the loader lock, signals the test and then allocates. + +#include +#include +#include "vld.h" + +static volatile LONG g_armed = 0; +static volatile LONG g_inThreadAttachAlloc = 0; +static HANDLE g_inThreadAttach = NULL; + +extern "C" __declspec(dllexport) void ArmThreadAttach(HANDLE inThreadAttach) +{ + g_inThreadAttach = inThreadAttach; + InterlockedExchange(&g_armed, 1); +} + +extern "C" __declspec(dllexport) LONG IsInThreadAttachAlloc() +{ + return InterlockedCompareExchange(&g_inThreadAttachAlloc, 0, 0); +} + +#pragma optimize("", off) +extern "C" __declspec(dllexport) __declspec(noinline) void* LeakFromHelper(size_t size) +{ + return malloc(size); +} +#pragma optimize("", on) + +BOOL APIENTRY DllMain(HMODULE, DWORD reason, LPVOID) +{ + if (reason == DLL_THREAD_ATTACH && InterlockedExchange(&g_armed, 0) != 0) + { + InterlockedExchange(&g_inThreadAttachAlloc, 1); + SetEvent(g_inThreadAttach); + void* p = malloc(16); + free(p); + InterlockedExchange(&g_inThreadAttachAlloc, 0); + } + return TRUE; +} diff --git a/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp new file mode 100644 index 00000000..87359331 --- /dev/null +++ b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp @@ -0,0 +1,164 @@ +// heapmaplock_deadlock_test.cpp - VLD must not resolve symbols while holding +// g_heapMapLock. +// +// VLDGetLeaksCount holds g_heapMapLock (taken by every allocation hook) while +// it resolves leak call stacks with dbghelp. dbghelp loads a module's symbols +// on first use, and that load can need the loader lock (a symbol server path +// makes symsrv/wininet load DLLs). A thread running DLL_THREAD_ATTACH holds the +// loader lock and blocks in VLD's allocation hook on g_heapMapLock: deadlock. +// +// This test makes that ordering deterministic. A dbghelp callback on the +// deferred symbol load of the helper DLL starts a thread whose +// DLL_THREAD_ATTACH in the helper allocates, waits until that thread is inside +// thread attach (holding the loader lock), then calls LoadLibrary, standing in +// for symsrv. If VLD is inside g_heapMapLock at that point, neither thread can +// proceed; a watchdog reports the deadlock and terminates the process. + +#include +#include +#include +#include "vld.h" + +namespace +{ +// From the SDK dbghelp.h, which this test cannot include (VLD's src/dbghelp.h +// shadows it). +const ULONG CBA_DEFERRED_SYMBOL_LOAD_START = 0x00000001; +struct DeferredSymbolLoadW64 +{ + DWORD SizeOfStruct; + DWORD64 BaseOfImage; + DWORD CheckSum; + DWORD TimeDateStamp; + WCHAR FileName[MAX_PATH + 1]; +}; +typedef BOOL (CALLBACK* SymbolRegisteredCallback64)(HANDLE, ULONG, ULONG64, ULONG64); + +typedef void (*ArmThreadAttach_t)(HANDLE); +typedef LONG (*IsInThreadAttachAlloc_t)(); +typedef void* (*LeakFromHelper_t)(size_t); +typedef BOOL (WINAPI* SymRegisterCallbackW64_t)(HANDLE, SymbolRegisteredCallback64, ULONG64); + +const DWORD WATCHDOG_MS = 30000; +const wchar_t HELPER_DLL[] = L"heapmaplock_deadlock_dll.dll"; + +ArmThreadAttach_t g_armThreadAttach = NULL; +IsInThreadAttachAlloc_t g_isInThreadAttachAlloc = NULL; +HANDLE g_inThreadAttach = NULL; +HANDLE g_done = NULL; +volatile LONG g_callbackArmed = 0; +volatile LONG g_callbackFired = 0; +volatile LONG g_inLoadLibrary = 0; + +void WriteStdout(const char* text) +{ + DWORD written; + WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), text, (DWORD)strlen(text), &written, NULL); +} + +DWORD WINAPI Watchdog(LPVOID) +{ + if (WaitForSingleObject(g_done, WATCHDOG_MS) == WAIT_TIMEOUT) + { + char state[256]; + sprintf_s(state, "main thread: in VLDGetLeaksCount -> dbghelp deferred symbol load -> LoadLibrary: %s\n" + "new thread: in helper DLL_THREAD_ATTACH (loader lock held) -> malloc -> VLD hook: %s\n", + InterlockedCompareExchange(&g_inLoadLibrary, 0, 0) ? "yes" : "no", + g_isInThreadAttachAlloc() ? "yes" : "no"); + WriteStdout(state); + // ExitProcess would need the loader lock, which is part of the deadlock. + WriteStdout("FAIL: DEADLOCK - VLD resolved symbols while holding g_heapMapLock\n"); + TerminateProcess(GetCurrentProcess(), 3); + } + return 0; +} + +DWORD WINAPI NewThread(LPVOID) +{ + return 0; +} + +BOOL CALLBACK SymbolCallback(HANDLE, ULONG action, ULONG64 data, ULONG64) +{ + if (action != CBA_DEFERRED_SYMBOL_LOAD_START || data == 0) + return FALSE; + const DeferredSymbolLoadW64* load = (const DeferredSymbolLoadW64*)data; + if (wcsstr(load->FileName, L"heapmaplock_deadlock_dll") == NULL) + return FALSE; + if (InterlockedExchange(&g_callbackArmed, 0) == 0) + return FALSE; + InterlockedExchange(&g_callbackFired, 1); + + // A thread that holds the loader lock (DLL_THREAD_ATTACH) and allocates. + g_armThreadAttach(g_inThreadAttach); + HANDLE thread = CreateThread(NULL, 0, NewThread, NULL, 0, NULL); + if (thread == NULL || WaitForSingleObject(g_inThreadAttach, 10000) != WAIT_OBJECT_0) + { + WriteStdout("FAIL: helper DLL_THREAD_ATTACH did not run\n"); + TerminateProcess(GetCurrentProcess(), 2); + } + + // What symsrv/wininet do while loading symbols: take the loader lock. + InterlockedExchange(&g_inLoadLibrary, 1); + HMODULE version = LoadLibraryW(L"version.dll"); + InterlockedExchange(&g_inLoadLibrary, 0); + if (version != NULL) + FreeLibrary(version); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + return FALSE; +} +} + +int main() +{ + g_done = CreateEventW(NULL, TRUE, FALSE, NULL); + g_inThreadAttach = CreateEventW(NULL, TRUE, FALSE, NULL); + HANDLE watchdog = CreateThread(NULL, 0, Watchdog, NULL, 0, NULL); + if (g_done == NULL || g_inThreadAttach == NULL || watchdog == NULL) + { + printf("FAIL: setup\n"); + return 2; + } + + HMODULE helper = LoadLibraryW(HELPER_DLL); + if (helper == NULL) + { + printf("FAIL: LoadLibrary(%ls) failed, error %lu\n", HELPER_DLL, GetLastError()); + return 2; + } + g_armThreadAttach = (ArmThreadAttach_t)GetProcAddress(helper, "ArmThreadAttach"); + g_isInThreadAttachAlloc = (IsInThreadAttachAlloc_t)GetProcAddress(helper, "IsInThreadAttachAlloc"); + LeakFromHelper_t leakFromHelper = (LeakFromHelper_t)GetProcAddress(helper, "LeakFromHelper"); + + // The same dbghelp instance and process handle VLD uses. + HMODULE dbghelp = GetModuleHandleW(L"dbghelp.dll"); + SymRegisterCallbackW64_t symRegisterCallbackW64 = dbghelp == NULL ? NULL : + (SymRegisterCallbackW64_t)GetProcAddress(dbghelp, "SymRegisterCallbackW64"); + if (g_armThreadAttach == NULL || g_isInThreadAttachAlloc == NULL || leakFromHelper == NULL || + symRegisterCallbackW64 == NULL || + !symRegisterCallbackW64(GetCurrentProcess(), SymbolCallback, 0)) + { + printf("FAIL: could not set up the helper DLL or the dbghelp callback\n"); + return 2; + } + + // A leak whose call stack runs through the helper, whose symbols are not loaded yet. + void* leak = leakFromHelper(64); + + InterlockedExchange(&g_callbackArmed, 1); + SIZE_T leaks = VLDGetLeaksCount(); + SetEvent(g_done); + WaitForSingleObject(watchdog, INFINITE); + + free(leak); + VLDMarkAllLeaksAsReported(); + + if (InterlockedCompareExchange(&g_callbackFired, 0, 0) == 0) + { + printf("FAIL: the deferred symbol load of the helper DLL never happened (inconclusive)\n"); + return 2; + } + printf("PASS: no deadlock (%zu leaks counted)\n", leaks); + return 0; +} diff --git a/src/tests/heapmaplock_deadlock_test/vld.ini b/src/tests/heapmaplock_deadlock_test/vld.ini new file mode 100644 index 00000000..09102d09 --- /dev/null +++ b/src/tests/heapmaplock_deadlock_test/vld.ini @@ -0,0 +1,15 @@ +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Visual Leak Detector - Initialization/Configuration File (test config) +;; +;; Config for heapmaplock_deadlock_test: SkipCrtStartupLeaks makes +;; VLDGetLeaksCount resolve call stacks; the fast stack walk keeps dbghelp out +;; of the allocation hook. +;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +[Options] +VLD = on +ReportTo = stdout +StackWalkMethod = fast +SkipCrtStartupLeaks = yes From 70d8b87d3a7035287ca4f2e5629ebb84306992dd Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 12:02:01 -0800 Subject: [PATCH 02/91] Load leak symbols before taking g_heapMapLock GetLeaksCount, GetThreadLeaksCount, ReportLeaks and ReportThreadLeaks resolve leak call stacks while holding g_heapMapLock, which every allocation takes. dbghelp loads a module's symbols on first use and that load can take the loader lock (a symbol server path loads symsrv, wininet and their dependencies), while a thread in DLL_THREAD_ATTACH holds the loader lock and waits for g_heapMapLock in VLD's allocation hook: deadlock (heapmaplock_deadlock_test). loadLeakSymbols collects the code pages of the unreported leaks' call stacks under g_heapMapLock, releases it, and makes dbghelp load the symbols of each module those pages belong to. The locked pass then only does in-memory lookups. Modules first seen in leaks allocated in between are still loaded under the lock. ResolveCallstacks and GetAllocationResolveResults already take the loader lock first and are unchanged; so is the report from the destructor. heapmaplock_deadlock_test now passes on x64 and x86 (local), ARM64 native and x64 under emulation (Windows 26300 ARM64), Debug and RelWithDebInfo; all other tests unchanged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.h | 1 + src/vld.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++++++++ src/vldint.h | 1 + 3 files changed, 69 insertions(+) diff --git a/src/callstack.h b/src/callstack.h index 80c58894..1a09254f 100644 --- a/src/callstack.h +++ b/src/callstack.h @@ -90,6 +90,7 @@ class CallStack int resolve(BOOL showinternalframes); // Formats the stack frame into a human readable format, and saves it for later retrieval. CONST WCHAR* getResolvedCallstack(BOOL showinternalframes); + UINT32 size() const { return m_size; } virtual DWORD getHashValue() const = 0; virtual VOID getStackTrace (UINT32 maxdepth, const context_t& context) = 0; bool isLeakSuppressed(); diff --git a/src/vld.cpp b/src/vld.cpp index 2324e717..f8d2c642 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2753,6 +2753,65 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) return g_vld.m_ignoreFunctions->find(functioninfo) != g_vld.m_ignoreFunctions->end(); } +// loadLeakSymbols - Makes dbghelp load the symbols of every module that appears +// in the call stack of an unreported leak, without holding g_heapMapLock. +// +// Leak counting and reporting resolve call stacks while holding +// g_heapMapLock, which every allocation takes. dbghelp loads a module's +// symbols on first use and that load can take the loader lock (a symbol +// server path loads symsrv, wininet and their dependencies). A thread in +// DLL_THREAD_ATTACH holds the loader lock and, when it allocates, waits for +// g_heapMapLock: a deadlock. Loading the symbols here first leaves only +// in-memory lookups for the locked pass. Modules first seen in leaks +// allocated after this runs are still loaded under the lock. +// +// - threadId (IN): Only leaks allocated by this thread, or all leaks if -1. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::loadLeakSymbols (DWORD threadId) +{ +#if defined(_M_ARM64) + // getFunctionName does not use dbghelp during the teardown report. + if (VldArm64InTeardownReport()) + return; +#endif + // One program counter per code page is enough to name every module. + Set pages; + { + CriticalSectionLocker<> cs(g_heapMapLock); + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + BlockMap* blockmap = &(*heapit).second->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + blockinfo_t* info = (*blockit).second; + if (info->reported || info->callStack == NULL) + continue; + if (threadId != ((DWORD)-1) && info->threadId != threadId) + continue; + for (UINT32 frame = 0; frame < info->callStack->size(); frame++) + pages.insert((*info->callStack)[frame] & ~(UINT_PTR)0xFFF); + } + } + } + + Set modules; + BYTE symbolBuffer[sizeof(SYMBOL_INFOW) + MAX_SYMBOL_NAME_SIZE] = { 0 }; + SYMBOL_INFOW* symbol = (SYMBOL_INFOW*)symbolBuffer; + for (Set::Iterator it = pages.begin(); it != pages.end(); ++it) { + HMODULE module = GetCallingModule(*it); + if (module == NULL || modules.find(module) != modules.end()) + continue; + modules.insert(module); + symbol->SizeOfStruct = sizeof(SYMBOL_INFOW); + symbol->MaxNameLen = MAX_SYMBOL_NAME_LENGTH; + DWORD64 displacement; + CriticalSectionLocker locker(g_DbgHelp); + g_DbgHelp.SymFromAddrW(g_currentProcess, *it, &displacement, symbol, locker); + } +} + SIZE_T VisualLeakDetector::GetLeaksCount() { if (m_options & VLD_OPT_VLDOFF) { @@ -2760,6 +2819,8 @@ SIZE_T VisualLeakDetector::GetLeaksCount() return 0; } + loadLeakSymbols(); + SIZE_T leaksCount = 0; // Generate a memory leak report for each heap in the process. CriticalSectionLocker<> cs(g_heapMapLock); @@ -2779,6 +2840,8 @@ SIZE_T VisualLeakDetector::GetThreadLeaksCount(DWORD threadId) return 0; } + loadLeakSymbols(threadId); + SIZE_T leaksCount = 0; // Generate a memory leak report for each heap in the process. CriticalSectionLocker<> cs(g_heapMapLock); @@ -2798,6 +2861,8 @@ SIZE_T VisualLeakDetector::ReportLeaks( ) return 0; } + loadLeakSymbols(); + // Generate a memory leak report for each heap in the process. SIZE_T leaksCount = 0; CriticalSectionLocker<> cs(g_heapMapLock); @@ -2819,6 +2884,8 @@ SIZE_T VisualLeakDetector::ReportThreadLeaks( DWORD threadId ) return 0; } + loadLeakSymbols(threadId); + // Generate a memory leak report for each heap in the process. SIZE_T leaksCount = 0; CriticalSectionLocker<> cs(g_heapMapLock); diff --git a/src/vldint.h b/src/vldint.h index f916bf48..9b6fe5ad 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -338,6 +338,7 @@ class VisualLeakDetector : public IMalloc static int getCrtBlockUse (LPCVOID block, bool ucrt); static size_t getCrtBlockSize(LPCVOID block, bool ucrt); SIZE_T getLeaksCount (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); + VOID loadLeakSymbols (DWORD threadId = (DWORD)-1); SIZE_T reportLeaks(heapinfo_t* heapinfo, bool &firstLeak, Set &aggregatedLeaks, DWORD threadId = (DWORD)-1); VOID markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); VOID unmapBlock (HANDLE heap, LPCVOID mem, const context_t &context); From ced7efcf1e8f52b15a727efc568c07219bda5b04 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 12:39:15 -0800 Subject: [PATCH 03/91] Re-check leak symbols under g_heapMapLock; skip them when not needed (review) The symbols are loaded without g_heapMapLock, so a leak allocated in between could bring a module whose symbols are still deferred. The four APIs now take g_heapMapLock through LeakSymbolsHeapMapLock, which checks under the lock (SymGetModuleInfoW64, no loading) that no module in the unreported leaks' call stacks is still deferred, and otherwise releases the lock, loads them and retries (up to 8 times). GetLeaksCount and GetThreadLeaksCount only resolve call stacks with SkipCrtStartupLeaks, so they no longer load symbols without it. The loads deliberately do not hold the loader lock either: tried, and heapmaplock_deadlock_test deadlocked again, because with the loader lock held LoadLibrary waits for a thread that is initializing and needs that lock. (ResolveCallstacks and GetAllocationResolveResults resolve under the loader lock and are exposed to the same deadlock; not changed here.) The test no longer insists that its thread reaches DLL_THREAD_ATTACH (VLD holding the loader lock would keep it out, which is not a deadlock), joins it from main instead of from the dbghelp callback, and its watchdog only writes static strings. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- .../heapmaplock_deadlock_test.cpp | 40 +++-- src/vld.cpp | 150 +++++++++++++----- src/vldint.h | 5 +- 3 files changed, 134 insertions(+), 61 deletions(-) diff --git a/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp index 87359331..933cdbd5 100644 --- a/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp +++ b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp @@ -9,10 +9,11 @@ // // This test makes that ordering deterministic. A dbghelp callback on the // deferred symbol load of the helper DLL starts a thread whose -// DLL_THREAD_ATTACH in the helper allocates, waits until that thread is inside -// thread attach (holding the loader lock), then calls LoadLibrary, standing in -// for symsrv. If VLD is inside g_heapMapLock at that point, neither thread can -// proceed; a watchdog reports the deadlock and terminates the process. +// DLL_THREAD_ATTACH in the helper allocates, gives that thread up to 2 s to +// get inside thread attach (holding the loader lock), then calls LoadLibrary, +// standing in for symsrv. If VLD is inside g_heapMapLock at that point, +// neither thread can proceed; a watchdog reports the deadlock and terminates +// the process. If VLD holds the loader lock instead, the thread simply waits. #include #include @@ -49,6 +50,7 @@ HANDLE g_done = NULL; volatile LONG g_callbackArmed = 0; volatile LONG g_callbackFired = 0; volatile LONG g_inLoadLibrary = 0; +HANDLE g_thread = NULL; void WriteStdout(const char* text) { @@ -60,14 +62,14 @@ DWORD WINAPI Watchdog(LPVOID) { if (WaitForSingleObject(g_done, WATCHDOG_MS) == WAIT_TIMEOUT) { - char state[256]; - sprintf_s(state, "main thread: in VLDGetLeaksCount -> dbghelp deferred symbol load -> LoadLibrary: %s\n" - "new thread: in helper DLL_THREAD_ATTACH (loader lock held) -> malloc -> VLD hook: %s\n", - InterlockedCompareExchange(&g_inLoadLibrary, 0, 0) ? "yes" : "no", - g_isInThreadAttachAlloc() ? "yes" : "no"); - WriteStdout(state); + WriteStdout(InterlockedCompareExchange(&g_inLoadLibrary, 0, 0) ? + "main thread: in VLDGetLeaksCount -> dbghelp deferred symbol load -> LoadLibrary: yes\n" : + "main thread: in VLDGetLeaksCount -> dbghelp deferred symbol load -> LoadLibrary: no\n"); + WriteStdout(g_isInThreadAttachAlloc() ? + "new thread: in helper DLL_THREAD_ATTACH (loader lock held) -> malloc -> VLD hook: yes\n" : + "new thread: in helper DLL_THREAD_ATTACH (loader lock held) -> malloc -> VLD hook: no\n"); // ExitProcess would need the loader lock, which is part of the deadlock. - WriteStdout("FAIL: DEADLOCK - VLD resolved symbols while holding g_heapMapLock\n"); + WriteStdout("FAIL: DEADLOCK in VLDGetLeaksCount while dbghelp loaded symbols\n"); TerminateProcess(GetCurrentProcess(), 3); } return 0; @@ -90,13 +92,16 @@ BOOL CALLBACK SymbolCallback(HANDLE, ULONG action, ULONG64 data, ULONG64) InterlockedExchange(&g_callbackFired, 1); // A thread that holds the loader lock (DLL_THREAD_ATTACH) and allocates. + // If VLD holds the loader lock here, the thread cannot enter thread attach + // until VLD is done, which is not a deadlock: wait only briefly. g_armThreadAttach(g_inThreadAttach); - HANDLE thread = CreateThread(NULL, 0, NewThread, NULL, 0, NULL); - if (thread == NULL || WaitForSingleObject(g_inThreadAttach, 10000) != WAIT_OBJECT_0) + g_thread = CreateThread(NULL, 0, NewThread, NULL, 0, NULL); + if (g_thread == NULL) { - WriteStdout("FAIL: helper DLL_THREAD_ATTACH did not run\n"); + WriteStdout("FAIL: CreateThread failed\n"); TerminateProcess(GetCurrentProcess(), 2); } + WaitForSingleObject(g_inThreadAttach, 2000); // What symsrv/wininet do while loading symbols: take the loader lock. InterlockedExchange(&g_inLoadLibrary, 1); @@ -104,8 +109,6 @@ BOOL CALLBACK SymbolCallback(HANDLE, ULONG action, ULONG64 data, ULONG64) InterlockedExchange(&g_inLoadLibrary, 0); if (version != NULL) FreeLibrary(version); - WaitForSingleObject(thread, INFINITE); - CloseHandle(thread); return FALSE; } } @@ -148,6 +151,11 @@ int main() InterlockedExchange(&g_callbackArmed, 1); SIZE_T leaks = VLDGetLeaksCount(); + if (g_thread != NULL) + { + WaitForSingleObject(g_thread, INFINITE); + CloseHandle(g_thread); + } SetEvent(g_done); WaitForSingleObject(watchdog, INFINITE); diff --git a/src/vld.cpp b/src/vld.cpp index f8d2c642..cd57163d 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2753,17 +2753,21 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) return g_vld.m_ignoreFunctions->find(functioninfo) != g_vld.m_ignoreFunctions->end(); } -// loadLeakSymbols - Makes dbghelp load the symbols of every module that appears -// in the call stack of an unreported leak, without holding g_heapMapLock. -// -// Leak counting and reporting resolve call stacks while holding -// g_heapMapLock, which every allocation takes. dbghelp loads a module's -// symbols on first use and that load can take the loader lock (a symbol -// server path loads symsrv, wininet and their dependencies). A thread in -// DLL_THREAD_ATTACH holds the loader lock and, when it allocates, waits for -// g_heapMapLock: a deadlock. Loading the symbols here first leaves only -// in-memory lookups for the locked pass. Modules first seen in leaks -// allocated after this runs are still loaded under the lock. +// Leak counting and reporting resolve call stacks while holding g_heapMapLock, +// which every allocation takes. dbghelp loads a module's symbols on first use +// and that load can need the loader (a symbol server path loads symsrv, +// wininet and their dependencies), while a thread in DLL_THREAD_ATTACH holds +// the loader lock and waits for g_heapMapLock when it allocates: a deadlock. +// So the symbols of every module in the unreported leaks' call stacks are +// loaded first, holding neither g_heapMapLock nor the loader lock (with the +// loader lock held, LoadLibrary waits for threads that are initializing and +// need that lock), and the locked pass only does in-memory lookups. + +// collectLeakPages - Collects the code pages of the unreported leaks' call +// stacks; one address per page is enough to name every module. Call with +// g_heapMapLock held. +// +// - pages (OUT): The code pages. // // - threadId (IN): Only leaks allocated by this thread, or all leaks if -1. // @@ -2771,31 +2775,60 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) // // None. // -VOID VisualLeakDetector::loadLeakSymbols (DWORD threadId) +VOID VisualLeakDetector::collectLeakPages (Set& pages, DWORD threadId) { -#if defined(_M_ARM64) - // getFunctionName does not use dbghelp during the teardown report. - if (VldArm64InTeardownReport()) - return; -#endif - // One program counter per code page is enough to name every module. - Set pages; - { - CriticalSectionLocker<> cs(g_heapMapLock); - for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { - BlockMap* blockmap = &(*heapit).second->blockMap; - for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { - blockinfo_t* info = (*blockit).second; - if (info->reported || info->callStack == NULL) - continue; - if (threadId != ((DWORD)-1) && info->threadId != threadId) - continue; - for (UINT32 frame = 0; frame < info->callStack->size(); frame++) - pages.insert((*info->callStack)[frame] & ~(UINT_PTR)0xFFF); - } + for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + BlockMap* blockmap = &(*heapit).second->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + blockinfo_t* info = (*blockit).second; + if (info->reported || info->callStack == NULL) + continue; + if (threadId != ((DWORD)-1) && info->threadId != threadId) + continue; + for (UINT32 frame = 0; frame < info->callStack->size(); frame++) + pages.insert((*info->callStack)[frame] & ~(UINT_PTR)0xFFF); } } +} + +// areModuleSymbolsLoaded - Checks, without loading anything, that dbghelp is +// done with the deferred symbol load of the module of every page. +// +// - pages (IN): Code pages from collectLeakPages. +// +// Return Value: +// +// TRUE if no module still has deferred symbols. +// +BOOL VisualLeakDetector::areModuleSymbolsLoaded (const Set& pages) +{ + Set modules; + for (Set::Iterator it = pages.begin(); it != pages.end(); ++it) { + HMODULE module = GetCallingModule(*it); + if (module == NULL || modules.find(module) != modules.end()) + continue; + modules.insert(module); + IMAGEHLP_MODULEW64 moduleInfo = { 0 }; + moduleInfo.SizeOfStruct = sizeof(moduleInfo); + CriticalSectionLocker locker(g_DbgHelp); + if (g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, (DWORD64)module, &moduleInfo, locker) && + moduleInfo.SymType == SymDeferred) + return FALSE; + } + return TRUE; +} +// loadModuleSymbols - Makes dbghelp load the symbols of the module of every +// page. Call without g_heapMapLock or the loader lock held. +// +// - pages (IN): Code pages from collectLeakPages. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::loadModuleSymbols (const Set& pages) +{ Set modules; BYTE symbolBuffer[sizeof(SYMBOL_INFOW) + MAX_SYMBOL_NAME_SIZE] = { 0 }; SYMBOL_INFOW* symbol = (SYMBOL_INFOW*)symbolBuffer; @@ -2812,6 +2845,43 @@ VOID VisualLeakDetector::loadLeakSymbols (DWORD threadId) } } +// Holds g_heapMapLock, entered only once the symbols of every module in the +// unreported leaks' call stacks are loaded. Leaks allocated while the symbols +// load can bring new modules, so the check repeats under the lock. +class LeakSymbolsHeapMapLock +{ +public: + LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1) + { +#if defined(_M_ARM64) + // getFunctionName does not use dbghelp during the teardown report. + if (VldArm64InTeardownReport()) + loadSymbols = false; +#endif + const int maxAttempts = 8; + for (int attempt = 1; ; attempt++) { + g_heapMapLock.Enter(); + if (!loadSymbols) + return; + Set pages; + vld.collectLeakPages(pages, threadId); + if (attempt == maxAttempts || VisualLeakDetector::areModuleSymbolsLoaded(pages)) + return; + g_heapMapLock.Leave(); + VisualLeakDetector::loadModuleSymbols(pages); + } + } + + ~LeakSymbolsHeapMapLock() + { + g_heapMapLock.Leave(); + } + +private: + LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); + LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); +}; + SIZE_T VisualLeakDetector::GetLeaksCount() { if (m_options & VLD_OPT_VLDOFF) { @@ -2819,11 +2889,9 @@ SIZE_T VisualLeakDetector::GetLeaksCount() return 0; } - loadLeakSymbols(); - SIZE_T leaksCount = 0; // Generate a memory leak report for each heap in the process. - CriticalSectionLocker<> cs(g_heapMapLock); + LeakSymbolsHeapMapLock cs(*this, (m_options & VLD_OPT_SKIP_CRTSTARTUP_LEAKS) != 0); for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { HANDLE heap = (*heapit).first; UNREFERENCED_PARAMETER(heap); @@ -2840,11 +2908,9 @@ SIZE_T VisualLeakDetector::GetThreadLeaksCount(DWORD threadId) return 0; } - loadLeakSymbols(threadId); - SIZE_T leaksCount = 0; // Generate a memory leak report for each heap in the process. - CriticalSectionLocker<> cs(g_heapMapLock); + LeakSymbolsHeapMapLock cs(*this, (m_options & VLD_OPT_SKIP_CRTSTARTUP_LEAKS) != 0, threadId); for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { HANDLE heap = (*heapit).first; UNREFERENCED_PARAMETER(heap); @@ -2861,11 +2927,9 @@ SIZE_T VisualLeakDetector::ReportLeaks( ) return 0; } - loadLeakSymbols(); - // Generate a memory leak report for each heap in the process. SIZE_T leaksCount = 0; - CriticalSectionLocker<> cs(g_heapMapLock); + LeakSymbolsHeapMapLock cs(*this, true); bool firstLeak = true; Set aggregatedLeaks; for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { @@ -2884,11 +2948,9 @@ SIZE_T VisualLeakDetector::ReportThreadLeaks( DWORD threadId ) return 0; } - loadLeakSymbols(threadId); - // Generate a memory leak report for each heap in the process. SIZE_T leaksCount = 0; - CriticalSectionLocker<> cs(g_heapMapLock); + LeakSymbolsHeapMapLock cs(*this, true, threadId); bool firstLeak = true; Set aggregatedLeaks; for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { diff --git a/src/vldint.h b/src/vldint.h index 9b6fe5ad..fbe0b0f8 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -338,7 +338,10 @@ class VisualLeakDetector : public IMalloc static int getCrtBlockUse (LPCVOID block, bool ucrt); static size_t getCrtBlockSize(LPCVOID block, bool ucrt); SIZE_T getLeaksCount (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); - VOID loadLeakSymbols (DWORD threadId = (DWORD)-1); + VOID collectLeakPages (Set& pages, DWORD threadId); + static BOOL areModuleSymbolsLoaded (const Set& pages); + static VOID loadModuleSymbols (const Set& pages); + friend class LeakSymbolsHeapMapLock; SIZE_T reportLeaks(heapinfo_t* heapinfo, bool &firstLeak, Set &aggregatedLeaks, DWORD threadId = (DWORD)-1); VOID markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); VOID unmapBlock (HANDLE heap, LPCVOID mem, const context_t &context); From 11b9fa9a552a946305cef7394f9ca310034fadda Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 12:52:24 -0800 Subject: [PATCH 04/91] Never load symbols under g_heapMapLock in leak queries (review) Two holes left by the check-and-retry: - after the last attempt the locked pass could still trigger a deferred load. Now, while a thread holds g_heapMapLock through LeakSymbolsHeapMapLock, getFunctionName and the line lookup skip a module whose symbols are still deferred (SymGetModuleInfoW64, no load) and show the frame as an address; the retry loop only makes that rare. - a second leak query could hold g_heapMapLock while waiting for g_DbgHelp held by a thread loading symbols, closing a cycle with a thread in DLL_THREAD_ATTACH. g_leakQueryLock now serializes the four leak queries before any other lock. Not changed: with StackWalkMethod = safe the allocation hook walks the stack under g_DbgHelp, so a thread in DLL_THREAD_ATTACH can still wait for a thread loading symbols, as before this series. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.cpp | 22 ++++++++++++++++++++-- src/vld.cpp | 27 +++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/src/callstack.cpp b/src/callstack.cpp index 39ff1bbe..11ea5479 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -50,6 +50,22 @@ extern DbgHelp g_DbgHelp; extern "C" bool VldArm64InTeardownReport(void); #endif +// Defined in vld.cpp. True on the thread that holds g_heapMapLock for leak +// counting or reporting, where a deferred symbol load could deadlock. +extern "C" bool VldSymbolLoadForbidden(void); + +// True when resolving programCounter would make dbghelp load deferred symbols +// on a thread where that is forbidden; the frame is then shown as an address. +static bool isSymbolLoadPending(SIZE_T programCounter, CriticalSectionLocker& locker) +{ + if (!VldSymbolLoadForbidden()) + return false; + IMAGEHLP_MODULEW64 moduleInfo = { 0 }; + moduleInfo.SizeOfStruct = sizeof(moduleInfo); + return g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, programCounter, &moduleInfo, locker) && + moduleInfo.SymType == SymDeferred; +} + // Helper function to compare the begin of a string with a substring // template @@ -233,7 +249,8 @@ LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement6 } #endif DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId()); - if (g_DbgHelp.SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo, locker)) { + if (!isSymbolLoadPending(programCounter, locker) && + g_DbgHelp.SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo, locker)) { functionName = functionInfo->Name; #if defined(_M_X64) // Without symbols dbghelp names ARM64EC code (x64 process on ARM64) @@ -489,7 +506,8 @@ int CallStack::resolve(BOOL showInternalFrames) #if defined(_M_ARM64) if (!VldArm64InTeardownReport()) #endif - foundline = g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo, locker); + if (!isSymbolLoadPending(programCounter, locker)) + foundline = g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo, locker); bool isFrameInternal = false; if (foundline && !showInternalFrames) { diff --git a/src/vld.cpp b/src/vld.cpp index cd57163d..d7572c97 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -52,6 +52,7 @@ HANDLE g_currentProcess; // Pseudo-handle for the current process. HANDLE g_currentThread; // Pseudo-handle for the current thread. HANDLE g_processHeap; // Handle to the process's heap (COM allocations come from here). CriticalSection g_heapMapLock; // Serializes access to the heap and block maps. +CriticalSection g_leakQueryLock; // Serializes leak counting and reporting (see LeakSymbolsHeapMapLock). ReportHookSet* g_pReportHooks; DbgHelp g_DbgHelp; ImageDirectoryEntries g_Ide; @@ -422,6 +423,7 @@ VisualLeakDetector::VisualLeakDetector () LoaderLock ll; g_heapMapLock.Initialize(); + g_leakQueryLock.Initialize(); g_vldHeap = HeapCreate(0x0, 0, 0); g_vldHeapLock.Initialize(); g_pReportHooks = new ReportHookSet; @@ -828,6 +830,7 @@ VisualLeakDetector::~VisualLeakDetector () m_modulesLock.Delete(); m_tlsLock.Delete(); g_heapMapLock.Delete(); + g_leakQueryLock.Delete(); g_vldHeapLock.Delete(); if (m_tlsIndex != TLS_OUT_OF_INDEXES) { @@ -2845,9 +2848,21 @@ VOID VisualLeakDetector::loadModuleSymbols (const Set& pages) } } -// Holds g_heapMapLock, entered only once the symbols of every module in the +// The thread that holds g_heapMapLock through LeakSymbolsHeapMapLock; dbghelp +// must not load symbols on it (see CallStack::isSymbolLoadPending). +static volatile LONG g_noSymbolLoadThreadId = 0; + +extern "C" bool VldSymbolLoadForbidden(void) +{ + return static_cast(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) == GetCurrentThreadId(); +} + +// Holds g_heapMapLock, entered once the symbols of every module in the // unreported leaks' call stacks are loaded. Leaks allocated while the symbols -// load can bring new modules, so the check repeats under the lock. +// load can bring new modules, so the check repeats under the lock; whatever is +// still deferred after that is not loaded under the lock but shown as an +// address. g_leakQueryLock keeps a second caller from holding g_heapMapLock +// while it waits for g_DbgHelp, which a loading thread holds. class LeakSymbolsHeapMapLock { public: @@ -2858,23 +2873,27 @@ class LeakSymbolsHeapMapLock if (VldArm64InTeardownReport()) loadSymbols = false; #endif + g_leakQueryLock.Enter(); const int maxAttempts = 8; for (int attempt = 1; ; attempt++) { g_heapMapLock.Enter(); if (!loadSymbols) - return; + break; Set pages; vld.collectLeakPages(pages, threadId); if (attempt == maxAttempts || VisualLeakDetector::areModuleSymbolsLoaded(pages)) - return; + break; g_heapMapLock.Leave(); VisualLeakDetector::loadModuleSymbols(pages); } + InterlockedExchange(&g_noSymbolLoadThreadId, static_cast(GetCurrentThreadId())); } ~LeakSymbolsHeapMapLock() { + InterlockedExchange(&g_noSymbolLoadThreadId, 0); g_heapMapLock.Leave(); + g_leakQueryLock.Leave(); } private: From d4127c35aa068ea811300f6f408140fa7bb41413 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 12:59:37 -0800 Subject: [PATCH 05/91] Leak queries nested under g_heapMapLock load nothing (review) A leak query from a thread that already owns g_heapMapLock (e.g. from a report hook while a report runs) took g_leakQueryLock after g_heapMapLock (lock order inversion), loaded symbols while the outer g_heapMapLock was still held, and cleared the outer query's no-load guard when it returned. Such a query now takes no lock and loads nothing; it only sets the guard and restores the previous guard value when it returns. The ownership check uses CRITICAL_SECTION::OwningThread (CriticalSection::IsOwnedByCurrentThread), because the existing IsLockedByCurrentThread is cleared by any nested Leave. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/criticalsection.h | 6 ++++++ src/vld.cpp | 48 ++++++++++++++++++++++++++----------------- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/src/criticalsection.h b/src/criticalsection.h index 983145ba..d92c1f33 100644 --- a/src/criticalsection.h +++ b/src/criticalsection.h @@ -37,6 +37,12 @@ class CriticalSection return m_ownerThreadId == GetCurrentThreadId(); } + // Unlike IsLockedByCurrentThread, stays true after a nested Leave. + bool IsOwnedByCurrentThread() + { + return (DWORD)(ULONG_PTR)m_critRegion.OwningThread == GetCurrentThreadId(); + } + // try enter the section bool TryEnter() { diff --git a/src/vld.cpp b/src/vld.cpp index d7572c97..6cfe0cb2 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2862,41 +2862,51 @@ extern "C" bool VldSymbolLoadForbidden(void) // load can bring new modules, so the check repeats under the lock; whatever is // still deferred after that is not loaded under the lock but shown as an // address. g_leakQueryLock keeps a second caller from holding g_heapMapLock -// while it waits for g_DbgHelp, which a loading thread holds. +// while it waits for g_DbgHelp, which a loading thread holds. A query from a +// thread that already owns g_heapMapLock (e.g. a report hook) loads nothing +// and takes no lock. class LeakSymbolsHeapMapLock { public: LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1) + : m_nested(g_heapMapLock.IsOwnedByCurrentThread()) + , m_previousNoSymbolLoadThreadId(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) { + if (!m_nested) { #if defined(_M_ARM64) - // getFunctionName does not use dbghelp during the teardown report. - if (VldArm64InTeardownReport()) - loadSymbols = false; + // getFunctionName does not use dbghelp during the teardown report. + if (VldArm64InTeardownReport()) + loadSymbols = false; #endif - g_leakQueryLock.Enter(); - const int maxAttempts = 8; - for (int attempt = 1; ; attempt++) { - g_heapMapLock.Enter(); - if (!loadSymbols) - break; - Set pages; - vld.collectLeakPages(pages, threadId); - if (attempt == maxAttempts || VisualLeakDetector::areModuleSymbolsLoaded(pages)) - break; - g_heapMapLock.Leave(); - VisualLeakDetector::loadModuleSymbols(pages); + g_leakQueryLock.Enter(); + const int maxAttempts = 8; + for (int attempt = 1; ; attempt++) { + g_heapMapLock.Enter(); + if (!loadSymbols) + break; + Set pages; + vld.collectLeakPages(pages, threadId); + if (attempt == maxAttempts || VisualLeakDetector::areModuleSymbolsLoaded(pages)) + break; + g_heapMapLock.Leave(); + VisualLeakDetector::loadModuleSymbols(pages); + } } InterlockedExchange(&g_noSymbolLoadThreadId, static_cast(GetCurrentThreadId())); } ~LeakSymbolsHeapMapLock() { - InterlockedExchange(&g_noSymbolLoadThreadId, 0); - g_heapMapLock.Leave(); - g_leakQueryLock.Leave(); + InterlockedExchange(&g_noSymbolLoadThreadId, m_previousNoSymbolLoadThreadId); + if (!m_nested) { + g_heapMapLock.Leave(); + g_leakQueryLock.Leave(); + } } private: + const bool m_nested; + const LONG m_previousNoSymbolLoadThreadId; LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); }; From 4df8a39588ad748c6593c124f184c5f0539cb1f9 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 13:07:00 -0800 Subject: [PATCH 06/91] Take the previous no-load guard value once g_heapMapLock is held (review) The constructor read the previous guard value before waiting for the locks, so a thread could later restore the ID of a query that had already finished and forbid symbol loading outside any leak query. The value now comes from the InterlockedExchange that sets the guard. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 6cfe0cb2..699b2ddc 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2870,7 +2870,6 @@ class LeakSymbolsHeapMapLock public: LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1) : m_nested(g_heapMapLock.IsOwnedByCurrentThread()) - , m_previousNoSymbolLoadThreadId(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) { if (!m_nested) { #if defined(_M_ARM64) @@ -2892,7 +2891,8 @@ class LeakSymbolsHeapMapLock VisualLeakDetector::loadModuleSymbols(pages); } } - InterlockedExchange(&g_noSymbolLoadThreadId, static_cast(GetCurrentThreadId())); + m_previousNoSymbolLoadThreadId = + InterlockedExchange(&g_noSymbolLoadThreadId, static_cast(GetCurrentThreadId())); } ~LeakSymbolsHeapMapLock() @@ -2906,7 +2906,7 @@ class LeakSymbolsHeapMapLock private: const bool m_nested; - const LONG m_previousNoSymbolLoadThreadId; + LONG m_previousNoSymbolLoadThreadId; LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); }; From b41ec97eaf0e956c5ca4eb7d64762d78d6d0a56d Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 20:52:29 -0800 Subject: [PATCH 07/91] Add chaos tests; HeapDestroy must not load symbols under g_heapMapLock New src/tests/chaos suite: stress and race tests that try to make VLD hang, crash or misreport. A shared watchdog turns hangs into failures; tests share one output directory, vld.ini and a helper DLL. chaos_heapdestroy_deadlock: VLD's HeapDestroy hook reports the heap's remaining blocks (reportHeapLeaks) while holding g_heapMapLock and resolved their call stacks there, the same symbol load under g_heapMapLock that deadlocks against a thread in DLL_THREAD_ATTACH (as fixed for the leak queries). It hung on x64 Debug and RelWithDebInfo. reportHeapLeaks now uses LeakSymbolsHeapMapLock, which loads the symbols first and only for that heap's blocks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 52 ++++++++ src/tests/chaos/chaos_common.h | 124 ++++++++++++++++++ .../chaos/chaos_heapdestroy_deadlock.cpp | 106 +++++++++++++++ src/tests/chaos/chaos_helper_dll.cpp | 90 +++++++++++++ src/tests/chaos/vld.ini | 15 +++ src/vld.cpp | 80 +++++------ src/vldint.h | 2 +- 7 files changed, 430 insertions(+), 39 deletions(-) create mode 100644 src/tests/chaos/chaos_common.h create mode 100644 src/tests/chaos/chaos_heapdestroy_deadlock.cpp create mode 100644 src/tests/chaos/chaos_helper_dll.cpp create mode 100644 src/tests/chaos/vld.ini diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index b5a269f4..ec72d3fd 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -887,3 +887,55 @@ if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/ignore_modules_getaddrinfo_test/ignore_mod COMMENT "Copying getaddrinfo_missing_free_test vld.ini, VLD DLL, and dbghelp.dll" ) endif() + +# ============================================================================ +# Chaos tests +# +# Stress and race tests that try to make VLD hang, crash or misreport. Each +# test prints "FAIL: ..." (a watchdog turns hangs into failures) and must exit +# with code 0 and no leaks in VLD's exit report. They share one output +# directory, vld.ini and the chaos_helper_dll helper. +# ============================================================================ +set(VLD_CHAOS_TESTS + chaos_heapdestroy_deadlock +) + +function(set_chaos_output_dir TARGET_NAME) + set_target_properties(${TARGET_NAME} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$/chaos" + RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin/Debug/chaos" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin/Release/chaos" + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/bin/RelWithDebInfo/chaos" + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/bin/MinSizeRel/chaos" + ) +endfunction() + +add_vld_test(chaos_helper_dll + IS_DLL + SOURCES chaos/chaos_helper_dll.cpp +) +set_chaos_output_dir(chaos_helper_dll) +add_custom_command(TARGET chaos_helper_dll POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_CURRENT_SOURCE_DIR}/chaos/vld.ini" + "$/vld.ini" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "$" + "$/$" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_SOURCE_DIR}/setup/dbghelp/${DBGHELP_ARCH}/dbghelp.dll" + "$/dbghelp.dll" + COMMENT "Copying chaos vld.ini, VLD DLL, and dbghelp.dll" +) + +foreach(CHAOS_TEST ${VLD_CHAOS_TESTS}) + add_vld_test(${CHAOS_TEST} + SOURCES chaos/${CHAOS_TEST}.cpp + HEADERS chaos/chaos_common.h + ) + add_dependencies(${CHAOS_TEST} chaos_helper_dll) + set_chaos_output_dir(${CHAOS_TEST}) + set_tests_properties(${CHAOS_TEST} PROPERTIES + TIMEOUT 30 + FAIL_REGULAR_EXPRESSION "FAIL:|Visual Leak Detector detected [0-9]+ memory leak") +endforeach() diff --git a/src/tests/chaos/chaos_common.h b/src/tests/chaos/chaos_common.h new file mode 100644 index 00000000..0ea915ac --- /dev/null +++ b/src/tests/chaos/chaos_common.h @@ -0,0 +1,124 @@ +// chaos_common.h - shared helpers for the VLD chaos tests. +// +// Every chaos test is a console program that ends with "CHAOS PASS" on +// success. A watchdog turns a hang into a failure: it prints the test's +// current phase and terminates the process with exit code 3, without running +// any exit code that could itself need a lock held by the hung threads. + +#pragma once + +#include +#include +#include + +namespace chaos +{ +inline HANDLE& WatchdogDone() +{ + static HANDLE done = NULL; + return done; +} + +inline volatile LONG& WatchdogMs() +{ + static volatile LONG ms = 0; + return ms; +} + +inline const char* volatile& Phase() +{ + static const char* volatile phase = "start"; + return phase; +} + +inline void Write(const char* text) +{ + DWORD written; + WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), text, (DWORD)strlen(text), &written, NULL); +} + +inline void SetPhase(const char* phase) +{ + Phase() = phase; +} + +// Prints "FAIL: " and terminates without running exit handlers. +inline void Fail(const char* message, UINT exitCode = 1) +{ + char line[512]; + _snprintf_s(line, _TRUNCATE, "FAIL: %s (phase: %s)\n", message, Phase()); + Write(line); + TerminateProcess(GetCurrentProcess(), exitCode); +} + +inline DWORD WINAPI WatchdogThread(LPVOID) +{ + if (WaitForSingleObject(WatchdogDone(), (DWORD)WatchdogMs()) == WAIT_TIMEOUT) + { + Fail("HANG detected by the watchdog", 3); + } + return 0; +} + +inline void StartWatchdog(DWORD ms) +{ + WatchdogMs() = (LONG)ms; + WatchdogDone() = CreateEventW(NULL, TRUE, FALSE, NULL); + HANDLE thread = CreateThread(NULL, 0, WatchdogThread, NULL, 0, NULL); + if (WatchdogDone() == NULL || thread == NULL) + { + Fail("could not start the watchdog", 2); + } + CloseHandle(thread); +} + +inline void StopWatchdog() +{ + SetEvent(WatchdogDone()); +} + +inline void Check(bool condition, const char* message) +{ + if (!condition) + { + Fail(message); + } +} + +// Small deterministic PRNG (xorshift32), one per thread. +struct Random +{ + unsigned int state; + explicit Random(unsigned int seed) : state(seed ? seed : 0x9E3779B9u) {} + unsigned int Next() + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; + } + unsigned int Below(unsigned int n) { return Next() % n; } +}; + +inline void RunThreads(int count, LPTHREAD_START_ROUTINE routine) +{ + HANDLE threads[64]; + Check(count <= 64, "too many threads"); + for (int i = 0; i < count; i++) + { + threads[i] = CreateThread(NULL, 0, routine, (LPVOID)(INT_PTR)i, 0, NULL); + Check(threads[i] != NULL, "CreateThread failed"); + } + WaitForMultipleObjects(count, threads, TRUE, INFINITE); + for (int i = 0; i < count; i++) + { + CloseHandle(threads[i]); + } +} + +inline void Pass() +{ + StopWatchdog(); + Write("CHAOS PASS\n"); +} +} diff --git a/src/tests/chaos/chaos_heapdestroy_deadlock.cpp b/src/tests/chaos/chaos_heapdestroy_deadlock.cpp new file mode 100644 index 00000000..d6644a13 --- /dev/null +++ b/src/tests/chaos/chaos_heapdestroy_deadlock.cpp @@ -0,0 +1,106 @@ +// chaos_heapdestroy_deadlock.cpp - HeapDestroy of a heap with live blocks must +// not resolve symbols while holding g_heapMapLock. +// +// VLD's HeapDestroy hook reports the heap's remaining blocks before the heap +// goes away. Same hazard as the leak queries: if dbghelp loads a module's +// symbols there (a symbol server load needs the loader lock) while VLD holds +// g_heapMapLock, a thread in DLL_THREAD_ATTACH that allocates waits for +// g_heapMapLock while holding the loader lock. A dbghelp callback on the +// helper DLL's deferred symbol load makes that ordering deterministic. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const ULONG CBA_DEFERRED_SYMBOL_LOAD_START = 0x00000001; +struct DeferredSymbolLoadW64 +{ + DWORD SizeOfStruct; + DWORD64 BaseOfImage; + DWORD CheckSum; + DWORD TimeDateStamp; + WCHAR FileName[MAX_PATH + 1]; +}; +typedef BOOL (CALLBACK* SymbolRegisteredCallback64)(HANDLE, ULONG, ULONG64, ULONG64); +typedef BOOL (WINAPI* SymRegisterCallbackW64_t)(HANDLE, SymbolRegisteredCallback64, ULONG64); +typedef void (*ArmThreadAttach_t)(HANDLE); +typedef void* (*HelperHeapAlloc_t)(HANDLE, size_t); + +ArmThreadAttach_t g_armThreadAttach = NULL; +HANDLE g_inThreadAttach = NULL; +HANDLE g_thread = NULL; +volatile LONG g_callbackArmed = 0; +volatile LONG g_callbackFired = 0; + +DWORD WINAPI NewThread(LPVOID) +{ + return 0; +} + +BOOL CALLBACK SymbolCallback(HANDLE, ULONG action, ULONG64 data, ULONG64) +{ + if (action != CBA_DEFERRED_SYMBOL_LOAD_START || data == 0) + { + return FALSE; + } + const DeferredSymbolLoadW64* load = (const DeferredSymbolLoadW64*)data; + if (wcsstr(load->FileName, L"chaos_helper_dll") == NULL || InterlockedExchange(&g_callbackArmed, 0) == 0) + { + return FALSE; + } + InterlockedExchange(&g_callbackFired, 1); + chaos::SetPhase("dbghelp deferred load of the helper: new thread in DLL_THREAD_ATTACH + LoadLibrary"); + g_armThreadAttach(g_inThreadAttach); + g_thread = CreateThread(NULL, 0, NewThread, NULL, 0, NULL); + chaos::Check(g_thread != NULL, "CreateThread failed"); + WaitForSingleObject(g_inThreadAttach, 2000); + HMODULE version = LoadLibraryW(L"version.dll"); + if (version != NULL) + { + FreeLibrary(version); + } + return FALSE; +} + +int __cdecl SwallowReport(int, wchar_t*, int*) +{ + return 1; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + g_inThreadAttach = CreateEventW(NULL, TRUE, FALSE, NULL); + + HMODULE helper = LoadLibraryW(L"chaos_helper_dll.dll"); + chaos::Check(helper != NULL, "LoadLibrary(chaos_helper_dll.dll) failed"); + g_armThreadAttach = (ArmThreadAttach_t)GetProcAddress(helper, "ArmThreadAttach"); + HelperHeapAlloc_t helperHeapAlloc = (HelperHeapAlloc_t)GetProcAddress(helper, "HelperHeapAlloc"); + HMODULE dbghelp = GetModuleHandleW(L"dbghelp.dll"); + SymRegisterCallbackW64_t symRegisterCallbackW64 = dbghelp == NULL ? NULL : + (SymRegisterCallbackW64_t)GetProcAddress(dbghelp, "SymRegisterCallbackW64"); + chaos::Check(g_armThreadAttach != NULL && helperHeapAlloc != NULL && symRegisterCallbackW64 != NULL && + symRegisterCallbackW64(GetCurrentProcess(), SymbolCallback, 0), "setup"); + + HANDLE heap = HeapCreate(0, 0, 0); + chaos::Check(heap != NULL, "HeapCreate failed"); + chaos::Check(helperHeapAlloc(heap, 64) != NULL, "HeapAlloc failed"); + + // The destroyed heap's block is reported by design; keep it out of stdout. + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowReport); + InterlockedExchange(&g_callbackArmed, 1); + chaos::SetPhase("HeapDestroy of a heap with a live block allocated from the helper"); + HeapDestroy(heap); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowReport); + if (g_thread != NULL) + { + WaitForSingleObject(g_thread, INFINITE); + CloseHandle(g_thread); + } + chaos::Check(InterlockedCompareExchange(&g_callbackFired, 0, 0) != 0, + "the helper's deferred symbol load never happened (inconclusive)"); + chaos::Pass(); + return 0; +} diff --git a/src/tests/chaos/chaos_helper_dll.cpp b/src/tests/chaos/chaos_helper_dll.cpp new file mode 100644 index 00000000..03be6f80 --- /dev/null +++ b/src/tests/chaos/chaos_helper_dll.cpp @@ -0,0 +1,90 @@ +// chaos_helper_dll.cpp - helper DLL shared by the VLD chaos tests. +// +// Links VLD so that its allocations are tracked. Exposes allocation entry +// points whose call stacks run through this DLL, and optional allocation +// activity in DLL_THREAD_ATTACH/DETACH (which run under the loader lock). + +#include +#include +#include "vld.h" + +static volatile LONG g_armed = 0; +static volatile LONG g_inThreadAttachAlloc = 0; +static HANDLE g_inThreadAttach = NULL; +static volatile LONG g_threadChurn = 0; +static DWORD g_tlsIndex = TLS_OUT_OF_INDEXES; + +#pragma optimize("", off) +extern "C" __declspec(dllexport) __declspec(noinline) void* HelperMalloc(size_t size) +{ + return malloc(size); +} + +extern "C" __declspec(dllexport) __declspec(noinline) void HelperFree(void* p) +{ + free(p); +} + +extern "C" __declspec(dllexport) __declspec(noinline) void* HelperHeapAlloc(HANDLE heap, size_t size) +{ + return HeapAlloc(heap, 0, size); +} +#pragma optimize("", on) + +// The next DLL_THREAD_ATTACH signals inThreadAttach, then allocates while the +// new thread holds the loader lock. +extern "C" __declspec(dllexport) void ArmThreadAttach(HANDLE inThreadAttach) +{ + g_inThreadAttach = inThreadAttach; + InterlockedExchange(&g_armed, 1); +} + +extern "C" __declspec(dllexport) LONG IsInThreadAttachAlloc() +{ + return InterlockedCompareExchange(&g_inThreadAttachAlloc, 0, 0); +} + +// While enabled, every thread allocates in DLL_THREAD_ATTACH and frees in +// DLL_THREAD_DETACH. +extern "C" __declspec(dllexport) void SetThreadChurn(LONG enabled) +{ + InterlockedExchange(&g_threadChurn, enabled); +} + +BOOL APIENTRY DllMain(HMODULE, DWORD reason, LPVOID) +{ + switch (reason) + { + case DLL_PROCESS_ATTACH: + g_tlsIndex = TlsAlloc(); + break; + case DLL_PROCESS_DETACH: + if (g_tlsIndex != TLS_OUT_OF_INDEXES) + { + TlsFree(g_tlsIndex); + } + break; + case DLL_THREAD_ATTACH: + if (InterlockedExchange(&g_armed, 0) != 0) + { + InterlockedExchange(&g_inThreadAttachAlloc, 1); + SetEvent(g_inThreadAttach); + void* p = malloc(16); + free(p); + InterlockedExchange(&g_inThreadAttachAlloc, 0); + } + if (InterlockedCompareExchange(&g_threadChurn, 0, 0) != 0 && g_tlsIndex != TLS_OUT_OF_INDEXES) + { + TlsSetValue(g_tlsIndex, malloc(48)); + } + break; + case DLL_THREAD_DETACH: + if (g_tlsIndex != TLS_OUT_OF_INDEXES) + { + free(TlsGetValue(g_tlsIndex)); + TlsSetValue(g_tlsIndex, NULL); + } + break; + } + return TRUE; +} diff --git a/src/tests/chaos/vld.ini b/src/tests/chaos/vld.ini new file mode 100644 index 00000000..47ad80dd --- /dev/null +++ b/src/tests/chaos/vld.ini @@ -0,0 +1,15 @@ +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Visual Leak Detector - Initialization/Configuration File (test config) +;; +;; Shared by the chaos tests. SkipCrtStartupLeaks makes leak queries and +;; heap-destroy reports resolve call stacks with dbghelp. +;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +[Options] +VLD = on +ReportTo = stdout +StackWalkMethod = fast +SkipCrtStartupLeaks = yes +AggregateDuplicates = no diff --git a/src/vld.cpp b/src/vld.cpp index 699b2ddc..0d806ffd 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1924,41 +1924,6 @@ SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) return memoryleaks; } -// reportleaks - Generates a memory leak report for the specified heap. -// -// - heap (IN): Handle to the heap for which to generate a memory leak -// report. -// -// Return Value: -// -// None. -// -SIZE_T VisualLeakDetector::reportHeapLeaks (HANDLE heap) -{ - assert(heap != NULL); - - // Find the heap's information (blockmap, etc). - CriticalSectionLocker<> cs(g_heapMapLock); - HeapMap::Iterator heapit = m_heapMap->find(heap); - if (heapit == m_heapMap->end()) { - // Nothing is allocated from this heap. No leaks. - return 0; - } - - Set aggregatedLeaks; - heapinfo_t* heapinfo = (*heapit).second; - // Generate a memory leak report for heap. - bool firstLeak = true; - SIZE_T leaks_count = reportLeaks(heapinfo, firstLeak, aggregatedLeaks); - - // Show a summary. - if (leaks_count != 0) { - Report(L"Visual Leak Detector detected %Iu memory leak%s in heap " ADDRESSFORMAT L"\n", - leaks_count, (leaks_count > 1) ? L"s" : L"", heap); - } - return leaks_count; -} - int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) { if (!ucrt) @@ -2774,13 +2739,17 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) // // - threadId (IN): Only leaks allocated by this thread, or all leaks if -1. // +// - heap (IN): Only leaks in this heap, or in all heaps if NULL. +// // Return Value: // // None. // -VOID VisualLeakDetector::collectLeakPages (Set& pages, DWORD threadId) +VOID VisualLeakDetector::collectLeakPages (Set& pages, DWORD threadId, HANDLE heap) { for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { + if (heap != NULL && (*heapit).first != heap) + continue; BlockMap* blockmap = &(*heapit).second->blockMap; for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { blockinfo_t* info = (*blockit).second; @@ -2868,7 +2837,7 @@ extern "C" bool VldSymbolLoadForbidden(void) class LeakSymbolsHeapMapLock { public: - LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1) + LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1, HANDLE heap = NULL) : m_nested(g_heapMapLock.IsOwnedByCurrentThread()) { if (!m_nested) { @@ -2884,7 +2853,7 @@ class LeakSymbolsHeapMapLock if (!loadSymbols) break; Set pages; - vld.collectLeakPages(pages, threadId); + vld.collectLeakPages(pages, threadId, heap); if (attempt == maxAttempts || VisualLeakDetector::areModuleSymbolsLoaded(pages)) break; g_heapMapLock.Leave(); @@ -2991,6 +2960,41 @@ SIZE_T VisualLeakDetector::ReportThreadLeaks( DWORD threadId ) return leaksCount; } +// reportleaks - Generates a memory leak report for the specified heap. +// +// - heap (IN): Handle to the heap for which to generate a memory leak +// report. +// +// Return Value: +// +// None. +// +SIZE_T VisualLeakDetector::reportHeapLeaks (HANDLE heap) +{ + assert(heap != NULL); + + // Find the heap's information (blockmap, etc). + LeakSymbolsHeapMapLock cs(*this, true, (DWORD)-1, heap); + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) { + // Nothing is allocated from this heap. No leaks. + return 0; + } + + Set aggregatedLeaks; + heapinfo_t* heapinfo = (*heapit).second; + // Generate a memory leak report for heap. + bool firstLeak = true; + SIZE_T leaks_count = reportLeaks(heapinfo, firstLeak, aggregatedLeaks); + + // Show a summary. + if (leaks_count != 0) { + Report(L"Visual Leak Detector detected %Iu memory leak%s in heap " ADDRESSFORMAT L"\n", + leaks_count, (leaks_count > 1) ? L"s" : L"", heap); + } + return leaks_count; +} + VOID VisualLeakDetector::MarkAllLeaksAsReported( ) { if (m_options & VLD_OPT_VLDOFF) { diff --git a/src/vldint.h b/src/vldint.h index fbe0b0f8..8a9b9798 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -338,7 +338,7 @@ class VisualLeakDetector : public IMalloc static int getCrtBlockUse (LPCVOID block, bool ucrt); static size_t getCrtBlockSize(LPCVOID block, bool ucrt); SIZE_T getLeaksCount (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); - VOID collectLeakPages (Set& pages, DWORD threadId); + VOID collectLeakPages (Set& pages, DWORD threadId, HANDLE heap = NULL); static BOOL areModuleSymbolsLoaded (const Set& pages); static VOID loadModuleSymbols (const Set& pages); friend class LeakSymbolsHeapMapLock; From d938f621d376ffd4ee3cb44af9d7821a743c396e Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 20:52:44 -0800 Subject: [PATCH 08/91] Report hooks: serialize the hook set and call hooks outside its lock CallReportHook walked g_pReportHooks without any lock while VLDSetReportHook changed it under m_optionsLock, so a leak report racing a hook install/remove could walk a set node being freed. The set now has its own lock (g_reportHooksLock); CallReportHook copies the hooks under it and calls them after releasing it, so a hook may itself install or remove hooks, and allocating in a hook cannot invert locks with g_heapMapLock. The destructor clears the set under the same lock. At most MAX_REPORT_HOOKS (64) hooks can be installed. chaos_report_hook_race installs and removes hooks on three threads while two threads print leak reports. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_report_hook_race.cpp | 98 ++++++++++++++++++++++ src/utility.cpp | 21 ++++- src/vld.cpp | 25 +++++- src/vldint.h | 1 + 5 files changed, 141 insertions(+), 5 deletions(-) create mode 100644 src/tests/chaos/chaos_report_hook_race.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index ec72d3fd..010b2902 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -898,6 +898,7 @@ endif() # ============================================================================ set(VLD_CHAOS_TESTS chaos_heapdestroy_deadlock + chaos_report_hook_race ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_report_hook_race.cpp b/src/tests/chaos/chaos_report_hook_race.cpp new file mode 100644 index 00000000..883fa5a0 --- /dev/null +++ b/src/tests/chaos/chaos_report_hook_race.cpp @@ -0,0 +1,98 @@ +// chaos_report_hook_race.cpp - report hooks installed and removed while other +// threads print leak reports. +// +// VLDSetReportHook changes the hook set under VLD's options lock; every +// printed report line walks that set. A leak report running concurrently with +// hook installs/removals must neither crash nor lose the permanent hook. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 3000; +volatile LONG g_stop = 0; +volatile LONG g_leakedLines = 0; + +template +int __cdecl Hook(int, wchar_t* message, int*) +{ + if (message != NULL && wcsstr(message, L"Leak Hash") != NULL) + { + InterlockedIncrement(&g_leakedLines); + } + return 1; +} + +int __cdecl PermanentHook(int, wchar_t* message, int*) +{ + if (message != NULL && wcsstr(message, L"Leak Hash") != NULL) + { + InterlockedIncrement(&g_leakedLines); + } + return 1; +} + +VLD_REPORT_HOOK const g_hooks[] = { Hook<0>, Hook<1>, Hook<2>, Hook<3>, Hook<4>, Hook<5>, Hook<6>, Hook<7> }; + +DWORD WINAPI Churn(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 7919u + 1); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + VLD_REPORT_HOOK hook = g_hooks[random.Below(_countof(g_hooks))]; + VLDSetReportHook(VLD_RPTHOOK_INSTALL, hook); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, hook); + } + return 0; +} + +DWORD WINAPI Reporter(LPVOID) +{ + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + VLDReportLeaks(); + } + return 0; +} + +DWORD WINAPI Worker(LPVOID p) +{ + INT_PTR index = (INT_PTR)p; + if (index < 3) + { + return Churn(p); + } + if (index < 5) + { + return Reporter(p); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + chaos::Check(VLDSetReportHook(VLD_RPTHOOK_INSTALL, PermanentHook) == 0, "install failed"); + void* leaks[4]; + for (int i = 0; i < 4; i++) + { + leaks[i] = malloc(32 + i); + } + + chaos::SetPhase("hook install/remove racing VLDReportLeaks"); + chaos::RunThreads(6, Worker); + + chaos::SetPhase("cleanup"); + for (int i = 0; i < 4; i++) + { + free(leaks[i]); + } + VLDSetReportHook(VLD_RPTHOOK_REMOVE, PermanentHook); + chaos::Check(InterlockedCompareExchange(&g_leakedLines, 0, 0) > 0, "no leak report reached the permanent hook"); + chaos::Pass(); + return 0; +} diff --git a/src/utility.cpp b/src/utility.cpp index 5680ac92..d3e6ddcc 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -33,6 +33,7 @@ // Imported Global Variables extern ReportHookSet* g_pReportHooks; +extern CriticalSection g_reportHooksLock; extern VisualLeakDetector g_vld; extern ImageDirectoryEntries g_Ide; #if defined(_M_ARM64) @@ -1193,11 +1194,27 @@ BOOL PatchModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tables int CallReportHook(int reportType, LPWSTR message, int* hook_retval) { + // Called outside the lock: other threads, or the hook itself, may install + // or remove hooks meanwhile. + VLD_REPORT_HOOK hooks[MAX_REPORT_HOOKS]; + size_t count = 0; + // Messages printed before VLD creates the hook set (and its lock) or after + // it is gone have no hooks. if (g_pReportHooks == NULL) return 0; - for (ReportHookSet::Iterator it = g_pReportHooks->begin(); it != g_pReportHooks->end(); ++it) { - int result = (*it)(reportType, message, hook_retval); + CriticalSectionLocker<> cs(g_reportHooksLock); + if (g_pReportHooks == NULL) + return 0; + for (ReportHookSet::Iterator it = g_pReportHooks->begin(); + it != g_pReportHooks->end() && count < MAX_REPORT_HOOKS; ++it) + { + hooks[count++] = *it; + } + } + for (size_t i = 0; i < count; i++) + { + int result = hooks[i](reportType, message, hook_retval); if (result) // handled return result; } diff --git a/src/vld.cpp b/src/vld.cpp index 0d806ffd..af0727ee 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -53,6 +53,7 @@ HANDLE g_currentThread; // Pseudo-handle for the current thread. HANDLE g_processHeap; // Handle to the process's heap (COM allocations come from here). CriticalSection g_heapMapLock; // Serializes access to the heap and block maps. CriticalSection g_leakQueryLock; // Serializes leak counting and reporting (see LeakSymbolsHeapMapLock). +CriticalSection g_reportHooksLock; // Serializes access to g_pReportHooks. ReportHookSet* g_pReportHooks; DbgHelp g_DbgHelp; ImageDirectoryEntries g_Ide; @@ -424,6 +425,7 @@ VisualLeakDetector::VisualLeakDetector () g_heapMapLock.Initialize(); g_leakQueryLock.Initialize(); + g_reportHooksLock.Initialize(); g_vldHeap = HeapCreate(0x0, 0, 0); g_vldHeapLock.Initialize(); g_pReportHooks = new ReportHookSet; @@ -812,8 +814,13 @@ VisualLeakDetector::~VisualLeakDetector () } Report(L"Visual Leak Detector is now exiting.\n"); - delete g_pReportHooks; - g_pReportHooks = NULL; + ReportHookSet* reportHooks; + { + CriticalSectionLocker<> cs(g_reportHooksLock); + reportHooks = g_pReportHooks; + g_pReportHooks = NULL; + } + delete reportHooks; checkInternalMemoryLeaks(); } @@ -831,6 +838,7 @@ VisualLeakDetector::~VisualLeakDetector () m_tlsLock.Delete(); g_heapMapLock.Delete(); g_leakQueryLock.Delete(); + g_reportHooksLock.Delete(); g_vldHeapLock.Delete(); if (m_tlsIndex != TLS_OUT_OF_INDEXES) { @@ -3280,9 +3288,20 @@ int VisualLeakDetector::SetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook) // VLD has been turned off. return -1; } - CriticalSectionLocker<> cs(m_optionsLock); + CriticalSectionLocker<> cs(g_reportHooksLock); + if (g_pReportHooks == NULL) { + return -1; + } if (mode == VLD_RPTHOOK_INSTALL) { + // CallReportHook copies the hooks into a fixed-size array. + size_t count = 0; + for (ReportHookSet::Iterator it = g_pReportHooks->begin(); it != g_pReportHooks->end(); ++it) { + count++; + } + if (count >= MAX_REPORT_HOOKS && g_pReportHooks->find(pfnNewHook) == g_pReportHooks->end()) { + return -1; + } ReportHookSet::Iterator it = g_pReportHooks->insert(pfnNewHook); return (it != g_pReportHooks->end()) ? 0 : -1; } diff --git a/src/vldint.h b/src/vldint.h index 8a9b9798..c433b857 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -161,6 +161,7 @@ struct moduleinfo_t { typedef Set ModuleSet; typedef Set ReportHookSet; +#define MAX_REPORT_HOOKS 64 struct functioninfo_t { BOOL operator < (const struct functioninfo_t& other) const { From 490ab6196f485f34c1f9b27f62fa7adae0db27b5 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 20:52:52 -0800 Subject: [PATCH 09/91] Format reports without the CRT's printf (debug CRT lock inversion) chaos_report_hook_race hung in Debug: a thread in VLDReportLeaks held g_heapMapLock and, in Report's _vsnwprintf_s, waited for the debug CRT heap lock (the debug CRT's free takes it even to free nothing), while an exiting thread's FLS cleanup in VLD's own static debug CRT held that lock and freed through VLD's HeapFree hook, which waited for g_heapMapLock. VLD's own CRT heap calls reach the hooks through kernel32's patched import slots. Report now formats with ntdll's _vsnwprintf, which uses neither the heap nor locks, and the memory dumps format bytes by hand. The one Report format using %zu, which ntdll does not support, uses %Iu. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/utility.cpp | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/src/utility.cpp b/src/utility.cpp index d3e6ddcc..cd32c7df 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -49,6 +49,16 @@ static encoding_e s_reportEncoding = ascii; // Output encoding of the memory #define IS_ORDINAL(name) (((UINT_PTR)name & 0xFFFF) == ((UINT_PTR)name)) +// Formats one dump byte as "XX " without the CRT's printf (see Report). +static void FormatHexByte(BYTE byte, WCHAR* out) +{ + static const WCHAR digits[] = L"0123456789ABCDEF"; + out[0] = digits[byte >> 4]; + out[1] = digits[byte & 0xF]; + out[2] = L' '; + out[3] = L'\0'; +} + #if defined(_M_ARM64) // On ARM64, kernel32's heap exports (HeapCreate/HeapAlloc/HeapReAlloc/HeapFree/ // HeapDestroy) are fast-forward dispatch thunks: their target slot is resolved @@ -130,8 +140,7 @@ VOID DumpMemoryA (LPCVOID address, SIZE_T size) SIZE_T ascIndex = wordIndex + wordIndex / 8; // 1 character per byte, plus a 1-character space after every 8 bytes. if (byteIndex < size) { BYTE byte = ((PBYTE)address)[byteIndex]; - _snwprintf_s(formatBuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte); - formatBuf[3] = '\0'; + FormatHexByte(byte, formatBuf); wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, formatBuf, 4); if (isgraph(byte)) { ascDump[ascIndex] = (WCHAR)byte; @@ -199,8 +208,7 @@ VOID DumpMemoryW (LPCVOID address, SIZE_T size) SIZE_T uniIndex = ((byteIndex / 2) % 8) + ((byteIndex / 2) % 8) / 8; // 1 character every other byte, plus a 1-character space after every 8 bytes. if (byteIndex < size) { BYTE byte = ((PBYTE)address)[byteIndex]; - _snwprintf_s(formatBuf, BYTEFORMATBUFFERLENGTH, _TRUNCATE, L"%.2X ", byte); - formatBuf[BYTEFORMATBUFFERLENGTH - 1] = '\0'; + FormatHexByte(byte, formatBuf); wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, formatBuf, 4); if (((byteIndex % 2) == 0) && ((byteIndex + 1) < dumpLen)) { // On every even byte, print one character. @@ -1018,7 +1026,7 @@ BOOL PatchImport (HMODULE importmodule, moduleentry_t *patchModule) { // we only process MAX_PATCH_ENTRY_COUNT, if we exceed it crash // if this abort is ever hit, it means that MAX_PATCH_ENTRY_COUNT should be bumped up - Report(L"MAX_PATCH_ENTRY_COUNT is set to %zu, but has been exceeded, MAX_PATCH_ENTRY_COUNT needs to be increased.\n", MAX_PATCH_ENTRY_COUNT); + Report(L"MAX_PATCH_ENTRY_COUNT is set to %Iu, but has been exceeded, MAX_PATCH_ENTRY_COUNT needs to be increased.\n", MAX_PATCH_ENTRY_COUNT); abort(); break; } @@ -1297,13 +1305,25 @@ VOID Print (LPWSTR messagew) // // None. // +// VLD formats report lines while holding g_heapMapLock. The CRT's printf frees +// a work buffer when done, and the debug CRT's free takes the CRT heap lock, +// which VLD's own CRT holds while its heap calls go through VLD's hooks (and +// so wait for g_heapMapLock). ntdll's formatter uses no heap and no locks. +typedef int (__cdecl *VsnwprintfFunc)(wchar_t*, size_t, const wchar_t*, va_list); +static const VsnwprintfFunc s_ntdllVsnwprintf = + (VsnwprintfFunc)GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "_vsnwprintf"); + VOID Report (LPCWSTR format, ...) { va_list args; WCHAR messagew [MAXREPORTLENGTH + 1]; va_start(args, format); - int result = _vsnwprintf_s(messagew, MAXREPORTLENGTH + 1, _TRUNCATE, format, args); + int result; + if (s_ntdllVsnwprintf != NULL) + result = s_ntdllVsnwprintf(messagew, MAXREPORTLENGTH, format, args); + else + result = _vsnwprintf_s(messagew, MAXREPORTLENGTH + 1, _TRUNCATE, format, args); va_end(args); messagew[MAXREPORTLENGTH] = L'\0'; From 933123951c8cd3ea9f360b837ba66eab3b92a2ef Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 20:55:55 -0800 Subject: [PATCH 10/91] Truncate over-long call stack lines inside the line buffer CallStack::resolveFunction took fmt::format_to_n's untruncated size as the line length, so a frame line longer than MAXREPORTLENGTH (long source path, module and function names) wrote its terminating NUL past the static stack_line buffer and lost its newline: the next frame was appended to the same report line, and the resolved length overcounted. The length is now what was written, and a truncated line ends with a newline. chaos_long_frame leaks from a function with a 252-character name in a DLL with a 138-character file name built from a 111-character source file name, and checks the report. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.cpp | 6 +- src/tests/CMakeLists.txt | 11 ++++ src/tests/chaos/chaos_long_frame.cpp | 55 +++++++++++++++++++ ..._source_file_name_source_file_name_end.cpp | 14 +++++ 4 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 src/tests/chaos/chaos_long_frame.cpp create mode 100644 src/tests/chaos/chaos_longname_dll_source_file_name_source_file_name_source_file_name_source_file_name_source_file_name_end.cpp diff --git a/src/callstack.cpp b/src/callstack.cpp index 11ea5479..290ac74e 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -323,7 +323,11 @@ DWORD CallStack::resolveFunction(SIZE_T programCounter, IMAGEHLP_LINEW64* source moduleName, functionName, displacement); } } - DWORD NumChars = static_cast(result.size); + // format_to_n returns the untruncated size. A truncated line still ends + // with a newline so that the next frame starts a line of its own. + DWORD NumChars = static_cast(result.out - stack_line); + if (result.size > NumChars && NumChars > 0) + stack_line[NumChars - 1] = L'\n'; stack_line[NumChars] = L'\0'; return NumChars; } diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 010b2902..4d4d4054 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -899,6 +899,7 @@ endif() set(VLD_CHAOS_TESTS chaos_heapdestroy_deadlock chaos_report_hook_race + chaos_long_frame ) function(set_chaos_output_dir TARGET_NAME) @@ -940,3 +941,13 @@ foreach(CHAOS_TEST ${VLD_CHAOS_TESTS}) TIMEOUT 30 FAIL_REGULAR_EXPRESSION "FAIL:|Visual Leak Detector detected [0-9]+ memory leak") endforeach() + +# A file name long enough that, with a long function name and source path, +# a leak report line exceeds MAXREPORTLENGTH. +add_vld_test(chaos_longname_dll + IS_DLL + SOURCES chaos/chaos_longname_dll_source_file_name_source_file_name_source_file_name_source_file_name_source_file_name_end.cpp +) +set_chaos_output_dir(chaos_longname_dll) +set_target_properties(chaos_longname_dll PROPERTIES OUTPUT_NAME "chaos_longname_012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789end") +add_dependencies(chaos_long_frame chaos_longname_dll) diff --git a/src/tests/chaos/chaos_long_frame.cpp b/src/tests/chaos/chaos_long_frame.cpp new file mode 100644 index 00000000..29fcf7cc --- /dev/null +++ b/src/tests/chaos/chaos_long_frame.cpp @@ -0,0 +1,55 @@ +// chaos_long_frame.cpp - a call stack frame longer than VLD's report line. +// +// The leak report line for a frame is " (): !()". +// With a long source path, module name and function name it exceeds +// MAXREPORTLENGTH. VLD must truncate it without writing past its line buffer +// and keep every following frame on its own line. + +#include "chaos_common.h" +#include +#include "vld.h" + +namespace +{ +typedef void* (*LongNameAlloc_t)(size_t); + +wchar_t g_report[64 * 1024]; +size_t g_reportLength = 0; + +int __cdecl CaptureReport(int, wchar_t* message, int*) +{ + size_t length = wcslen(message); + if (g_reportLength + length < _countof(g_report)) + { + wmemcpy(g_report + g_reportLength, message, length); + g_reportLength += length; + g_report[g_reportLength] = L'\0'; + } + return 1; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + HMODULE dll = LoadLibraryW(L"chaos_longname_012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789end.dll"); + chaos::Check(dll != NULL, "LoadLibrary of the long-named helper failed"); + LongNameAlloc_t alloc = (LongNameAlloc_t)GetProcAddress(dll, "LongName_abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijxyz"); + chaos::Check(alloc != NULL, "GetProcAddress failed"); + + void* leak = alloc(24); + chaos::SetPhase("leak report with an over-long frame line"); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, CaptureReport); + VLDReportLeaks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, CaptureReport); + free(leak); + + const wchar_t* longFrame = wcsstr(g_report, L"LongName_"); + chaos::Check(longFrame != NULL, "the long frame is missing from the report"); + const wchar_t* mainFrame = wcsstr(longFrame, L"chaos_long_frame.exe!main()"); + chaos::Check(mainFrame != NULL, "the main frame is missing from the report"); + const wchar_t* lineEnd = wcschr(longFrame, L'\n'); + chaos::Check(lineEnd != NULL && lineEnd < mainFrame, "the frame after the over-long line is not on its own line"); + chaos::Pass(); + return 0; +} \ No newline at end of file diff --git a/src/tests/chaos/chaos_longname_dll_source_file_name_source_file_name_source_file_name_source_file_name_source_file_name_end.cpp b/src/tests/chaos/chaos_longname_dll_source_file_name_source_file_name_source_file_name_source_file_name_source_file_name_end.cpp new file mode 100644 index 00000000..cb12a1e4 --- /dev/null +++ b/src/tests/chaos/chaos_longname_dll_source_file_name_source_file_name_source_file_name_source_file_name_source_file_name_end.cpp @@ -0,0 +1,14 @@ +// chaos_longname_dll_source_file_name_source_file_name_source_file_name_source_file_name_source_file_name_end.cpp - helper for chaos_long_frame: a DLL with a very long +// file name exporting a function with a very long name, so that the leak +// report line for its frame exceeds VLD's report line length. + +#include +#include +#include "vld.h" + +#pragma optimize("", off) +extern "C" __declspec(dllexport) __declspec(noinline) void* LongName_abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijxyz(size_t size) +{ + return malloc(size); +} +#pragma optimize("", on) \ No newline at end of file From e0619f6181bdf8797764a68d3b241fd203209237 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:11:26 -0800 Subject: [PATCH 11/91] chaos tests - report failures without the CRT Fail() formatted with _snprintf_s; a test whose hung thread holds a CRT lock made the watchdog hang too, so the hang was reported as a CTest timeout. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_common.h | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/tests/chaos/chaos_common.h b/src/tests/chaos/chaos_common.h index 0ea915ac..806b01fe 100644 --- a/src/tests/chaos/chaos_common.h +++ b/src/tests/chaos/chaos_common.h @@ -42,12 +42,15 @@ inline void SetPhase(const char* phase) Phase() = phase; } -// Prints "FAIL: " and terminates without running exit handlers. +// Prints "FAIL: " and terminates without running exit handlers. Uses +// no CRT, whose locks the hung or crashed threads may hold. inline void Fail(const char* message, UINT exitCode = 1) { - char line[512]; - _snprintf_s(line, _TRUNCATE, "FAIL: %s (phase: %s)\n", message, Phase()); - Write(line); + Write("FAIL: "); + Write(message); + Write(" (phase: "); + Write(Phase()); + Write(")\n"); TerminateProcess(GetCurrentProcess(), exitCode); } From 3e4bd1b33da25fdeaf0d910ab6fa8a308fdd7e7a Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:11:43 -0800 Subject: [PATCH 12/91] Defer block map changes made by report hooks during a leak walk Report hooks run on the reporting thread with g_heapMapLock held, in the middle of a walk over a heap's block map. A hook that freed a tracked block erased a map entry (Tree::erase moves the successor's contents, invalidating the walk) and deleted the blockinfo_t under it: chaos_hook_reenter crashed with _purecall in reportLeaks in RelWithDebInfo every run. LeakSymbolsHeapMapLock now marks a block walk. While the walking thread frees, reallocates in place, maps over an address or destroys a heap, the entry is marked reported and its erasure, the old call stack or the heap unmap is deferred to the end of the outermost walk. reportLeaks reads the CRT request id and the data to dump before its first Report call, since the hook can free the block being reported (Debug hit the CRT block size assert reading the freed header). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_hook_reenter.cpp | 71 +++++++++++++++ src/vld.cpp | 119 +++++++++++++++++++++++-- src/vldint.h | 19 ++++ 4 files changed, 201 insertions(+), 9 deletions(-) create mode 100644 src/tests/chaos/chaos_hook_reenter.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 4d4d4054..8a35c243 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -900,6 +900,7 @@ set(VLD_CHAOS_TESTS chaos_heapdestroy_deadlock chaos_report_hook_race chaos_long_frame + chaos_hook_reenter ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_hook_reenter.cpp b/src/tests/chaos/chaos_hook_reenter.cpp new file mode 100644 index 00000000..a1d98522 --- /dev/null +++ b/src/tests/chaos/chaos_hook_reenter.cpp @@ -0,0 +1,71 @@ +// chaos_hook_reenter.cpp - a report hook that allocates, frees and queries VLD +// while VLD is walking its block maps to print the report. +// +// Report hooks run on the reporting thread with g_heapMapLock held, in the +// middle of the walk over a heap's blocks. A hook that formats a string +// allocates and frees (inserting into and erasing from the map being +// walked); one that frees a tracked block erases another entry. Neither may +// crash VLD or corrupt its counts. + +#include "chaos_common.h" +#include +#include "vld.h" + +namespace +{ +void* volatile g_other = NULL; +volatile LONG g_inHook = 0; +volatile LONG g_calls = 0; + +int __cdecl ReenterHook(int, wchar_t* message, int*) +{ + if (InterlockedExchange(&g_inHook, 1) != 0) + { + return 1; + } + InterlockedIncrement(&g_calls); + std::wstring copy(message); + copy += L" (seen by the hook)"; + void* scratch = malloc(copy.size() * sizeof(wchar_t)); + free(scratch); + void* other = InterlockedExchangePointer((PVOID volatile*)&g_other, NULL); + if (other != NULL) + { + free(other); + VLDGetLeaksCount(); + } + InterlockedExchange(&g_inHook, 0); + return 1; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + SIZE_T base = VLDGetLeaksCount(); + + void* keep[16]; + for (int i = 0; i < 16; i++) + { + keep[i] = malloc(40 + i); + } + g_other = malloc(77); + + chaos::SetPhase("leak report with an allocating, freeing, querying hook"); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, ReenterHook); + VLDReportLeaks(); + VLDReportLeaks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, ReenterHook); + chaos::Check(InterlockedCompareExchange(&g_calls, 0, 0) > 0, "the hook never ran"); + chaos::Check(g_other == NULL, "the hook did not free the extra block"); + + chaos::SetPhase("counting after the reports"); + chaos::Check(VLDGetLeaksCount() == base + 16, "wrong leak count after the hook freed a block"); + for (int i = 0; i < 16; i++) + { + free(keep[i]); + } + chaos::Check(VLDGetLeaksCount() == base, "leaks left after freeing everything"); + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index af0727ee..ee217a7c 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -433,6 +433,11 @@ VisualLeakDetector::VisualLeakDetector () // Initialize remaining private data. m_heapMap = new HeapMap; m_heapMap->reserve(HEAP_MAP_RESERVE); + m_blockWalkDepth = 0; + m_blockWalkThreadId = 0; + m_deferredBlocks = new DeferredBlockSet; + m_deferredCallStacks = new DeferredCallStackSet; + m_deferredHeaps = new DeferredHeapSet; m_iMalloc = NULL; m_requestCurr = 1; m_totalAlloc = 0; @@ -796,6 +801,9 @@ VisualLeakDetector::~VisualLeakDetector () delete blockmap; } delete m_heapMap; + delete m_deferredBlocks; + delete m_deferredCallStacks; + delete m_deferredHeaps; } delete m_loadedModules; delete m_ignoreFunctions; @@ -827,6 +835,9 @@ VisualLeakDetector::~VisualLeakDetector () else { // VLD failed to load properly. delete m_heapMap; + delete m_deferredBlocks; + delete m_deferredCallStacks; + delete m_deferredHeaps; delete m_tlsMap; delete g_pReportHooks; g_pReportHooks = NULL; @@ -1552,6 +1563,15 @@ VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool d blockinfo_t* info = (*blockit).second; m_curAlloc -= info->size; Report(L"VLD: New allocation at already allocated address: 0x%p with size: %u and new size: %u\n", mem, info->size, size); + if (isBlockWalkThread()) { + // Replace the entry's information in place; endBlockWalk deletes + // the old information. + info->reported = true; + deferredblock_t deferred = { heap, mem, info }; + m_deferredBlocks->insert(deferred); + const_cast&>(*blockit).second = blockinfo; + return; + } delete info; blockmap->erase(blockit); blockmap->insert(mem, blockinfo); @@ -1659,6 +1679,13 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & // Free the blockinfo_t structure and erase it from the block map. blockinfo_t *info = (*blockit).second; m_curAlloc -= info->size; + if (isBlockWalkThread()) { + // The walk skips it; endBlockWalk erases it. + info->reported = true; + deferredblock_t deferred = { heap, mem, info }; + m_deferredBlocks->insert(deferred); + return; + } delete info; blockmap->erase(blockit); } @@ -1687,6 +1714,14 @@ VOID VisualLeakDetector::unmapHeap (HANDLE heap) // Free all of the blockinfo_t structures stored in the block map. heapinfo_t *heapinfo = (*heapit).second; BlockMap *blockmap = &heapinfo->blockMap; + if (isBlockWalkThread()) { + // The walk skips its blocks; endBlockWalk unmaps the heap. + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + (*blockit).second->reported = true; + } + m_deferredHeaps->insert(heap); + return; + } for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { m_curAlloc -= (*blockit).second->size; delete (*blockit).second; @@ -1762,7 +1797,10 @@ VOID VisualLeakDetector::remapBlock (HANDLE heap, LPCVOID mem, LPCVOID newmem, S blockinfo_t* info = (*blockit).second; if (info->callStack) { - info->callStack.reset(); + if (isBlockWalkThread()) + m_deferredCallStacks->insert(info->callStack.release()); + else + info->callStack.reset(); } if (m_totalAlloc < SIZE_MAX) @@ -2013,6 +2051,19 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S } } + // A report hook may free the block, so read it before the first Report. +#ifdef _DEBUG + SIZE_T crtRequest = 0; + if (info->debugCrtAlloc) + crtRequest = ((crtdbgblockheader_t*)block)->request; +#endif + SIZE_T dumpSize = (m_maxDataDump < size) ? m_maxDataDump : size; + LPBYTE dumpData = NULL; + if (dumpSize != 0) { + dumpData = new BYTE[dumpSize]; + memcpy(dumpData, address, dumpSize); + } + // It looks like a real memory leak. if (firstLeak) { // A confusing way to only display this message once Report(L"WARNING: Visual Leak Detector detected memory leaks!\n"); @@ -2022,11 +2073,7 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", info->serialNumber, address, size); #ifdef _DEBUG if (info->debugCrtAlloc) - { - crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; - Report(L" CRT Alloc ID: %Iu\n", crtheader->request); - assert(size == getCrtBlockSize(block, info->ucrt)); - } + Report(L" CRT Alloc ID: %Iu\n", crtRequest); #endif assert(info->callStack); if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { @@ -2057,12 +2104,13 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S if (m_maxDataDump != 0) { Report(L" Data:\n"); if (m_options & VLD_OPT_UNICODE_REPORT) { - DumpMemoryW(address, (m_maxDataDump < size) ? m_maxDataDump : size); + DumpMemoryW(dumpData, dumpSize); } else { - DumpMemoryA(address, (m_maxDataDump < size) ? m_maxDataDump : size); + DumpMemoryA(dumpData, dumpSize); } } + delete [] dumpData; Report(L"\n\n"); } @@ -2832,6 +2880,56 @@ static volatile LONG g_noSymbolLoadThreadId = 0; extern "C" bool VldSymbolLoadForbidden(void) { return static_cast(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) == GetCurrentThreadId(); +// While a thread walks the heap and block maps under g_heapMapLock, code it +// runs can free or reallocate tracked blocks or destroy heaps on the same +// thread: report hooks and dbghelp callbacks. Erasing map entries would break +// the walk (Tree::erase moves the successor's contents) and deleting a block's +// information would pull it from under the walk, so such changes are deferred +// to the end of the outermost walk. Call with g_heapMapLock held. +VOID VisualLeakDetector::beginBlockWalk () +{ + if (m_blockWalkDepth++ == 0) + m_blockWalkThreadId = GetCurrentThreadId(); +} + +bool VisualLeakDetector::isBlockWalkThread () const +{ + return m_blockWalkDepth != 0 && m_blockWalkThreadId == GetCurrentThreadId(); +} + +VOID VisualLeakDetector::endBlockWalk () +{ + if (--m_blockWalkDepth != 0) + return; + m_blockWalkThreadId = 0; + + while (m_deferredBlocks->begin() != m_deferredBlocks->end()) { + DeferredBlockSet::Iterator it = m_deferredBlocks->begin(); + deferredblock_t deferred = *it; + m_deferredBlocks->erase(it); + HeapMap::Iterator heapit = m_heapMap->find(deferred.heap); + if (heapit != m_heapMap->end()) { + BlockMap* blockmap = &(*heapit).second->blockMap; + BlockMap::Iterator blockit = blockmap->find(deferred.block); + if (blockit != blockmap->end() && (*blockit).second == deferred.info) + blockmap->erase(blockit); + } + delete deferred.info; + } + while (m_deferredCallStacks->begin() != m_deferredCallStacks->end()) { + DeferredCallStackSet::Iterator it = m_deferredCallStacks->begin(); + CallStack* callStack = *it; + m_deferredCallStacks->erase(it); + delete callStack; + } + while (m_deferredHeaps->begin() != m_deferredHeaps->end()) { + DeferredHeapSet::Iterator it = m_deferredHeaps->begin(); + HANDLE heap = *it; + m_deferredHeaps->erase(it); + unmapHeap(heap); + } +} + } // Holds g_heapMapLock, entered once the symbols of every module in the @@ -2846,7 +2944,7 @@ class LeakSymbolsHeapMapLock { public: LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1, HANDLE heap = NULL) - : m_nested(g_heapMapLock.IsOwnedByCurrentThread()) + : m_vld(vld), m_nested(g_heapMapLock.IsOwnedByCurrentThread()) { if (!m_nested) { #if defined(_M_ARM64) @@ -2873,10 +2971,12 @@ class LeakSymbolsHeapMapLock } ~LeakSymbolsHeapMapLock() + m_vld.beginBlockWalk(); { InterlockedExchange(&g_noSymbolLoadThreadId, m_previousNoSymbolLoadThreadId); if (!m_nested) { g_heapMapLock.Leave(); + m_vld.endBlockWalk(); g_leakQueryLock.Leave(); } } @@ -2885,6 +2985,7 @@ class LeakSymbolsHeapMapLock const bool m_nested; LONG m_previousNoSymbolLoadThreadId; LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); + VisualLeakDetector& m_vld; LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); }; diff --git a/src/vldint.h b/src/vldint.h index c433b857..1c9d8f8a 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -131,6 +131,17 @@ struct heapinfo_t { // HeapMaps map heaps (via their handles) to BlockMaps. typedef Map HeapMap; + +// A block freed while its thread walks the block maps (see beginBlockWalk). +struct deferredblock_t { + BOOL operator < (const struct deferredblock_t& other) const { return info < other.info; } + HANDLE heap; + LPCVOID block; + blockinfo_t* info; +}; +typedef Set DeferredBlockSet; +typedef Set DeferredCallStackSet; +typedef Set DeferredHeapSet; typedef std::basic_string, vldallocator > vldstring; // This structure stores information, primarily the virtual address range, about @@ -347,6 +358,9 @@ class VisualLeakDetector : public IMalloc VOID markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); VOID unmapBlock (HANDLE heap, LPCVOID mem, const context_t &context); VOID unmapHeap (HANDLE heap); + VOID beginBlockWalk (); + VOID endBlockWalk (); + bool isBlockWalkThread () const; int resolveStacks(heapinfo_t* heapinfo); // Static functions (callbacks) @@ -398,6 +412,11 @@ class VisualLeakDetector : public IMalloc WCHAR m_ignoreModuleList [MAXIGNOREMODULELISTLENGTH]; // List of modules to be excluded from leak detection. WCHAR m_ignoreFunctionsList [MAXIGNOREFUNCTIONLISTLENGTH]; // List of functions to be ignored in leak detection. HeapMap *m_heapMap; // Map of all active heaps in the process. + UINT32 m_blockWalkDepth; // Nesting of block map walks on m_blockWalkThreadId (see beginBlockWalk). + DWORD m_blockWalkThreadId; // Thread walking the block maps, while m_blockWalkDepth > 0. + DeferredBlockSet *m_deferredBlocks; // Blocks freed during the walk. + DeferredCallStackSet *m_deferredCallStacks; // Call stacks replaced during the walk. + DeferredHeapSet *m_deferredHeaps; // Heaps destroyed during the walk. IMalloc *m_iMalloc; // Pointer to the system implementation of IMalloc. SIZE_T m_requestCurr; // Current request number. From 51a06b728aca1f590dbcc7cc0d6ea5941c1a6dd0 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:12:52 -0800 Subject: [PATCH 13/91] Fix lines misplaced by the block walk deferral commit The previous commit was staged from zero-context hunks, which put beginBlockWalk, endBlockWalk, the m_vld member and VldSymbolLoadForbidden's opening lines at the wrong places, so it did not build. Move them where they belong. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index ee217a7c..4f4e91b8 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2877,9 +2877,6 @@ VOID VisualLeakDetector::loadModuleSymbols (const Set& pages) // must not load symbols on it (see CallStack::isSymbolLoadPending). static volatile LONG g_noSymbolLoadThreadId = 0; -extern "C" bool VldSymbolLoadForbidden(void) -{ - return static_cast(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) == GetCurrentThreadId(); // While a thread walks the heap and block maps under g_heapMapLock, code it // runs can free or reallocate tracked blocks or destroy heaps on the same // thread: report hooks and dbghelp callbacks. Erasing map entries would break @@ -2930,6 +2927,9 @@ VOID VisualLeakDetector::endBlockWalk () } } +extern "C" bool VldSymbolLoadForbidden(void) +{ + return static_cast(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) == GetCurrentThreadId(); } // Holds g_heapMapLock, entered once the symbols of every module in the @@ -2968,24 +2968,24 @@ class LeakSymbolsHeapMapLock } m_previousNoSymbolLoadThreadId = InterlockedExchange(&g_noSymbolLoadThreadId, static_cast(GetCurrentThreadId())); + m_vld.beginBlockWalk(); } ~LeakSymbolsHeapMapLock() - m_vld.beginBlockWalk(); { + m_vld.endBlockWalk(); InterlockedExchange(&g_noSymbolLoadThreadId, m_previousNoSymbolLoadThreadId); if (!m_nested) { g_heapMapLock.Leave(); - m_vld.endBlockWalk(); g_leakQueryLock.Leave(); } } private: + VisualLeakDetector& m_vld; const bool m_nested; LONG m_previousNoSymbolLoadThreadId; LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); - VisualLeakDetector& m_vld; LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); }; From 63e425f1dbcf18cdd9f9bd8e9d21b954496a784b Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:13:02 -0800 Subject: [PATCH 14/91] Load symbols before g_heapMapLock in ResolveCallstacks VLDResolveCallstacks and VLDGetAllocationResolveResults took the loader lock and g_heapMapLock and then resolved symbols, so dbghelp could call LoadLibrary with g_heapMapLock held. That waits for the loader's load owner, and an exiting thread that owns the loader frees FLS data into unmapBlock, which waits for g_heapMapLock: chaos_api_storm hung in Debug. Both now use LeakSymbolsHeapMapLock like the leak report: symbols are loaded before g_heapMapLock is taken and never under it, and the loader lock is not taken. A frame whose symbols are still pending is shown as an address, so GetAllocationResolveResults no longer asserts that everything resolved. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 4f4e91b8..97be4d65 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -3491,18 +3491,14 @@ blockinfo_t* VisualLeakDetector::getAllocationBlockInfo(void* alloc) const wchar_t* VisualLeakDetector::GetAllocationResolveResults(void* alloc, BOOL showInternalFrames) { - LoaderLock ll; - if (m_options & VLD_OPT_VLDOFF) return NULL; - CriticalSectionLocker<> cs(g_heapMapLock); + LeakSymbolsHeapMapLock cs(*this, true); blockinfo_t* info = getAllocationBlockInfo(alloc); if (info != NULL) { - int unresolvedFunctionsCount = info->callStack->resolve(showInternalFrames); - _ASSERT(unresolvedFunctionsCount == 0); - (void)unresolvedFunctionsCount; // Used only in debug assert + info->callStack->resolve(showInternalFrames); return info->callStack->getResolvedCallstack(showInternalFrames); } return NULL; @@ -3564,14 +3560,12 @@ int VisualLeakDetector::resolveStacks(heapinfo_t* heapinfo) int VisualLeakDetector::ResolveCallstacks() { - LoaderLock ll; - if (m_options & VLD_OPT_VLDOFF) return 0; int unresolvedFunctionsCount = 0; // Generate the Callstacks early - CriticalSectionLocker<> cs(g_heapMapLock); + LeakSymbolsHeapMapLock cs(*this, true); for (HeapMap::Iterator heapiter = m_heapMap->begin(); heapiter != m_heapMap->end(); ++heapiter) { HANDLE heap = (*heapiter).first; From edbe5f496cb9bda93bb7078682197e6b552546b9 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:13:10 -0800 Subject: [PATCH 15/91] Take g_DbgHelp before the loader lock in RefreshModules RefreshModules held the loader lock while attachToLoadedModules waited for g_DbgHelp. A thread loading symbols holds g_DbgHelp while dbghelp calls LoadLibrary, which waits for the loader's load owner; a starting thread that owned the loader waited for the loader lock. chaos_api_storm hung on that cycle once ResolveCallstacks stopped holding g_heapMapLock. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 97be4d65..d059460a 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2478,11 +2478,14 @@ NTSTATUS VisualLeakDetector::_LdrUnloadDll(IN PVOID BaseAddress) VOID VisualLeakDetector::RefreshModules() { - LoaderLock ll; - if (m_options & VLD_OPT_VLDOFF) return; + // g_DbgHelp before the loader lock: a thread holding g_DbgHelp can be + // loading a DLL for dbghelp, waiting for the thread that owns the loader. + CriticalSectionLocker dbgLocker(g_DbgHelp); + LoaderLock ll; + ModuleSet* newmodules = new ModuleSet(); newmodules->reserve(MODULE_SET_RESERVE); { From 15e1f7628283fdc90791dbfc0592278a231f4655 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:13:19 -0800 Subject: [PATCH 16/91] Forget the old address of a block reallocated while VLD is off A realloc made while VLD is disabled, or from an excluded module, did not update the block map. When the block moved, its old address stayed mapped although the heap had freed it; the next allocation there printed "New allocation at already allocated address" and replaced it. Unmap the old address when the block moves. chaos_api_storm toggles every control API (Disable/Enable/Restore, GlobalDisable/Enable, SetOptions, counts, ResolveCallstacks, RefreshModules) while threads allocate, reallocate and free, then checks that tracking is still exact. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_api_storm.cpp | 125 ++++++++++++++++++++++++++++ src/vld.cpp | 5 ++ src/vld_hooks.cpp | 22 ++++- 4 files changed, 151 insertions(+), 2 deletions(-) create mode 100644 src/tests/chaos/chaos_api_storm.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 8a35c243..fea7c05a 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -901,6 +901,7 @@ set(VLD_CHAOS_TESTS chaos_report_hook_race chaos_long_frame chaos_hook_reenter + chaos_api_storm ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_api_storm.cpp b/src/tests/chaos/chaos_api_storm.cpp new file mode 100644 index 00000000..55f525f6 --- /dev/null +++ b/src/tests/chaos/chaos_api_storm.cpp @@ -0,0 +1,125 @@ +// chaos_api_storm.cpp - every VLD control API at once, concurrently with +// allocation traffic. +// +// Threads toggle VLDDisable/VLDEnable/VLDRestore, VLDGlobalDisable/Enable, +// change options, mark leaks as reported, count and resolve call stacks +// while others allocate, reallocate and free. Afterwards VLD must still +// track allocations exactly. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 3000; +volatile LONG g_stop = 0; + +DWORD WINAPI Allocator(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 97 + 3); + void* slots[32] = { 0 }; + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + unsigned i = random.Below(32); + switch (random.Below(3)) + { + case 0: + free(slots[i]); + slots[i] = malloc(1 + random.Below(300)); + break; + case 1: + slots[i] = realloc(slots[i], 1 + random.Below(3000)); + break; + default: + free(slots[i]); + slots[i] = NULL; + break; + } + } + for (int i = 0; i < 32; i++) + { + free(slots[i]); + } + return 0; +} + +DWORD WINAPI Toggler(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 13 + 1); + UINT options = VLDGetOptions(); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + switch (random.Below(8)) + { + case 0: + VLDDisable(); + free(malloc(8)); + VLDRestore(); + break; + case 1: + VLDEnable(); + break; + case 2: + VLDGlobalDisable(); + VLDGlobalEnable(); + break; + case 3: + VLDSetOptions(VLD_OPT_SAFE_STACK_WALK, 256, 32); + VLDSetOptions(options, 256, 64); + break; + case 4: + VLDGetLeaksCount(); + break; + case 5: + VLDResolveCallstacks(); + break; + case 6: + VLDGetThreadLeaksCount(GetCurrentThreadId()); + break; + default: + VLDRefreshModules(); + break; + } + } + return 0; +} + +DWORD WINAPI Worker(LPVOID p) +{ + INT_PTR index = (INT_PTR)p; + if (index < 6) + { + return Allocator(p); + } + if (index < 9) + { + return Toggler(p); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + UINT options = VLDGetOptions(); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("API storm with allocation traffic"); + chaos::RunThreads(10, Worker); + + chaos::SetPhase("tracking after the storm"); + VLDGlobalEnable(); + VLDEnable(); + VLDSetOptions(options, 256, 64); + SIZE_T after = VLDGetLeaksCount(); + chaos::Check(after == base, "the storm left leaks behind"); + void* sentinel = malloc(47); + chaos::Check(VLDGetLeaksCount() == base + 1, "a new allocation is not tracked after the storm"); + free(sentinel); + chaos::Check(VLDGetLeaksCount() == base, "a freed allocation is still counted after the storm"); + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index d059460a..3f9bc3e0 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -3652,6 +3652,11 @@ CaptureContext::~CaptureContext() { pblockInfo->callStack.reset(callstack); } + else if (excluded && m_tls->newBlockWithoutGuard != NULL && m_tls->newBlockWithoutGuard != m_tls->blockWithoutGuard) { + // An excluded module moved a tracked block; the heap can hand the old + // address out again. + g_vld.unmapBlock(m_tls->heap, m_tls->blockWithoutGuard, m_tls->context); + } // Reset thread local flags and variables for the next allocation. Reset(); diff --git a/src/vld_hooks.cpp b/src/vld_hooks.cpp index a2992d03..6a173119 100644 --- a/src/vld_hooks.cpp +++ b/src/vld_hooks.cpp @@ -289,8 +289,17 @@ LPVOID VisualLeakDetector::_RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID // Reallocate the block. LPVOID newmem = RtlReAllocateHeap(heap, flags, mem, size); - if ((newmem == NULL) || !g_vld.enabled()) + if (newmem == NULL) return newmem; + if (!g_vld.enabled()) { + if (newmem != mem && !g_DbgHelp.IsLockedByCurrentThread()) { + // The heap can hand the old address out again; forget it. + CAPTURE_CONTEXT(); + context_.func = reinterpret_cast(RtlReAllocateHeap); + g_vld.unmapBlock(heap, mem, context_); + } + return newmem; + } if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls CAPTURE_CONTEXT(); @@ -320,8 +329,17 @@ LPVOID VisualLeakDetector::_HeapReAlloc (HANDLE heap, DWORD flags, LPVOID mem, S #else LPVOID newmem = HeapReAlloc(heap, flags, mem, size); #endif - if ((newmem == NULL) || !g_vld.enabled()) + if (newmem == NULL) return newmem; + if (!g_vld.enabled()) { + if (newmem != mem && !g_DbgHelp.IsLockedByCurrentThread()) { + // The heap can hand the old address out again; forget it. + CAPTURE_CONTEXT(); + context_.func = reinterpret_cast(HeapReAlloc); + g_vld.unmapBlock(heap, mem, context_); + } + return newmem; + } if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls CAPTURE_CONTEXT(); From 21bba73a2f399a0aad537445836c5962669d8549 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:13:29 -0800 Subject: [PATCH 17/91] chaos tests - CRT allocator matrix and private heap churn chaos_crt_matrix allocates through every CRT entry point (malloc, calloc, realloc, _recalloc, _aligned_*, _expand, new[], strdup family) from several threads and checks the leak count stays exact. chaos_heap_churn creates, uses and destroys private heaps from several threads, leaking on purpose into heaps that are then destroyed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 2 + src/tests/chaos/chaos_crt_matrix.cpp | 97 ++++++++++++++++++++++++++++ src/tests/chaos/chaos_heap_churn.cpp | 93 ++++++++++++++++++++++++++ 3 files changed, 192 insertions(+) create mode 100644 src/tests/chaos/chaos_crt_matrix.cpp create mode 100644 src/tests/chaos/chaos_heap_churn.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index fea7c05a..10ba7f59 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -901,6 +901,8 @@ set(VLD_CHAOS_TESTS chaos_report_hook_race chaos_long_frame chaos_hook_reenter + chaos_crt_matrix + chaos_heap_churn chaos_api_storm ) diff --git a/src/tests/chaos/chaos_crt_matrix.cpp b/src/tests/chaos/chaos_crt_matrix.cpp new file mode 100644 index 00000000..0b597141 --- /dev/null +++ b/src/tests/chaos/chaos_crt_matrix.cpp @@ -0,0 +1,97 @@ +// chaos_crt_matrix.cpp - exact leak counts through every CRT allocation shape. +// +// Each step allocates through one CRT entry point (including the edge cases +// realloc(NULL), realloc(p, 0), _recalloc, _expand and the aligned family) +// and checks VLD's count before and after freeing. A block must be counted +// exactly once while live and never after it is freed or moved. + +#include "chaos_common.h" +#include +#include +#include +#include "vld.h" + +namespace +{ +SIZE_T g_base = 0; + +void ExpectLive(SIZE_T live, const char* step) +{ + SIZE_T leaks = VLDGetLeaksCount(); + if (leaks != g_base + live) + { + char message[256]; + _snprintf_s(message, _TRUNCATE, "%s: expected %zu live blocks, VLD counts %zd", step, live, + (ptrdiff_t)(leaks - g_base)); + chaos::Fail(message); + } +} +} + +int main() +{ + chaos::StartWatchdog(20000); + g_base = VLDGetLeaksCount(); + + for (int round = 0; round < 50; round++) + { + chaos::SetPhase("realloc(NULL, n) and realloc(p, 0)"); + void* p = realloc(NULL, 73 + round); + ExpectLive(1, "realloc(NULL)"); + p = realloc(p, 4096 + round); + ExpectLive(1, "realloc grow"); + p = realloc(p, 8); + ExpectLive(1, "realloc shrink"); + p = realloc(p, 0); + if (p != NULL) + { + free(p); + } + ExpectLive(0, "realloc(p, 0)"); + + chaos::SetPhase("calloc and _recalloc"); + p = calloc(7, 9); + ExpectLive(1, "calloc"); + p = _recalloc(p, 70, 9); + ExpectLive(1, "_recalloc grow"); + free(p); + ExpectLive(0, "_recalloc free"); + + chaos::SetPhase("_expand and _msize"); + p = malloc(256); + void* expanded = _expand(p, 128); + chaos::Check(_msize(expanded != NULL ? expanded : p) >= 128, "_msize after _expand"); + ExpectLive(1, "_expand"); + free(expanded != NULL ? expanded : p); + ExpectLive(0, "_expand free"); + + chaos::SetPhase("aligned allocations"); + void* a = _aligned_malloc(100, 64); + chaos::Check(((UINT_PTR)a & 63) == 0, "_aligned_malloc alignment"); + ExpectLive(1, "_aligned_malloc"); + a = _aligned_realloc(a, 5000, 64); + chaos::Check(((UINT_PTR)a & 63) == 0, "_aligned_realloc alignment"); + ExpectLive(1, "_aligned_realloc"); + a = _aligned_recalloc(a, 10, 100, 64); + ExpectLive(1, "_aligned_recalloc"); + void* o = _aligned_offset_malloc(200, 32, 8); + ExpectLive(2, "_aligned_offset_malloc"); + _aligned_free(o); + _aligned_free(a); + ExpectLive(0, "_aligned_free"); + + chaos::SetPhase("strdup family and new[]"); + char* s = _strdup("chaos"); + wchar_t* w = _wcsdup(L"chaos"); + int* n = new int[17]; + char* single = new char; + ExpectLive(4, "_strdup/_wcsdup/new[]/new"); + free(s); + free(w); + delete[] n; + delete single; + ExpectLive(0, "strdup family freed"); + } + chaos::Pass(); + return 0; +} diff --git a/src/tests/chaos/chaos_heap_churn.cpp b/src/tests/chaos/chaos_heap_churn.cpp new file mode 100644 index 00000000..f07b70fe --- /dev/null +++ b/src/tests/chaos/chaos_heap_churn.cpp @@ -0,0 +1,93 @@ +// chaos_heap_churn.cpp - private heaps created and destroyed with live blocks on +// several threads while other threads count leaks. +// +// VLD maps every heap it sees created and reports and unmaps its blocks when +// the heap is destroyed. Destroying heaps that still hold blocks, from many +// threads at once, must not hang, crash or leave stale blocks counted. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 3000; +volatile LONG g_stop = 0; +volatile LONG g_heapsDestroyed = 0; + +int __cdecl SwallowReport(int, wchar_t*, int*) +{ + return 1; +} + +DWORD WINAPI HeapWorker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 31 + 7); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + HANDLE heap = HeapCreate(random.Below(2) ? HEAP_NO_SERIALIZE : 0, 0, 0); + chaos::Check(heap != NULL, "HeapCreate failed"); + int blocks = 1 + random.Below(40); + void* last = NULL; + for (int i = 0; i < blocks; i++) + { + last = HeapAlloc(heap, 0, 8 + random.Below(512)); + chaos::Check(last != NULL, "HeapAlloc failed"); + if (random.Below(3) == 0) + { + last = HeapReAlloc(heap, 0, last, 16 + random.Below(1024)); + chaos::Check(last != NULL, "HeapReAlloc failed"); + } + } + if (random.Below(2)) + { + HeapFree(heap, 0, last); + } + chaos::Check(HeapDestroy(heap) != FALSE, "HeapDestroy failed"); + InterlockedIncrement(&g_heapsDestroyed); + } + return 0; +} + +DWORD WINAPI Counter(LPVOID) +{ + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + VLDGetLeaksCount(); + } + return 0; +} + +DWORD WINAPI Worker(LPVOID p) +{ + INT_PTR index = (INT_PTR)p; + if (index < 6) + { + return HeapWorker(p); + } + if (index < 8) + { + return Counter(p); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + SIZE_T base = VLDGetLeaksCount(); + // Destroyed heaps report their remaining blocks by design. + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowReport); + + chaos::SetPhase("heap create/alloc/destroy churn with leak counts"); + chaos::RunThreads(9, Worker); + + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowReport); + chaos::SetPhase("final count"); + chaos::Check(InterlockedCompareExchange(&g_heapsDestroyed, 0, 0) > 0, "no heap was destroyed"); + chaos::Check(VLDGetLeaksCount() == base, "blocks of destroyed heaps are still counted"); + chaos::Pass(); + return 0; +} From ae2f35bc0601aff0d24b707db4064e3920599dcb Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:15:44 -0800 Subject: [PATCH 18/91] chaos tests - thread churn with allocating thread attach and detach Short-lived threads allocate in DLL_THREAD_ATTACH and free in DLL_THREAD_DETACH of a VLD-linked DLL while other threads load and unload DLLs and count leaks. The leak count must match the blocks still held by threads that are alive (thread pool and loader workers). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_helper_dll.cpp | 21 +++- src/tests/chaos/chaos_thread_churn.cpp | 134 +++++++++++++++++++++++++ 3 files changed, 154 insertions(+), 2 deletions(-) create mode 100644 src/tests/chaos/chaos_thread_churn.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 10ba7f59..6495530c 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -901,6 +901,7 @@ set(VLD_CHAOS_TESTS chaos_report_hook_race chaos_long_frame chaos_hook_reenter + chaos_thread_churn chaos_crt_matrix chaos_heap_churn chaos_api_storm diff --git a/src/tests/chaos/chaos_helper_dll.cpp b/src/tests/chaos/chaos_helper_dll.cpp index 03be6f80..effff9f4 100644 --- a/src/tests/chaos/chaos_helper_dll.cpp +++ b/src/tests/chaos/chaos_helper_dll.cpp @@ -12,6 +12,7 @@ static volatile LONG g_armed = 0; static volatile LONG g_inThreadAttachAlloc = 0; static HANDLE g_inThreadAttach = NULL; static volatile LONG g_threadChurn = 0; +static volatile LONG g_threadChurnLive = 0; static DWORD g_tlsIndex = TLS_OUT_OF_INDEXES; #pragma optimize("", off) @@ -51,6 +52,12 @@ extern "C" __declspec(dllexport) void SetThreadChurn(LONG enabled) InterlockedExchange(&g_threadChurn, enabled); } +// Blocks allocated in thread attach whose threads have not detached yet. +extern "C" __declspec(dllexport) LONG ThreadChurnLiveBlocks() +{ + return InterlockedCompareExchange(&g_threadChurnLive, 0, 0); +} + BOOL APIENTRY DllMain(HMODULE, DWORD reason, LPVOID) { switch (reason) @@ -75,13 +82,23 @@ BOOL APIENTRY DllMain(HMODULE, DWORD reason, LPVOID) } if (InterlockedCompareExchange(&g_threadChurn, 0, 0) != 0 && g_tlsIndex != TLS_OUT_OF_INDEXES) { - TlsSetValue(g_tlsIndex, malloc(48)); + void* block = malloc(48); + if (block != NULL) + { + InterlockedIncrement(&g_threadChurnLive); + } + TlsSetValue(g_tlsIndex, block); } break; case DLL_THREAD_DETACH: if (g_tlsIndex != TLS_OUT_OF_INDEXES) { - free(TlsGetValue(g_tlsIndex)); + void* block = TlsGetValue(g_tlsIndex); + if (block != NULL) + { + free(block); + InterlockedDecrement(&g_threadChurnLive); + } TlsSetValue(g_tlsIndex, NULL); } break; diff --git a/src/tests/chaos/chaos_thread_churn.cpp b/src/tests/chaos/chaos_thread_churn.cpp new file mode 100644 index 00000000..e412952f --- /dev/null +++ b/src/tests/chaos/chaos_thread_churn.cpp @@ -0,0 +1,134 @@ +// chaos_thread_churn.cpp - many short-lived threads whose DLL_THREAD_ATTACH and +// DLL_THREAD_DETACH allocate and free, while other threads load and unload +// DLLs and count leaks. +// +// Thread attach/detach run under the loader lock; leak queries and module +// (un)load notifications take VLD's locks in other orders. Nothing may hang, +// and every block allocated in thread attach is freed in thread detach. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +typedef void (*SetThreadChurn_t)(LONG); +typedef LONG (*ThreadChurnLiveBlocks_t)(); +const DWORD RUN_MS = 4000; +volatile LONG g_stop = 0; + +DWORD WINAPI ShortThread(LPVOID p) +{ + void* block = malloc(16 + ((INT_PTR)p % 64)); + free(block); + return 0; +} + +DWORD WINAPI Spawner(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p + 11); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + HANDLE threads[8]; + int count = 0; + for (int i = 0; i < 8; i++) + { + threads[count] = CreateThread(NULL, 0, ShortThread, (LPVOID)(INT_PTR)random.Next(), 0, NULL); + if (threads[count] != NULL) + { + count++; + } + } + WaitForMultipleObjects(count, threads, TRUE, INFINITE); + for (int i = 0; i < count; i++) + { + CloseHandle(threads[i]); + } + } + return 0; +} + +DWORD WINAPI Loader(LPVOID) +{ + const wchar_t* dlls[] = { L"version.dll", L"winmm.dll", L"dbgeng.dll", L"wtsapi32.dll" }; + int i = 0; + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + HMODULE module = LoadLibraryW(dlls[i++ % _countof(dlls)]); + if (module != NULL) + { + FreeLibrary(module); + } + } + return 0; +} + +DWORD WINAPI Counter(LPVOID) +{ + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + VLDGetLeaksCount(); + Sleep(1); + } + return 0; +} + +DWORD WINAPI Worker(LPVOID p) +{ + INT_PTR index = (INT_PTR)p; + if (index < 4) + { + return Spawner(p); + } + if (index < 6) + { + return Loader(p); + } + if (index < 7) + { + return Counter(p); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + HMODULE helper = LoadLibraryW(L"chaos_helper_dll.dll"); + chaos::Check(helper != NULL, "LoadLibrary(chaos_helper_dll.dll) failed"); + SetThreadChurn_t setThreadChurn = (SetThreadChurn_t)GetProcAddress(helper, "SetThreadChurn"); + chaos::Check(setThreadChurn != NULL, "GetProcAddress(SetThreadChurn) failed"); + ThreadChurnLiveBlocks_t liveBlocks = (ThreadChurnLiveBlocks_t)GetProcAddress(helper, "ThreadChurnLiveBlocks"); + chaos::Check(liveBlocks != NULL, "GetProcAddress(ThreadChurnLiveBlocks) failed"); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("thread churn with allocating thread attach/detach, DLL loads and leak counts"); + setThreadChurn(1); + chaos::RunThreads(8, Worker); + setThreadChurn(0); + + // Threads still alive that attached during the churn (thread pool and + // loader workers) legitimately hold their attach block. + chaos::SetPhase("final count"); + for (int attempt = 0; ; attempt++) + { + LONG live = liveBlocks(); + SIZE_T leaks = VLDGetLeaksCount(); + if (leaks - base == (SIZE_T)live && liveBlocks() == live) + { + break; + } + if (attempt == 50) + { + char message[128]; + _snprintf_s(message, _TRUNCATE, "%zu leaks left behind by thread churn, %ld blocks held by live threads", + leaks - base, live); + chaos::Fail(message); + } + Sleep(20); + } + chaos::Pass(); + return 0; +} From 14b8f732f1d70610ff03af909ba15ccfd2fb8227 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:25:22 -0800 Subject: [PATCH 19/91] Aggregate only the thread's unreported duplicates With AggregateDuplicates on, eraseDuplicates counted every block with the same size and call stack, ignoring the thread filter of ReportThreadLeaks and the blocks already marked as reported. VLDReportThreadLeaks for one thread counted another thread's duplicates (chaos_aggregate_threads: 5 instead of 3). Apply the same filters as reportLeaks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_aggregate_threads.cpp | 90 +++++++++++++++++++++ src/vld.cpp | 11 ++- src/vldint.h | 2 +- 4 files changed, 100 insertions(+), 4 deletions(-) create mode 100644 src/tests/chaos/chaos_aggregate_threads.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 6495530c..6f7c9a4a 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -905,6 +905,7 @@ set(VLD_CHAOS_TESTS chaos_crt_matrix chaos_heap_churn chaos_api_storm + chaos_aggregate_threads ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_aggregate_threads.cpp b/src/tests/chaos/chaos_aggregate_threads.cpp new file mode 100644 index 00000000..10d89815 --- /dev/null +++ b/src/tests/chaos/chaos_aggregate_threads.cpp @@ -0,0 +1,90 @@ +// chaos_aggregate_threads.cpp - duplicate aggregation must respect the thread +// filter and the leaks already marked as reported. +// +// Two threads leak blocks of the same size from the same call site, so with +// AggregateDuplicates on all of them are duplicates of each other. A report +// for one thread must count only that thread's blocks, and blocks marked as +// reported must not be counted again. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +HANDLE g_release = NULL; +void* g_blocks[8]; + +__declspec(noinline) void* LeakFrom() +{ + return malloc(72); +} + +struct LeakJob +{ + int first; + int count; + HANDLE done; +}; + +DWORD WINAPI Leaker(LPVOID p) +{ + LeakJob* job = (LeakJob*)p; + for (int i = 0; i < job->count; i++) + { + g_blocks[job->first + i] = LeakFrom(); + } + SetEvent(job->done); + WaitForSingleObject(g_release, INFINITE); + return 0; +} + +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + UINT options = VLDGetOptions(); + VLDSetOptions(options | VLD_OPT_AGGREGATE_DUPLICATES, 256, 64); + g_release = CreateEventW(NULL, TRUE, FALSE, NULL); + + chaos::SetPhase("two threads leaking duplicates"); + LeakJob jobA = { 0, 3, CreateEventW(NULL, TRUE, FALSE, NULL) }; + LeakJob jobB = { 3, 2, CreateEventW(NULL, TRUE, FALSE, NULL) }; + DWORD idA = 0; + DWORD idB = 0; + HANDLE threadA = CreateThread(NULL, 0, Leaker, &jobA, 0, &idA); + HANDLE threadB = CreateThread(NULL, 0, Leaker, &jobB, 0, &idB); + chaos::Check(threadA != NULL && threadB != NULL, "CreateThread failed"); + WaitForSingleObject(jobA.done, INFINITE); + WaitForSingleObject(jobB.done, INFINITE); + + chaos::SetPhase("per-thread counts with aggregation"); + chaos::Check(VLDGetThreadLeaksCount(idA) == 3, "VLDGetThreadLeaksCount(A) is not 3"); + chaos::Check(VLDGetThreadLeaksCount(idB) == 2, "VLDGetThreadLeaksCount(B) is not 2"); + chaos::Check(VLDReportThreadLeaks(idA) == 3, "VLDReportThreadLeaks(A) counted another thread's duplicates"); + chaos::Check(VLDReportThreadLeaks(idB) == 2, "VLDReportThreadLeaks(B) counted another thread's duplicates"); + + chaos::SetPhase("reported leaks are not aggregated again"); + VLDMarkThreadLeaksAsReported(idB); + chaos::Check(VLDReportThreadLeaks(idA) == 3, "VLDReportThreadLeaks(A) changed after B was marked reported"); + VLDMarkThreadLeaksAsReported(idA); + chaos::Check(VLDReportThreadLeaks(idA) == 0, "VLDReportThreadLeaks(A) reports leaks already marked reported"); + + chaos::SetPhase("cleanup"); + SetEvent(g_release); + WaitForSingleObject(threadA, INFINITE); + WaitForSingleObject(threadB, INFINITE); + for (int i = 0; i < 5; i++) + { + free(g_blocks[i]); + } + VLDSetOptions(options, 256, 64); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index 3f9bc3e0..33a1a541 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1422,11 +1422,14 @@ BOOL VisualLeakDetector::enabled () // - element (IN): BlockMap Iterator referencing the block of which to search // for duplicates. // +// - threadId (IN): Only blocks allocated by this thread count, or all blocks +// if (DWORD)-1. +// // Return Value: // // Returns the number of duplicate blocks erased from the block map. // -SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, Set &aggregatedLeaks) +SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, Set &aggregatedLeaks, DWORD threadId) { blockinfo_t *elementinfo = (*element).second; @@ -1446,7 +1449,9 @@ SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, S continue; } blockinfo_t *info = (*blockit).second; - if (info->callStack == NULL) + if (info->callStack == NULL || info->reported) + continue; + if (threadId != ((DWORD)-1) && info->threadId != threadId) continue; Set::Iterator it = aggregatedLeaks.find(info); if (it != aggregatedLeaks.end()) @@ -2079,7 +2084,7 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { // Aggregate all other leaks which are duplicates of this one // under this same heading, to cut down on clutter. - SIZE_T erased = eraseDuplicates(blockit, aggregatedLeaks); + SIZE_T erased = eraseDuplicates(blockit, aggregatedLeaks, threadId); // add only the number that were erased, since the 'one left over' // is already recorded as a leak diff --git a/src/vldint.h b/src/vldint.h index 1c9d8f8a..23f62996 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -335,7 +335,7 @@ class VisualLeakDetector : public IMalloc BOOL GetIniFilePath(LPTSTR lpPath, SIZE_T cchPath); VOID configure (); BOOL enabled (); - SIZE_T eraseDuplicates (const BlockMap::Iterator &element, Set &aggregatedLeak); + SIZE_T eraseDuplicates (const BlockMap::Iterator &element, Set &aggregatedLeak, DWORD threadId); tls_t* getTls (); VOID mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool crtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo); VOID mapHeap (HANDLE heap); From fccd6d21f8e9686edc5ad63fa935f1b1b93cbc5f Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:34:19 -0800 Subject: [PATCH 20/91] Keep a heap created during a block walk apart from the destroyed one A heap destroyed during a block walk (by a report hook) is unmapped at the end of the walk, by handle. When the hook then created a heap that got the same handle, its blocks went into the destroyed heap's block map and were dropped with it: chaos_hook_heap_ops lost the new heap's block in 15 of 20 runs. A heap destroyed during a walk is now flagged and deferred with its heapinfo_t. Mapping the same handle again (HeapCreate, or the first block of a heap VLD did not see created) swaps in new information in place and endBlockWalk frees the old one; it unmaps the handle only if it still maps to the deferred information. Deferred blocks are erased through their own heap information instead of a handle lookup. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_hook_heap_ops.cpp | 117 ++++++++++++++++++++++++ src/vld.cpp | 67 ++++++++++---- src/vldint.h | 12 ++- 4 files changed, 176 insertions(+), 21 deletions(-) create mode 100644 src/tests/chaos/chaos_hook_heap_ops.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 6f7c9a4a..65a00aea 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -906,6 +906,7 @@ set(VLD_CHAOS_TESTS chaos_heap_churn chaos_api_storm chaos_aggregate_threads + chaos_hook_heap_ops ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_hook_heap_ops.cpp b/src/tests/chaos/chaos_hook_heap_ops.cpp new file mode 100644 index 00000000..58e06bd0 --- /dev/null +++ b/src/tests/chaos/chaos_hook_heap_ops.cpp @@ -0,0 +1,117 @@ +// chaos_hook_heap_ops.cpp - a report hook that reallocates, destroys and +// creates heaps and reports again while VLD walks its maps. +// +// The hook runs with g_heapMapLock held in the middle of the walk. It moves a +// tracked block with realloc, destroys a private heap that still holds +// blocks, creates a new heap right away (which sometimes gets the destroyed +// heap's handle) and allocates from it, and nests a second report. +// Afterwards every live block must be counted exactly once. The scenario +// repeats so that the handle reuse happens in most runs. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +volatile LONG g_inHook = 0; +volatile LONG g_calls = 0; +void* volatile g_moving = NULL; +HANDLE volatile g_doomedHeap = NULL; +HANDLE volatile g_newHeap = NULL; +void* volatile g_newHeapBlock = NULL; +bool g_reused = false; + +int __cdecl HeapOpsHook(int, wchar_t*, int*) +{ + if (InterlockedExchange(&g_inHook, 1) != 0) + { + return 1; + } + switch (InterlockedIncrement(&g_calls)) + { + case 2: + g_moving = realloc(g_moving, 64 * 1024); + break; + case 4: + { + HANDLE doomed = g_doomedHeap; + HeapDestroy(doomed); + g_doomedHeap = NULL; + g_newHeap = HeapCreate(0, 0, 0); + g_reused = (g_newHeap == doomed); + break; + } + case 6: + g_newHeapBlock = HeapAlloc(g_newHeap, 0, 123); + break; + case 8: + VLDReportLeaks(); + break; + case 10: + VLDGetLeaksCount(); + break; + default: + break; + } + InterlockedExchange(&g_inHook, 0); + return 1; +} + +void Round(SIZE_T base) +{ + InterlockedExchange(&g_calls, 0); + g_newHeap = NULL; + g_newHeapBlock = NULL; + void* keep[8]; + for (int i = 0; i < 8; i++) + { + keep[i] = malloc(24 + i); + } + g_moving = malloc(16); + g_doomedHeap = HeapCreate(0, 0, 0); + chaos::Check(g_doomedHeap != NULL, "HeapCreate failed"); + for (int i = 0; i < 6; i++) + { + HeapAlloc(g_doomedHeap, 0, 40 + i); + } + chaos::Check(VLDGetLeaksCount() == base + 15, "setup count is wrong"); + + chaos::SetPhase("leak report with a hook that moves blocks and destroys and creates heaps"); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, HeapOpsHook); + VLDReportLeaks(); + VLDReportLeaks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, HeapOpsHook); + chaos::Check(InterlockedCompareExchange(&g_calls, 0, 0) >= 10, "the hook ran too few times"); + chaos::Check(g_doomedHeap == NULL, "the hook did not destroy the heap"); + chaos::Check(g_newHeapBlock != NULL, "the hook did not allocate from the new heap"); + + chaos::SetPhase(g_reused ? "counting after the reports (heap handle reused)" : "counting after the reports"); + chaos::Check(VLDGetLeaksCount() == base + 10, "wrong leak count after the hook's heap operations"); + HeapFree(g_newHeap, 0, g_newHeapBlock); + chaos::Check(VLDGetLeaksCount() == base + 9, "the new heap's block is not tracked"); + HeapDestroy(g_newHeap); + free(g_moving); + for (int i = 0; i < 8; i++) + { + free(keep[i]); + } + chaos::Check(VLDGetLeaksCount() == base, "leaks left after freeing everything"); +} +} + +int main() +{ + chaos::StartWatchdog(20000); + SIZE_T base = VLDGetLeaksCount(); + int reused = 0; + for (int round = 0; round < 25; round++) + { + Round(base); + reused += g_reused ? 1 : 0; + } + char line[64]; + _snprintf_s(line, _TRUNCATE, "heap handle reused in %d of 25 rounds\n", reused); + chaos::Write(line); + chaos::Pass(); + return 0; +} \ No newline at end of file diff --git a/src/vld.cpp b/src/vld.cpp index 33a1a541..a5223b01 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1551,8 +1551,9 @@ VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool d // Insert the block's information into the block map. HeapMap::Iterator heapit = m_heapMap->find(heap); - if (heapit == m_heapMap->end()) { - // We haven't mapped this heap to a block map yet. Do it now. + if (heapit == m_heapMap->end() || ((*heapit).second->flags & VLD_HEAP_DESTROYED)) { + // We haven't mapped this heap to a block map yet, or it was destroyed + // during this block walk and the handle reused. Do it now. mapHeap(heap); heapit = m_heapMap->find(heap); assert(heapit != m_heapMap->end()); @@ -1572,7 +1573,7 @@ VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool d // Replace the entry's information in place; endBlockWalk deletes // the old information. info->reported = true; - deferredblock_t deferred = { heap, mem, info }; + deferredblock_t deferred = { (*heapit).second, mem, info }; m_deferredBlocks->insert(deferred); const_cast&>(*blockit).second = blockinfo; return; @@ -1604,11 +1605,21 @@ VOID VisualLeakDetector::mapHeap (HANDLE heap) HeapMap::Iterator heapit = m_heapMap->insert(heap, heapinfo); if (heapit == m_heapMap->end()) { + heapit = m_heapMap->find(heap); + if (isBlockWalkThread()) { + // Replace the heap's information in place; endBlockWalk frees the + // old information. + heapinfo_t* oldinfo = (*heapit).second; + if (!(oldinfo->flags & VLD_HEAP_DESTROYED)) + Report(L"WARNING: Visual Leak Detector detected a duplicate heap (" ADDRESSFORMAT L").\n", heap); + deferUnmapHeap(heap, oldinfo); + const_cast&>(*heapit).second = heapinfo; + return; + } // Somehow this heap has been created twice without being destroyed, // or at least it was destroyed without VLD's knowledge. Unmap the heap // from the existing heapinfo, and remap it to the new one. Report(L"WARNING: Visual Leak Detector detected a duplicate heap (" ADDRESSFORMAT L").\n", heap); - heapit = m_heapMap->find(heap); unmapHeap((*heapit).first); m_heapMap->insert(heap, heapinfo); } @@ -1687,7 +1698,7 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & if (isBlockWalkThread()) { // The walk skips it; endBlockWalk erases it. info->reported = true; - deferredblock_t deferred = { heap, mem, info }; + deferredblock_t deferred = { (*heapit).second, mem, info }; m_deferredBlocks->insert(deferred); return; } @@ -1720,11 +1731,7 @@ VOID VisualLeakDetector::unmapHeap (HANDLE heap) heapinfo_t *heapinfo = (*heapit).second; BlockMap *blockmap = &heapinfo->blockMap; if (isBlockWalkThread()) { - // The walk skips its blocks; endBlockWalk unmaps the heap. - for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { - (*blockit).second->reported = true; - } - m_deferredHeaps->insert(heap); + deferUnmapHeap(heap, heapinfo); return; } for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { @@ -2902,6 +2909,21 @@ bool VisualLeakDetector::isBlockWalkThread () const return m_blockWalkDepth != 0 && m_blockWalkThreadId == GetCurrentThreadId(); } +// The walk skips the heap's blocks; endBlockWalk unmaps the heap, unless its +// handle was mapped to new information since. +VOID VisualLeakDetector::deferUnmapHeap (HANDLE heap, heapinfo_t* heapinfo) +{ + if (heapinfo->flags & VLD_HEAP_DESTROYED) + return; + heapinfo->flags |= VLD_HEAP_DESTROYED; + BlockMap* blockmap = &heapinfo->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + (*blockit).second->reported = true; + } + deferredheap_t deferred = { heap, heapinfo }; + m_deferredHeaps->insert(deferred); +} + VOID VisualLeakDetector::endBlockWalk () { if (--m_blockWalkDepth != 0) @@ -2912,13 +2934,10 @@ VOID VisualLeakDetector::endBlockWalk () DeferredBlockSet::Iterator it = m_deferredBlocks->begin(); deferredblock_t deferred = *it; m_deferredBlocks->erase(it); - HeapMap::Iterator heapit = m_heapMap->find(deferred.heap); - if (heapit != m_heapMap->end()) { - BlockMap* blockmap = &(*heapit).second->blockMap; - BlockMap::Iterator blockit = blockmap->find(deferred.block); - if (blockit != blockmap->end() && (*blockit).second == deferred.info) - blockmap->erase(blockit); - } + BlockMap* blockmap = &deferred.heapinfo->blockMap; + BlockMap::Iterator blockit = blockmap->find(deferred.block); + if (blockit != blockmap->end() && (*blockit).second == deferred.info) + blockmap->erase(blockit); delete deferred.info; } while (m_deferredCallStacks->begin() != m_deferredCallStacks->end()) { @@ -2929,9 +2948,19 @@ VOID VisualLeakDetector::endBlockWalk () } while (m_deferredHeaps->begin() != m_deferredHeaps->end()) { DeferredHeapSet::Iterator it = m_deferredHeaps->begin(); - HANDLE heap = *it; + deferredheap_t deferred = *it; m_deferredHeaps->erase(it); - unmapHeap(heap); + HeapMap::Iterator heapit = m_heapMap->find(deferred.heap); + if (heapit != m_heapMap->end() && (*heapit).second == deferred.heapinfo) { + unmapHeap(deferred.heap); + continue; + } + BlockMap* blockmap = &deferred.heapinfo->blockMap; + for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { + m_curAlloc -= (*blockit).second->size; + delete (*blockit).second; + } + delete deferred.heapinfo; } } diff --git a/src/vldint.h b/src/vldint.h index 23f62996..25f27a69 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -127,6 +127,7 @@ typedef Map BlockMap; struct heapinfo_t { BlockMap blockMap; // Map of all blocks allocated from this heap. UINT32 flags; // Heap status flags +#define VLD_HEAP_DESTROYED 0x1 // Destroyed during a block walk; endBlockWalk unmaps it. }; // HeapMaps map heaps (via their handles) to BlockMaps. @@ -135,13 +136,19 @@ typedef Map HeapMap; // A block freed while its thread walks the block maps (see beginBlockWalk). struct deferredblock_t { BOOL operator < (const struct deferredblock_t& other) const { return info < other.info; } - HANDLE heap; + heapinfo_t* heapinfo; LPCVOID block; blockinfo_t* info; }; +// A heap destroyed while its thread walks the block maps. +struct deferredheap_t { + BOOL operator < (const struct deferredheap_t& other) const { return heapinfo < other.heapinfo; } + HANDLE heap; + heapinfo_t* heapinfo; +}; typedef Set DeferredBlockSet; typedef Set DeferredCallStackSet; -typedef Set DeferredHeapSet; +typedef Set DeferredHeapSet; typedef std::basic_string, vldallocator > vldstring; // This structure stores information, primarily the virtual address range, about @@ -358,6 +365,7 @@ class VisualLeakDetector : public IMalloc VOID markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); VOID unmapBlock (HANDLE heap, LPCVOID mem, const context_t &context); VOID unmapHeap (HANDLE heap); + VOID deferUnmapHeap (HANDLE heap, heapinfo_t* heapinfo); VOID beginBlockWalk (); VOID endBlockWalk (); bool isBlockWalkThread () const; From 1189ef0d68d9fe7a2994f001e15a720848fa30bb Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:34:19 -0800 Subject: [PATCH 21/91] chaos tests - unusual heap flags and heap inspection under traffic HEAP_NO_SERIALIZE heaps, HEAP_GENERATE_EXCEPTIONS with a failing allocation, HEAP_REALLOC_IN_PLACE_ONLY that fails and that succeeds, zero-size blocks and reallocations to zero, and HeapLock/HeapWalk, HeapCompact and HeapValidate while other threads allocate from the process heap. Leak counts must stay exact. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_heap_flags.cpp | 166 +++++++++++++++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 src/tests/chaos/chaos_heap_flags.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 65a00aea..1c867616 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -907,6 +907,7 @@ set(VLD_CHAOS_TESTS chaos_api_storm chaos_aggregate_threads chaos_hook_heap_ops + chaos_heap_flags ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_heap_flags.cpp b/src/tests/chaos/chaos_heap_flags.cpp new file mode 100644 index 00000000..57b4567f --- /dev/null +++ b/src/tests/chaos/chaos_heap_flags.cpp @@ -0,0 +1,166 @@ +// chaos_heap_flags.cpp - unusual heap flags and heap inspection APIs under +// allocation traffic, with exact leak counts. +// +// Covers HEAP_NO_SERIALIZE heaps, HEAP_GENERATE_EXCEPTIONS with a failing +// allocation, HEAP_REALLOC_IN_PLACE_ONLY that fails or succeeds, zero-size +// blocks and reallocations to zero, and HeapLock/HeapWalk/HeapCompact/ +// HeapValidate running while other threads allocate from the same heap. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 2500; +volatile LONG g_stop = 0; + +DWORD WINAPI Allocator(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 31 + 7); + HANDLE heap = GetProcessHeap(); + void* slots[16] = { 0 }; + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + unsigned i = random.Below(16); + if (slots[i] == NULL) + { + slots[i] = HeapAlloc(heap, (random.Below(2) ? HEAP_ZERO_MEMORY : 0), random.Below(512)); + } + else if (random.Below(3) == 0) + { + void* moved = HeapReAlloc(heap, random.Below(2) ? HEAP_REALLOC_IN_PLACE_ONLY : 0, slots[i], random.Below(2048)); + if (moved != NULL) + { + slots[i] = moved; + } + } + else + { + HeapFree(heap, 0, slots[i]); + slots[i] = NULL; + } + } + for (int i = 0; i < 16; i++) + { + if (slots[i] != NULL) + { + HeapFree(heap, 0, slots[i]); + } + } + return 0; +} + +DWORD WINAPI Inspector(LPVOID p) +{ + HANDLE heap = GetProcessHeap(); + bool walk = ((INT_PTR)p % 2) == 0; + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + if (walk) + { + if (HeapLock(heap)) + { + PROCESS_HEAP_ENTRY entry = { 0 }; + int entries = 0; + while (HeapWalk(heap, &entry) && entries < 100000) + { + entries++; + } + HeapUnlock(heap); + } + } + else + { + HeapCompact(heap, 0); + HeapValidate(heap, 0, NULL); + } + Sleep(0); + } + return 0; +} + +DWORD WINAPI Worker(LPVOID p) +{ + INT_PTR index = (INT_PTR)p; + if (index < 4) + { + return Allocator(p); + } + if (index < 6) + { + return Inspector(p); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + return 0; +} + +bool AllocWithExceptions(HANDLE heap, SIZE_T size) +{ + __try + { + void* p = HeapAlloc(heap, HEAP_GENERATE_EXCEPTIONS, size); + if (p != NULL) + { + HeapFree(heap, 0, p); + } + return true; + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + return false; + } +} +} + +int main() +{ + chaos::StartWatchdog(25000); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("HEAP_NO_SERIALIZE heap"); + HANDLE noSerialize = HeapCreate(HEAP_NO_SERIALIZE, 0, 0); + chaos::Check(noSerialize != NULL, "HeapCreate(HEAP_NO_SERIALIZE) failed"); + void* blocks[10]; + for (int i = 0; i < 10; i++) + { + blocks[i] = HeapAlloc(noSerialize, HEAP_NO_SERIALIZE, 32 + i * 8); + } + chaos::Check(VLDGetLeaksCount() == base + 10, "HEAP_NO_SERIALIZE allocations not counted"); + void* grown = HeapReAlloc(noSerialize, HEAP_REALLOC_IN_PLACE_ONLY, blocks[0], 1024 * 1024); + chaos::Check(grown == NULL, "an in-place reallocation to 1 MB unexpectedly succeeded"); + chaos::Check(VLDGetLeaksCount() == base + 10, "a failed in-place reallocation changed the count"); + void* shrunk = HeapReAlloc(noSerialize, HEAP_REALLOC_IN_PLACE_ONLY, blocks[1], 8); + chaos::Check(shrunk == blocks[1], "an in-place shrink moved the block"); + void* zero = HeapReAlloc(noSerialize, 0, blocks[2], 0); + chaos::Check(zero != NULL, "HeapReAlloc to zero bytes failed"); + blocks[2] = zero; + chaos::Check(VLDGetLeaksCount() == base + 10, "reallocations changed the count"); + for (int i = 0; i < 10; i++) + { + HeapFree(noSerialize, 0, blocks[i]); + } + chaos::Check(VLDGetLeaksCount() == base, "HEAP_NO_SERIALIZE blocks still counted after HeapFree"); + HeapDestroy(noSerialize); + + chaos::SetPhase("HEAP_GENERATE_EXCEPTIONS with a failing allocation"); + HANDLE fixedHeap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 0, 64 * 1024); + chaos::Check(fixedHeap != NULL, "HeapCreate(HEAP_GENERATE_EXCEPTIONS) failed"); + chaos::Check(!AllocWithExceptions(fixedHeap, 1024 * 1024), "a 1 MB allocation from a 64 KB fixed heap did not raise"); + chaos::Check(AllocWithExceptions(fixedHeap, 100), "a small allocation raised"); + chaos::Check(VLDGetLeaksCount() == base, "a failed allocation was counted"); + HeapDestroy(fixedHeap); + + chaos::SetPhase("zero-size blocks"); + void* empty = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 0); + chaos::Check(empty != NULL, "HeapAlloc of zero bytes failed"); + chaos::Check(VLDGetLeaksCount() == base + 1, "a zero-size block is not counted"); + HeapFree(GetProcessHeap(), 0, empty); + chaos::Check(VLDGetLeaksCount() == base, "a freed zero-size block is still counted"); + + chaos::SetPhase("heap inspection under allocation traffic"); + chaos::RunThreads(7, Worker); + chaos::Check(VLDGetLeaksCount() == base, "allocation traffic with heap inspection left leaks"); + chaos::Pass(); + return 0; +} From b724e4bddf33a3b27debeb198117f5b35714c4af Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 21:38:25 -0800 Subject: [PATCH 22/91] chaos tests - process exit while threads allocate and report ExitProcess kills threads inside VLD's hooks, reports and symbol loading, then VLD reports from DLL_PROCESS_DETACH. The process must still exit with main's exit code, without crashing or hanging. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_exit_pressure.cpp | 90 +++++++++++++++++++++++++ 2 files changed, 91 insertions(+) create mode 100644 src/tests/chaos/chaos_exit_pressure.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 1c867616..a1ce8937 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -908,6 +908,7 @@ set(VLD_CHAOS_TESTS chaos_aggregate_threads chaos_hook_heap_ops chaos_heap_flags + chaos_exit_pressure ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_exit_pressure.cpp b/src/tests/chaos/chaos_exit_pressure.cpp new file mode 100644 index 00000000..1a47f708 --- /dev/null +++ b/src/tests/chaos/chaos_exit_pressure.cpp @@ -0,0 +1,90 @@ +// chaos_exit_pressure.cpp - the process exits while other threads allocate, +// free, report leaks and resolve call stacks. +// +// ExitProcess terminates the other threads wherever they are, including +// inside VLD's hooks holding its locks, and then VLD reports leaks from its +// DLL_PROCESS_DETACH. The process must exit with the code main returns, +// without crashing or hanging. A report hook swallows the leak report: the +// blocks held by the killed threads are expected leaks. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +DWORD WINAPI Churn(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 977 + 5); + HANDLE processHeap = GetProcessHeap(); + void* slots[64] = { 0 }; + for (;;) + { + unsigned i = random.Below(64); + switch (random.Below(5)) + { + case 0: + free(slots[i]); + slots[i] = malloc(1 + random.Below(400)); + break; + case 1: + slots[i] = realloc(slots[i], 1 + random.Below(4000)); + break; + case 2: + { + void* block = HeapAlloc(processHeap, 0, 1 + random.Below(200)); + HeapFree(processHeap, 0, block); + break; + } + case 3: + { + HANDLE heap = HeapCreate(0, 0, 0); + HeapAlloc(heap, 0, 64); + HeapDestroy(heap); + break; + } + default: + if (random.Below(50) == 0) + { + VLDGetLeaksCount(); + } + break; + } + } +} + +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} + +DWORD WINAPI Reporter(LPVOID p) +{ + for (;;) + { + if (((INT_PTR)p % 2) == 0) + { + VLDReportLeaks(); + } + else + { + VLDResolveCallstacks(); + } + } +} +} + +int main() +{ + chaos::StartWatchdog(25000); + chaos::SetPhase("exit while threads allocate, report and resolve call stacks"); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + for (INT_PTR i = 0; i < 10; i++) + { + HANDLE thread = CreateThread(NULL, 0, i < 8 ? Churn : Reporter, (LPVOID)i, 0, NULL); + chaos::Check(thread != NULL, "CreateThread failed"); + CloseHandle(thread); + } + Sleep(400); + chaos::Write("CHAOS PASS\n"); + return 0; +} From 5218e6703738fdb464f57197bb71f7809e8d597c Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 22:04:18 -0800 Subject: [PATCH 23/91] Do not hold g_heapMapLock while walking a stack with dbghelp SafeCallStack::getStackTrace took g_heapMapLock and then g_DbgHelp around StackWalk64. The walk only uses dbghelp, which g_DbgHelp serializes, but StackWalk64 can load symbols and dbghelp then calls LoadLibrary, which waits for the loader's load owner. An exiting thread that owned the loader freed FLS data into unmapBlock and waited for g_heapMapLock: chaos_api_storm hung with the safe stack walk enabled. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/callstack.cpp b/src/callstack.cpp index 290ac74e..d94e42cd 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -870,7 +870,8 @@ VOID SafeCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) frame.AddrFrame.Mode = AddrModeFlat; frame.Virtual = TRUE; - CriticalSectionLocker<> cs(g_heapMapLock); + // Not under g_heapMapLock: a thread holding g_DbgHelp can be loading a DLL + // for dbghelp, waiting for a loader owner that waits for g_heapMapLock. CriticalSectionLocker locker(g_DbgHelp); // Walk the stack. From f7d82d56ecba4ab80ca8cd07fc9e6cf8d3763ff8 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 22:04:18 -0800 Subject: [PATCH 24/91] Skip symbol server lookups when symsrv.dll is not beside dbghelp dbghelp loads symsrv.dll from its own directory every time it meets a symbol server element of the search path (from _NT_SYMBOL_PATH) or probes a directory as a symbol store. VLD's dbghelp has no symsrv.dll beside it, so every symbol load made a failing LoadLibrary that waited for the loader's load owner with g_DbgHelp held; a thread starting or exiting under the loader then waited for VLD's locks. chaos_api_storm (Debug) hung in about 4% of runs on x64, x64 emulated on ARM64 and native ARM64. When symsrv.dll is missing, drop the srv*, symsrv* and cache* elements from the search path and set SYMOPT_DISABLE_SYMSRV_AUTODETECT. They could never be used without symsrv.dll. 0 hangs in 150 runs afterwards. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 43 +++++++++++++++++++++++++++++++++++++++++-- src/vldint.h | 1 + 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index a5223b01..4bb12323 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -331,6 +331,7 @@ VisualLeakDetector::VisualLeakDetector () m_reportFile = NULL; wcsncpy_s(m_reportFilePath, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE); m_status = 0x0; + m_symsrvMissing = FALSE; HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); if (ntdll) @@ -511,9 +512,11 @@ VisualLeakDetector::VisualLeakDetector () set the DBGHELP_DBGOUT environment variable to a non-NULL value before calling the SymInitialize function. To log the information to a file, set the DBGHELP_LOG environment variable to the name of the log file to be used. */ - g_DbgHelp.SymSetOptions(SYMOPT_DEBUG | SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES); + g_DbgHelp.SymSetOptions(SYMOPT_DEBUG | SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES | + (m_symsrvMissing ? SYMOPT_DISABLE_SYMSRV_AUTODETECT : 0)); #else - g_DbgHelp.SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES); + g_DbgHelp.SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES | + (m_symsrvMissing ? SYMOPT_DISABLE_SYMSRV_AUTODETECT : 0)); #endif DbgTrace(L"dbghelp32.dll %i: SymInitializeW\n", GetCurrentThreadId()); if (!g_DbgHelp.SymInitializeW(g_currentProcess, symbolpath, FALSE)) { @@ -1163,6 +1166,42 @@ LPWSTR VisualLeakDetector::buildSymbolSearchPath () pos++; } + // dbghelp loads symsrv.dll from its own directory each time it meets a + // symbol server element, or a directory it probes as a symbol store. + // Without symsrv.dll there those can never work, and every failing load + // waits for the thread that owns the loader while g_DbgHelp is held, which + // can deadlock with that thread. Drop the server elements here; the caller + // disables the store probing. + HMODULE dbghelp = NULL; + WCHAR symsrvpath[MAX_PATH] = { 0 }; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCWSTR)&::SymInitializeW, &dbghelp) && + GetModuleFileNameW(dbghelp, symsrvpath, MAX_PATH) != 0) { + LPWSTR slash = wcsrchr(symsrvpath, L'\\'); + if (slash != NULL && wcscpy_s(slash + 1, MAX_PATH - (slash + 1 - symsrvpath), L"symsrv.dll") == 0 && + GetFileAttributesW(symsrvpath) == INVALID_FILE_ATTRIBUTES) { + m_symsrvMissing = TRUE; + LPWSTR write = path; + LPWSTR element = path; + while (*element != L'\0') { + LPWSTR end = wcschr(element, L';'); + SIZE_T elementLength = (end != NULL) ? (SIZE_T)(end - element) : wcslen(element); + bool server = (_wcsnicmp(element, L"srv*", 4) == 0) || (_wcsnicmp(element, L"symsrv*", 7) == 0) || + (_wcsnicmp(element, L"cache*", 6) == 0); + if (!server && elementLength != 0) { + memmove(write, element, elementLength * sizeof(WCHAR)); + write += elementLength; + if (end != NULL) + *write++ = L';'; + } + element += elementLength; + if (*element == L';') + element++; + } + *write = L'\0'; + } + } + return path; } diff --git a/src/vldint.h b/src/vldint.h index 25f27a69..924c9af7 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -420,6 +420,7 @@ class VisualLeakDetector : public IMalloc WCHAR m_ignoreModuleList [MAXIGNOREMODULELISTLENGTH]; // List of modules to be excluded from leak detection. WCHAR m_ignoreFunctionsList [MAXIGNOREFUNCTIONLISTLENGTH]; // List of functions to be ignored in leak detection. HeapMap *m_heapMap; // Map of all active heaps in the process. + BOOL m_symsrvMissing; // No symsrv.dll beside dbghelp.dll (see buildSymbolSearchPath). UINT32 m_blockWalkDepth; // Nesting of block map walks on m_blockWalkThreadId (see beginBlockWalk). DWORD m_blockWalkThreadId; // Thread walking the block maps, while m_blockWalkDepth > 0. DeferredBlockSet *m_deferredBlocks; // Blocks freed during the walk. From 3e5285f1379355ec6a81c1d400ff57bfbb7e26cf Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 22:31:50 -0800 Subject: [PATCH 25/91] Open and close the report file with no VLD lock held VLDSetReportOptions closed the report file without telling the report writer, which kept writing to the closed FILE, and never applied the new stdout and debugger settings unless a file was opened. It also opened and closed files while holding m_optionsLock; that allocates and frees through VLD's hooks, and the allocation hooks take m_optionsLock. A thread switching the destination waited for g_heapMapLock in fclose while a thread attach allocating under the loader lock waited for m_optionsLock. setReportDestination now swaps the report file, its encoding and the stdout and debugger settings at once (SwapReportFile, under an SRW lock that writes to the file share), then closes the previous file and opens the new one with no VLD lock held. The file buffer is allocated at open, so writes under the SRW lock never allocate. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/utility.cpp | 55 +++++++++----------- src/utility.h | 3 +- src/vld.cpp | 132 ++++++++++++++++++++++++------------------------ src/vldint.h | 3 +- 4 files changed, 93 insertions(+), 100 deletions(-) diff --git a/src/utility.cpp b/src/utility.cpp index cd32c7df..4d66e74e 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -43,6 +43,7 @@ extern "C" bool VldArm64InTeardown(void); // Global variables. static BOOL s_reportDelay = FALSE; // If TRUE, we sleep for a bit after calling OutputDebugString to give the debugger time to catch up. static FILE *s_reportFile = NULL; // Pointer to the file, if any, to send the memory leak report to. +static SRWLOCK s_reportFileLock = SRWLOCK_INIT; // Shared while writing to s_reportFile; exclusive to replace it. static BOOL s_reportToDebugger = TRUE; // If TRUE, a copy of the memory leak report will be sent to the debugger for display. static BOOL s_reportToStdOut = TRUE; // If TRUE, a copy of the memory leak report will be sent to standard output. static encoding_e s_reportEncoding = ascii; // Output encoding of the memory leak report. @@ -1250,10 +1251,12 @@ VOID Print (LPWSTR messagew) if (!CallReportHook(0, messagew, &hook_retval)) { if (s_reportEncoding == unicode) { + AcquireSRWLockShared(&s_reportFileLock); if (s_reportFile != NULL) { // Send the report to the previously specified file. fwrite(messagew, sizeof(WCHAR), wcslen(messagew), s_reportFile); } + ReleaseSRWLockShared(&s_reportFileLock); if ( s_reportToStdOut ) fputws(messagew, stdout); @@ -1270,10 +1273,12 @@ VOID Print (LPWSTR messagew) } messagea[MAXMESSAGELENGTH] = '\0'; + AcquireSRWLockShared(&s_reportFileLock); if (s_reportFile != NULL) { // Send the report to the previously specified file. fwrite(messagea, sizeof(CHAR), strlen(messagea), s_reportFile); } + ReleaseSRWLockShared(&s_reportFileLock); if ( s_reportToStdOut ) fputs(messagea, stdout); @@ -1493,50 +1498,38 @@ VOID RestoreModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tabl } } -// SetReportEncoding - Sets the output encoding of report messages to either -// ASCII (the default) or Unicode. +// SwapReportFile - Sets the file, if any, to which report messages are sent, +// its encoding, and whether they are copied to the debugger and stdout. +// Waits for writes to the previous file to finish, so the caller can close +// it. Writes happen under s_reportFileLock, so they must not allocate: the +// allocation could wait for a lock held by a thread that waits here. // -// - encoding (IN): Specifies either "ascii" or "unicode". +// - file (IN): Pointer to an open file, or NULL. // -// Return Value: -// -// None. +// - encoding (IN): The file's encoding, "ascii" or "unicode". Ignored if file +// is NULL. // -VOID SetReportEncoding (encoding_e encoding) -{ - switch (encoding) { - case ascii: - case unicode: - s_reportEncoding = encoding; - break; - - default: - assert(FALSE); - } -} - -// SetReportFile - Sets a destination file to which all report messages should -// be sent. If this function is not called to set a destination file, then -// report messages will be sent to the debugger instead of to a file. -// -// - file (IN): Pointer to an open file, to which future report messages should -// be sent. -// -// - copydebugger (IN): If true, in addition to sending report messages to -// the specified file, a copy of each message will also be sent to the +// - copydebugger (IN): If true, a copy of each message is also sent to the // debugger. // +// - tostdout (IN): If true, a copy of each message is also sent to stdout. +// // Return Value: // -// None. +// The previous file, or NULL. // -VOID SetReportFile (FILE *file, BOOL copydebugger, BOOL tostdout) +FILE* SwapReportFile (FILE *file, encoding_e encoding, BOOL copydebugger, BOOL tostdout) { + AcquireSRWLockExclusive(&s_reportFileLock); + FILE* previous = s_reportFile; s_reportFile = file; + if (file != NULL) + s_reportEncoding = encoding; s_reportToDebugger = copydebugger; s_reportToStdOut = tostdout; + ReleaseSRWLockExclusive(&s_reportFileLock); + return previous; } - // AppendString - Appends the specified source string to the specified destination // string. Allocates additional space so that the destination string "grows" // as new strings are appended to it. This is accomplished by deleting the diff --git a/src/utility.h b/src/utility.h index 48b90b7b..7926a088 100644 --- a/src/utility.h +++ b/src/utility.h @@ -191,8 +191,7 @@ VOID Report (LPCWSTR format, ...); #endif VOID RestoreImport (HMODULE importmodule, moduleentry_t* module); VOID RestoreModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize); -VOID SetReportEncoding (encoding_e encoding); -VOID SetReportFile (FILE *file, BOOL copydebugger, BOOL copytostdout); +FILE* SwapReportFile (FILE *file, encoding_e encoding, BOOL copydebugger, BOOL copytostdout); LPWSTR AppendString (LPWSTR dest, LPCWSTR source); BOOL StrToBool (LPCWSTR s); void ConvertModulePathToAscii( LPCWSTR modulename, LPSTR * modulenamea ); diff --git a/src/vld.cpp b/src/vld.cpp index 4bb12323..642aba51 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -328,7 +328,6 @@ VisualLeakDetector::VisualLeakDetector () m_maxDataDump = 0xffffffff; m_maxTraceFrames = 0xffffffff; m_options = 0x0; - m_reportFile = NULL; wcsncpy_s(m_reportFilePath, MAX_PATH, VLD_DEFAULT_REPORT_FILE_NAME, _TRUNCATE); m_status = 0x0; m_symsrvMissing = FALSE; @@ -471,7 +470,7 @@ VisualLeakDetector::VisualLeakDetector () m_status |= VLD_STATUS_NEVER_ENABLED; } if (m_options & VLD_OPT_REPORT_TO_FILE) { - setupReporting(); + setReportDestination(m_reportFilePath, m_options); } if (m_options & VLD_OPT_SLOW_DEBUGGER_DUMP) { // Insert a slight delay between messages sent to the debugger for @@ -859,8 +858,9 @@ VisualLeakDetector::~VisualLeakDetector () TlsFree(m_tlsIndex); } - if (m_reportFile != NULL) { - fclose(m_reportFile); + FILE* reportFile = SwapReportFile(NULL, ascii, FALSE, FALSE); + if (reportFile != NULL) { + fclose(reportFile); } // Decrement the library reference count. @@ -3429,34 +3429,34 @@ void VisualLeakDetector::SetReportOptions(UINT32 option_mask, CONST WCHAR *filen return; } - CriticalSectionLocker<> cs(m_optionsLock); - m_options &= ~(VLD_OPT_REPORT_TO_DEBUGGER | VLD_OPT_REPORT_TO_FILE | - VLD_OPT_REPORT_TO_STDOUT | VLD_OPT_UNICODE_REPORT); // clear used bits - - m_options |= option_mask & VLD_OPT_REPORT_TO_DEBUGGER; - if ( (option_mask & VLD_OPT_REPORT_TO_FILE) && ( filename != NULL )) + WCHAR path[MAX_PATH]; + UINT32 options; { - wcsncpy_s(m_reportFilePath, MAX_PATH, filename, _TRUNCATE); - m_options |= option_mask & VLD_OPT_REPORT_TO_FILE; - } - m_options |= option_mask & VLD_OPT_REPORT_TO_STDOUT; - m_options |= option_mask & VLD_OPT_UNICODE_REPORT; + CriticalSectionLocker<> cs(m_optionsLock); + m_options &= ~(VLD_OPT_REPORT_TO_DEBUGGER | VLD_OPT_REPORT_TO_FILE | + VLD_OPT_REPORT_TO_STDOUT | VLD_OPT_UNICODE_REPORT); // clear used bits - if ((m_options & VLD_OPT_UNICODE_REPORT) && !(m_options & VLD_OPT_REPORT_TO_FILE)) { - // If Unicode report encoding is enabled, then the report needs to be - // sent to a file because the debugger will not display Unicode - // characters, it will display question marks in their place instead. - m_options |= VLD_OPT_REPORT_TO_FILE; - m_status |= VLD_STATUS_FORCE_REPORT_TO_FILE; - } + m_options |= option_mask & VLD_OPT_REPORT_TO_DEBUGGER; + if ( (option_mask & VLD_OPT_REPORT_TO_FILE) && ( filename != NULL )) + { + wcsncpy_s(m_reportFilePath, MAX_PATH, filename, _TRUNCATE); + m_options |= option_mask & VLD_OPT_REPORT_TO_FILE; + } + m_options |= option_mask & VLD_OPT_REPORT_TO_STDOUT; + m_options |= option_mask & VLD_OPT_UNICODE_REPORT; - if (m_options & VLD_OPT_REPORT_TO_FILE) { - setupReporting(); - } - else if ( m_reportFile ) { //Close the previous report file if needed. - fclose(m_reportFile); - m_reportFile = NULL; + if ((m_options & VLD_OPT_UNICODE_REPORT) && !(m_options & VLD_OPT_REPORT_TO_FILE)) { + // If Unicode report encoding is enabled, then the report needs to be + // sent to a file because the debugger will not display Unicode + // characters, it will display question marks in their place instead. + m_options |= VLD_OPT_REPORT_TO_FILE; + m_status |= VLD_STATUS_FORCE_REPORT_TO_FILE; + } + wcsncpy_s(path, MAX_PATH, m_reportFilePath, _TRUNCATE); + options = m_options; } + + setReportDestination((options & VLD_OPT_REPORT_TO_FILE) ? path : NULL, options); } int VisualLeakDetector::SetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook) @@ -3490,50 +3490,52 @@ int VisualLeakDetector::SetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook) return -1; } -void VisualLeakDetector::setupReporting() +// setReportDestination - Sends the report to the file at path, or to no file +// if path is NULL, and to the debugger and stdout as the options say. Files +// are opened and closed with no VLD lock held: that allocates and frees +// through VLD's hooks, and allocation hooks take m_optionsLock. +// +// - path (IN): The report file, or NULL. +// +// - options (IN): The VLD_OPT_REPORT_* and VLD_OPT_UNICODE_REPORT options. +// +// Return Value: +// +// None. +// +VOID VisualLeakDetector::setReportDestination(LPCWSTR path, UINT32 options) { - WCHAR bom = BOM; // Unicode byte-order mark. + BOOL toDebugger = (options & VLD_OPT_REPORT_TO_DEBUGGER) != 0; + BOOL toStdout = (options & VLD_OPT_REPORT_TO_STDOUT) != 0; + bool isUnicode = (options & VLD_OPT_UNICODE_REPORT) != 0; - //Close the previous report file if needed. - if (m_reportFile) { - fclose(m_reportFile); - m_reportFile = NULL; - } + // Close the current file first; it can be the one to open again. + FILE* previous = SwapReportFile(NULL, ascii, toDebugger, toStdout); + if (previous != NULL) + fclose(previous); + if (path == NULL) + return; - // Reporting to file enabled. - if (m_options & VLD_OPT_UNICODE_REPORT) { - // Unicode data encoding has been enabled. Write the byte-order - // mark before anything else gets written to the file. Open the - // file for binary writing. - if (_wfopen_s(&m_reportFile, m_reportFilePath, L"wb") == EINVAL) { - // Couldn't open the file. - m_reportFile = NULL; - } - else if (m_reportFile) { - fwrite(&bom, sizeof(WCHAR), 1, m_reportFile); - SetReportEncoding(unicode); - } - } - else { - // Open the file in text mode for ASCII output. - if (_wfopen_s(&m_reportFile, m_reportFilePath, L"w") == EINVAL) { - // Couldn't open the file. - m_reportFile = NULL; - } - else if (m_reportFile) { - SetReportEncoding(ascii); - } - } - if (m_reportFile == NULL) { + // Unicode data encoding writes the byte-order mark before anything else, + // to a file opened for binary writing. + FILE* file = NULL; + if (_wfopen_s(&file, path, isUnicode ? L"wb" : L"w") != 0 || file == NULL) { Report(L"WARNING: Visual Leak Detector: Couldn't open report file for writing: %s\n" - L" The report will be sent to the debugger instead.\n", m_reportFilePath); + L" The report will be sent to the debugger instead.\n", path); + return; } - else { - // Set the "report" function to write to the file. - SetReportFile(m_reportFile, m_options & VLD_OPT_REPORT_TO_DEBUGGER, m_options & VLD_OPT_REPORT_TO_STDOUT); + // Allocate the buffer now: writes to the report file must not allocate + // (see SwapReportFile). + setvbuf(file, NULL, _IOFBF, 4096); + if (isUnicode) { + WCHAR bom = BOM; + fwrite(&bom, sizeof(WCHAR), 1, file); } + // Another thread may have set a file meanwhile. + previous = SwapReportFile(file, isUnicode ? unicode : ascii, toDebugger, toStdout); + if (previous != NULL) + fclose(previous); } - blockinfo_t* VisualLeakDetector::getAllocationBlockInfo(void* alloc) { // should be called under g_heapMapLock diff --git a/src/vldint.h b/src/vldint.h index 924c9af7..672eaa98 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -381,7 +381,7 @@ class VisualLeakDetector : public IMalloc static bool isFunctionIgnored(LPCWSTR functionName); blockinfo_t* findAllocedBlock(LPCVOID, __out HANDLE& heap); blockinfo_t* getAllocationBlockInfo(void* alloc); - void setupReporting(); + void setReportDestination(LPCWSTR path, UINT32 options); void checkInternalMemoryLeaks(); bool waitForAllVLDThreads(); @@ -445,7 +445,6 @@ class VisualLeakDetector : public IMalloc static patchentry_t m_ntdllImportPatch []; static patchentry_t m_ole32Patch []; static moduleentry_t m_patchTable [58]; // Table of imports patched for attaching VLD to other modules. - FILE *m_reportFile; // File where the memory leak report may be sent to. WCHAR m_reportFilePath [MAX_PATH]; // Full path and name of file to send memory leak report to. const char *m_selfTestFile; // Filename where the memory leak self-test block is leaked. int m_selfTestLine; // Line number where the memory leak self-test block is leaked. From 16ad149d9d92ec699ff75f79ab499e64a28e2b4f Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 22:32:01 -0800 Subject: [PATCH 26/91] Treat a NULL module list as empty in VLDSetModulesList wcsncpy_s with a NULL source raised an invalid parameter: a fast fail in release builds, an assertion dialog in debug builds. chaos_report_options switches the report destination between files and the debugger, including from a report hook and from several threads while others report, checks that a file gets nothing after reporting moved away from it, and passes NULL strings to the APIs. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_report_options.cpp | 148 +++++++++++++++++++++++ src/vld.cpp | 2 +- 3 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 src/tests/chaos/chaos_report_options.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index a1ce8937..2b0444b6 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -909,6 +909,7 @@ set(VLD_CHAOS_TESTS chaos_hook_heap_ops chaos_heap_flags chaos_exit_pressure + chaos_report_options ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_report_options.cpp b/src/tests/chaos/chaos_report_options.cpp new file mode 100644 index 00000000..23d89a3c --- /dev/null +++ b/src/tests/chaos/chaos_report_options.cpp @@ -0,0 +1,148 @@ +// chaos_report_options.cpp - changing the report destination while VLD reports. +// +// VLDSetReportOptions closes the report file when reporting moves away from +// it, and reopens it when a file is chosen again. Reports made afterwards, +// from any thread or from a report hook, must not touch a closed file, and +// each file must hold only what was reported while it was the destination. +// Also passes NULL to the APIs that take strings. + +#include "chaos_common.h" +#include +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 2000; +volatile LONG g_stop = 0; +wchar_t g_fileA[MAX_PATH]; +wchar_t g_fileB[MAX_PATH]; +volatile LONG g_hookSwitches = 0; + +LONGLONG FileSize(const wchar_t* path) +{ + WIN32_FILE_ATTRIBUTE_DATA data; + if (!GetFileAttributesExW(path, GetFileExInfoStandard, &data)) + { + return -1; + } + return ((LONGLONG)data.nFileSizeHigh << 32) | data.nFileSizeLow; +} + +DWORD WINAPI Switcher(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 7 + 1); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + switch (random.Below(3)) + { + case 0: + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, g_fileA); + break; + case 1: + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, g_fileB); + break; + default: + VLDSetReportOptions(VLD_OPT_REPORT_TO_DEBUGGER, NULL); + break; + } + } + return 0; +} + +DWORD WINAPI Reporter(LPVOID) +{ + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + VLDReportLeaks(); + } + return 0; +} + +DWORD WINAPI Worker(LPVOID p) +{ + INT_PTR index = (INT_PTR)p; + if (index < 2) + { + return Switcher(p); + } + if (index < 5) + { + return Reporter(p); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + return 0; +} + +int __cdecl SwitchingHook(int, wchar_t*, int*) +{ + if (InterlockedIncrement(&g_hookSwitches) % 3 == 0) + { + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, g_fileB); + } + else + { + VLDSetReportOptions(VLD_OPT_REPORT_TO_DEBUGGER, NULL); + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + wchar_t dir[MAX_PATH]; + GetTempPathW(MAX_PATH, dir); + _snwprintf_s(g_fileA, _TRUNCATE, L"%schaos_report_a_%lu.txt", dir, GetCurrentProcessId()); + _snwprintf_s(g_fileB, _TRUNCATE, L"%schaos_report_b_%lu.txt", dir, GetCurrentProcessId()); + UINT options = VLDGetOptions(); + void* leak = malloc(55); + + chaos::SetPhase("report to a file, then away from it"); + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, g_fileA); + VLDReportLeaks(); + VLDSetReportOptions(VLD_OPT_REPORT_TO_DEBUGGER, NULL); + LONGLONG sizeA = FileSize(g_fileA); + chaos::Check(sizeA > 0, "the report file is empty"); + VLDReportLeaks(); + VLDReportLeaks(); + chaos::Check(FileSize(g_fileA) == sizeA, "a report went to the file after reporting moved away from it"); + { + // A file opened now can reuse the closed report file's FILE object. + wchar_t mine[MAX_PATH]; + _snwprintf_s(mine, _TRUNCATE, L"%schaos_report_mine_%lu.txt", dir, GetCurrentProcessId()); + FILE* file = NULL; + chaos::Check(_wfopen_s(&file, mine, L"w") == 0 && file != NULL, "could not open a file"); + VLDReportLeaks(); + fclose(file); + LONGLONG mineSize = FileSize(mine); + DeleteFileW(mine); + chaos::Check(mineSize == 0, "a report went into a file the application opened"); + } + + chaos::SetPhase("NULL strings"); + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, NULL); + VLDReportLeaks(); + VLDSetModulesList(NULL, FALSE); + wchar_t modules[64]; + VLDGetModulesList(modules, _countof(modules)); + chaos::Check(modules[0] == L'\0', "VLDSetModulesList(NULL) left a module list"); + + chaos::SetPhase("a report hook that changes the report destination"); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwitchingHook); + VLDReportLeaks(); + VLDReportLeaks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwitchingHook); + + chaos::SetPhase("switching the destination while threads report"); + chaos::RunThreads(6, Worker); + + chaos::SetPhase("cleanup"); + VLDSetReportOptions(VLD_OPT_REPORT_TO_STDOUT, NULL); + VLDSetOptions(options, 256, 64); + free(leak); + DeleteFileW(g_fileA); + DeleteFileW(g_fileB); + chaos::Pass(); + return 0; +} \ No newline at end of file diff --git a/src/vld.cpp b/src/vld.cpp index 642aba51..50c97d55 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -3389,7 +3389,7 @@ void VisualLeakDetector::SetModulesList(CONST WCHAR *modules, BOOL includeModule } CriticalSectionLocker<> cs(m_optionsLock); - wcsncpy_s(m_forcedModuleList, MAXMODULELISTLENGTH, modules, _TRUNCATE); + wcsncpy_s(m_forcedModuleList, MAXMODULELISTLENGTH, (modules != NULL) ? modules : L"", _TRUNCATE); _wcslwr_s(m_forcedModuleList, MAXMODULELISTLENGTH); if (includeModules) m_options |= VLD_OPT_MODULE_LIST_INCLUDE; From 38fa7e7649a5b0237938706ed5e59186ac54988d Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 22:43:50 -0800 Subject: [PATCH 27/91] chaos tests - accept a failed in-place shrink in chaos_heap_flags HEAP_REALLOC_IN_PLACE_ONLY may fail. On ARM64 the shrink of a block in a HEAP_NO_SERIALIZE heap returns NULL; only a moved block is wrong. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_heap_flags.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tests/chaos/chaos_heap_flags.cpp b/src/tests/chaos/chaos_heap_flags.cpp index 57b4567f..f7564adb 100644 --- a/src/tests/chaos/chaos_heap_flags.cpp +++ b/src/tests/chaos/chaos_heap_flags.cpp @@ -131,7 +131,7 @@ int main() chaos::Check(grown == NULL, "an in-place reallocation to 1 MB unexpectedly succeeded"); chaos::Check(VLDGetLeaksCount() == base + 10, "a failed in-place reallocation changed the count"); void* shrunk = HeapReAlloc(noSerialize, HEAP_REALLOC_IN_PLACE_ONLY, blocks[1], 8); - chaos::Check(shrunk == blocks[1], "an in-place shrink moved the block"); + chaos::Check(shrunk == NULL || shrunk == blocks[1], "an in-place shrink moved the block"); void* zero = HeapReAlloc(noSerialize, 0, blocks[2], 0); chaos::Check(zero != NULL, "HeapReAlloc to zero bytes failed"); blocks[2] = zero; From cdf4d562c5b77d335fc71d0c7f9cb9d3c699af4f Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 23:04:59 -0800 Subject: [PATCH 28/91] Guard reads of tracked blocks against a concurrent realloc RtlReAllocateHeap and the CRT realloc free the old block before VLD remaps it under g_heapMapLock, so a leak walk can read a block whose memory was already freed and decommitted (AV in resolveStacks found by chaos_api_storm). Read CRT headers and leak dump data through an SEH-guarded copy and treat an unreadable block as freed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 74 ++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 50 insertions(+), 24 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 50c97d55..979bc5ee 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1936,16 +1936,35 @@ VOID VisualLeakDetector::reportConfig () } } +// readTrackedBlock - Copies bytes of a tracked block. A reallocation frees the +// old block before VLD remaps it, so a walk under g_heapMapLock can meet a +// block whose memory is already gone. +// +// Return Value: +// +// false if the block can no longer be read. +// +static bool readTrackedBlock (LPVOID dest, LPCVOID block, SIZE_T size) +{ + __try { + memcpy(dest, block, size); + return true; + } + __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) { // Autodetection allocations from statically linked CRT if (!info->debugCrtAlloc) { // Check if block is large enough to contain CRT debug header - if (info->size >= sizeof(crtdbgblockheader_t)) { - crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; - SIZE_T nSize = sizeof(crtdbgblockheader_t) + crtheader->size + GAPSIZE; + crtdbgblockheader_t crtheader; + if (info->size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader))) { + SIZE_T nSize = sizeof(crtdbgblockheader_t) + crtheader.size + GAPSIZE; int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); - if (_BLOCK_TYPE_IS_VALID(crtheader->use) && nValid && (nSize == info->size)) { + if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { info->debugCrtAlloc = true; info->ucrt = false; } @@ -1954,11 +1973,11 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) if (!info->debugCrtAlloc) { // Check if block is large enough to contain UCRT debug header - if (info->size >= sizeof(crtdbgblockheaderucrt_t)) { - crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; - SIZE_T nSize = sizeof(crtdbgblockheaderucrt_t) + crtheader->size + GAPSIZE; + crtdbgblockheaderucrt_t crtheader; + if (info->size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader))) { + SIZE_T nSize = sizeof(crtdbgblockheaderucrt_t) + crtheader.size + GAPSIZE; int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); - if (_BLOCK_TYPE_IS_VALID(crtheader->use) && nValid && (nSize == info->size)) { + if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { info->debugCrtAlloc = true; info->ucrt = true; } @@ -2023,15 +2042,16 @@ SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) { + // A block that can no longer be read is being freed. if (!ucrt) { - crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; - return crtheader->use; + crtdbgblockheader_t crtheader; + return readTrackedBlock(&crtheader, block, sizeof(crtheader)) ? crtheader.use : CRT_USE_FREE; } else { - crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; - return crtheader->use; + crtdbgblockheaderucrt_t crtheader; + return readTrackedBlock(&crtheader, block, sizeof(crtheader)) ? crtheader.use : CRT_USE_FREE; } } @@ -2039,13 +2059,13 @@ size_t VisualLeakDetector::getCrtBlockSize(LPCVOID block, bool ucrt) { if (!ucrt) { - crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; - return crtheader->size; + crtdbgblockheader_t crtheader; + return readTrackedBlock(&crtheader, block, sizeof(crtheader)) ? crtheader.size : 0; } else { - crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; - return crtheader->size; + crtdbgblockheaderucrt_t crtheader; + return readTrackedBlock(&crtheader, block, sizeof(crtheader)) ? crtheader.size : 0; } } @@ -2103,16 +2123,24 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S } // A report hook may free the block, so read it before the first Report. + // A block that can no longer be read is being freed. #ifdef _DEBUG SIZE_T crtRequest = 0; - if (info->debugCrtAlloc) - crtRequest = ((crtdbgblockheader_t*)block)->request; + if (info->debugCrtAlloc) { + crtdbgblockheader_t crtheader; + if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) + continue; + crtRequest = crtheader.request; + } #endif SIZE_T dumpSize = (m_maxDataDump < size) ? m_maxDataDump : size; LPBYTE dumpData = NULL; if (dumpSize != 0) { dumpData = new BYTE[dumpSize]; - memcpy(dumpData, address, dumpSize); + if (!readTrackedBlock(dumpData, address, dumpSize)) { + delete [] dumpData; + continue; + } } // It looks like a real memory leak. @@ -3608,14 +3636,12 @@ int VisualLeakDetector::resolveStacks(heapinfo_t* heapinfo) if (isDebugCrtAlloc(block, info)) { // This block is allocated to a CRT heap, so the block has a CRT // memory block header prepended to it. - crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; - if (!crtheader) - continue; + int blockUse = getCrtBlockUse(block, info->ucrt); // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise // DynamicLoader/Thread test will randomly fail with less leaks being reported. - if (CRT_USE_TYPE(crtheader->use) == CRT_USE_FREE || - CRT_USE_TYPE(crtheader->use) == CRT_USE_INTERNAL) + if (CRT_USE_TYPE(blockUse) == CRT_USE_FREE || + CRT_USE_TYPE(blockUse) == CRT_USE_INTERNAL) { // This block is marked as being used internally by the CRT. // The CRT will free the block after VLD is destroyed. From 49ad5236c89a763f0fee7d6e23dd62e8eeeb1ca2 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 23:04:59 -0800 Subject: [PATCH 29/91] Take the loader lock before g_DbgHelp in RefreshModules Reverts the order from edbe5f4. With g_DbgHelp held first, RefreshModules waited for the loader while a thread attach owned the loader and waited for the CRT heap lock, whose holder was in a hook waiting for g_DbgHelp. The order loader then g_DbgHelp matches RegisterLoadedModule and attachToLoadedModules; dbghelp no longer loads symsrv under g_DbgHelp (f7d82d5), which was the reason for the reversed order. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 979bc5ee..f2818a49 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2557,14 +2557,11 @@ NTSTATUS VisualLeakDetector::_LdrUnloadDll(IN PVOID BaseAddress) VOID VisualLeakDetector::RefreshModules() { + LoaderLock ll; + if (m_options & VLD_OPT_VLDOFF) return; - // g_DbgHelp before the loader lock: a thread holding g_DbgHelp can be - // loading a DLL for dbghelp, waiting for the thread that owns the loader. - CriticalSectionLocker dbgLocker(g_DbgHelp); - LoaderLock ll; - ModuleSet* newmodules = new ModuleSet(); newmodules->reserve(MODULE_SET_RESERVE); { From bbb409714c15be756fc1b6de168ee9dde596dcf6 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 23:30:22 -0800 Subject: [PATCH 30/91] Unmap the old address of a moved block only if it still maps that block The heap frees the old block inside the real realloc, before VLD unmaps the old address. Another thread can be handed that address and map it first; the late unmap then erased that thread's live block, so real leaks went missing. This explains the dynamic_app MultithreadLoadingTests under-count (1150 of 1152) on the x64 on ARM64 gate. The realloc hooks now record the serial number mapped at the old address before the real call, and every unmap of the old address after a move checks it. Serial numbers skip 0, which now means no block was mapped. The ARM64 early return in ~CaptureContext also unmaps the old address of a moved block, as the other disabled paths do. chaos_realloc_reuse lost leaked blocks in 8 of 10 runs before the fix and in none of 25 after. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_realloc_reuse.cpp | 117 ++++++++++++++++++++++++ src/vld.cpp | 55 ++++++++++- src/vld_hooks.cpp | 10 +- src/vldint.h | 7 +- 5 files changed, 179 insertions(+), 11 deletions(-) create mode 100644 src/tests/chaos/chaos_realloc_reuse.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 2b0444b6..a0ed3f71 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -910,6 +910,7 @@ set(VLD_CHAOS_TESTS chaos_heap_flags chaos_exit_pressure chaos_report_options + chaos_realloc_reuse ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_realloc_reuse.cpp b/src/tests/chaos/chaos_realloc_reuse.cpp new file mode 100644 index 00000000..3cba73b0 --- /dev/null +++ b/src/tests/chaos/chaos_realloc_reuse.cpp @@ -0,0 +1,117 @@ +// chaos_realloc_reuse.cpp - a realloc that moves a block must not forget a +// block another thread got at the old address. +// +// The heap frees the old block inside the real realloc, before VLD forgets +// the old address, so another thread can be handed that address first. Movers +// reallocate same-size blocks that VLD does not track, or tracked ones while +// VLD is disabled for the thread, to a larger size so they move; leakers keep +// every block they allocate. Each leaker's count must match exactly. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 3000; +const int MOVERS = 8; +const int LEAKERS = 8; +const int MAX_KEPT = 3000; +const size_t SIZE = 48; +volatile LONG g_stop = 0; + +struct Leaker +{ + HANDLE thread; + DWORD id; + int kept; + void* blocks[MAX_KEPT]; +}; +Leaker g_leakers[LEAKERS]; + +DWORD WINAPI Mover(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 31 + 7); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + bool untracked = random.Below(2) == 0; + if (untracked) + VLDDisable(); + void* block = malloc(SIZE); + if (untracked) + VLDRestore(); + else + VLDDisable(); + block = realloc(block, 4096 + random.Below(4096)); + if (!untracked) + VLDRestore(); + free(block); + } + return 0; +} + +DWORD WINAPI LeakerThread(LPVOID p) +{ + Leaker* leaker = (Leaker*)p; + while (!InterlockedCompareExchange(&g_stop, 0, 0) && leaker->kept < MAX_KEPT) + { + leaker->blocks[leaker->kept++] = malloc(SIZE); + if ((leaker->kept & 15) == 0) + Sleep(0); + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("movers and leakers"); + HANDLE movers[MOVERS]; + for (int i = 0; i < MOVERS; i++) + { + movers[i] = CreateThread(NULL, 0, Mover, (LPVOID)(INT_PTR)i, 0, NULL); + chaos::Check(movers[i] != NULL, "CreateThread failed"); + } + for (int i = 0; i < LEAKERS; i++) + { + g_leakers[i].thread = CreateThread(NULL, 0, LeakerThread, &g_leakers[i], 0, &g_leakers[i].id); + chaos::Check(g_leakers[i].thread != NULL, "CreateThread failed"); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + WaitForMultipleObjects(MOVERS, movers, TRUE, INFINITE); + for (int i = 0; i < LEAKERS; i++) + { + WaitForSingleObject(g_leakers[i].thread, INFINITE); + } + + chaos::SetPhase("counting each leaker's blocks"); + for (int i = 0; i < LEAKERS; i++) + { + UINT counted = VLDGetThreadLeaksCount(g_leakers[i].id); + if (counted != (UINT)g_leakers[i].kept) + { + char message[128]; + sprintf_s(message, "leaker %d kept %d blocks but VLD counts %u", i, g_leakers[i].kept, counted); + chaos::Fail(message); + } + } + + chaos::SetPhase("cleanup"); + for (int i = 0; i < LEAKERS; i++) + { + for (int j = 0; j < g_leakers[i].kept; j++) + { + free(g_leakers[i].blocks[j]); + } + CloseHandle(g_leakers[i].thread); + } + for (int i = 0; i < MOVERS; i++) + { + CloseHandle(movers[i]); + } + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index f2818a49..c813e9a1 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1573,6 +1573,9 @@ VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool d blockinfo->callStack = NULL; pblockInfo = blockinfo; blockinfo->threadId = threadId; + // 0 means "not mapped" to unmapMovedBlock. + if (m_requestCurr == 0) + m_requestCurr = 1; blockinfo->serialNumber = m_requestCurr++; blockinfo->size = size; blockinfo->reported = false; @@ -1811,12 +1814,12 @@ VOID VisualLeakDetector::unmapHeap (HANDLE heap) // None. // VOID VisualLeakDetector::remapBlock (HANDLE heap, LPCVOID mem, LPCVOID newmem, SIZE_T size, - bool debugcrtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo, const context_t &context) + bool debugcrtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo, SIZE_T serial, const context_t &context) { if (newmem != mem) { // The block was not reallocated in-place. Instead the old block was // freed and a new block allocated to satisfy the new size. - unmapBlock(heap, mem, context); + unmapMovedBlock(heap, mem, serial, context); mapBlock(heap, newmem, size, debugcrtalloc, ucrt, threadId, pblockInfo); return; } @@ -1875,6 +1878,42 @@ VOID VisualLeakDetector::remapBlock (HANDLE heap, LPCVOID mem, LPCVOID newmem, S pblockInfo = info; } +// getBlockSerial - Returns the serial number of the block mapped at the +// specified address, or 0 if no block is mapped there. +// +SIZE_T VisualLeakDetector::getBlockSerial (HANDLE heap, LPCVOID mem) +{ + if (NULL == mem) + return 0; + + CriticalSectionLocker<> cs(g_heapMapLock); + HeapMap::Iterator heapit = m_heapMap->find(heap); + if (heapit == m_heapMap->end()) + return 0; + BlockMap::Iterator blockit = (*heapit).second->blockMap.find(mem); + if (blockit == (*heapit).second->blockMap.end()) + return 0; + return (*blockit).second->serialNumber; +} + +// unmapMovedBlock - Unmaps the old address of a block that a reallocation +// moved. The heap frees the old block before VLD gets here, so another +// thread may already have been handed that address and mapped it; only the +// block that was mapped there before the reallocation is unmapped. +// +// - serial (IN): Serial number returned by getBlockSerial before the +// reallocation. +// +VOID VisualLeakDetector::unmapMovedBlock (HANDLE heap, LPCVOID mem, SIZE_T serial, const context_t &context) +{ + if (serial == 0) + return; + + CriticalSectionLocker<> cs(g_heapMapLock); + if (getBlockSerial(heap, mem) == serial) + unmapBlock(heap, mem, context); +} + // reportconfig - Generates a brief report summarizing Visual Leak Detector's // configuration, as loaded from the vld.ini file. // @@ -3715,6 +3754,11 @@ CaptureContext::~CaptureContext() { // ~VisualLeakDetector). Such allocations are never user leaks, so this // reports no different leak -- it only avoids the wedge-prone query. if (!g_vld.enabled() || g_DbgHelp.IsLockedByCurrentThread()) { + // Leak detection can be disabled by another thread after the inner + // hook recorded a move; the heap can hand the old address out again. + if (!g_DbgHelp.IsLockedByCurrentThread() && m_tls->blockWithoutGuard != NULL && + m_tls->newBlockWithoutGuard != NULL && m_tls->newBlockWithoutGuard != m_tls->blockWithoutGuard) + g_vld.unmapMovedBlock(m_tls->heap, m_tls->blockWithoutGuard, m_tls->blockSerial, m_tls->context); Reset(); return; } @@ -3745,7 +3789,7 @@ CaptureContext::~CaptureContext() { (m_tls->flags & VLD_TLS_DEBUGCRTALLOC) != 0, (m_tls->flags & VLD_TLS_UCRT) != 0, m_tls->threadId, - pblockInfo, m_tls->context); + pblockInfo, m_tls->blockSerial, m_tls->context); } pblockInfo->callStack.reset(callstack); @@ -3753,18 +3797,19 @@ CaptureContext::~CaptureContext() { else if (excluded && m_tls->newBlockWithoutGuard != NULL && m_tls->newBlockWithoutGuard != m_tls->blockWithoutGuard) { // An excluded module moved a tracked block; the heap can hand the old // address out again. - g_vld.unmapBlock(m_tls->heap, m_tls->blockWithoutGuard, m_tls->context); + g_vld.unmapMovedBlock(m_tls->heap, m_tls->blockWithoutGuard, m_tls->blockSerial, m_tls->context); } // Reset thread local flags and variables for the next allocation. Reset(); } -void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size) { +void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size, SIZE_T serial) { m_tls->heap = heap; m_tls->blockWithoutGuard = mem; m_tls->newBlockWithoutGuard = newmem; m_tls->size = size; + m_tls->blockSerial = serial; if ((m_tls->blockWithoutGuard) && (g_vld.m_options & VLD_OPT_TRACE_INTERNAL_FRAMES)) { // If VLD_OPT_TRACE_INTERNAL_FRAMES is specified then we capture the frame pointer upto the function that actually diff --git a/src/vld_hooks.cpp b/src/vld_hooks.cpp index 6a173119..d74d89ef 100644 --- a/src/vld_hooks.cpp +++ b/src/vld_hooks.cpp @@ -288,6 +288,7 @@ LPVOID VisualLeakDetector::_RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID PRINT_HOOKED_FUNCTION(); // Reallocate the block. + SIZE_T serial = g_DbgHelp.IsLockedByCurrentThread() ? 0 : g_vld.getBlockSerial(heap, mem); LPVOID newmem = RtlReAllocateHeap(heap, flags, mem, size); if (newmem == NULL) return newmem; @@ -296,7 +297,7 @@ LPVOID VisualLeakDetector::_RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID // The heap can hand the old address out again; forget it. CAPTURE_CONTEXT(); context_.func = reinterpret_cast(RtlReAllocateHeap); - g_vld.unmapBlock(heap, mem, context_); + g_vld.unmapMovedBlock(heap, mem, serial, context_); } return newmem; } @@ -304,7 +305,7 @@ LPVOID VisualLeakDetector::_RtlReAllocateHeap (HANDLE heap, DWORD flags, LPVOID if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls CAPTURE_CONTEXT(); CaptureContext cc(RtlReAllocateHeap, context_); - cc.Set(heap, mem, newmem, size); + cc.Set(heap, mem, newmem, size, serial); } return newmem; @@ -316,6 +317,7 @@ LPVOID VisualLeakDetector::_HeapReAlloc (HANDLE heap, DWORD flags, LPVOID mem, S PRINT_HOOKED_FUNCTION(); // Reallocate the block. + SIZE_T serial = g_DbgHelp.IsLockedByCurrentThread() ? 0 : g_vld.getBlockSerial(heap, mem); #if defined(_M_ARM64) LPVOID newmem; { @@ -336,7 +338,7 @@ LPVOID VisualLeakDetector::_HeapReAlloc (HANDLE heap, DWORD flags, LPVOID mem, S // The heap can hand the old address out again; forget it. CAPTURE_CONTEXT(); context_.func = reinterpret_cast(HeapReAlloc); - g_vld.unmapBlock(heap, mem, context_); + g_vld.unmapMovedBlock(heap, mem, serial, context_); } return newmem; } @@ -344,7 +346,7 @@ LPVOID VisualLeakDetector::_HeapReAlloc (HANDLE heap, DWORD flags, LPVOID mem, S if (!g_DbgHelp.IsLockedByCurrentThread()) { // skip dbghelp.dll calls CAPTURE_CONTEXT(); CaptureContext cc(HeapReAlloc, context_); - cc.Set(heap, mem, newmem, size); + cc.Set(heap, mem, newmem, size, serial); } return newmem; diff --git a/src/vldint.h b/src/vldint.h index 672eaa98..248351b3 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -211,6 +211,7 @@ struct tls_t { LPVOID blockWithoutGuard; // Store pointer to block. LPVOID newBlockWithoutGuard; SIZE_T size; + SIZE_T blockSerial; // Serial number mapped at blockWithoutGuard before a reallocation, 0 if none. }; // Allocation state: @@ -226,7 +227,7 @@ class CaptureContext { public: CaptureContext(void* func, context_t& context, BOOL debug = FALSE, BOOL ucrt = FALSE); ~CaptureContext(); - __forceinline void Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size); + __forceinline void Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size, SIZE_T serial = 0); private: // Disallow certain operations CaptureContext(); @@ -347,7 +348,9 @@ class VisualLeakDetector : public IMalloc VOID mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool crtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo); VOID mapHeap (HANDLE heap); VOID remapBlock (HANDLE heap, LPCVOID mem, LPCVOID newmem, SIZE_T size, - bool crtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo, const context_t &context); + bool crtalloc, bool ucrt, DWORD threadId, blockinfo_t* &pblockInfo, SIZE_T serial, const context_t &context); + SIZE_T getBlockSerial (HANDLE heap, LPCVOID mem); + VOID unmapMovedBlock (HANDLE heap, LPCVOID mem, SIZE_T serial, const context_t &context); public: VOID PatchCurrentModule(HMODULE module); private: From 185aba662e8dc2ff2332759a0061a7f9c414cfef Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 23:38:18 -0800 Subject: [PATCH 31/91] Zero the realloc serial in a new thread's TLS Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/vld.cpp b/src/vld.cpp index c813e9a1..980e6567 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1540,6 +1540,7 @@ tls_t* VisualLeakDetector::getTls () tls->oldFlags = 0x0; tls->threadId = threadId; tls->blockWithoutGuard = NULL; + tls->blockSerial = 0; TlsSetValue(m_tlsIndex, tls); } From 1e688f5cf5e9e045f7104e97a12fa26b690641c2 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Wed, 11 Nov 2026 23:47:30 -0800 Subject: [PATCH 32/91] chaos tests - move blocks through every reallocation API in chaos_realloc_reuse Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_realloc_reuse.cpp | 53 ++++++++++++++++++++++--- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/src/tests/chaos/chaos_realloc_reuse.cpp b/src/tests/chaos/chaos_realloc_reuse.cpp index 3cba73b0..778ce9cb 100644 --- a/src/tests/chaos/chaos_realloc_reuse.cpp +++ b/src/tests/chaos/chaos_realloc_reuse.cpp @@ -3,12 +3,17 @@ // // The heap frees the old block inside the real realloc, before VLD forgets // the old address, so another thread can be handed that address first. Movers -// reallocate same-size blocks that VLD does not track, or tracked ones while -// VLD is disabled for the thread, to a larger size so they move; leakers keep -// every block they allocate. Each leaker's count must match exactly. +// reallocate blocks that VLD does not track, or tracked ones while VLD is +// disabled for the thread, through every reallocation API to a larger size +// so they move; leakers keep every block they allocate. Each leaker's count +// must match exactly. #include "chaos_common.h" #include "vld.h" +#include +#include + +#pragma comment(lib, "ole32.lib") namespace { @@ -28,23 +33,59 @@ struct Leaker }; Leaker g_leakers[LEAKERS]; +enum Api { CRT_REALLOC, CRT_RECALLOC, HEAP_REALLOC, COTASKMEM_REALLOC, API_COUNT }; + +void* Allocate(Api api) +{ + switch (api) + { + case CRT_REALLOC: return malloc(SIZE); + case CRT_RECALLOC: return calloc(1, SIZE); + case HEAP_REALLOC: return HeapAlloc(GetProcessHeap(), 0, SIZE); + default: return CoTaskMemAlloc(SIZE); + } +} + +void* Reallocate(Api api, void* block, size_t size) +{ + switch (api) + { + case CRT_REALLOC: return realloc(block, size); + case CRT_RECALLOC: return _recalloc(block, 1, size); + case HEAP_REALLOC: return HeapReAlloc(GetProcessHeap(), 0, block, size); + default: return CoTaskMemRealloc(block, size); + } +} + +void Free(Api api, void* block) +{ + switch (api) + { + case CRT_REALLOC: + case CRT_RECALLOC: free(block); break; + case HEAP_REALLOC: HeapFree(GetProcessHeap(), 0, block); break; + default: CoTaskMemFree(block); break; + } +} + DWORD WINAPI Mover(LPVOID p) { chaos::Random random((unsigned)(INT_PTR)p * 31 + 7); while (!InterlockedCompareExchange(&g_stop, 0, 0)) { + Api api = (Api)random.Below(API_COUNT); bool untracked = random.Below(2) == 0; if (untracked) VLDDisable(); - void* block = malloc(SIZE); + void* block = Allocate(api); if (untracked) VLDRestore(); else VLDDisable(); - block = realloc(block, 4096 + random.Below(4096)); + void* moved = Reallocate(api, block, 4096 + random.Below(4096)); if (!untracked) VLDRestore(); - free(block); + Free(api, moved != NULL ? moved : block); } return 0; } From 9baa5f358efd02851b85ad73d002be089edaa1f0 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 00:04:54 -0800 Subject: [PATCH 33/91] Require the debug CRT no-man's land before treating a block as a CRT block isDebugCrtAlloc guesses that a block the hooks did not mark as a debug CRT allocation is one when its first bytes look like a debug header. A release CRT block holds uninitialized data, which can look like the header of a freed or CRT-internal block; that leak was then skipped. This is the other source of the dynamic_app under-counts, including the single-threaded LoaderTests (17 of 18). Also require the 0xFD guard bytes the debug CRT writes on both sides of the data. chaos_fake_crt_header leaks release blocks that look like debug headers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_fake_crt_header.cpp | 65 +++++++++++++++++++++++ src/vld.cpp | 22 +++++++- 3 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 src/tests/chaos/chaos_fake_crt_header.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index a0ed3f71..21dc0d5b 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -911,6 +911,7 @@ set(VLD_CHAOS_TESTS chaos_exit_pressure chaos_report_options chaos_realloc_reuse + chaos_fake_crt_header ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_fake_crt_header.cpp b/src/tests/chaos/chaos_fake_crt_header.cpp new file mode 100644 index 00000000..bfbd71ec --- /dev/null +++ b/src/tests/chaos/chaos_fake_crt_header.cpp @@ -0,0 +1,65 @@ +// chaos_fake_crt_header.cpp - user data that looks like a CRT debug header +// must not hide a leak. +// +// Uninitialized heap memory holds whatever was there before, such as a freed +// block's CRT debug header. A leaked block whose first bytes look like a +// header of a freed or CRT-internal block must still be counted. + +#include "chaos_common.h" +#include "vld.h" +#include + +namespace +{ +// The UCRT debug heap block header. +struct FakeHeader +{ + void* next; + void* prev; + const char* file; + int line; + int use; + size_t size; + long request; + unsigned char gap[4]; +}; + +const int USES[] = { 0 /* free */, 2 /* CRT */, 3 /* ignore */ }; +const size_t BLOCK_SIZE = 96; +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("leaking blocks that look like CRT debug headers"); + void* blocks[_countof(USES)]; + for (int i = 0; i < _countof(USES); i++) + { + blocks[i] = malloc(BLOCK_SIZE); + chaos::Check(blocks[i] != NULL, "malloc failed"); + memset(blocks[i], 0, BLOCK_SIZE); + FakeHeader* header = (FakeHeader*)blocks[i]; + header->use = USES[i]; + header->size = BLOCK_SIZE - sizeof(FakeHeader) - 4; + memset(header->gap, 0xFD, sizeof(header->gap)); + } + + chaos::SetPhase("counting"); + UINT counted = VLDGetLeaksCount(); + if (counted != _countof(USES)) + { + char message[96]; + sprintf_s(message, "leaked %d blocks but VLD counts %u", (int)_countof(USES), counted); + chaos::Fail(message); + } + + chaos::SetPhase("cleanup"); + for (int i = 0; i < _countof(USES); i++) + { + free(blocks[i]); + } + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index 980e6567..cb0a2cf8 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1995,6 +1995,22 @@ static bool readTrackedBlock (LPVOID dest, LPCVOID block, SIZE_T size) } } +// hasCrtNoMansLand - Checks the no-man's land the debug CRT writes on both +// sides of a block's data. Uninitialized user data can look like a debug +// header, but is unlikely to also carry both guards. +// +static bool hasCrtNoMansLand (LPCVOID block, const unsigned char* gap, SIZE_T headerSize, SIZE_T dataSize) +{ + unsigned char trailer[GAPSIZE]; + if (!readTrackedBlock(trailer, (const BYTE*)block + headerSize + dataSize, GAPSIZE)) + return false; + for (int i = 0; i < GAPSIZE; i++) { + if (gap[i] != 0xFD || trailer[i] != 0xFD) + return false; + } + return true; +} + bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) { // Autodetection allocations from statically linked CRT @@ -2004,7 +2020,8 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) if (info->size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader))) { SIZE_T nSize = sizeof(crtdbgblockheader_t) + crtheader.size + GAPSIZE; int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); - if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { + if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size) && + hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) { info->debugCrtAlloc = true; info->ucrt = false; } @@ -2017,7 +2034,8 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) if (info->size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader))) { SIZE_T nSize = sizeof(crtdbgblockheaderucrt_t) + crtheader.size + GAPSIZE; int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); - if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { + if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size) && + hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) { info->debugCrtAlloc = true; info->ucrt = true; } From 287012c3e8f03164fee78cd4c3e4843bda3826c6 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 00:49:31 -0800 Subject: [PATCH 34/91] Check the CRT no-man's land only before skipping a block as freed or internal Requiring the guards to classify a block as a debug CRT allocation made a genuine static debug CRT block with a buffer overrun report its header as user data. Classify as before, and require intact guards only before a block whose header says freed or CRT-internal is skipped as a leak. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index cb0a2cf8..e63e8903 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1996,8 +1996,9 @@ static bool readTrackedBlock (LPVOID dest, LPCVOID block, SIZE_T size) } // hasCrtNoMansLand - Checks the no-man's land the debug CRT writes on both -// sides of a block's data. Uninitialized user data can look like a debug -// header, but is unlikely to also carry both guards. +// sides of a block's data. Uninitialized user data can look like the debug +// header of a freed or CRT-internal block, but is unlikely to also carry +// both guards; such a block must not be skipped as a leak. // static bool hasCrtNoMansLand (LPCVOID block, const unsigned char* gap, SIZE_T headerSize, SIZE_T dataSize) { @@ -2020,8 +2021,7 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) if (info->size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader))) { SIZE_T nSize = sizeof(crtdbgblockheader_t) + crtheader.size + GAPSIZE; int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); - if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size) && - hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) { + if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { info->debugCrtAlloc = true; info->ucrt = false; } @@ -2034,8 +2034,7 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) if (info->size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader))) { SIZE_T nSize = sizeof(crtdbgblockheaderucrt_t) + crtheader.size + GAPSIZE; int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); - if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size) && - hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) { + if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { info->debugCrtAlloc = true; info->ucrt = true; } @@ -2101,16 +2100,30 @@ SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) { // A block that can no longer be read is being freed. + int use; if (!ucrt) { crtdbgblockheader_t crtheader; - return readTrackedBlock(&crtheader, block, sizeof(crtheader)) ? crtheader.use : CRT_USE_FREE; + if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) + return CRT_USE_FREE; + use = crtheader.use; + if (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL) { + if (!hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) + use = CRT_USE_NORMAL; + } } else { crtdbgblockheaderucrt_t crtheader; - return readTrackedBlock(&crtheader, block, sizeof(crtheader)) ? crtheader.use : CRT_USE_FREE; + if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) + return CRT_USE_FREE; + use = crtheader.use; + if (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL) { + if (!hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) + use = CRT_USE_NORMAL; + } } + return use; } size_t VisualLeakDetector::getCrtBlockSize(LPCVOID block, bool ucrt) From 97f14108622c32de76baaf74711b9d6439ffb65b Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 01:00:58 -0800 Subject: [PATCH 35/91] chaos tests - count blocks from the less common CRT allocation APIs Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_crt_odd_apis.cpp | 142 +++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 src/tests/chaos/chaos_crt_odd_apis.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 21dc0d5b..c67ebd82 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -912,6 +912,7 @@ set(VLD_CHAOS_TESTS chaos_report_options chaos_realloc_reuse chaos_fake_crt_header + chaos_crt_odd_apis ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_crt_odd_apis.cpp b/src/tests/chaos/chaos_crt_odd_apis.cpp new file mode 100644 index 00000000..6302a7e6 --- /dev/null +++ b/src/tests/chaos/chaos_crt_odd_apis.cpp @@ -0,0 +1,142 @@ +// chaos_crt_odd_apis.cpp - the less common CRT allocation APIs must be +// tracked exactly. +// +// Several threads allocate through _expand, _recalloc, the aligned family, +// _strdup/_wcsdup, nothrow new and _malloca, free most blocks and +// keep a known number. VLD must count exactly the kept blocks. + +#include "chaos_common.h" +#include "vld.h" +#include +#include +#include + +namespace +{ +const int THREADS = 8; +const int ROUNDS = 400; + +struct Kept +{ + DWORD id; + int count; + void* blocks[ROUNDS]; + bool aligned[ROUNDS]; + bool isNew[ROUNDS]; +}; +Kept g_kept[THREADS]; + +void Release(void* block, bool aligned, bool isNew) +{ + if (aligned) + _aligned_free(block); + else if (isNew) + delete[] (char*)block; + else + free(block); +} + +DWORD WINAPI Worker(LPVOID p) +{ + int index = (int)(INT_PTR)p; + Kept* kept = &g_kept[index]; + kept->id = GetCurrentThreadId(); + chaos::Random random(index * 7919 + 17); + for (int round = 0; round < ROUNDS; round++) + { + void* block = NULL; + bool aligned = false; + bool isNew = false; + switch (random.Below(8)) + { + case 0: + block = malloc(256); + if (block != NULL && _expand(block, 64 + random.Below(150)) == NULL) + { + // The block stays as it was. + } + break; + case 1: + block = _recalloc(NULL, 4, 16); + block = _recalloc(block, 8 + random.Below(64), 16); + break; + case 2: + block = _aligned_malloc(40 + random.Below(400), (size_t)16 << random.Below(5)); + block = _aligned_realloc(block, 900 + random.Below(900), 64); + aligned = true; + break; + case 3: + block = _aligned_offset_malloc(100, 32, 8); + block = _aligned_offset_realloc(block, 2000, 32, 8); + aligned = true; + break; + case 4: + block = _strdup("chaos_crt_odd_apis"); + break; + case 5: + block = _wcsdup(L"chaos_crt_odd_apis"); + break; + case 6: + block = _aligned_recalloc(NULL, 3, 40, 32); + block = _aligned_recalloc(block, 30 + random.Below(60), 40, 32); + aligned = true; + break; + default: + { + block = new (std::nothrow) char[1 + random.Below(500)]; + isNew = true; + void* scratch = _malloca(64 + random.Below(4000)); + _freea(scratch); + break; + } + } + if (block == NULL) + continue; + if (random.Below(4) == 0) + { + kept->blocks[kept->count] = block; + kept->aligned[kept->count] = aligned; + kept->isNew[kept->count] = isNew; + kept->count++; + } + else + { + Release(block, aligned, isNew); + } + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("allocating through odd CRT APIs"); + chaos::RunThreads(THREADS, Worker); + + chaos::SetPhase("counting kept blocks"); + for (int i = 0; i < THREADS; i++) + { + UINT counted = VLDGetThreadLeaksCount(g_kept[i].id); + if (counted != (UINT)g_kept[i].count) + { + char message[128]; + sprintf_s(message, "thread %d kept %d blocks but VLD counts %u", i, g_kept[i].count, counted); + chaos::Fail(message); + } + } + + chaos::SetPhase("freeing kept blocks"); + for (int i = 0; i < THREADS; i++) + { + for (int j = 0; j < g_kept[i].count; j++) + { + Release(g_kept[i].blocks[j], g_kept[i].aligned[j], g_kept[i].isNew[j]); + } + chaos::Check(VLDGetThreadLeaksCount(g_kept[i].id) == 0, "freed blocks are still counted"); + } + chaos::Pass(); + return 0; +} From c6f3f1999057e2860288f444595e70fb9fb26dbc Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 01:02:40 -0800 Subject: [PATCH 36/91] chaos tests - report and resolve leaks from a DLL that keeps unloading Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_unload_report.cpp | 113 ++++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 src/tests/chaos/chaos_unload_report.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index c67ebd82..8adb9b53 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -913,6 +913,7 @@ set(VLD_CHAOS_TESTS chaos_realloc_reuse chaos_fake_crt_header chaos_crt_odd_apis + chaos_unload_report ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_unload_report.cpp b/src/tests/chaos/chaos_unload_report.cpp new file mode 100644 index 00000000..22147521 --- /dev/null +++ b/src/tests/chaos/chaos_unload_report.cpp @@ -0,0 +1,113 @@ +// chaos_unload_report.cpp - reporting and resolving leaks whose call stacks +// run through a DLL that other threads keep unloading and reloading. +// +// Loaders leak blocks from chaos_helper_dll and unload it, so the call stacks +// point into code that is gone, or into a newer copy of the DLL at the same +// or another address. Reporters report, count and resolve the whole time. +// Afterwards every leaked block must still be counted. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 3000; +const int LOADERS = 4; +const int REPORTERS = 3; +const int MAX_LEAKS = 4000; +volatile LONG g_stop = 0; +volatile LONG g_leaked = 0; + +typedef void* (*HelperMalloc_t)(size_t); + +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} + +DWORD WINAPI Loader(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 53 + 11); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + HMODULE helper = LoadLibraryW(L"chaos_helper_dll.dll"); + chaos::Check(helper != NULL, "LoadLibrary(chaos_helper_dll) failed"); + HelperMalloc_t helperMalloc = (HelperMalloc_t)GetProcAddress(helper, "HelperMalloc"); + chaos::Check(helperMalloc != NULL, "HelperMalloc not found"); + int count = 1 + random.Below(4); + for (int i = 0; i < count; i++) + { + if (InterlockedIncrement(&g_leaked) > MAX_LEAKS) + { + InterlockedDecrement(&g_leaked); + break; + } + chaos::Check(helperMalloc(16 + random.Below(200)) != NULL, "HelperMalloc failed"); + } + FreeLibrary(helper); + } + return 0; +} + +DWORD WINAPI Reporter(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 29 + 5); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + switch (random.Below(4)) + { + case 0: + VLDReportLeaks(); + break; + case 1: + VLDGetLeaksCount(); + break; + case 2: + VLDResolveCallstacks(); + break; + default: + VLDRefreshModules(); + break; + } + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("unloading while reporting"); + HANDLE threads[LOADERS + REPORTERS]; + for (int i = 0; i < LOADERS + REPORTERS; i++) + { + threads[i] = CreateThread(NULL, 0, i < LOADERS ? Loader : Reporter, (LPVOID)(INT_PTR)i, 0, NULL); + chaos::Check(threads[i] != NULL, "CreateThread failed"); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + WaitForMultipleObjects(LOADERS + REPORTERS, threads, TRUE, INFINITE); + + chaos::SetPhase("counting leaks from the unloaded DLL"); + UINT counted = VLDGetLeaksCount(); + if (counted != (UINT)g_leaked) + { + char message[96]; + sprintf_s(message, "leaked %ld blocks but VLD counts %u", g_leaked, counted); + chaos::Fail(message); + } + chaos::Check(VLDReportLeaks() == counted, "VLDReportLeaks disagrees with VLDGetLeaksCount"); + + chaos::SetPhase("cleanup"); + VLDMarkAllLeaksAsReported(); + for (int i = 0; i < LOADERS + REPORTERS; i++) + { + CloseHandle(threads[i]); + } + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} From 016835768ad99e5c3bc3e5c762dd448e652c2d68 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 01:03:29 -0800 Subject: [PATCH 37/91] chaos tests - allocations that throw through the hooks Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_alloc_throw.cpp | 143 ++++++++++++++++++++++++++ 2 files changed, 144 insertions(+) create mode 100644 src/tests/chaos/chaos_alloc_throw.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 8adb9b53..792a620e 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -914,6 +914,7 @@ set(VLD_CHAOS_TESTS chaos_fake_crt_header chaos_crt_odd_apis chaos_unload_report + chaos_alloc_throw ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_alloc_throw.cpp b/src/tests/chaos/chaos_alloc_throw.cpp new file mode 100644 index 00000000..b7804315 --- /dev/null +++ b/src/tests/chaos/chaos_alloc_throw.cpp @@ -0,0 +1,143 @@ +// chaos_alloc_throw.cpp - allocations that fail by throwing through VLD's +// hooks must not disturb tracking of later allocations on the same thread. +// +// operator new throws std::bad_alloc and a HEAP_GENERATE_EXCEPTIONS heap +// raises STATUS_NO_MEMORY from inside VLD's allocation hooks. Each thread +// then leaks a known number of blocks through every path, which VLD must +// count exactly. + +#include "chaos_common.h" +#include "vld.h" +#include +#include + +namespace +{ +const int THREADS = 6; +const int ROUNDS = 300; +const size_t HUGE_SIZE = (size_t)-1 / 2; + +struct Kept +{ + DWORD id; + int count; + HANDLE heap; +}; +Kept g_kept[THREADS]; + +bool ThrowingNew() +{ + try + { + char* volatile p = new char[HUGE_SIZE]; + delete[] p; + return false; + } + catch (const std::bad_alloc&) + { + return true; + } +} + +bool RaisingHeapAlloc(HANDLE heap) +{ + __try + { + HeapAlloc(heap, HEAP_GENERATE_EXCEPTIONS, HUGE_SIZE); + return false; + } + __except (GetExceptionCode() == STATUS_NO_MEMORY ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) + { + return true; + } +} + +bool RaisingHeapReAlloc(HANDLE heap, void* block) +{ + __try + { + HeapReAlloc(heap, HEAP_GENERATE_EXCEPTIONS, block, HUGE_SIZE); + return false; + } + __except (GetExceptionCode() == STATUS_NO_MEMORY ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) + { + return true; + } +} + +DWORD WINAPI Worker(LPVOID p) +{ + Kept* kept = &g_kept[(INT_PTR)p]; + kept->id = GetCurrentThreadId(); + kept->heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS, 0, 0); + chaos::Check(kept->heap != NULL, "HeapCreate failed"); + chaos::Random random((unsigned)(INT_PTR)p * 101 + 3); + for (int round = 0; round < ROUNDS; round++) + { + switch (random.Below(4)) + { + case 0: + chaos::Check(ThrowingNew(), "new of a huge size did not throw"); + break; + case 1: + chaos::Check(RaisingHeapAlloc(kept->heap), "HeapAlloc of a huge size did not raise"); + break; + case 2: + { + void* block = HeapAlloc(kept->heap, 0, 64); + chaos::Check(block != NULL, "HeapAlloc failed"); + chaos::Check(RaisingHeapReAlloc(kept->heap, block), "HeapReAlloc to a huge size did not raise"); + HeapFree(kept->heap, 0, block); + break; + } + default: + chaos::Check(malloc(HUGE_SIZE) == NULL, "malloc of a huge size succeeded"); + break; + } + switch (random.Below(3)) + { + case 0: + chaos::Check(malloc(24) != NULL, "malloc failed"); + break; + case 1: + chaos::Check(new char[24] != NULL, "new failed"); + break; + default: + chaos::Check(HeapAlloc(kept->heap, 0, 24) != NULL, "HeapAlloc failed"); + break; + } + kept->count++; + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("failing allocations that throw through the hooks"); + chaos::RunThreads(THREADS, Worker); + + chaos::SetPhase("counting"); + for (int i = 0; i < THREADS; i++) + { + UINT counted = VLDGetThreadLeaksCount(g_kept[i].id); + if (counted != (UINT)g_kept[i].count) + { + char message[128]; + sprintf_s(message, "thread %d leaked %d blocks but VLD counts %u", i, g_kept[i].count, counted); + chaos::Fail(message); + } + } + + chaos::SetPhase("cleanup"); + VLDMarkAllLeaksAsReported(); + for (int i = 0; i < THREADS; i++) + { + HeapDestroy(g_kept[i].heap); + } + chaos::Pass(); + return 0; +} From a85bbfde4c13fcde6ab251fc642a112149c3ad17 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 01:17:59 -0800 Subject: [PATCH 38/91] chaos tests - allocations on switching fibers Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_fibers.cpp | 127 +++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 src/tests/chaos/chaos_fibers.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 792a620e..fa5aaf09 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -915,6 +915,7 @@ set(VLD_CHAOS_TESTS chaos_crt_odd_apis chaos_unload_report chaos_alloc_throw + chaos_fibers ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_fibers.cpp b/src/tests/chaos/chaos_fibers.cpp new file mode 100644 index 00000000..812093b3 --- /dev/null +++ b/src/tests/chaos/chaos_fibers.cpp @@ -0,0 +1,127 @@ +// chaos_fibers.cpp - allocations made on fibers. +// +// Each thread runs several fibers that allocate, reallocate and free, and +// switch to each other between operations, so call stacks are captured on +// fiber stacks and blocks are freed by a different fiber than allocated +// them. VLD must count each thread's kept blocks exactly. + +#include "chaos_common.h" +#include "vld.h" +#include + +namespace +{ +const int THREADS = 4; +const int FIBERS = 6; +const int ROUNDS = 300; +const int SLOTS = 16; + +struct ThreadState +{ + DWORD id; + LPVOID main; + LPVOID fibers[FIBERS]; + int done; + void* slots[SLOTS]; + int kept; +}; +ThreadState g_threads[THREADS]; + +struct FiberArg +{ + ThreadState* state; + int index; +}; +FiberArg g_args[THREADS][FIBERS]; + +void Next(ThreadState* state, int index) +{ + SwitchToFiber(state->fibers[(index + 1) % FIBERS]); +} + +VOID CALLBACK FiberProc(LPVOID p) +{ + FiberArg* arg = (FiberArg*)p; + ThreadState* state = arg->state; + chaos::Random random(arg->index * 389 + (unsigned)state->id); + for (int round = 0; round < ROUNDS; round++) + { + int slot = random.Below(SLOTS); + switch (random.Below(3)) + { + case 0: + free(state->slots[slot]); + state->slots[slot] = malloc(8 + random.Below(500)); + break; + case 1: + state->slots[slot] = realloc(state->slots[slot], 8 + random.Below(5000)); + break; + default: + chaos::Check(malloc(32) != NULL, "malloc failed"); + state->kept++; + break; + } + Next(state, arg->index); + } + state->done++; + // A finished fiber keeps passing control on until every fiber is done. + for (;;) + { + if (state->done == FIBERS) + SwitchToFiber(state->main); + Next(state, arg->index); + } +} + +DWORD WINAPI Worker(LPVOID p) +{ + ThreadState* state = &g_threads[(INT_PTR)p]; + state->id = GetCurrentThreadId(); + state->main = ConvertThreadToFiber(NULL); + chaos::Check(state->main != NULL, "ConvertThreadToFiber failed"); + for (int i = 0; i < FIBERS; i++) + { + g_args[(INT_PTR)p][i].state = state; + g_args[(INT_PTR)p][i].index = i; + state->fibers[i] = CreateFiber(64 * 1024, FiberProc, &g_args[(INT_PTR)p][i]); + chaos::Check(state->fibers[i] != NULL, "CreateFiber failed"); + } + SwitchToFiber(state->fibers[0]); + for (int i = 0; i < FIBERS; i++) + { + DeleteFiber(state->fibers[i]); + } + for (int i = 0; i < SLOTS; i++) + { + free(state->slots[i]); + state->slots[i] = NULL; + } + ConvertFiberToThread(); + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("fibers allocating and switching"); + chaos::RunThreads(THREADS, Worker); + + chaos::SetPhase("counting"); + for (int i = 0; i < THREADS; i++) + { + UINT counted = VLDGetThreadLeaksCount(g_threads[i].id); + if (counted != (UINT)g_threads[i].kept) + { + char message[128]; + sprintf_s(message, "thread %d kept %d blocks but VLD counts %u", i, g_threads[i].kept, counted); + chaos::Fail(message); + } + } + + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} From 087ea60270da3572780564f02664a13c24c5e098 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 01:19:05 -0800 Subject: [PATCH 39/91] chaos tests - leak and report under extreme option values Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_option_extremes.cpp | 73 +++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 src/tests/chaos/chaos_option_extremes.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index fa5aaf09..5487bd7a 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -916,6 +916,7 @@ set(VLD_CHAOS_TESTS chaos_unload_report chaos_alloc_throw chaos_fibers + chaos_option_extremes ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_option_extremes.cpp b/src/tests/chaos/chaos_option_extremes.cpp new file mode 100644 index 00000000..b10673bc --- /dev/null +++ b/src/tests/chaos/chaos_option_extremes.cpp @@ -0,0 +1,73 @@ +// chaos_option_extremes.cpp - extreme option values must not break tracking +// or reporting. +// +// Leaks are made and reported under trace depths of 0, 1 and 65535 frames, +// data dumps of 0 bytes and of more than the block, with the safe and the +// fast stack walker, with and without duplicate aggregation. Counts must be +// exact and reporting must not crash or hang. + +#include "chaos_common.h" +#include "vld.h" +#include + +namespace +{ +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} + +__declspec(noinline) void* Recurse(int depth, size_t size) +{ + if (depth == 0) + return malloc(size); + void* volatile result = Recurse(depth - 1, size); + return result; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + UINT options = VLDGetOptions(); + + const UINT frames[] = { 0, 1, 2, 64, 65535 }; + const SIZE_T dumps[] = { 0, 1, 4096, (SIZE_T)-1 }; + const UINT flags[] = { 0, VLD_OPT_SAFE_STACK_WALK, VLD_OPT_AGGREGATE_DUPLICATES, VLD_OPT_SAFE_STACK_WALK | VLD_OPT_AGGREGATE_DUPLICATES }; + + chaos::SetPhase("leaking and reporting under extreme options"); + for (int f = 0; f < _countof(frames); f++) + { + for (int d = 0; d < _countof(dumps); d++) + { + for (int o = 0; o < _countof(flags); o++) + { + VLDMarkAllLeaksAsReported(); + VLDSetOptions(VLD_OPT_SAFE_STACK_WALK | VLD_OPT_AGGREGATE_DUPLICATES, 0, 0); + VLDSetOptions(flags[o], dumps[d], frames[f]); + void* blocks[5]; + for (int i = 0; i < 5; i++) + { + blocks[i] = Recurse(i * 40, 33); + chaos::Check(blocks[i] != NULL, "malloc failed"); + } + chaos::Check(VLDGetLeaksCount() == 5, "VLDGetLeaksCount is not 5"); + chaos::Check(VLDReportLeaks() == 5, "VLDReportLeaks is not 5"); + VLDResolveCallstacks(); + for (int i = 0; i < 5; i++) + { + free(blocks[i]); + } + chaos::Check(VLDGetLeaksCount() == 0, "freed blocks are still counted"); + } + } + } + + chaos::SetPhase("cleanup"); + VLDSetOptions(VLD_OPT_SAFE_STACK_WALK | VLD_OPT_AGGREGATE_DUPLICATES, 0, 0); + VLDSetOptions(options, 256, 64); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} From 6bc7fae99ed587ee22efd20a74eb3e41d60a83a2 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 01:45:25 -0800 Subject: [PATCH 40/91] chaos tests - report tens of thousands of leaks under the watchdog Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_many_leaks.cpp | 70 ++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 src/tests/chaos/chaos_many_leaks.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 5487bd7a..45fbebee 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -917,6 +917,7 @@ set(VLD_CHAOS_TESTS chaos_alloc_throw chaos_fibers chaos_option_extremes + chaos_many_leaks ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_many_leaks.cpp b/src/tests/chaos/chaos_many_leaks.cpp new file mode 100644 index 00000000..6436f959 --- /dev/null +++ b/src/tests/chaos/chaos_many_leaks.cpp @@ -0,0 +1,70 @@ +// chaos_many_leaks.cpp - reporting many leaks must finish in bounded time. +// +// Leaks tens of thousands of blocks from a few call sites, with and without +// duplicate aggregation, and reports, counts and resolves them, each under +// the watchdog. Quadratic work in the report path shows up as a hang. + +#include "chaos_common.h" +#include "vld.h" +#include + +namespace +{ +const int LEAKS = 20000; +void* g_blocks[LEAKS]; + +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} + +__declspec(noinline) void* SiteA(size_t size) { return malloc(size); } +__declspec(noinline) void* SiteB(size_t size) { return malloc(size); } +__declspec(noinline) void* SiteC(size_t size) { return malloc(size); } +} + +int main() +{ + chaos::StartWatchdog(28000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + UINT options = VLDGetOptions(); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("leaking"); + for (int i = 0; i < LEAKS; i++) + { + switch (i % 3) + { + case 0: g_blocks[i] = SiteA(24); break; + case 1: g_blocks[i] = SiteB(40); break; + default: g_blocks[i] = SiteC(24 + (i % 5) * 8); break; + } + chaos::Check(g_blocks[i] != NULL, "malloc failed"); + } + + chaos::SetPhase("counting"); + chaos::Check(VLDGetLeaksCount() == LEAKS, "VLDGetLeaksCount is wrong"); + + chaos::SetPhase("reporting with aggregation"); + VLDSetOptions(options | VLD_OPT_AGGREGATE_DUPLICATES, 16, 16); + chaos::Check(VLDReportLeaks() == LEAKS, "VLDReportLeaks with aggregation is wrong"); + + chaos::SetPhase("resolving"); + VLDResolveCallstacks(); + + chaos::SetPhase("reporting without aggregation"); + VLDSetOptions(options & ~VLD_OPT_AGGREGATE_DUPLICATES, 0, 16); + chaos::Check(VLDReportLeaks() == LEAKS, "VLDReportLeaks without aggregation is wrong"); + + chaos::SetPhase("freeing"); + for (int i = 0; i < LEAKS; i++) + { + free(g_blocks[i]); + } + chaos::Check(VLDGetLeaksCount() == 0, "freed blocks are still counted"); + + VLDSetOptions(options, 256, 64); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} From 0b11a471cde411bc10579528dc8748f20b4fb9a2 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 02:38:37 -0800 Subject: [PATCH 41/91] Do not crash on GetProcAddress by ordinal for patched modules _GetProcAddress and _GetProcAddressForCaller passed an ordinal request to strcmp against every named patch table entry, so GetProcAddress(kernel32, MAKEINTRESOURCEA(n)) crashed any process running VLD. Compare names with names and ordinals with ordinals; a name and an ordinal match when they resolve to the same export, so an allocation API found by ordinal is hooked like the same API found by name. chaos_proc_ordinal looks up every export of the patched modules by ordinal and allocates through HeapAlloc found by ordinal. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_proc_ordinal.cpp | 77 ++++++++++++++++++++++++++ src/vld.cpp | 53 +++++++++--------- 3 files changed, 103 insertions(+), 28 deletions(-) create mode 100644 src/tests/chaos/chaos_proc_ordinal.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 45fbebee..0ed2ddda 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -918,6 +918,7 @@ set(VLD_CHAOS_TESTS chaos_fibers chaos_option_extremes chaos_many_leaks + chaos_proc_ordinal ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_proc_ordinal.cpp b/src/tests/chaos/chaos_proc_ordinal.cpp new file mode 100644 index 00000000..d9990a34 --- /dev/null +++ b/src/tests/chaos/chaos_proc_ordinal.cpp @@ -0,0 +1,77 @@ +// chaos_proc_ordinal.cpp - GetProcAddress by ordinal on modules VLD patches. +// +// Looks up every export of the modules whose imports VLD replaces by ordinal +// instead of by name. The lookup must not crash, and an allocation API found +// by ordinal must be tracked like the same API found by name. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +typedef LPVOID (WINAPI *HeapAlloc_t)(HANDLE, DWORD, SIZE_T); + +// Returns the ordinal of a named export, or 0. +WORD OrdinalOf(HMODULE module, const char* name) +{ + BYTE* base = (BYTE*)module; + IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + ((IMAGE_DOS_HEADER*)base)->e_lfanew); + IMAGE_DATA_DIRECTORY dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (dir.VirtualAddress == 0) + return 0; + IMAGE_EXPORT_DIRECTORY* exports = (IMAGE_EXPORT_DIRECTORY*)(base + dir.VirtualAddress); + DWORD* names = (DWORD*)(base + exports->AddressOfNames); + WORD* ordinals = (WORD*)(base + exports->AddressOfNameOrdinals); + for (DWORD i = 0; i < exports->NumberOfNames; i++) + { + if (strcmp((const char*)(base + names[i]), name) == 0) + return (WORD)(exports->Base + ordinals[i]); + } + return 0; +} + +void LookUpAllOrdinals(HMODULE module) +{ + BYTE* base = (BYTE*)module; + IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + ((IMAGE_DOS_HEADER*)base)->e_lfanew); + IMAGE_DATA_DIRECTORY dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (dir.VirtualAddress == 0) + return; + IMAGE_EXPORT_DIRECTORY* exports = (IMAGE_EXPORT_DIRECTORY*)(base + dir.VirtualAddress); + for (DWORD i = 0; i < exports->NumberOfFunctions; i++) + { + GetProcAddress(module, MAKEINTRESOURCEA(exports->Base + i)); + } +} +} + +int main() +{ + chaos::StartWatchdog(20000); + + const wchar_t* modules[] = { L"kernel32.dll", L"kernelbase.dll", L"ntdll.dll", L"ucrtbase.dll", + L"ucrtbased.dll", L"msvcrt.dll", L"ole32.dll", L"combase.dll", L"vcruntime140.dll", L"vcruntime140d.dll" }; + chaos::SetPhase("GetProcAddress by ordinal for every export"); + for (int i = 0; i < _countof(modules); i++) + { + HMODULE module = GetModuleHandleW(modules[i]); + if (module != NULL) + LookUpAllOrdinals(module); + } + + chaos::SetPhase("allocating through HeapAlloc found by ordinal"); + HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); + WORD ordinal = OrdinalOf(kernel32, "HeapAlloc"); + chaos::Check(ordinal != 0, "HeapAlloc has no ordinal"); + HeapAlloc_t heapAlloc = (HeapAlloc_t)GetProcAddress(kernel32, MAKEINTRESOURCEA(ordinal)); + chaos::Check(heapAlloc != NULL, "GetProcAddress(HeapAlloc ordinal) failed"); + VLDMarkAllLeaksAsReported(); + void* block = heapAlloc(GetProcessHeap(), 0, 40); + chaos::Check(block != NULL, "HeapAlloc failed"); + chaos::Check(VLDGetLeaksCount() == 1, "a block from HeapAlloc found by ordinal is not tracked"); + HeapFree(GetProcessHeap(), 0, block); + chaos::Check(VLDGetLeaksCount() == 0, "the freed block is still counted"); + + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index e63e8903..172eac6e 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2441,6 +2441,23 @@ BOOL VisualLeakDetector::detachFromModule (PCWSTR /*modulepath*/, DWORD64 module // //////////////////////////////////////////////////////////////////////////////// +// matchesProcName - Checks whether a GetProcAddress request names the import +// of a patch table entry. Either can be a name or an ordinal; a name and an +// ordinal match when they resolve to the same export. +// +// - original (IN): Address the real GetProcAddress returned for procname. +// +static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPCSTR procname, FARPROC original) +{ + bool entryIsOrdinal = HIWORD(patchentry->importName) == 0; + bool requestIsOrdinal = HIWORD(procname) == 0; + if (entryIsOrdinal && requestIsOrdinal) + return (UINT_PTR)patchentry->importName == (UINT_PTR)procname; + if (!entryIsOrdinal && !requestIsOrdinal) + return strcmp(patchentry->importName, procname) == 0; + return g_vld._RGetProcAddress(module, patchentry->importName) == original; +} + // _GetProcAddress - Calls to GetProcAddress are patched through to this // function. If the requested function is a function that has been patched // through to one of VLD's handlers, then the address of VLD's handler @@ -2478,20 +2495,10 @@ FARPROC VisualLeakDetector::_GetProcAddress (HMODULE module, LPCSTR procname) // imports name matches the entry's import name (or ordinal), then // return the address of the replacement instead of the address of the // actual import. - if (HIWORD(patchentry->importName) == 0) { - // Import name is a function ordinal value. - if ((UINT_PTR)patchentry->importName == (UINT_PTR)procname) { - if (patchentry->original != NULL) - *patchentry->original = original; - return (FARPROC)patchentry->replacement; - } - } else { - // Import name is a function name value. - if (strcmp(patchentry->importName, procname) == 0) { - if (patchentry->original != NULL) - *patchentry->original = original; - return (FARPROC)patchentry->replacement; - } + if (matchesProcName(module, patchentry, procname, original)) { + if (patchentry->original != NULL) + *patchentry->original = original; + return (FARPROC)patchentry->replacement; } patchentry++; } @@ -2546,20 +2553,10 @@ FARPROC VisualLeakDetector::_GetProcAddressForCaller(HMODULE module, LPCSTR proc // imports name matches the entry's import name (or ordinal), then // return the address of the replacement instead of the address of the // actual import. - if (HIWORD(patchentry->importName) == 0) { - // Import name is a function ordinal value. - if ((UINT_PTR)patchentry->importName == (UINT_PTR)procname) { - if (patchentry->original != NULL) - *patchentry->original = original; - return (FARPROC)patchentry->replacement; - } - } else { - // Import name is a function name value. - if (strcmp(patchentry->importName, procname) == 0) { - if (patchentry->original != NULL) - *patchentry->original = original; - return (FARPROC)patchentry->replacement; - } + if (matchesProcName(module, patchentry, procname, original)) { + if (patchentry->original != NULL) + *patchentry->original = original; + return (FARPROC)patchentry->replacement; } patchentry++; } From 2acda92d0c910ff5d86791e68363c88190e95e06 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 02:41:33 -0800 Subject: [PATCH 42/91] Report a leak whose data cannot be read instead of skipping it The guarded copy from cdf4d56 skipped a leak whose data could not be read, taking it for a block being freed. A live block can have pages the application made inaccessible, so VLDReportLeaks then disagreed with VLDGetLeaksCount. Report the leak and note that its data is not readable. chaos_noaccess_leak leaks a block with a PAGE_NOACCESS interior page. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_noaccess_leak.cpp | 51 +++++++++++++++++++++++++ src/vld.cpp | 8 +++- 3 files changed, 58 insertions(+), 2 deletions(-) create mode 100644 src/tests/chaos/chaos_noaccess_leak.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 0ed2ddda..2f697877 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -919,6 +919,7 @@ set(VLD_CHAOS_TESTS chaos_option_extremes chaos_many_leaks chaos_proc_ordinal + chaos_noaccess_leak ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_noaccess_leak.cpp b/src/tests/chaos/chaos_noaccess_leak.cpp new file mode 100644 index 00000000..b74a0911 --- /dev/null +++ b/src/tests/chaos/chaos_noaccess_leak.cpp @@ -0,0 +1,51 @@ +// chaos_noaccess_leak.cpp - a leaked block with inaccessible pages is still +// a leak. +// +// The application makes an interior page of a large leaked block +// PAGE_NOACCESS. Counting and reporting must agree on the leak, with a data +// dump that spans the page. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + UINT options = VLDGetOptions(); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("leaking a block with an inaccessible page"); + const SIZE_T size = 64 * 1024; + BYTE* block = (BYTE*)HeapAlloc(GetProcessHeap(), 0, size); + chaos::Check(block != NULL, "HeapAlloc failed"); + SYSTEM_INFO si; + GetSystemInfo(&si); + BYTE* page = (BYTE*)(((UINT_PTR)block + 2 * si.dwPageSize) & ~((UINT_PTR)si.dwPageSize - 1)); + DWORD old = 0; + chaos::Check(VirtualProtect(page, si.dwPageSize, PAGE_NOACCESS, &old) != FALSE, "VirtualProtect failed"); + + chaos::SetPhase("counting and reporting"); + VLDSetOptions(options, size, 64); + UINT counted = VLDGetLeaksCount(); + UINT reported = VLDReportLeaks(); + + chaos::SetPhase("cleanup"); + VirtualProtect(page, si.dwPageSize, old, &old); + VLDSetOptions(options, 256, 64); + chaos::Check(counted == 1, "VLDGetLeaksCount is not 1"); + chaos::Check(reported == 1, "VLDReportLeaks skipped a leak whose data is not readable"); + HeapFree(GetProcessHeap(), 0, block); + chaos::Check(VLDGetLeaksCount() == 0, "the freed block is still counted"); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} diff --git a/src/vld.cpp b/src/vld.cpp index 172eac6e..a0547059 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2209,8 +2209,9 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S if (dumpSize != 0) { dumpData = new BYTE[dumpSize]; if (!readTrackedBlock(dumpData, address, dumpSize)) { + // A live block can have pages the application made inaccessible. delete [] dumpData; - continue; + dumpData = NULL; } } @@ -2251,7 +2252,10 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S info->callStack->dump(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); // Dump the data in the user data section of the memory block. - if (m_maxDataDump != 0) { + if (m_maxDataDump != 0 && dumpData == NULL && dumpSize != 0) { + Report(L" Data: (not readable)\n"); + } + else if (m_maxDataDump != 0) { Report(L" Data:\n"); if (m_options & VLD_OPT_UNICODE_REPORT) { DumpMemoryW(dumpData, dumpSize); From f324457e448034cda122bb3eed4bda1745648aa5 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 02:43:52 -0800 Subject: [PATCH 43/91] chaos tests - leaks from over-aligned operator new Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_aligned_new.cpp | 53 +++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/tests/chaos/chaos_aligned_new.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 2f697877..f88dd029 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -920,6 +920,7 @@ set(VLD_CHAOS_TESTS chaos_many_leaks chaos_proc_ordinal chaos_noaccess_leak + chaos_aligned_new ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_aligned_new.cpp b/src/tests/chaos/chaos_aligned_new.cpp new file mode 100644 index 00000000..7fb1afea --- /dev/null +++ b/src/tests/chaos/chaos_aligned_new.cpp @@ -0,0 +1,53 @@ +// chaos_aligned_new.cpp - leaks from the over-aligned and nothrow forms of +// operator new must be counted. +// +// C++17 routes new of an over-aligned type to operator new(size_t, +// align_val_t), a separate export from the plain operator new. + +#include "chaos_common.h" +#include "vld.h" +#include + +namespace +{ +struct alignas(64) Wide +{ + char bytes[64]; +}; + +struct alignas(256) Wider +{ + char bytes[24]; +}; +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("leaking over-aligned objects"); + Wide* wide = new Wide; + Wider* wider = new Wider[3]; + Wide* nothrowWide = new (std::nothrow) Wide; + void* raw = ::operator new(40, std::align_val_t(128)); + chaos::Check(wide != NULL && wider != NULL && nothrowWide != NULL && raw != NULL, "allocation failed"); + + chaos::SetPhase("counting"); + UINT counted = VLDGetLeaksCount(); + if (counted != 4) + { + char message[96]; + sprintf_s(message, "leaked 4 over-aligned blocks but VLD counts %u", counted); + chaos::Fail(message); + } + + chaos::SetPhase("freeing"); + delete wide; + delete[] wider; + delete nothrowWide; + ::operator delete(raw, std::align_val_t(128)); + chaos::Check(VLDGetLeaksCount() == 0, "freed blocks are still counted"); + chaos::Pass(); + return 0; +} From c0ca3db3410366c9c4ac91a89ff39b9f9b63dd04 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 03:00:54 -0800 Subject: [PATCH 44/91] Check the CRT guards only for blocks guessed to be debug CRT blocks A block the hooks marked as a debug CRT allocation is one, so its freed or CRT-internal type is authoritative even when an overrun damaged its guards. Only a block classified from its first bytes needs the guards to prove the header is real. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 15 +++++++++------ src/vldint.h | 3 ++- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index a0547059..8c230a1d 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1581,6 +1581,7 @@ VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool d blockinfo->size = size; blockinfo->reported = false; blockinfo->debugCrtAlloc = debugcrtalloc; + blockinfo->crtGuessed = false; blockinfo->ucrt = ucrt; if (SIZE_MAX - m_totalAlloc > size) @@ -2023,6 +2024,7 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { info->debugCrtAlloc = true; + info->crtGuessed = true; info->ucrt = false; } } @@ -2036,6 +2038,7 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) int nValid = _CrtIsValidPointer(block, (unsigned int)info->size, TRUE); if (_BLOCK_TYPE_IS_VALID(crtheader.use) && nValid && (nSize == info->size)) { info->debugCrtAlloc = true; + info->crtGuessed = true; info->ucrt = true; } } @@ -2073,7 +2076,7 @@ SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) if (isDebugCrtAlloc(block, info)) { // This block is allocated to a CRT heap, so the block has a CRT // memory block header pretended to it. - int blockUse = getCrtBlockUse(block, info->ucrt); + int blockUse = getCrtBlockUse(block, info->ucrt, info->crtGuessed); // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise // DynamicLoader/Thread test will randomly fail with less leaks being reported. if (CRT_USE_TYPE(blockUse) == CRT_USE_FREE || @@ -2097,7 +2100,7 @@ SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) return memoryleaks; } -int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) +int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt, bool guessed) { // A block that can no longer be read is being freed. int use; @@ -2107,7 +2110,7 @@ int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) return CRT_USE_FREE; use = crtheader.use; - if (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL) { + if (guessed && (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL)) { if (!hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) use = CRT_USE_NORMAL; } @@ -2118,7 +2121,7 @@ int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt) if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) return CRT_USE_FREE; use = crtheader.use; - if (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL) { + if (guessed && (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL)) { if (!hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) use = CRT_USE_NORMAL; } @@ -2167,7 +2170,7 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S if (isDebugCrtAlloc( block, info )) { // This block is allocated to a CRT heap, so the block has a CRT // memory block header pretended to it. - int blockUse = getCrtBlockUse( block, info->ucrt ); + int blockUse = getCrtBlockUse( block, info->ucrt, info->crtGuessed ); // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise // DynamicLoader/Thread test will randomly fail with less leaks being reported. if (CRT_USE_TYPE(blockUse) == CRT_USE_FREE || @@ -3705,7 +3708,7 @@ int VisualLeakDetector::resolveStacks(heapinfo_t* heapinfo) if (isDebugCrtAlloc(block, info)) { // This block is allocated to a CRT heap, so the block has a CRT // memory block header prepended to it. - int blockUse = getCrtBlockUse(block, info->ucrt); + int blockUse = getCrtBlockUse(block, info->ucrt, info->crtGuessed); // Leaks identified as CRT_USE_IGNORE should not be ignored here otherwise // DynamicLoader/Thread test will randomly fail with less leaks being reported. diff --git a/src/vldint.h b/src/vldint.h index 248351b3..cdc723e7 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -116,6 +116,7 @@ struct blockinfo_t { bool reported; bool debugCrtAlloc; bool ucrt; + bool crtGuessed; // debugCrtAlloc was guessed from the block's first bytes. }; // BlockMaps map memory blocks (via their addresses) to blockinfo_t structures. @@ -357,7 +358,7 @@ class VisualLeakDetector : public IMalloc VOID reportConfig (); static bool isDebugCrtAlloc(LPCVOID block, blockinfo_t* info); SIZE_T reportHeapLeaks (HANDLE heap); - static int getCrtBlockUse (LPCVOID block, bool ucrt); + static int getCrtBlockUse (LPCVOID block, bool ucrt, bool guessed); static size_t getCrtBlockSize(LPCVOID block, bool ucrt); SIZE_T getLeaksCount (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); VOID collectLeakPages (Set& pages, DWORD threadId, HANDLE heap = NULL); From 4566b93d88cd29dbc885cba8387600f5bae34818 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 03:56:46 -0800 Subject: [PATCH 45/91] Match GetProcAddress ordinals against names through the export table 0b11a47 resolved a patch entry's name with GetProcAddress to compare it with an ordinal request. On ARM64 that call reaches VLD's own GetProcAddressForCaller hook in kernelbase, which resolved the name back to an ordinal the same way, until the stack overflowed (chaos_proc_ordinal on native ARM64). Look the name's ordinal up in the module's export table instead. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 39 ++++++++++++++++++++++++++++++++------- 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 8c230a1d..cd2036a8 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2448,13 +2448,36 @@ BOOL VisualLeakDetector::detachFromModule (PCWSTR /*modulepath*/, DWORD64 module // //////////////////////////////////////////////////////////////////////////////// +// exportOrdinal - Returns the ordinal of a module's export named name, or 0. +// Reads the export table directly: GetProcAddress can be hooked by VLD +// itself, through kernelbase on ARM64. +// +static UINT_PTR exportOrdinal (HMODULE module, LPCSTR name) +{ + __try { + BYTE* base = (BYTE*)module; + IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + ((IMAGE_DOS_HEADER*)base)->e_lfanew); + IMAGE_DATA_DIRECTORY dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (dir.VirtualAddress == 0) + return 0; + IMAGE_EXPORT_DIRECTORY* exports = (IMAGE_EXPORT_DIRECTORY*)(base + dir.VirtualAddress); + DWORD* names = (DWORD*)(base + exports->AddressOfNames); + WORD* ordinals = (WORD*)(base + exports->AddressOfNameOrdinals); + for (DWORD i = 0; i < exports->NumberOfNames; i++) { + if (strcmp((LPCSTR)(base + names[i]), name) == 0) + return exports->Base + ordinals[i]; + } + } + __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + } + return 0; +} + // matchesProcName - Checks whether a GetProcAddress request names the import // of a patch table entry. Either can be a name or an ordinal; a name and an -// ordinal match when they resolve to the same export. -// -// - original (IN): Address the real GetProcAddress returned for procname. +// ordinal match when the name is exported with that ordinal. // -static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPCSTR procname, FARPROC original) +static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPCSTR procname) { bool entryIsOrdinal = HIWORD(patchentry->importName) == 0; bool requestIsOrdinal = HIWORD(procname) == 0; @@ -2462,7 +2485,9 @@ static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPC return (UINT_PTR)patchentry->importName == (UINT_PTR)procname; if (!entryIsOrdinal && !requestIsOrdinal) return strcmp(patchentry->importName, procname) == 0; - return g_vld._RGetProcAddress(module, patchentry->importName) == original; + if (requestIsOrdinal) + return exportOrdinal(module, patchentry->importName) == (UINT_PTR)procname; + return exportOrdinal(module, procname) == (UINT_PTR)patchentry->importName; } // _GetProcAddress - Calls to GetProcAddress are patched through to this @@ -2502,7 +2527,7 @@ FARPROC VisualLeakDetector::_GetProcAddress (HMODULE module, LPCSTR procname) // imports name matches the entry's import name (or ordinal), then // return the address of the replacement instead of the address of the // actual import. - if (matchesProcName(module, patchentry, procname, original)) { + if (matchesProcName(module, patchentry, procname)) { if (patchentry->original != NULL) *patchentry->original = original; return (FARPROC)patchentry->replacement; @@ -2560,7 +2585,7 @@ FARPROC VisualLeakDetector::_GetProcAddressForCaller(HMODULE module, LPCSTR proc // imports name matches the entry's import name (or ordinal), then // return the address of the replacement instead of the address of the // actual import. - if (matchesProcName(module, patchentry, procname, original)) { + if (matchesProcName(module, patchentry, procname)) { if (patchentry->original != NULL) *patchentry->original = original; return (FARPROC)patchentry->replacement; From 1173596c5d8f175c0657c0e2afed183743cab01f Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 05:14:00 -0800 Subject: [PATCH 46/91] Hold g_DbgHelp while RefreshModules enumerates modules dbghelp is not thread safe, and other threads resolve symbols under g_DbgHelp while RefreshModules enumerated the loaded modules with no lock. Take g_DbgHelp after the loader lock, in the same order as attachToLoadedModules and RegisterLoadedModule. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/vld.cpp b/src/vld.cpp index cd2036a8..8eea3d7f 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2665,6 +2665,10 @@ VOID VisualLeakDetector::RefreshModules() ModuleSet* newmodules = new ModuleSet(); newmodules->reserve(MODULE_SET_RESERVE); { + // dbghelp is not thread safe; other threads resolve symbols under + // g_DbgHelp. + CriticalSectionLocker dbgLocker(g_DbgHelp); + // Duplicate code here in this method. Consider refactoring out to another method. // Create a new set of all loaded modules, including any newly loaded // modules. From 5daf4011c9a9dcfd5df85af6e8a19f129b7f93fa Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 06:13:51 -0800 Subject: [PATCH 47/91] Do not record a call-through original that leads back into VLD on ARM64 When GetProcAddress resolved a patched function, the hooks stored the real export address as the replacement's call-through original. On ARM64 a kernel32 export can be a fast-forward thunk through kernel32's own import slot, which VLD has already patched, so _HeapFree called itself until the stack overflowed (chaos_proc_ordinal on native ARM64; a lookup by name hits it too). Skip such an address, as PatchImport already does. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/utility.h | 1 + src/vld.cpp | 23 +++++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/utility.h b/src/utility.h index 7926a088..4abf5f51 100644 --- a/src/utility.h +++ b/src/utility.h @@ -172,6 +172,7 @@ LPVOID Arm64LookupKernelbaseHeapProc (LPCSTR importname); VOID DumpMemoryA (LPCVOID address, SIZE_T length); VOID DumpMemoryW (LPCVOID address, SIZE_T length); BOOL FindImport (HMODULE importmodule, HMODULE exportmodule, LPCSTR exportmodulename, LPCSTR importname); +LPVOID FindRealCode (LPVOID pCode); BOOL FindImportByExportAddress (HMODULE importmodule, LPCSTR exportmodulename, LPCVOID exportAddress); BOOL FindPatch (HMODULE importmodule, moduleentry_t* module); VOID InsertReportDelay (); diff --git a/src/vld.cpp b/src/vld.cpp index 8eea3d7f..72202e61 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2490,6 +2490,23 @@ static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPC return exportOrdinal(module, procname) == (UINT_PTR)patchentry->importName; } +// saveOriginal - Records the real address of a patched import, for VLD's +// replacement to call through to. +// +static void saveOriginal (patchentry_t* patchentry, FARPROC original) +{ + if (patchentry->original == NULL) + return; +#if defined(_M_ARM64) + // A kernel32 export can be a fast-forward thunk through kernel32's own + // import slot, which VLD has already patched; calling through it would + // make the replacement call itself. PatchImport records the real address. + if (GetCallingModule((UINT_PTR)FindRealCode((LPVOID)original)) == GetCallingModule((UINT_PTR)&saveOriginal)) + return; +#endif + *patchentry->original = original; +} + // _GetProcAddress - Calls to GetProcAddress are patched through to this // function. If the requested function is a function that has been patched // through to one of VLD's handlers, then the address of VLD's handler @@ -2528,8 +2545,7 @@ FARPROC VisualLeakDetector::_GetProcAddress (HMODULE module, LPCSTR procname) // return the address of the replacement instead of the address of the // actual import. if (matchesProcName(module, patchentry, procname)) { - if (patchentry->original != NULL) - *patchentry->original = original; + saveOriginal(patchentry, original); return (FARPROC)patchentry->replacement; } patchentry++; @@ -2586,8 +2602,7 @@ FARPROC VisualLeakDetector::_GetProcAddressForCaller(HMODULE module, LPCSTR proc // return the address of the replacement instead of the address of the // actual import. if (matchesProcName(module, patchentry, procname)) { - if (patchentry->original != NULL) - *patchentry->original = original; + saveOriginal(patchentry, original); return (FARPROC)patchentry->replacement; } patchentry++; From 38ab647d6fe0a4be2e072aacb366ceab5235a427 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 07:02:47 -0800 Subject: [PATCH 48/91] chaos tests - do not report thread churn blocks held by live threads at exit Threads that attached during the churn and still run at exit (thread pool and loader workers) keep their attach block, which the test already accepts in its count. Mark them as reported so the exit report does not list them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_thread_churn.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tests/chaos/chaos_thread_churn.cpp b/src/tests/chaos/chaos_thread_churn.cpp index e412952f..29a38372 100644 --- a/src/tests/chaos/chaos_thread_churn.cpp +++ b/src/tests/chaos/chaos_thread_churn.cpp @@ -129,6 +129,8 @@ int main() } Sleep(20); } + // Their attach blocks stay allocated past the exit report. + VLDMarkAllLeaksAsReported(); chaos::Pass(); return 0; } From b8914fddb16a884a61c2edce9579d58dfc52854e Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 07:17:55 -0800 Subject: [PATCH 49/91] Do not call dbghelp under g_heapMapLock or wait for it in allocation hooks dbghelp allocates from the process heap. An application thread that holds HeapLock on the process heap and allocates waits in VLD's hooks for g_DbgHelp (safe stack walk) or g_heapMapLock, while a reporting thread holds those locks and waits in dbghelp for the heap lock: a deadlock. Leak counting and reporting now cache the symbols of every frame of the unreported leaks before they take g_heapMapLock, and a thread that owns g_heapMapLock reads symbols only from that cache, showing a missing frame as an address. The cache is cleared when RefreshModules sees a module unload or move. The safe stack walk waits at most 100 ms for g_DbgHelp and then captures that stack with RtlCaptureStackBackTrace; after a timeout the thread only tries the lock until it gets it again. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.cpp | 291 ++++++++++++++++++++++++++++++++++++------ src/callstack.h | 25 +++- src/criticalsection.h | 8 ++ src/dbghelp.h | 4 + src/vld.cpp | 140 +++++++------------- src/vldint.h | 5 +- 6 files changed, 331 insertions(+), 142 deletions(-) diff --git a/src/callstack.cpp b/src/callstack.cpp index d94e42cd..cc0c268a 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -50,20 +50,136 @@ extern DbgHelp g_DbgHelp; extern "C" bool VldArm64InTeardownReport(void); #endif -// Defined in vld.cpp. True on the thread that holds g_heapMapLock for leak -// counting or reporting, where a deferred symbol load could deadlock. -extern "C" bool VldSymbolLoadForbidden(void); +// Symbols of call stack frames. dbghelp allocates from the process heap, so it +// must not run under g_heapMapLock: an application thread that holds the +// process heap lock (HeapLock) and allocates waits for g_heapMapLock in VLD's +// hooks. Leak counting and reporting cache the symbols of the leaks' frames +// before they take g_heapMapLock, and a thread that owns g_heapMapLock reads +// symbols only from the cache, showing a frame missing from it as an address. +struct cachedsymbol_t { + DWORD64 displacement64; + BOOL foundLine; + DWORD lineNumber; + DWORD lineDisplacement; + WCHAR* functionName; + WCHAR* fileName; +}; +typedef Map SymbolCache; +static SymbolCache* g_symbolCache = NULL; +// Guards g_symbolCache. Held only for map operations and copies, never while +// another lock is taken. +CriticalSection g_symbolCacheLock; + +static WCHAR* duplicateString(LPCWSTR source) +{ + size_t length = wcslen(source) + 1; + WCHAR* copy = new WCHAR[length]; + wcscpy_s(copy, length, source); + return copy; +} -// True when resolving programCounter would make dbghelp load deferred symbols -// on a thread where that is forbidden; the frame is then shown as an address. -static bool isSymbolLoadPending(SIZE_T programCounter, CriticalSectionLocker& locker) +static bool usesSymbolCacheOnly() { - if (!VldSymbolLoadForbidden()) - return false; - IMAGEHLP_MODULEW64 moduleInfo = { 0 }; - moduleInfo.SizeOfStruct = sizeof(moduleInfo); - return g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, programCounter, &moduleInfo, locker) && - moduleInfo.SymType == SymDeferred; + return g_heapMapLock.IsOwnedByCurrentThread(); +} + +// cacheSymbols - Looks up the symbols of the program counters that are not in +// the cache yet and adds them. Call without g_heapMapLock held. +// +// - programCounters (IN): Program counters of call stack frames. +// +// Return Value: +// +// None. +// +VOID CallStack::cacheSymbols (const Set& programCounters) +{ + BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE]; + for (Set::Iterator it = programCounters.begin(); it != programCounters.end(); ++it) { + UINT_PTR programCounter = *it; + { + CriticalSectionLocker<> cs(g_symbolCacheLock); + if (g_symbolCache != NULL && g_symbolCache->find(programCounter) != g_symbolCache->end()) + continue; + } + + cachedsymbol_t* symbol = new cachedsymbol_t; + IMAGEHLP_LINE64 sourceInfo = { 0 }; + sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); + { + CriticalSectionLocker locker(g_DbgHelp); + symbol->functionName = duplicateString(getFunctionName(programCounter, symbol->displacement64, + (SYMBOL_INFO*)symbolBuffer, locker)); + symbol->lineDisplacement = 0; + symbol->foundLine = FALSE; +#if defined(_M_ARM64) + if (!VldArm64InTeardownReport()) +#endif + symbol->foundLine = g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, + &symbol->lineDisplacement, &sourceInfo, locker); + symbol->lineNumber = symbol->foundLine ? sourceInfo.LineNumber : 0; + symbol->fileName = (symbol->foundLine && sourceInfo.FileName != NULL) ? + duplicateString(sourceInfo.FileName) : NULL; + if (symbol->fileName == NULL) + symbol->foundLine = FALSE; + } + + CriticalSectionLocker<> cs(g_symbolCacheLock); + if (g_symbolCache == NULL) + g_symbolCache = new SymbolCache; + if (g_symbolCache->find(programCounter) == g_symbolCache->end()) { + g_symbolCache->insert(programCounter, symbol); + continue; + } + cs.Leave(); + delete [] symbol->functionName; + delete [] symbol->fileName; + delete symbol; + } +} + +// areSymbolsCached - Checks that the cache has every program counter. +// +// - programCounters (IN): Program counters of call stack frames. +// +// Return Value: +// +// Returns true if every program counter is in the cache. +// +bool CallStack::areSymbolsCached (const Set& programCounters) +{ + CriticalSectionLocker<> cs(g_symbolCacheLock); + for (Set::Iterator it = programCounters.begin(); it != programCounters.end(); ++it) { + if (g_symbolCache == NULL || g_symbolCache->find(*it) == g_symbolCache->end()) + return false; + } + return true; +} + +// clearSymbolCache - Empties the cache, whose symbols can be stale once modules +// unload and others load at their addresses. +// +// Return Value: +// +// None. +// +VOID CallStack::clearSymbolCache () +{ + SymbolCache* cache; + { + CriticalSectionLocker<> cs(g_symbolCacheLock); + cache = g_symbolCache; + g_symbolCache = NULL; + } + if (cache == NULL) + return; + for (SymbolCache::Iterator it = cache->begin(); it != cache->end(); ++it) { + cachedsymbol_t* symbol = (*it).second; + delete [] symbol->functionName; + delete [] symbol->fileName; + delete symbol; + } + delete cache; } // Helper function to compare the begin of a string with a substring @@ -226,8 +342,70 @@ VOID CallStack::clear () m_resolvedLength = 0; } +// getFunctionName - Names the function of a program counter from the symbol +// cache. If the cache does not have it, asks dbghelp, or uses the address on +// a thread that owns g_heapMapLock. +LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + SYMBOL_INFO* functionInfo) +{ + displacement64 = 0; + { + CriticalSectionLocker<> cs(g_symbolCacheLock); + if (g_symbolCache != NULL) { + SymbolCache::Iterator it = g_symbolCache->find(programCounter); + if (it != g_symbolCache->end()) { + displacement64 = (*it).second->displacement64; + wcsncpy_s(functionInfo->Name, MAX_SYMBOL_NAME_LENGTH, (*it).second->functionName, _TRUNCATE); + return functionInfo->Name; + } + } + } + if (!usesSymbolCacheOnly()) { + CriticalSectionLocker locker(g_DbgHelp); + return getFunctionName(programCounter, displacement64, functionInfo, locker); + } + auto result = fmt::format_to_n(functionInfo->Name, MAX_SYMBOL_NAME_LENGTH - 1, L"" ADDRESSCPPFORMAT, programCounter); + *result.out = L'\0'; + return functionInfo->Name; +} + +// getLine - Finds the source line of a program counter in the symbol cache. If +// the cache does not have it, asks dbghelp, except on a thread that owns +// g_heapMapLock. sourceInfo->FileName points to fileName on success. +BOOL CallStack::getLine(SIZE_T programCounter, DWORD& displacement, IMAGEHLP_LINEW64* sourceInfo, + LPWSTR fileName, DWORD fileNameSize) +{ + { + CriticalSectionLocker<> cs(g_symbolCacheLock); + if (g_symbolCache != NULL) { + SymbolCache::Iterator it = g_symbolCache->find(programCounter); + if (it != g_symbolCache->end()) { + if (!(*it).second->foundLine) + return FALSE; + wcsncpy_s(fileName, fileNameSize, (*it).second->fileName, _TRUNCATE); + sourceInfo->FileName = fileName; + sourceInfo->LineNumber = (*it).second->lineNumber; + displacement = (*it).second->lineDisplacement; + return TRUE; + } + } + } + if (usesSymbolCacheOnly()) + return FALSE; +#if defined(_M_ARM64) + if (VldArm64InTeardownReport()) + return FALSE; +#endif + CriticalSectionLocker locker(g_DbgHelp); + if (!g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, sourceInfo, locker)) + return FALSE; + wcsncpy_s(fileName, fileNameSize, sourceInfo->FileName, _TRUNCATE); + sourceInfo->FileName = fileName; + return TRUE; +} + LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement64, - SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker) const + SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker) { // Initialize structures passed to the symbol handler. functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO); @@ -249,8 +427,7 @@ LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement6 } #endif DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId()); - if (!isSymbolLoadPending(programCounter, locker) && - g_DbgHelp.SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo, locker)) { + if (g_DbgHelp.SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo, locker)) { functionName = functionInfo->Name; #if defined(_M_X64) // Without symbols dbghelp names ARM64EC code (x64 process on ARM64) @@ -353,11 +530,7 @@ bool CallStack::isLeakSuppressed() return false; } - IMAGEHLP_LINE64 sourceInfo = { 0 }; - sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); - BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 }; - CriticalSectionLocker locker(g_DbgHelp); // Iterate through each frame in the call stack. for (UINT32 frame = 0; frame < m_size; frame++) { @@ -373,7 +546,7 @@ bool CallStack::isLeakSuppressed() } DWORD64 displacement64; - LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, locker); + LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer); m_status |= isCrtStartupFunction(functionName); if (m_status & CALLSTACK_STATUS_STARTUPCRT) { @@ -465,7 +638,7 @@ int CallStack::resolve(BOOL showInternalFrames) static WCHAR stack_line[MAXREPORTLENGTH + 1] = L""; bool isPrevFrameInternal = false; DWORD NumChars = 0; - CriticalSectionLocker locker(g_DbgHelp); + static WCHAR fileName[MAX_PATH * 4]; const size_t max_line_length = MAXREPORTLENGTH + 1; m_resolvedCapacity = m_size * max_line_length; @@ -486,7 +659,7 @@ int CallStack::resolve(BOOL showInternalFrames) DWORD64 displacement64; BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE]; - LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, locker); + LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer); if (skipStartupLeaks) { if (!(m_status & (CALLSTACK_STATUS_STARTUPCRT | CALLSTACK_STATUS_NOTSTARTUPCRT))) { @@ -501,17 +674,8 @@ int CallStack::resolve(BOOL showInternalFrames) } } - // It turns out that calls to SymGetLineFromAddrW64 may free the very memory we are scrutinizing here - // in this method. If this is the case, m_Resolved will be null after SymGetLineFromAddrW64 returns. - // When that happens there is nothing we can do except crash. DWORD displacement = 0; - DbgTrace(L"dbghelp32.dll %i: SymGetLineFromAddrW64\n", GetCurrentThreadId()); - BOOL foundline = FALSE; -#if defined(_M_ARM64) - if (!VldArm64InTeardownReport()) -#endif - if (!isSymbolLoadPending(programCounter, locker)) - foundline = g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo, locker); + BOOL foundline = getLine(programCounter, displacement, &sourceInfo, fileName, _countof(fileName)); bool isFrameInternal = false; if (foundline && !showInternalFrames) { @@ -553,6 +717,11 @@ const WCHAR* CallStack::getResolvedCallstack( BOOL showinternalframes ) return m_resolved; } +bool CallStack::needsSymbols() const +{ + return m_resolved == NULL && !(m_status & CALLSTACK_STATUS_STARTUPCRT); +} + // push_back - Pushes a frame's program counter onto the CallStack. Pushes are // always appended to the back of the chunk list (aka the "top" chunk). // @@ -784,12 +953,17 @@ VOID FastCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) framePointer = (UINT_PTR*)*framePointer; } #elif defined(_M_X64)*/ + m_hashValue = captureBackTrace(maxdepth, context); +//#endif +} + +ULONG CallStack::captureBackTrace (UINT32 maxdepth, const context_t& context) +{ UINT32 maxframes = min(62, maxdepth + 10); - UINT_PTR* myFrames = new UINT_PTR[maxframes]; - ZeroMemory(myFrames, sizeof(UINT_PTR) * maxframes); + UINT_PTR myFrames [62] = {}; ULONG BackTraceHash; maxframes = RtlCaptureStackBackTrace(0, maxframes, reinterpret_cast(myFrames), &BackTraceHash); - m_hashValue = BackTraceHash; + UINT32 count = 0; UINT32 startIndex = 0; // Find the frame matching context.fp to skip VLD internal frames @@ -808,8 +982,39 @@ VOID FastCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) push_back(myFrames[count]); count++; } - delete [] myFrames; -//#endif + return BackTraceHash; +} + +// Longest wait for g_DbgHelp, in milliseconds. +static const ULONGLONG DBGHELP_WAIT_MS = 100; + +// enterDbgHelp - Enters g_DbgHelp, giving up after DBGHELP_WAIT_MS. The caller +// can hold a heap lock (HeapLock) that the owner of g_DbgHelp waits for, +// since dbghelp allocates from the process heap; waiting forever would +// deadlock. After a timeout the thread only tries the lock once until it +// gets it again, so a deadlock costs one wait rather than one per allocation. +// +// Return Value: +// +// Returns true if g_DbgHelp was entered, false if the caller must capture +// the stack without dbghelp. +// +bool CallStack::enterDbgHelp () +{ + tls_t* tls = g_vld.getTls(); + bool entered = g_DbgHelp.TryEnter(); + if (!entered && (tls->flags & VLD_TLS_DBGHELP_TIMEDOUT) == 0) { + ULONGLONG deadline = GetTickCount64() + DBGHELP_WAIT_MS; + while (!entered && GetTickCount64() < deadline) { + Sleep(1); + entered = g_DbgHelp.TryEnter(); + } + if (!entered) + tls->flags |= VLD_TLS_DBGHELP_TIMEDOUT; + } + if (entered) + tls->flags &= ~VLD_TLS_DBGHELP_TIMEDOUT; + return entered; } // getStackTrace - Traces the stack as far back as possible, or until 'maxdepth' @@ -846,6 +1051,14 @@ VOID SafeCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) return; } + // Not under g_heapMapLock: a thread holding g_DbgHelp can be loading a DLL + // for dbghelp, waiting for a loader owner that waits for g_heapMapLock. + if (!enterDbgHelp()) { + captureBackTrace(maxdepth, context); + return; + } + CriticalSectionLocker locker(g_DbgHelp, CriticalSectionLocker::Adopt()); + count++; push_back(CONTEXT_IPREG(context)); @@ -870,10 +1083,6 @@ VOID SafeCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) frame.AddrFrame.Mode = AddrModeFlat; frame.Virtual = TRUE; - // Not under g_heapMapLock: a thread holding g_DbgHelp can be loading a DLL - // for dbghelp, waiting for a loader owner that waits for g_heapMapLock. - CriticalSectionLocker locker(g_DbgHelp); - // Walk the stack. while (count < maxdepth) { count++; diff --git a/src/callstack.h b/src/callstack.h index 1a09254f..126af20b 100644 --- a/src/callstack.h +++ b/src/callstack.h @@ -32,6 +32,8 @@ #include #include "utility.h" +template class Set; + #define CALLSTACK_CHUNK_SIZE 32 // Number of frame slots in each CallStack chunk. #define MAX_SYMBOL_NAME_LENGTH 256 // Maximum symbol name length that we will allow. Longer names will be truncated. #define MAX_SYMBOL_NAME_SIZE ((MAX_SYMBOL_NAME_LENGTH * sizeof(WCHAR)) - 1) @@ -94,12 +96,27 @@ class CallStack virtual DWORD getHashValue() const = 0; virtual VOID getStackTrace (UINT32 maxdepth, const context_t& context) = 0; bool isLeakSuppressed(); + // False once the stack is resolved or known to be a CRT startup stack. + bool needsSymbols() const; + + // Symbols of call stack frames are looked up by dbghelp only outside + // g_heapMapLock, into a cache; see the definitions. + static VOID cacheSymbols (const Set& programCounters); + static bool areSymbolsCached (const Set& programCounters); + static VOID clearSymbolCache (); BOOL operator == (const CallStack &other) const; UINT_PTR operator [] (UINT32 index) const; VOID push_back (const UINT_PTR programcounter); protected: + // Pushes the frames above context.fp, as RtlCaptureStackBackTrace sees + // them, and returns the back trace hash. + ULONG captureBackTrace (UINT32 maxdepth, const context_t& context); + + // Enters g_DbgHelp unless that may deadlock; see the definition. + static bool enterDbgHelp (); + // Protected data. UINT32 m_status; // Status flags: #define CALLSTACK_STATUS_INCOMPLETE 0x1 // If set, the stack trace stored in this CallStack appears to be incomplete. @@ -128,8 +145,12 @@ class CallStack bool isInternalModule( const PWSTR filename ) const; UINT isCrtStartupFunction( LPCWSTR functionName ) const; bool isIgnoreFunction(LPCWSTR functionName) const; - LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, - SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker) const; + static LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + SYMBOL_INFO* functionInfo); + static LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker); + static BOOL getLine(SIZE_T programCounter, DWORD& displacement, IMAGEHLP_LINEW64* sourceInfo, + LPWSTR fileName, DWORD fileNameSize); DWORD resolveFunction(SIZE_T programCounter, IMAGEHLP_LINEW64* sourceInfo, DWORD displacement, LPCWSTR functionName, LPWSTR stack_line, DWORD stackLineSize) const; diff --git a/src/criticalsection.h b/src/criticalsection.h index d92c1f33..7fc4150d 100644 --- a/src/criticalsection.h +++ b/src/criticalsection.h @@ -77,6 +77,14 @@ class CriticalSectionLocker m_critSect.Enter(); } + // Takes over a lock the caller has already entered. + struct Adopt {}; + CriticalSectionLocker(T& cs, Adopt) + : m_leave(false) + , m_critSect(cs) + { + } + ~CriticalSectionLocker() { LeaveLock(); diff --git a/src/dbghelp.h b/src/dbghelp.h index 23b54d88..a0f679df 100644 --- a/src/dbghelp.h +++ b/src/dbghelp.h @@ -18,6 +18,10 @@ class DbgHelp { m_lock.Enter(); } + bool TryEnter() + { + return m_lock.TryEnter(); + } void Leave() { m_lock.Leave(); diff --git a/src/vld.cpp b/src/vld.cpp index 72202e61..253d4911 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -53,6 +53,7 @@ HANDLE g_currentThread; // Pseudo-handle for the current thread. HANDLE g_processHeap; // Handle to the process's heap (COM allocations come from here). CriticalSection g_heapMapLock; // Serializes access to the heap and block maps. CriticalSection g_leakQueryLock; // Serializes leak counting and reporting (see LeakSymbolsHeapMapLock). +extern CriticalSection g_symbolCacheLock; CriticalSection g_reportHooksLock; // Serializes access to g_pReportHooks. ReportHookSet* g_pReportHooks; DbgHelp g_DbgHelp; @@ -425,6 +426,7 @@ VisualLeakDetector::VisualLeakDetector () g_heapMapLock.Initialize(); g_leakQueryLock.Initialize(); + g_symbolCacheLock.Initialize(); g_reportHooksLock.Initialize(); g_vldHeap = HeapCreate(0x0, 0, 0); g_vldHeapLock.Initialize(); @@ -844,6 +846,7 @@ VisualLeakDetector::~VisualLeakDetector () delete g_pReportHooks; g_pReportHooks = NULL; } + CallStack::clearSymbolCache(); HeapDestroy(g_vldHeap); m_optionsLock.Delete(); @@ -851,6 +854,7 @@ VisualLeakDetector::~VisualLeakDetector () m_tlsLock.Delete(); g_heapMapLock.Delete(); g_leakQueryLock.Delete(); + g_symbolCacheLock.Delete(); g_reportHooksLock.Delete(); g_vldHeapLock.Delete(); @@ -2699,6 +2703,17 @@ VOID VisualLeakDetector::RefreshModules() ModuleSet* oldmodules = m_loadedModules; m_loadedModules = newmodules; + // Cached symbols of an unloaded module could name code loaded at its + // addresses later. + for (ModuleSet::Iterator it = oldmodules->begin(); it != oldmodules->end(); ++it) { + ModuleSet::Iterator found = newmodules->find(*it); + if (found == newmodules->end() || (*found).addrLow != (*it).addrLow || + (*found).addrHigh != (*it).addrHigh || (*found).path != (*it).path) { + CallStack::clearSymbolCache(); + break; + } + } + // Free resources used by the old module list. delete oldmodules; } @@ -2976,20 +2991,21 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) } // Leak counting and reporting resolve call stacks while holding g_heapMapLock, -// which every allocation takes. dbghelp loads a module's symbols on first use -// and that load can need the loader (a symbol server path loads symsrv, -// wininet and their dependencies), while a thread in DLL_THREAD_ATTACH holds -// the loader lock and waits for g_heapMapLock when it allocates: a deadlock. -// So the symbols of every module in the unreported leaks' call stacks are -// loaded first, holding neither g_heapMapLock nor the loader lock (with the -// loader lock held, LoadLibrary waits for threads that are initializing and -// need that lock), and the locked pass only does in-memory lookups. - -// collectLeakPages - Collects the code pages of the unreported leaks' call -// stacks; one address per page is enough to name every module. Call with -// g_heapMapLock held. -// -// - pages (OUT): The code pages. +// which every allocation takes, so they do not call dbghelp then: dbghelp +// allocates from the process heap, which an application thread can hold +// (HeapLock) while it allocates and waits for g_heapMapLock, and it loads a +// module's symbols on first use, which can need the loader (a symbol server +// path loads symsrv, wininet and their dependencies) while a thread in +// DLL_THREAD_ATTACH holds the loader lock and waits for g_heapMapLock. So the +// symbols of every frame of the unreported leaks are cached first, holding +// neither g_heapMapLock nor the loader lock (with the loader lock held, +// LoadLibrary waits for threads that are initializing and need that lock), +// and the locked pass only reads the cache (CallStack::cacheSymbols). + +// collectLeakFrames - Collects the program counters of the unreported leaks' +// call stacks. Call with g_heapMapLock held. +// +// - frames (OUT): The program counters. // // - threadId (IN): Only leaks allocated by this thread, or all leaks if -1. // @@ -2999,7 +3015,7 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) // // None. // -VOID VisualLeakDetector::collectLeakPages (Set& pages, DWORD threadId, HANDLE heap) +VOID VisualLeakDetector::collectLeakFrames (Set& frames, DWORD threadId, HANDLE heap) { for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { if (heap != NULL && (*heapit).first != heap) @@ -3007,74 +3023,16 @@ VOID VisualLeakDetector::collectLeakPages (Set& pages, DWORD threadId, BlockMap* blockmap = &(*heapit).second->blockMap; for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { blockinfo_t* info = (*blockit).second; - if (info->reported || info->callStack == NULL) + if (info->reported || info->callStack == NULL || !info->callStack->needsSymbols()) continue; if (threadId != ((DWORD)-1) && info->threadId != threadId) continue; for (UINT32 frame = 0; frame < info->callStack->size(); frame++) - pages.insert((*info->callStack)[frame] & ~(UINT_PTR)0xFFF); + frames.insert((*info->callStack)[frame]); } } } -// areModuleSymbolsLoaded - Checks, without loading anything, that dbghelp is -// done with the deferred symbol load of the module of every page. -// -// - pages (IN): Code pages from collectLeakPages. -// -// Return Value: -// -// TRUE if no module still has deferred symbols. -// -BOOL VisualLeakDetector::areModuleSymbolsLoaded (const Set& pages) -{ - Set modules; - for (Set::Iterator it = pages.begin(); it != pages.end(); ++it) { - HMODULE module = GetCallingModule(*it); - if (module == NULL || modules.find(module) != modules.end()) - continue; - modules.insert(module); - IMAGEHLP_MODULEW64 moduleInfo = { 0 }; - moduleInfo.SizeOfStruct = sizeof(moduleInfo); - CriticalSectionLocker locker(g_DbgHelp); - if (g_DbgHelp.SymGetModuleInfoW64(g_currentProcess, (DWORD64)module, &moduleInfo, locker) && - moduleInfo.SymType == SymDeferred) - return FALSE; - } - return TRUE; -} - -// loadModuleSymbols - Makes dbghelp load the symbols of the module of every -// page. Call without g_heapMapLock or the loader lock held. -// -// - pages (IN): Code pages from collectLeakPages. -// -// Return Value: -// -// None. -// -VOID VisualLeakDetector::loadModuleSymbols (const Set& pages) -{ - Set modules; - BYTE symbolBuffer[sizeof(SYMBOL_INFOW) + MAX_SYMBOL_NAME_SIZE] = { 0 }; - SYMBOL_INFOW* symbol = (SYMBOL_INFOW*)symbolBuffer; - for (Set::Iterator it = pages.begin(); it != pages.end(); ++it) { - HMODULE module = GetCallingModule(*it); - if (module == NULL || modules.find(module) != modules.end()) - continue; - modules.insert(module); - symbol->SizeOfStruct = sizeof(SYMBOL_INFOW); - symbol->MaxNameLen = MAX_SYMBOL_NAME_LENGTH; - DWORD64 displacement; - CriticalSectionLocker locker(g_DbgHelp); - g_DbgHelp.SymFromAddrW(g_currentProcess, *it, &displacement, symbol, locker); - } -} - -// The thread that holds g_heapMapLock through LeakSymbolsHeapMapLock; dbghelp -// must not load symbols on it (see CallStack::isSymbolLoadPending). -static volatile LONG g_noSymbolLoadThreadId = 0; - // While a thread walks the heap and block maps under g_heapMapLock, code it // runs can free or reallocate tracked blocks or destroy heaps on the same // thread: report hooks and dbghelp callbacks. Erasing map entries would break @@ -3147,19 +3105,13 @@ VOID VisualLeakDetector::endBlockWalk () } } -extern "C" bool VldSymbolLoadForbidden(void) -{ - return static_cast(InterlockedCompareExchange(&g_noSymbolLoadThreadId, 0, 0)) == GetCurrentThreadId(); -} - -// Holds g_heapMapLock, entered once the symbols of every module in the -// unreported leaks' call stacks are loaded. Leaks allocated while the symbols -// load can bring new modules, so the check repeats under the lock; whatever is -// still deferred after that is not loaded under the lock but shown as an -// address. g_leakQueryLock keeps a second caller from holding g_heapMapLock -// while it waits for g_DbgHelp, which a loading thread holds. A query from a -// thread that already owns g_heapMapLock (e.g. a report hook) loads nothing -// and takes no lock. +// Holds g_heapMapLock, entered once the symbols of every frame of the +// unreported leaks are cached. Leaks allocated while the symbols are looked up +// bring new frames, so the check repeats under the lock; whatever is still +// missing after that is shown as an address. g_leakQueryLock keeps a second +// caller from holding g_heapMapLock while it waits for g_DbgHelp, which a +// caching thread holds. A query from a thread that already owns +// g_heapMapLock (e.g. a report hook) caches nothing and takes no lock. class LeakSymbolsHeapMapLock { public: @@ -3178,23 +3130,20 @@ class LeakSymbolsHeapMapLock g_heapMapLock.Enter(); if (!loadSymbols) break; - Set pages; - vld.collectLeakPages(pages, threadId, heap); - if (attempt == maxAttempts || VisualLeakDetector::areModuleSymbolsLoaded(pages)) + Set frames; + vld.collectLeakFrames(frames, threadId, heap); + if (attempt == maxAttempts || CallStack::areSymbolsCached(frames)) break; g_heapMapLock.Leave(); - VisualLeakDetector::loadModuleSymbols(pages); + CallStack::cacheSymbols(frames); } } - m_previousNoSymbolLoadThreadId = - InterlockedExchange(&g_noSymbolLoadThreadId, static_cast(GetCurrentThreadId())); m_vld.beginBlockWalk(); } ~LeakSymbolsHeapMapLock() { m_vld.endBlockWalk(); - InterlockedExchange(&g_noSymbolLoadThreadId, m_previousNoSymbolLoadThreadId); if (!m_nested) { g_heapMapLock.Leave(); g_leakQueryLock.Leave(); @@ -3204,7 +3153,6 @@ class LeakSymbolsHeapMapLock private: VisualLeakDetector& m_vld; const bool m_nested; - LONG m_previousNoSymbolLoadThreadId; LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); }; diff --git a/src/vldint.h b/src/vldint.h index cdc723e7..c727a1b0 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -206,6 +206,7 @@ struct tls_t { #define VLD_TLS_DISABLED 0x2 // If set, memory leak detection is disabled for the current thread. #define VLD_TLS_ENABLED 0x4 // If set, memory leak detection is enabled for the current thread. #define VLD_TLS_UCRT 0x8 // If set, the current allocation is a UCRT allocation. +#define VLD_TLS_DBGHELP_TIMEDOUT 0x10 // If set, the last wait for g_DbgHelp on this thread timed out. UINT32 oldFlags; // Thread-local status old flags DWORD threadId; // Thread ID of the thread that owns this TLS structure. HANDLE heap; @@ -361,9 +362,7 @@ class VisualLeakDetector : public IMalloc static int getCrtBlockUse (LPCVOID block, bool ucrt, bool guessed); static size_t getCrtBlockSize(LPCVOID block, bool ucrt); SIZE_T getLeaksCount (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); - VOID collectLeakPages (Set& pages, DWORD threadId, HANDLE heap = NULL); - static BOOL areModuleSymbolsLoaded (const Set& pages); - static VOID loadModuleSymbols (const Set& pages); + VOID collectLeakFrames (Set& frames, DWORD threadId, HANDLE heap = NULL); friend class LeakSymbolsHeapMapLock; SIZE_T reportLeaks(heapinfo_t* heapinfo, bool &firstLeak, Set &aggregatedLeaks, DWORD threadId = (DWORD)-1); VOID markAllLeaksAsReported (heapinfo_t* heapinfo, DWORD threadId = (DWORD)-1); From 35c5fe19238c9fcf05e8e57c3de1764a0a31370e Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 07:17:55 -0800 Subject: [PATCH 50/91] chaos tests - allocate under HeapLock while reporting with the safe stack walk Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_heaplock.cpp | 98 ++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 src/tests/chaos/chaos_heaplock.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index f88dd029..0a9ff61e 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -921,6 +921,7 @@ set(VLD_CHAOS_TESTS chaos_proc_ordinal chaos_noaccess_leak chaos_aligned_new + chaos_heaplock ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_heaplock.cpp b/src/tests/chaos/chaos_heaplock.cpp new file mode 100644 index 00000000..00b535fd --- /dev/null +++ b/src/tests/chaos/chaos_heaplock.cpp @@ -0,0 +1,98 @@ +// chaos_heaplock.cpp - an application holding HeapLock while it allocates. +// +// Lockers hold HeapLock on the process heap and allocate from it, so VLD's +// hooks run with the heap locked. Reporters make VLD resolve symbols and +// walk stacks, where dbghelp allocates from the process heap. With the safe +// stack walker the hooks take g_DbgHelp, so this checks that VLD never +// waits for g_DbgHelp while a dbghelp caller waits for the heap. Only +// HeapAlloc runs under the lock: the debug CRT's malloc takes the CRT heap +// lock before the process heap lock, so malloc there deadlocks without VLD. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD RUN_MS = 3000; +volatile LONG g_stop = 0; +volatile LONG g_leaked = 0; + +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} + +DWORD WINAPI Locker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 41 + 9); + HANDLE heap = GetProcessHeap(); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + chaos::Check(HeapLock(heap) != FALSE, "HeapLock failed"); + void* a = HeapAlloc(heap, 0, 16 + random.Below(300)); + void* b = HeapAlloc(heap, 0, 16 + random.Below(300)); + HeapFree(heap, 0, a); + if (random.Below(8) == 0) + InterlockedIncrement(&g_leaked); + else + HeapFree(heap, 0, b); + HeapUnlock(heap); + } + return 0; +} + +DWORD WINAPI Reporter(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 23 + 1); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + switch (random.Below(3)) + { + case 0: VLDReportLeaks(); break; + case 1: VLDResolveCallstacks(); break; + default: VLDRefreshModules(); break; + } + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + UINT options = VLDGetOptions(); + VLDSetOptions(options | VLD_OPT_SAFE_STACK_WALK, 256, 64); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("allocating under HeapLock while reporting"); + HANDLE threads[6]; + for (int i = 0; i < 6; i++) + { + threads[i] = CreateThread(NULL, 0, i < 4 ? Locker : Reporter, (LPVOID)(INT_PTR)i, 0, NULL); + chaos::Check(threads[i] != NULL, "CreateThread failed"); + } + Sleep(RUN_MS); + InterlockedExchange(&g_stop, 1); + WaitForMultipleObjects(6, threads, TRUE, INFINITE); + + chaos::SetPhase("counting"); + UINT counted = VLDGetLeaksCount(); + if (counted != (UINT)g_leaked) + { + char message[96]; + sprintf_s(message, "leaked %ld blocks but VLD counts %u", g_leaked, counted); + chaos::Fail(message); + } + + chaos::SetPhase("cleanup"); + VLDMarkAllLeaksAsReported(); + VLDSetOptions(options, 256, 64); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + for (int i = 0; i < 6; i++) + { + CloseHandle(threads[i]); + } + chaos::Pass(); + return 0; +} From 219f681445d6c4b68c446597359836bf2618e839 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 07:32:41 -0800 Subject: [PATCH 51/91] Keep the symbol cache consistent and never walk with dbghelp under g_heapMapLock The safe stack walk falls back to RtlCaptureStackBackTrace on a thread that owns g_heapMapLock (wrong-heap diagnostics, report hooks), since StackWalk64 can allocate from the process heap. A module unload notification clears the symbol cache, a clear makes lookups started before it drop their results, and the cache is freed before VLD checks its own internal leaks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.cpp | 24 +++++++++++++++++------- src/vld.cpp | 5 +++++ 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/callstack.cpp b/src/callstack.cpp index cc0c268a..fad735be 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -66,8 +66,10 @@ struct cachedsymbol_t { }; typedef Map SymbolCache; static SymbolCache* g_symbolCache = NULL; -// Guards g_symbolCache. Held only for map operations and copies, never while -// another lock is taken. +// Counts clears, so that symbols looked up before a clear are not cached. +static ULONG g_symbolCacheGeneration = 0; +// Guards g_symbolCache and g_symbolCacheGeneration. Held only for map +// operations and copies, never while another lock is taken. CriticalSection g_symbolCacheLock; static WCHAR* duplicateString(LPCWSTR source) @@ -97,10 +99,12 @@ VOID CallStack::cacheSymbols (const Set& programCounters) BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE]; for (Set::Iterator it = programCounters.begin(); it != programCounters.end(); ++it) { UINT_PTR programCounter = *it; + ULONG generation; { CriticalSectionLocker<> cs(g_symbolCacheLock); if (g_symbolCache != NULL && g_symbolCache->find(programCounter) != g_symbolCache->end()) continue; + generation = g_symbolCacheGeneration; } cachedsymbol_t* symbol = new cachedsymbol_t; @@ -125,11 +129,13 @@ VOID CallStack::cacheSymbols (const Set& programCounters) } CriticalSectionLocker<> cs(g_symbolCacheLock); - if (g_symbolCache == NULL) - g_symbolCache = new SymbolCache; - if (g_symbolCache->find(programCounter) == g_symbolCache->end()) { - g_symbolCache->insert(programCounter, symbol); - continue; + if (generation == g_symbolCacheGeneration) { + if (g_symbolCache == NULL) + g_symbolCache = new SymbolCache; + if (g_symbolCache->find(programCounter) == g_symbolCache->end()) { + g_symbolCache->insert(programCounter, symbol); + continue; + } } cs.Leave(); delete [] symbol->functionName; @@ -170,6 +176,7 @@ VOID CallStack::clearSymbolCache () CriticalSectionLocker<> cs(g_symbolCacheLock); cache = g_symbolCache; g_symbolCache = NULL; + g_symbolCacheGeneration++; } if (cache == NULL) return; @@ -1001,6 +1008,9 @@ static const ULONGLONG DBGHELP_WAIT_MS = 100; // bool CallStack::enterDbgHelp () { + // StackWalk64 can allocate from the process heap. + if (g_heapMapLock.IsOwnedByCurrentThread()) + return false; tls_t* tls = g_vld.getTls(); bool entered = g_DbgHelp.TryEnter(); if (!entered && (tls->flags & VLD_TLS_DBGHELP_TIMEDOUT) == 0) { diff --git a/src/vld.cpp b/src/vld.cpp index 253d4911..4bef890f 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -834,6 +834,7 @@ VisualLeakDetector::~VisualLeakDetector () } delete reportHooks; + CallStack::clearSymbolCache(); checkInternalMemoryLeaks(); } else { @@ -2906,6 +2907,10 @@ VOID VisualLeakDetector::UnregisterLoadedModule(HMODULE module, ULONG sizeOfImag break; m_loadedModules->erase(it); } + cs.Leave(); + + // Cached symbols of the module could name code loaded at its addresses later. + CallStack::clearSymbolCache(); } // Find the information for the module that initiated this reallocation. From dc099818a24bf05018b25de370610da3d5446331 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 07:36:03 -0800 Subject: [PATCH 52/91] chaos tests - write a minidump of a hung test when CHAOS_DUMP_DIR is set With CHAOS_DUMP_DIR set, StartWatchdog starts a copy of the test as a dumper that waits for the watchdog's hang event and writes a full minidump of the test into that directory from outside the hung process, so the watchdog itself allocates nothing. The gate sets CHAOS_DUMP_DIR inside the build directory and publishes that directory even when ctest fails, so hangs that only reproduce in the gate can be debugged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- build/templates/build-arch.yml | 3 + src/tests/chaos/chaos_common.h | 113 +++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) diff --git a/build/templates/build-arch.yml b/build/templates/build-arch.yml index aff8535f..e3c41ed3 100644 --- a/build/templates/build-arch.yml +++ b/build/templates/build-arch.yml @@ -118,9 +118,12 @@ steps: inputs: script: '"$(ctestPath)" -C "${{ parameters.configuration }}" --output-on-failure' workingDirectory: 'build_${{ parameters.arch }}' + env: + CHAOS_DUMP_DIR: '$(Build.SourcesDirectory)\build_${{ parameters.arch }}\chaos_dumps' - task: PublishPipelineArtifact@1 displayName: 'Publish ${{ parameters.arch }}${{ parameters.artifactSuffix }} build' + condition: succeededOrFailed() inputs: targetPath: 'build_${{ parameters.arch }}' artifact: 'build_${{ parameters.arch }}${{ parameters.artifactSuffix }}' diff --git a/src/tests/chaos/chaos_common.h b/src/tests/chaos/chaos_common.h index 806b01fe..b75310ad 100644 --- a/src/tests/chaos/chaos_common.h +++ b/src/tests/chaos/chaos_common.h @@ -8,8 +8,10 @@ #pragma once #include +#include #include #include +#include namespace chaos { @@ -54,10 +56,119 @@ inline void Fail(const char* message, UINT exitCode = 1) TerminateProcess(GetCurrentProcess(), exitCode); } +// With CHAOS_DUMP_DIR set, StartWatchdog starts a copy of the test as a dumper +// that waits for a hang and writes a minidump of the test into that directory, +// from outside the hung process. +inline HANDLE& DumpRequest() +{ + static HANDLE request = NULL; + return request; +} + +inline HANDLE& DumpWritten() +{ + static HANDLE written = NULL; + return written; +} + +inline void DumpEventName(wchar_t* name, size_t size, const wchar_t* kind, DWORD pid) +{ + swprintf_s(name, size, L"Local\\chaos_%s_%lu", kind, pid); +} + +// MiniDumpWriteDump, loaded at run time; the MINIDUMP_TYPE values are those of +// MiniDumpWithFullMemory, MiniDumpWithHandleData, MiniDumpWithUnloadedModules +// and MiniDumpWithThreadInfo. +typedef BOOL (WINAPI *MiniDumpWriteDump_t)(HANDLE, DWORD, HANDLE, DWORD, PVOID, PVOID, PVOID); +const DWORD CHAOS_MINIDUMP_TYPE = 0x2 | 0x4 | 0x20 | 0x1000; + +// Runs the dumper and exits if this process was started as one. +inline void RunDumperIfRequested() +{ + int argc = 0; + LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); + if (argv == NULL || argc != 3 || wcscmp(argv[1], L"--chaos-dumper") != 0) + { + return; + } + DWORD pid = wcstoul(argv[2], NULL, 10); + wchar_t name[64]; + DumpEventName(name, _countof(name), L"hang", pid); + HANDLE request = OpenEventW(SYNCHRONIZE, FALSE, name); + DumpEventName(name, _countof(name), L"dumped", pid); + HANDLE written = OpenEventW(EVENT_MODIFY_STATE, FALSE, name); + HANDLE test = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_DUP_HANDLE, FALSE, pid); + if (request == NULL || written == NULL || test == NULL) + { + ExitProcess(1); + } + HANDLE waits[2] = { request, test }; + if (WaitForMultipleObjects(2, waits, FALSE, INFINITE) == WAIT_OBJECT_0) + { + wchar_t dir[MAX_PATH]; + wchar_t exe[MAX_PATH]; + wchar_t path[MAX_PATH * 2]; + DWORD length = GetEnvironmentVariableW(L"CHAOS_DUMP_DIR", dir, _countof(dir)); + GetModuleFileNameW(NULL, exe, _countof(exe)); + const wchar_t* base = wcsrchr(exe, L'\\'); + base = base ? base + 1 : exe; + HMODULE dbghelp = LoadLibraryW(L"dbghelp.dll"); + MiniDumpWriteDump_t writeDump = dbghelp ? (MiniDumpWriteDump_t)GetProcAddress(dbghelp, "MiniDumpWriteDump") : NULL; + if (length > 0 && length < _countof(dir) && writeDump != NULL) + { + CreateDirectoryW(dir, NULL); + swprintf_s(path, L"%s\\%s.%lu.dmp", dir, base, pid); + HANDLE file = CreateFileW(path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (file != INVALID_HANDLE_VALUE) + { + writeDump(test, pid, file, CHAOS_MINIDUMP_TYPE, NULL, NULL, NULL); + CloseHandle(file); + } + } + SetEvent(written); + } + ExitProcess(0); +} + +inline void StartDumper() +{ + wchar_t dir[MAX_PATH]; + if (GetEnvironmentVariableW(L"CHAOS_DUMP_DIR", dir, _countof(dir)) == 0) + { + return; + } + DWORD pid = GetCurrentProcessId(); + wchar_t name[64]; + DumpEventName(name, _countof(name), L"hang", pid); + HANDLE request = CreateEventW(NULL, TRUE, FALSE, name); + DumpEventName(name, _countof(name), L"dumped", pid); + HANDLE written = CreateEventW(NULL, TRUE, FALSE, name); + wchar_t exe[MAX_PATH]; + wchar_t commandLine[MAX_PATH + 64]; + GetModuleFileNameW(NULL, exe, _countof(exe)); + swprintf_s(commandLine, L"\"%s\" --chaos-dumper %lu", exe, pid); + STARTUPINFOW startup = { sizeof(startup) }; + PROCESS_INFORMATION process = { 0 }; + if (request == NULL || written == NULL || + !CreateProcessW(exe, commandLine, NULL, NULL, FALSE, DETACHED_PROCESS, NULL, NULL, &startup, &process)) + { + return; + } + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + DumpWritten() = written; + DumpRequest() = request; +} + inline DWORD WINAPI WatchdogThread(LPVOID) { if (WaitForSingleObject(WatchdogDone(), (DWORD)WatchdogMs()) == WAIT_TIMEOUT) { + // Allocates nothing: the hung threads may hold the heap or loader lock. + if (DumpRequest() != NULL && SetEvent(DumpRequest())) + { + WaitForSingleObject(DumpWritten(), 120000); + } Fail("HANG detected by the watchdog", 3); } return 0; @@ -65,7 +176,9 @@ inline DWORD WINAPI WatchdogThread(LPVOID) inline void StartWatchdog(DWORD ms) { + RunDumperIfRequested(); WatchdogMs() = (LONG)ms; + StartDumper(); WatchdogDone() = CreateEventW(NULL, TRUE, FALSE, NULL); HANDLE thread = CreateThread(NULL, 0, WatchdogThread, NULL, 0, NULL); if (WatchdogDone() == NULL || thread == NULL) From 223b9543136806b18c4b521a55c3801dc92ebc29 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 07:50:58 -0800 Subject: [PATCH 53/91] chaos tests - bound each heap walk in chaos_heap_flags On Windows Server 2022 a HeapWalk of the process heap while other threads change its LFH can take tens of seconds per walk (the gate dump showed one thread in RtlWalkHeap for 24 s of user time, holding the heap lock, with no VLD frame on any stack). Stop each walk after 100 ms or when the test stops. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_heap_flags.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/tests/chaos/chaos_heap_flags.cpp b/src/tests/chaos/chaos_heap_flags.cpp index f7564adb..06da1d0e 100644 --- a/src/tests/chaos/chaos_heap_flags.cpp +++ b/src/tests/chaos/chaos_heap_flags.cpp @@ -60,11 +60,18 @@ DWORD WINAPI Inspector(LPVOID p) { if (HeapLock(heap)) { + // Bounded: on Windows Server 2022 a walk of a heap whose LFH + // other threads keep changing can take tens of seconds. PROCESS_HEAP_ENTRY entry = { 0 }; int entries = 0; + ULONGLONG deadline = GetTickCount64() + 100; while (HeapWalk(heap, &entry) && entries < 100000) { entries++; + if (GetTickCount64() > deadline || InterlockedCompareExchange(&g_stop, 0, 0)) + { + break; + } } HeapUnlock(heap); } From 06f8c5c21d741850edd4d0f1198221286e2abbd6 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:09:24 -0800 Subject: [PATCH 54/91] Print report output only after g_heapMapLock is released Report hooks, the CRT's stdout and file streams and OutputDebugStringW can allocate from the process heap. VLD printed leak reports while holding g_heapMapLock, so an application thread that holds HeapLock on the process heap and allocates, waiting in VLD's hook for g_heapMapLock, deadlocked with the reporting thread waiting for the heap. g_heapMapLock is now a HeapMapLock. Print queues messages, in VLD's private heap, on a thread that owns it, and the release of the outermost hold prints them, so report hooks and every output run without the lock. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/callstack.cpp | 2 +- src/criticalsection.h | 6 ++ src/tests/chaos/chaos_hook_heap_ops.cpp | 4 +- src/tests/chaos/chaos_hook_reenter.cpp | 11 ++-- src/utility.cpp | 81 +++++++++++++++++++++++-- src/utility.h | 30 +++++++++ src/vld.cpp | 24 ++++---- src/vld.h | 4 +- src/vld_hooks.cpp | 6 +- 9 files changed, 139 insertions(+), 29 deletions(-) diff --git a/src/callstack.cpp b/src/callstack.cpp index fad735be..b45ab90b 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -39,7 +39,7 @@ // Imported global variables. extern HANDLE g_currentProcess; extern HANDLE g_currentThread; -extern CriticalSection g_heapMapLock; +extern HeapMapLock g_heapMapLock; extern VisualLeakDetector g_vld; extern DbgHelp g_DbgHelp; diff --git a/src/criticalsection.h b/src/criticalsection.h index 7fc4150d..1a295fc5 100644 --- a/src/criticalsection.h +++ b/src/criticalsection.h @@ -43,6 +43,12 @@ class CriticalSection return (DWORD)(ULONG_PTR)m_critRegion.OwningThread == GetCurrentThreadId(); } + // True if the next Leave releases the section. + bool IsOwnedOnceByCurrentThread() + { + return IsOwnedByCurrentThread() && m_critRegion.RecursionCount == 1; + } + // try enter the section bool TryEnter() { diff --git a/src/tests/chaos/chaos_hook_heap_ops.cpp b/src/tests/chaos/chaos_hook_heap_ops.cpp index 58e06bd0..45dbf239 100644 --- a/src/tests/chaos/chaos_hook_heap_ops.cpp +++ b/src/tests/chaos/chaos_hook_heap_ops.cpp @@ -1,7 +1,7 @@ // chaos_hook_heap_ops.cpp - a report hook that reallocates, destroys and -// creates heaps and reports again while VLD walks its maps. +// creates heaps and reports again while VLD reports. // -// The hook runs with g_heapMapLock held in the middle of the walk. It moves a +// The hook runs right after VLD walks its maps for the report. It moves a // tracked block with realloc, destroys a private heap that still holds // blocks, creates a new heap right away (which sometimes gets the destroyed // heap's handle) and allocates from it, and nests a second report. diff --git a/src/tests/chaos/chaos_hook_reenter.cpp b/src/tests/chaos/chaos_hook_reenter.cpp index a1d98522..81accfc4 100644 --- a/src/tests/chaos/chaos_hook_reenter.cpp +++ b/src/tests/chaos/chaos_hook_reenter.cpp @@ -1,11 +1,10 @@ // chaos_hook_reenter.cpp - a report hook that allocates, frees and queries VLD -// while VLD is walking its block maps to print the report. +// while VLD reports. // -// Report hooks run on the reporting thread with g_heapMapLock held, in the -// middle of the walk over a heap's blocks. A hook that formats a string -// allocates and frees (inserting into and erasing from the map being -// walked); one that frees a tracked block erases another entry. Neither may -// crash VLD or corrupt its counts. +// Report hooks run on the reporting thread right after VLD walks its block +// maps for the report. A hook that formats a string allocates and frees; one +// that frees a tracked block erases a map entry. Neither may crash VLD or +// corrupt its counts. #include "chaos_common.h" #include diff --git a/src/utility.cpp b/src/utility.cpp index 4d66e74e..091b0551 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -34,6 +34,7 @@ // Imported Global Variables extern ReportHookSet* g_pReportHooks; extern CriticalSection g_reportHooksLock; +extern HeapMapLock g_heapMapLock; extern VisualLeakDetector g_vld; extern ImageDirectoryEntries g_Ide; #if defined(_M_ARM64) @@ -1242,11 +1243,8 @@ int CallReportHook(int reportType, LPWSTR message, int* hook_retval) // // None. // -VOID Print (LPWSTR messagew) +static VOID PrintNow (LPWSTR messagew) { - if (NULL == messagew) - return; - int hook_retval=0; if (!CallReportHook(0, messagew, &hook_retval)) { @@ -1295,6 +1293,81 @@ VOID Print (LPWSTR messagew) } } +// Messages queued by Print, each followed by its terminating null. Accessed +// only by the thread that owns g_heapMapLock. +struct deferredreport_t { + WCHAR* text; + size_t length; + size_t capacity; +}; +static deferredreport_t* s_deferredReport = NULL; + +static VOID DeferPrint (LPCWSTR messagew) +{ + size_t length = wcslen(messagew) + 1; + deferredreport_t* report = s_deferredReport; + if (report == NULL) { + report = new deferredreport_t; + report->text = NULL; + report->length = 0; + report->capacity = 0; + s_deferredReport = report; + } + if (report->length + length > report->capacity) { + size_t capacity = max(report->capacity * 2, report->length + length + 4096); + WCHAR* text = new WCHAR[capacity]; + if (report->length > 0) + memcpy(text, report->text, report->length * sizeof(WCHAR)); + delete [] report->text; + report->text = text; + report->capacity = capacity; + } + memcpy(report->text + report->length, messagew, length * sizeof(WCHAR)); + report->length += length; +} + +// TakeDeferredReport - Takes the queued messages. Call with g_heapMapLock held. +deferredreport_t* TakeDeferredReport () +{ + deferredreport_t* report = s_deferredReport; + s_deferredReport = NULL; + return report; +} + +// PrintDeferredReport - Prints and frees messages from TakeDeferredReport. +// Call without g_heapMapLock held. +VOID PrintDeferredReport (deferredreport_t* report) +{ + for (size_t offset = 0; offset < report->length; ) { + LPWSTR messagew = report->text + offset; + offset += wcslen(messagew) + 1; + Print(messagew); + } + delete [] report->text; + delete report; +} + +// Print - Sends a message to the report hooks, the debugger, stdout and/or the +// report file. A thread that owns g_heapMapLock queues it instead, to be +// printed when it releases the lock (see HeapMapLock). +// +// - messagew (IN): The message. +// +// Return Value: +// +// None. +// +VOID Print (LPWSTR messagew) +{ + if (NULL == messagew) + return; + if (g_heapMapLock.IsOwnedByCurrentThread()) { + DeferPrint(messagew); + return; + } + PrintNow(messagew); +} + // Report - Sends a printf-style formatted message to the debugger for display // and/or to a file. // diff --git a/src/utility.h b/src/utility.h index 4abf5f51..60a4b87f 100644 --- a/src/utility.h +++ b/src/utility.h @@ -32,6 +32,7 @@ Applications should never include this header." #include #include #include +#include "criticalsection.h" #ifdef _WIN64 #define ADDRESSFORMAT L"0x%.16X" // Format string for 64-bit addresses @@ -181,6 +182,35 @@ BOOL PatchImport (HMODULE importmodule, moduleentry_t *module); BOOL PatchModule (HMODULE importmodule, moduleentry_t patchtable [], UINT tablesize); VOID Print (LPWSTR message); VOID Report (LPCWSTR format, ...); + +// Report output that a thread produces while it owns g_heapMapLock; see Print. +struct deferredreport_t; +deferredreport_t* TakeDeferredReport (); +VOID PrintDeferredReport (deferredreport_t* report); + +// The lock of VLD's heap and block maps, which every allocation hook takes. +// Printing can allocate from the process heap (report hooks, the CRT, +// OutputDebugStringW), which an application thread can hold with HeapLock +// while its allocation waits for this lock. So output produced under the lock +// is queued and printed once the outermost hold is released. +class HeapMapLock +{ +public: + void Initialize () { m_lock.Initialize(); } + void Delete () { m_lock.Delete(); } + void Enter () { m_lock.Enter(); } + bool IsOwnedByCurrentThread () { return m_lock.IsOwnedByCurrentThread(); } + void Leave () + { + deferredreport_t* report = m_lock.IsOwnedOnceByCurrentThread() ? TakeDeferredReport() : NULL; + m_lock.Leave(); + if (report != NULL) + PrintDeferredReport(report); + } + +private: + CriticalSection m_lock; +}; #ifndef NDEBUG #define DbgPrint(x) Print(x) #define DbgReport(...) Report(__VA_ARGS__) diff --git a/src/vld.cpp b/src/vld.cpp index 4bef890f..29840010 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -51,7 +51,7 @@ extern CriticalSection g_vldHeapLock; HANDLE g_currentProcess; // Pseudo-handle for the current process. HANDLE g_currentThread; // Pseudo-handle for the current thread. HANDLE g_processHeap; // Handle to the process's heap (COM allocations come from here). -CriticalSection g_heapMapLock; // Serializes access to the heap and block maps. +HeapMapLock g_heapMapLock; // Serializes access to the heap and block maps. CriticalSection g_leakQueryLock; // Serializes leak counting and reporting (see LeakSymbolsHeapMapLock). extern CriticalSection g_symbolCacheLock; CriticalSection g_reportHooksLock; // Serializes access to g_pReportHooks. @@ -796,7 +796,7 @@ VisualLeakDetector::~VisualLeakDetector () { // Free internally allocated resources used by the heapmap and blockmap. - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { BlockMap *blockmap = &(*heapit).second->blockMap; for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { @@ -1483,7 +1483,7 @@ SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, S SIZE_T erased = 0; // Iterate through all block maps, looking for blocks with the same size // and callstack as the specified element. - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { BlockMap *blockmap = &(*heapit).second->blockMap; for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { @@ -1645,7 +1645,7 @@ VOID VisualLeakDetector::mapBlock (HANDLE heap, LPCVOID mem, SIZE_T size, bool d // VOID VisualLeakDetector::mapHeap (HANDLE heap) { - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); // Create a new block map for this heap and insert it into the heap map. heapinfo_t* heapinfo = new heapinfo_t; @@ -1691,7 +1691,7 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & return; // Find this heap's block map. - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); HeapMap::Iterator heapit = m_heapMap->find(heap); if (heapit == m_heapMap->end()) { // We don't have a block map for this heap. We must not have monitored @@ -1768,7 +1768,7 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & VOID VisualLeakDetector::unmapHeap (HANDLE heap) { // Find this heap's block map. - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); HeapMap::Iterator heapit = m_heapMap->find(heap); if (heapit == m_heapMap->end()) { // This heap hasn't been mapped. We must not have monitored this heap's @@ -1893,7 +1893,7 @@ SIZE_T VisualLeakDetector::getBlockSerial (HANDLE heap, LPCVOID mem) if (NULL == mem) return 0; - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); HeapMap::Iterator heapit = m_heapMap->find(heap); if (heapit == m_heapMap->end()) return 0; @@ -1916,7 +1916,7 @@ VOID VisualLeakDetector::unmapMovedBlock (HANDLE heap, LPCVOID mem, SIZE_T seria if (serial == 0) return; - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); if (getBlockSerial(heap, mem) == serial) unmapBlock(heap, mem, context); } @@ -2307,7 +2307,7 @@ blockinfo_t* VisualLeakDetector::findAllocedBlock(LPCVOID mem, __out HANDLE& hea heap = NULL; blockinfo_t* result = NULL; // Iterate through all heaps - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); for (HeapMap::Iterator it = m_heapMap->begin(); it != m_heapMap->end(); ++it) @@ -3285,7 +3285,7 @@ VOID VisualLeakDetector::MarkAllLeaksAsReported( ) } // Generate a memory leak report for each heap in the process. - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { HANDLE heap = (*heapit).first; UNREFERENCED_PARAMETER(heap); @@ -3302,7 +3302,7 @@ VOID VisualLeakDetector::MarkThreadLeaksAsReported( DWORD threadId ) } // Generate a memory leak report for each heap in the process. - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); for (HeapMap::Iterator heapit = m_heapMap->begin(); heapit != m_heapMap->end(); ++heapit) { HANDLE heap = (*heapit).first; UNREFERENCED_PARAMETER(heap); @@ -3803,7 +3803,7 @@ CaptureContext::~CaptureContext() { CallStack* callstack = CallStack::Create(); callstack->getStackTrace(g_vld.m_maxTraceFrames, m_tls->context); - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); if (m_tls->newBlockWithoutGuard == NULL) { g_vld.mapBlock(m_tls->heap, diff --git a/src/vld.h b/src/vld.h index 8912c34c..3ac63a4a 100644 --- a/src/vld.h +++ b/src/vld.h @@ -302,7 +302,9 @@ __declspec(dllimport) VLD_BOOL VLDGetModulesList(wchar_t *modules, VLD_UINT size __declspec(dllimport) void VLDSetReportOptions(VLD_UINT option_mask, const wchar_t *filename); // VLDSetReportHook - Installs or uninstalls a client-defined reporting function by hooking it -// into the C run-time debug reporting process (debug version only). +// into the C run-time debug reporting process (debug version only). Hooks run on the +// reporting thread after VLD releases its internal locks, so a hook may allocate and +// call VLD. // // mode: The action to take: VLD_RPTHOOK_INSTALL or VLD_RPTHOOK_REMOVE. // diff --git a/src/vld_hooks.cpp b/src/vld_hooks.cpp index d74d89ef..dfbf46d8 100644 --- a/src/vld_hooks.cpp +++ b/src/vld_hooks.cpp @@ -39,7 +39,7 @@ #include "loaderlock.h" extern HANDLE g_currentProcess; -extern CriticalSection g_heapMapLock; +extern HeapMapLock g_heapMapLock; extern DbgHelp g_DbgHelp; //////////////////////////////////////////////////////////////////////////////// @@ -65,7 +65,7 @@ HANDLE VisualLeakDetector::_GetProcessHeap() // Get the process heap. HANDLE heap = m_GetProcessHeap(); - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); HeapMap::Iterator heapit = g_vld.m_heapMap->find(heap); if (heapit == g_vld.m_heapMap->end()) { @@ -96,7 +96,7 @@ HANDLE VisualLeakDetector::_HeapCreate (DWORD options, SIZE_T initsize, SIZE_T m // Create the heap. HANDLE heap = m_HeapCreate(options, initsize, maxsize); - CriticalSectionLocker<> cs(g_heapMapLock); + CriticalSectionLocker cs(g_heapMapLock); // Map the created heap handle to a new block map. g_vld.mapHeap(heap); From a9ac1b3a8f457b7dc90ab0d94e93d192a3d6f4c6 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:09:25 -0800 Subject: [PATCH 55/91] chaos tests - report to the debugger and an allocating hook while threads allocate under HeapLock Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_heaplock_report.cpp | 113 ++++++++++++++++++++++ 2 files changed, 114 insertions(+) create mode 100644 src/tests/chaos/chaos_heaplock_report.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 0a9ff61e..f47ec54c 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -922,6 +922,7 @@ set(VLD_CHAOS_TESTS chaos_noaccess_leak chaos_aligned_new chaos_heaplock + chaos_heaplock_report ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_heaplock_report.cpp b/src/tests/chaos/chaos_heaplock_report.cpp new file mode 100644 index 00000000..44544f7f --- /dev/null +++ b/src/tests/chaos/chaos_heaplock_report.cpp @@ -0,0 +1,113 @@ +// chaos_heaplock_report.cpp - leak reports that allocate from the process heap +// while other threads hold HeapLock and allocate. +// +// VLD sends every report line to the report hooks and the debugger while it +// walks its maps. A report hook may allocate, and OutputDebugStringW converts +// on the process heap. Lockers hold HeapLock on the process heap and allocate +// from it, so VLD must never print or call a hook while a hooked allocation +// can wait for it. + +#include "chaos_common.h" +#include "vld.h" + +namespace +{ +const DWORD PHASE_MS = 2000; +volatile LONG g_stop = 0; +volatile LONG g_leaked = 0; +volatile LONG g_hookCalls = 0; + +int __cdecl AllocatingHook(int, wchar_t* message, int* returnValue) +{ + InterlockedIncrement(&g_hookCalls); + size_t length = wcslen(message) + 1; + wchar_t* copy = (wchar_t*)malloc(length * sizeof(wchar_t)); + if (copy != NULL) + { + wcscpy_s(copy, length, message); + free(copy); + } + void* block = HeapAlloc(GetProcessHeap(), 0, 64); + HeapFree(GetProcessHeap(), 0, block); + *returnValue = 0; + return 1; +} + +DWORD WINAPI Locker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 59 + 3); + HANDLE heap = GetProcessHeap(); + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + chaos::Check(HeapLock(heap) != FALSE, "HeapLock failed"); + void* a = HeapAlloc(heap, 0, 16 + random.Below(300)); + void* b = HeapAlloc(heap, 0, 16 + random.Below(300)); + HeapFree(heap, 0, a); + if (random.Below(16) == 0) + InterlockedIncrement(&g_leaked); + else + HeapFree(heap, 0, b); + HeapUnlock(heap); + } + return 0; +} + +DWORD WINAPI Reporter(LPVOID) +{ + while (!InterlockedCompareExchange(&g_stop, 0, 0)) + { + VLDReportLeaks(); + } + return 0; +} + +void RunPhase(const char* phase) +{ + chaos::SetPhase(phase); + InterlockedExchange(&g_stop, 0); + HANDLE threads[5]; + for (int i = 0; i < 5; i++) + { + threads[i] = CreateThread(NULL, 0, i < 4 ? Locker : Reporter, (LPVOID)(INT_PTR)i, 0, NULL); + chaos::Check(threads[i] != NULL, "CreateThread failed"); + } + Sleep(PHASE_MS); + InterlockedExchange(&g_stop, 1); + WaitForMultipleObjects(5, threads, TRUE, INFINITE); + for (int i = 0; i < 5; i++) + { + CloseHandle(threads[i]); + } +} +} + +int main() +{ + chaos::StartWatchdog(25000); + UINT options = VLDGetOptions(); + VLDMarkAllLeaksAsReported(); + + VLDSetReportOptions(VLD_OPT_REPORT_TO_DEBUGGER, NULL); + RunPhase("reporting to the debugger while lockers allocate under HeapLock"); + + VLDSetReportHook(VLD_RPTHOOK_INSTALL, AllocatingHook); + RunPhase("an allocating report hook while lockers allocate under HeapLock"); + chaos::Check(g_hookCalls > 0, "the report hook was never called"); + + chaos::SetPhase("counting"); + UINT counted = VLDGetLeaksCount(); + if (counted != (UINT)g_leaked) + { + char message[96]; + sprintf_s(message, "leaked %ld blocks but VLD counts %u", g_leaked, counted); + chaos::Fail(message); + } + + chaos::SetPhase("cleanup"); + VLDMarkAllLeaksAsReported(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, AllocatingHook); + VLDSetReportOptions(VLD_OPT_REPORT_TO_STDOUT, NULL); + VLDSetOptions(options, 256, 64); + chaos::Pass(); + return 0; +} From 360d2f08e632a79b856e9994cb681665a5b3714a Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:14:29 -0800 Subject: [PATCH 56/91] Survive a failed allocation or a throwing hook when printing queued report output The queue of report output grows in VLD's private heap, whose operator new returns NULL when it is exhausted: a message that does not fit is now dropped and counted, and the count is reported. The queue is printed from HeapMapLock::Leave, which can run in a destructor, so an exception thrown by a report hook is discarded there instead of terminating the process. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/utility.cpp | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/utility.cpp b/src/utility.cpp index 091b0551..e2a04fed 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -1299,6 +1299,7 @@ struct deferredreport_t { WCHAR* text; size_t length; size_t capacity; + size_t dropped; // Messages lost because the queue could not grow. }; static deferredreport_t* s_deferredReport = NULL; @@ -1308,14 +1309,21 @@ static VOID DeferPrint (LPCWSTR messagew) deferredreport_t* report = s_deferredReport; if (report == NULL) { report = new deferredreport_t; + if (report == NULL) + return; report->text = NULL; report->length = 0; report->capacity = 0; + report->dropped = 0; s_deferredReport = report; } if (report->length + length > report->capacity) { size_t capacity = max(report->capacity * 2, report->length + length + 4096); WCHAR* text = new WCHAR[capacity]; + if (text == NULL) { + report->dropped++; + return; + } if (report->length > 0) memcpy(text, report->text, report->length * sizeof(WCHAR)); delete [] report->text; @@ -1335,13 +1343,25 @@ deferredreport_t* TakeDeferredReport () } // PrintDeferredReport - Prints and frees messages from TakeDeferredReport. -// Call without g_heapMapLock held. +// Call without g_heapMapLock held. Runs from HeapMapLock::Leave, which can +// be a destructor, so an exception thrown by a report hook is discarded. VOID PrintDeferredReport (deferredreport_t* report) { for (size_t offset = 0; offset < report->length; ) { LPWSTR messagew = report->text + offset; offset += wcslen(messagew) + 1; - Print(messagew); + try { + Print(messagew); + } + catch (...) { + } + } + if (report->dropped > 0) { + try { + Report(L"WARNING: Visual Leak Detector: %Iu report lines were lost: out of memory.\n", report->dropped); + } + catch (...) { + } } delete [] report->text; delete report; From 0f00937b98f3ab171fa0c0547da410273bb796cf Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:18:04 -0800 Subject: [PATCH 57/91] chaos tests - list the blocks chaos_unload_report misses On a miscount the test reports its leaks again through a hook that collects the reported addresses and prints every leaked block that is missing, with its index, its thread and its first bytes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_unload_report.cpp | 71 ++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/src/tests/chaos/chaos_unload_report.cpp b/src/tests/chaos/chaos_unload_report.cpp index 22147521..8bb58143 100644 --- a/src/tests/chaos/chaos_unload_report.cpp +++ b/src/tests/chaos/chaos_unload_report.cpp @@ -17,6 +17,8 @@ const int REPORTERS = 3; const int MAX_LEAKS = 4000; volatile LONG g_stop = 0; volatile LONG g_leaked = 0; +void* volatile g_blocks[MAX_LEAKS]; +volatile LONG g_blockThreads[MAX_LEAKS]; typedef void* (*HelperMalloc_t)(size_t); @@ -25,6 +27,66 @@ int __cdecl SwallowHook(int, wchar_t*, int*) return 1; } +// Addresses of the blocks a diagnostic report lists. +void* g_reported[MAX_LEAKS * 2]; +volatile LONG g_reportedCount = 0; + +int __cdecl CollectHook(int, wchar_t* message, int*) +{ + const wchar_t* at = wcsstr(message, L"---------- Block "); + if (at != NULL) + { + at = wcsstr(at, L" at 0x"); + if (at != NULL) + { + ULONG_PTR address = (ULONG_PTR)_wcstoui64(at + 6, NULL, 16); + LONG slot = InterlockedIncrement(&g_reportedCount) - 1; + if (slot < (LONG)_countof(g_reported)) + g_reported[slot] = (void*)address; + } + } + return 1; +} + +// Lists the leaked blocks that VLD does not report, to find out why it misses them. +void DescribeMissingBlocks() +{ + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, CollectHook); + VLDReportLeaks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, CollectHook); + LONG reported = min(g_reportedCount, (LONG)_countof(g_reported)); + char line[256]; + sprintf_s(line, "diagnostic report lists %ld blocks\n", reported); + chaos::Write(line); + int missing = 0; + for (LONG i = 0; i < g_leaked && i < MAX_LEAKS; i++) + { + bool found = false; + for (LONG j = 0; j < reported && !found; j++) + found = (ULONG_PTR)g_blocks[i] - (ULONG_PTR)g_reported[j] <= 64; + if (found) + continue; + if (++missing > 40) + continue; + const unsigned char* bytes = (const unsigned char*)g_blocks[i]; + int length = sprintf_s(line, "missing #%ld thread %ld at %p:", i, g_blockThreads[i], bytes); + __try + { + for (int b = 0; b < 16; b++) + length += sprintf_s(line + length, _countof(line) - length, " %02X", bytes[b]); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + length += sprintf_s(line + length, _countof(line) - length, " (not readable)"); + } + sprintf_s(line + length, _countof(line) - length, "\n"); + chaos::Write(line); + } + sprintf_s(line, "%d blocks missing from the diagnostic report\n", missing); + chaos::Write(line); +} + DWORD WINAPI Loader(LPVOID p) { chaos::Random random((unsigned)(INT_PTR)p * 53 + 11); @@ -37,12 +99,16 @@ DWORD WINAPI Loader(LPVOID p) int count = 1 + random.Below(4); for (int i = 0; i < count; i++) { - if (InterlockedIncrement(&g_leaked) > MAX_LEAKS) + LONG index = InterlockedIncrement(&g_leaked); + if (index > MAX_LEAKS) { InterlockedDecrement(&g_leaked); break; } - chaos::Check(helperMalloc(16 + random.Below(200)) != NULL, "HelperMalloc failed"); + void* block = helperMalloc(16 + random.Below(200)); + chaos::Check(block != NULL, "HelperMalloc failed"); + g_blocks[index - 1] = block; + g_blockThreads[index - 1] = (LONG)(INT_PTR)p; } FreeLibrary(helper); } @@ -95,6 +161,7 @@ int main() UINT counted = VLDGetLeaksCount(); if (counted != (UINT)g_leaked) { + DescribeMissingBlocks(); char message[96]; sprintf_s(message, "leaked %ld blocks but VLD counts %u", g_leaked, counted); chaos::Fail(message); From aabb877ad5f9b6cf96634ef1530b53d2bafa6018 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:39:13 -0800 Subject: [PATCH 58/91] chaos tests - COM task memory from racing threads with exact leak counts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_cotaskmem.cpp | 111 ++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 src/tests/chaos/chaos_cotaskmem.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index f47ec54c..e16359f5 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -923,6 +923,7 @@ set(VLD_CHAOS_TESTS chaos_aligned_new chaos_heaplock chaos_heaplock_report + chaos_cotaskmem ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_cotaskmem.cpp b/src/tests/chaos/chaos_cotaskmem.cpp new file mode 100644 index 00000000..0f04afe1 --- /dev/null +++ b/src/tests/chaos/chaos_cotaskmem.cpp @@ -0,0 +1,111 @@ +// chaos_cotaskmem.cpp - COM task memory from many threads at once, starting +// with a race on the first CoGetMalloc, with exact leak counts. +// +// VLD hooks CoGetMalloc and wraps the returned IMalloc, and hooks +// CoTaskMemAlloc and CoTaskMemRealloc. Threads that have not initialized COM +// race to get the task allocator, then allocate, reallocate (including to +// and from zero bytes), free through IMalloc and through CoTaskMemFree, and +// leak a known number of blocks. + +#include "chaos_common.h" +#include +#include "vld.h" + +#pragma comment(lib, "ole32.lib") + +namespace +{ +const int THREADS = 8; +const int ROUNDS = 400; +volatile LONG g_go = 0; +volatile LONG g_leaked = 0; + +DWORD WINAPI Worker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 37 + 13); + while (!InterlockedCompareExchange(&g_go, 0, 0)) + { + YieldProcessor(); + } + IMalloc* malloc = NULL; + chaos::Check(SUCCEEDED(CoGetMalloc(1, &malloc)) && malloc != NULL, "CoGetMalloc failed"); + for (int round = 0; round < ROUNDS; round++) + { + void* block = NULL; + switch (random.Below(4)) + { + case 0: + block = CoTaskMemAlloc(1 + random.Below(300)); + break; + case 1: + block = malloc->Alloc(1 + random.Below(300)); + break; + case 2: + block = CoTaskMemRealloc(NULL, 1 + random.Below(300)); + break; + default: + block = malloc->Realloc(NULL, 1 + random.Below(300)); + break; + } + chaos::Check(block != NULL, "a COM task allocation failed"); + if (random.Below(2)) + { + void* moved = random.Below(2) ? CoTaskMemRealloc(block, 1 + random.Below(2000)) : malloc->Realloc(block, 1 + random.Below(2000)); + chaos::Check(moved != NULL, "a COM task reallocation failed"); + block = moved; + } + if (random.Below(20) == 0) + { + InterlockedIncrement(&g_leaked); + continue; + } + switch (random.Below(3)) + { + case 0: + CoTaskMemFree(block); + break; + case 1: + malloc->Free(block); + break; + default: + // Reallocating to zero bytes frees the block. + chaos::Check(CoTaskMemRealloc(block, 0) == NULL, "CoTaskMemRealloc to zero bytes returned a block"); + break; + } + } + malloc->Release(); + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("racing first CoGetMalloc, then COM task memory churn"); + HANDLE threads[THREADS]; + for (int i = 0; i < THREADS; i++) + { + threads[i] = CreateThread(NULL, 0, Worker, (LPVOID)(INT_PTR)i, 0, NULL); + chaos::Check(threads[i] != NULL, "CreateThread failed"); + } + InterlockedExchange(&g_go, 1); + WaitForMultipleObjects(THREADS, threads, TRUE, INFINITE); + for (int i = 0; i < THREADS; i++) + { + CloseHandle(threads[i]); + } + + chaos::SetPhase("counting"); + SIZE_T counted = VLDGetLeaksCount() - base; + if (counted != (SIZE_T)g_leaked) + { + char message[96]; + sprintf_s(message, "leaked %ld COM task blocks but VLD counts %zu", g_leaked, counted); + chaos::Fail(message); + } + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} From 1ddc5d295243d4db7897a23a0eac77b0337c6fb7 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:44:02 -0800 Subject: [PATCH 59/91] Map blocks allocated by an allocation nested in another one The first hooked call of an allocation owns the thread's capture context, and the heap hooks record the block they see in the thread's state, mapped when that first call returns. An allocation made while another is in progress on the same thread (a CRT allocation hook that allocates, an allocator that allocates) recorded its block in the same state, and the outer allocation's block overwrote it, so it was never tracked: a debug CRT alloc hook that leaks lost every one of its leaks. CaptureContext::Set now maps a different block still recorded before it records a new one, under the call stack of the first call, and freeing a block that is recorded but not yet mapped forgets it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 34 ++++++++++++++++++++++++++++++---- src/vldint.h | 2 ++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 29840010..62d6208e 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1690,6 +1690,15 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & if (NULL == mem) return; + // A block allocated by an allocation nested in another one is mapped only + // when the outer one records its own block (CaptureContext::Set); a free + // before that leaves nothing to map. + tls_t* tls = getTls(); + if (tls->blockWithoutGuard == mem && tls->heap == heap && tls->newBlockWithoutGuard == NULL) { + tls->blockWithoutGuard = NULL; + tls->size = 0; + } + // Find this heap's block map. CriticalSectionLocker cs(g_heapMapLock); HeapMap::Iterator heapit = m_heapMap->find(heap); @@ -3798,6 +3807,15 @@ CaptureContext::~CaptureContext() { #endif BOOL excluded = IsExcludedModule(); + Commit(excluded); + + // Reset thread local flags and variables for the next allocation. + Reset(); +} + +// Commit - Maps the block that the hooks recorded in the thread's state, under +// the call stack of the first call that entered VLD. +void CaptureContext::Commit(BOOL excluded) { if ((m_tls->blockWithoutGuard) && (!excluded)) { blockinfo_t* pblockInfo = NULL; CallStack* callstack = CallStack::Create(); @@ -3832,12 +3850,16 @@ CaptureContext::~CaptureContext() { // address out again. g_vld.unmapMovedBlock(m_tls->heap, m_tls->blockWithoutGuard, m_tls->blockSerial, m_tls->context); } - - // Reset thread local flags and variables for the next allocation. - Reset(); } void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size, SIZE_T serial) { + // A block recorded earlier in this allocation belongs to an allocation + // nested in it (a CRT allocation hook, or an allocator that allocates), + // which has returned: map it before it is overwritten. + if (m_tls->blockWithoutGuard != NULL && mem != NULL && + (m_tls->heap != heap || m_tls->blockWithoutGuard != mem || m_tls->newBlockWithoutGuard != newmem)) { + Commit(IsExcludedModule(m_tls->context.fp)); + } m_tls->heap = heap; m_tls->blockWithoutGuard = mem; m_tls->newBlockWithoutGuard = newmem; @@ -3892,7 +3914,11 @@ BOOL CaptureContext::ShouldReportLeaksForModule(HMODULE hModule) { } BOOL CaptureContext::IsExcludedModule() { - HMODULE hModule = GetCallingModule(m_context.fp); + return IsExcludedModule(m_context.fp); +} + +BOOL CaptureContext::IsExcludedModule(UINT_PTR fp) { + HMODULE hModule = GetCallingModule(fp); if (hModule == g_vld.m_dbghlpBase) return TRUE; diff --git a/src/vldint.h b/src/vldint.h index c727a1b0..20eec841 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -237,8 +237,10 @@ class CaptureContext { CaptureContext& operator=(const CaptureContext&); private: BOOL IsExcludedModule(); + BOOL IsExcludedModule(UINT_PTR fp); BOOL IsCrtModuleWithNoReporting(HMODULE hModule); BOOL ShouldReportLeaksForModule(HMODULE hModule); + void Commit(BOOL excluded); void Reset(); private: tls_t *m_tls; From 52b7c48f349a43e5a44441537c36953162132498 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:44:02 -0800 Subject: [PATCH 60/91] chaos tests - a debug CRT alloc hook that allocates, leaks and vetoes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_crt_alloc_hook.cpp | 95 ++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 src/tests/chaos/chaos_crt_alloc_hook.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index e16359f5..b71455b6 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -924,6 +924,7 @@ set(VLD_CHAOS_TESTS chaos_heaplock chaos_heaplock_report chaos_cotaskmem + chaos_crt_alloc_hook ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_crt_alloc_hook.cpp b/src/tests/chaos/chaos_crt_alloc_hook.cpp new file mode 100644 index 00000000..9b1819d7 --- /dev/null +++ b/src/tests/chaos/chaos_crt_alloc_hook.cpp @@ -0,0 +1,95 @@ +// chaos_crt_alloc_hook.cpp - a debug CRT allocation hook that allocates and +// vetoes allocations, from several threads. +// +// The hook runs inside the debug CRT's malloc, before VLD sees the heap +// allocation. It allocates itself (guarded against recursion), leaks some of +// those blocks, and refuses every seventh allocation so that malloc returns +// NULL. VLD must count exactly the blocks that were allocated and leaked. In +// a release CRT the hook is not called, and only the plain leaks count. + +#include "chaos_common.h" +#include +#include +#include "vld.h" + +namespace +{ +const int THREADS = 6; +const int ROUNDS = 600; +volatile LONG g_leaked = 0; +volatile LONG g_vetoed = 0; +volatile LONG g_calls = 0; +__declspec(thread) int t_inHook = 0; + +int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigned char*, int) +{ + if (type != _HOOK_ALLOC || blockUse != _NORMAL_BLOCK || t_inHook) + return TRUE; + t_inHook = 1; + LONG call = InterlockedIncrement(&g_calls); + void* inner = malloc(24); + if (inner != NULL) + { + if (call % 11 == 0) + InterlockedIncrement(&g_leaked); + else + free(inner); + } + t_inHook = 0; + if (call % 7 == 0) + { + InterlockedIncrement(&g_vetoed); + return FALSE; + } + return TRUE; +} + +DWORD WINAPI Worker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 71 + 3); + for (int round = 0; round < ROUNDS; round++) + { + void* block = malloc(1 + random.Below(400)); + if (block == NULL) + continue; + if (random.Below(2)) + { + void* moved = realloc(block, 1 + random.Below(800)); + if (moved != NULL) + block = moved; + } + if (random.Below(25) == 0) + InterlockedIncrement(&g_leaked); + else + free(block); + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("allocating through a vetoing, allocating CRT alloc hook"); + _CRT_ALLOC_HOOK previous = _CrtSetAllocHook(AllocHook); + (void)&AllocHook; + chaos::RunThreads(THREADS, Worker); + _CrtSetAllocHook(previous); + + chaos::SetPhase("counting"); +#ifdef _DEBUG + chaos::Check(g_vetoed > 0, "the CRT alloc hook never vetoed an allocation"); +#endif + SIZE_T counted = VLDGetLeaksCount() - base; + if (counted != (SIZE_T)g_leaked) + { + char message[128]; + sprintf_s(message, "leaked %ld blocks (%ld allocations vetoed) but VLD counts %zu", g_leaked, g_vetoed, counted); + chaos::Fail(message); + } + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} From f157342600a5c93a03e318d1e1fbbcc15b1760c5 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:44:57 -0800 Subject: [PATCH 61/91] chaos tests - move a block from inside the CRT alloc hook Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_crt_alloc_hook.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/tests/chaos/chaos_crt_alloc_hook.cpp b/src/tests/chaos/chaos_crt_alloc_hook.cpp index 9b1819d7..e2c69ed5 100644 --- a/src/tests/chaos/chaos_crt_alloc_hook.cpp +++ b/src/tests/chaos/chaos_crt_alloc_hook.cpp @@ -20,6 +20,7 @@ volatile LONG g_leaked = 0; volatile LONG g_vetoed = 0; volatile LONG g_calls = 0; __declspec(thread) int t_inHook = 0; +__declspec(thread) void* t_moving = NULL; int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigned char*, int) { @@ -35,6 +36,10 @@ int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigne else free(inner); } + // A block that the hook keeps moving; each thread leaks it at the end. + void* moved = realloc(t_moving, 16 + (call % 5) * 200); + if (moved != NULL) + t_moving = moved; t_inHook = 0; if (call % 7 == 0) { @@ -63,6 +68,8 @@ DWORD WINAPI Worker(LPVOID p) else free(block); } + if (t_moving != NULL) + InterlockedIncrement(&g_leaked); return 0; } } From 05ae61f9fac17eb0b727f3105d9beeba91f497ee Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:52:43 -0800 Subject: [PATCH 62/91] Handle moves and frees of a nested block before it is mapped A reallocation of a block recorded but not yet mapped now moves the recorded block instead of mapping its old, already freed address. Freeing the recorded block's current address forgets it, and also unmaps the old address of a recorded move. A block mapped with the CRT flags of the first call keeps them as a guess unless it holds a debug CRT header that accounts for the whole block, since a block allocated inside the CRT (by an allocation hook, or after the hook vetoed the CRT's own allocation) is not a CRT block. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 61 +++++++++++++++++++++++++++++++++++++++++++--------- src/vldint.h | 3 ++- 2 files changed, 53 insertions(+), 11 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 62d6208e..8fd2d1bc 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -1691,12 +1691,18 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & return; // A block allocated by an allocation nested in another one is mapped only - // when the outer one records its own block (CaptureContext::Set); a free - // before that leaves nothing to map. + // when the outer one records its own block (CaptureContext::Set); freeing + // it before that leaves nothing to map, except the old address of a + // recorded move, which is gone too. tls_t* tls = getTls(); - if (tls->blockWithoutGuard == mem && tls->heap == heap && tls->newBlockWithoutGuard == NULL) { + if (tls->blockWithoutGuard != NULL && tls->heap == heap && + (tls->newBlockWithoutGuard != NULL ? tls->newBlockWithoutGuard : tls->blockWithoutGuard) == mem) { + if (tls->newBlockWithoutGuard != NULL && tls->newBlockWithoutGuard != tls->blockWithoutGuard) + unmapMovedBlock(heap, tls->blockWithoutGuard, tls->blockSerial, context); tls->blockWithoutGuard = NULL; + tls->newBlockWithoutGuard = NULL; tls->size = 0; + tls->blockSerial = 0; } // Find this heap's block map. @@ -2027,6 +2033,23 @@ static bool hasCrtNoMansLand (LPCVOID block, const unsigned char* gap, SIZE_T he return true; } +// hasCrtHeader - Checks that a heap block of the given size holds a debug CRT +// block: a header whose data size accounts for the whole block, and the +// no-man's land on both sides of the data. +bool VisualLeakDetector::hasCrtHeader (LPCVOID block, SIZE_T size, bool ucrt) +{ + if (!ucrt) { + crtdbgblockheader_t crtheader; + return size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader)) && + sizeof(crtheader) + crtheader.size + GAPSIZE == size && + hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size); + } + crtdbgblockheaderucrt_t crtheader; + return size >= sizeof(crtheader) && readTrackedBlock(&crtheader, block, sizeof(crtheader)) && + sizeof(crtheader) + crtheader.size + GAPSIZE == size && + hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size); +} + bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) { // Autodetection allocations from statically linked CRT @@ -3807,15 +3830,18 @@ CaptureContext::~CaptureContext() { #endif BOOL excluded = IsExcludedModule(); - Commit(excluded); + Commit(excluded, false); // Reset thread local flags and variables for the next allocation. Reset(); } // Commit - Maps the block that the hooks recorded in the thread's state, under -// the call stack of the first call that entered VLD. -void CaptureContext::Commit(BOOL excluded) { +// the call stack of the first call that entered VLD. The thread's CRT flags +// come from the first call, and need not describe a block allocated by an +// allocation nested in it (or by a CRT hook after the CRT vetoed its own +// allocation), so a block without a debug CRT header only guesses them. +void CaptureContext::Commit(BOOL excluded, bool nested) { if ((m_tls->blockWithoutGuard) && (!excluded)) { blockinfo_t* pblockInfo = NULL; CallStack* callstack = CallStack::Create(); @@ -3844,6 +3870,10 @@ void CaptureContext::Commit(BOOL excluded) { } pblockInfo->callStack.reset(callstack); + if (pblockInfo->debugCrtAlloc && + (nested || !g_vld.hasCrtHeader(m_tls->newBlockWithoutGuard != NULL ? m_tls->newBlockWithoutGuard : m_tls->blockWithoutGuard, + m_tls->size, pblockInfo->ucrt))) + pblockInfo->crtGuessed = true; } else if (excluded && m_tls->newBlockWithoutGuard != NULL && m_tls->newBlockWithoutGuard != m_tls->blockWithoutGuard) { // An excluded module moved a tracked block; the heap can hand the old @@ -3853,12 +3883,23 @@ void CaptureContext::Commit(BOOL excluded) { } void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size, SIZE_T serial) { - // A block recorded earlier in this allocation belongs to an allocation - // nested in it (a CRT allocation hook, or an allocator that allocates), - // which has returned: map it before it is overwritten. if (m_tls->blockWithoutGuard != NULL && mem != NULL && (m_tls->heap != heap || m_tls->blockWithoutGuard != mem || m_tls->newBlockWithoutGuard != newmem)) { - Commit(IsExcludedModule(m_tls->context.fp)); + LPVOID pending = m_tls->newBlockWithoutGuard != NULL ? m_tls->newBlockWithoutGuard : m_tls->blockWithoutGuard; + if (newmem != NULL && heap == m_tls->heap && mem == pending) { + // A reallocation of the block recorded but not mapped yet moves + // that block; the address it leaves was never mapped. + if (m_tls->newBlockWithoutGuard != NULL) + m_tls->newBlockWithoutGuard = newmem; + else + m_tls->blockWithoutGuard = newmem; + m_tls->size = size; + return; + } + // The block recorded earlier belongs to an allocation nested in this + // one (a CRT allocation hook, or an allocator that allocates), which + // has returned: map it before it is overwritten. + Commit(IsExcludedModule(m_tls->context.fp), true); } m_tls->heap = heap; m_tls->blockWithoutGuard = mem; diff --git a/src/vldint.h b/src/vldint.h index 20eec841..28a70ae9 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -240,7 +240,7 @@ class CaptureContext { BOOL IsExcludedModule(UINT_PTR fp); BOOL IsCrtModuleWithNoReporting(HMODULE hModule); BOOL ShouldReportLeaksForModule(HMODULE hModule); - void Commit(BOOL excluded); + void Commit(BOOL excluded, bool nested); void Reset(); private: tls_t *m_tls; @@ -360,6 +360,7 @@ class VisualLeakDetector : public IMalloc private: VOID reportConfig (); static bool isDebugCrtAlloc(LPCVOID block, blockinfo_t* info); + static bool hasCrtHeader (LPCVOID block, SIZE_T size, bool ucrt); SIZE_T reportHeapLeaks (HANDLE heap); static int getCrtBlockUse (LPCVOID block, bool ucrt, bool guessed); static size_t getCrtBlockSize(LPCVOID block, bool ucrt); From 59b86e822ee500d4d4a26bcd41a243e960a1f9c2 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:52:43 -0800 Subject: [PATCH 63/91] chaos tests - move, shrink and leak raw heap blocks from inside the CRT alloc hook Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_crt_alloc_hook.cpp | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/src/tests/chaos/chaos_crt_alloc_hook.cpp b/src/tests/chaos/chaos_crt_alloc_hook.cpp index e2c69ed5..838a8132 100644 --- a/src/tests/chaos/chaos_crt_alloc_hook.cpp +++ b/src/tests/chaos/chaos_crt_alloc_hook.cpp @@ -21,6 +21,7 @@ volatile LONG g_vetoed = 0; volatile LONG g_calls = 0; __declspec(thread) int t_inHook = 0; __declspec(thread) void* t_moving = NULL; +__declspec(thread) void* t_tracked = NULL; int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigned char*, int) { @@ -40,6 +41,48 @@ int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigne void* moved = realloc(t_moving, 16 + (call % 5) * 200); if (moved != NULL) t_moving = moved; + + // Raw heap blocks from inside the hook, while the CRT allocation that + // called it is in progress. + HANDLE heap = GetProcessHeap(); + switch (call % 3) + { + case 0: + { + // Allocated, then moved. + void* raw = HeapAlloc(heap, 0, 32); + void* grown = raw != NULL ? HeapReAlloc(heap, 0, raw, 4096) : NULL; + if (grown != NULL) + { + if (call % 4 == 0) + InterlockedIncrement(&g_leaked); + else + HeapFree(heap, 0, grown); + } + else if (raw != NULL) + { + HeapFree(heap, 0, raw); + } + break; + } + case 1: + // A tracked block shrunk in place, then freed. + if (t_tracked != NULL) + { + HeapReAlloc(heap, HEAP_REALLOC_IN_PLACE_ONLY, t_tracked, 64); + HeapFree(heap, 0, t_tracked); + t_tracked = NULL; + } + break; + default: + // Zero-filled, which looks like the header of a freed CRT block. + if (call % 4 == 2) + { + if (HeapAlloc(heap, HEAP_ZERO_MEMORY, 64) != NULL) + InterlockedIncrement(&g_leaked); + } + break; + } t_inHook = 0; if (call % 7 == 0) { @@ -54,6 +97,8 @@ DWORD WINAPI Worker(LPVOID p) chaos::Random random((unsigned)(INT_PTR)p * 71 + 3); for (int round = 0; round < ROUNDS; round++) { + if (t_tracked == NULL) + t_tracked = HeapAlloc(GetProcessHeap(), 0, 128); void* block = malloc(1 + random.Below(400)); if (block == NULL) continue; @@ -70,6 +115,8 @@ DWORD WINAPI Worker(LPVOID p) } if (t_moving != NULL) InterlockedIncrement(&g_leaked); + if (t_tracked != NULL) + HeapFree(GetProcessHeap(), 0, t_tracked); return 0; } } From 249450b5db1c413d6e09bb429f03e49cd20e0cb5 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 08:54:32 -0800 Subject: [PATCH 64/91] Keep the internal frames context when a nested block is moved before it is mapped Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/vld.cpp b/src/vld.cpp index 8fd2d1bc..aefa3b76 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -3894,6 +3894,8 @@ void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size, SI else m_tls->blockWithoutGuard = newmem; m_tls->size = size; + if (g_vld.m_options & VLD_OPT_TRACE_INTERNAL_FRAMES) + m_tls->context = m_context; return; } // The block recorded earlier belongs to an allocation nested in this From 064985ad50cdc47a0638f55b8344e8cb0c48ec94 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 09:17:18 -0800 Subject: [PATCH 65/91] Compare ignored function names ordinally lstrcmpW is locale aware and can initialize NLS caches on first use, which allocates from the process heap. The ignore function set is searched while VLD counts leaks, so on some OS builds those allocations were reported as leaks of the caller (ignore_modules_getaddrinfo_test on the ARM64 gate agents). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vldint.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/vldint.h b/src/vldint.h index 28a70ae9..091fc595 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -185,7 +185,8 @@ typedef Set ReportHookSet; struct functioninfo_t { BOOL operator < (const struct functioninfo_t& other) const { - if (lstrcmpW(name, other.name) < 0) { + // Ordinal: lstrcmpW may allocate NLS data while VLD counts leaks. + if (wcscmp(name, other.name) < 0) { return TRUE; } else { return FALSE; From 42d9bccfd442f30f0bd11894aadfdae34a1a9a90 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 09:17:18 -0800 Subject: [PATCH 66/91] Print the agent OS build and CPU in every build job Gate ARM64 agents and the ARM64 dev box behave differently; log both so failures can be tied to an OS build and CPU. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- build/templates/build-arch.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/build/templates/build-arch.yml b/build/templates/build-arch.yml index e3c41ed3..f3e04b95 100644 --- a/build/templates/build-arch.yml +++ b/build/templates/build-arch.yml @@ -35,6 +35,16 @@ steps: exit 1 } +- task: PowerShell@2 + displayName: 'Agent OS and CPU' + inputs: + targetType: 'inline' + script: | + $os = Get-CimInstance Win32_OperatingSystem + $ubr = (Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion').UBR + Write-Host "OS: $($os.Caption) $($os.Version).$ubr $($os.OSArchitecture)" + Get-CimInstance Win32_Processor | ForEach-Object { Write-Host "CPU: $($_.Name) ($($_.Manufacturer)) cores=$($_.NumberOfCores) lp=$($_.NumberOfLogicalProcessors)" } + # Discover Visual Studio and setup build variables - task: PowerShell@2 displayName: 'Discover Visual Studio (${{ parameters.arch }})' From 8f3f12ac466c4c9e71ce7bd9904507896de9215d Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 09:24:52 -0800 Subject: [PATCH 67/91] Print 64-bit addresses in full ADDRESSFORMAT used %X, which takes a 32-bit argument, so 64-bit reports dropped the upper half of every block and heap address. Use the I size prefix so the format takes a pointer-sized value on both platforms. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/utility.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/utility.h b/src/utility.h index 60a4b87f..667bbfcd 100644 --- a/src/utility.h +++ b/src/utility.h @@ -35,10 +35,10 @@ Applications should never include this header." #include "criticalsection.h" #ifdef _WIN64 -#define ADDRESSFORMAT L"0x%.16X" // Format string for 64-bit addresses +#define ADDRESSFORMAT L"0x%.16IX" // Format string for 64-bit addresses #define ADDRESSCPPFORMAT L"0x{:016X}" // Format string for 64-bit addresses #else -#define ADDRESSFORMAT L"0x%.8X" // Format string for 32-bit addresses +#define ADDRESSFORMAT L"0x%.8IX" // Format string for 32-bit addresses #define ADDRESSCPPFORMAT L"0x{:08X}" // Format string for 32-bit addresses #endif // _WIN64 #define BOM 0xFEFF // Unicode byte-order mark. From b1c72149a03d930137be1da8d6c196d0710d9488 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 09:24:52 -0800 Subject: [PATCH 68/91] Report heap blocks allocated inside a CRT allocation as heap blocks A block allocated from the heap while a debug CRT allocation is in progress (for example from a CRT alloc hook) is mapped with the CRT flag and marked as guessed. The report then took its address and size from a CRT header the block does not have. A guessed block that is readable and has no consistent CRT header is now treated as a plain heap block when counting, reporting and looking it up. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/vld.cpp b/src/vld.cpp index aefa3b76..270c5a93 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2081,6 +2081,14 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) } } + // A guessed block without a consistent header is a heap block that was + // allocated while a CRT allocation was in progress. A block that cannot + // be read is being freed, which getCrtBlockUse reports for CRT blocks. + if (info->debugCrtAlloc && info->crtGuessed) { + BYTE first; + if (readTrackedBlock(&first, block, sizeof(first)) && !hasCrtHeader(block, info->size, info->ucrt)) + return false; + } return info->debugCrtAlloc; } From b641b65305965f09cc686b49be6565249f7ebb6c Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 09:24:52 -0800 Subject: [PATCH 69/91] chaos tests - check that leaked blocks are reported at their own address Move the missing block diagnostics of chaos_unload_report to chaos_ledger.h. chaos_crt_alloc_hook records every block it leaks, prints the missed ones on a miscount, and fails if the report does not list each of them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_crt_alloc_hook.cpp | 30 ++++-- src/tests/chaos/chaos_ledger.h | 117 +++++++++++++++++++++++ src/tests/chaos/chaos_unload_report.cpp | 71 +------------- 3 files changed, 142 insertions(+), 76 deletions(-) create mode 100644 src/tests/chaos/chaos_ledger.h diff --git a/src/tests/chaos/chaos_crt_alloc_hook.cpp b/src/tests/chaos/chaos_crt_alloc_hook.cpp index 838a8132..a4c8fc89 100644 --- a/src/tests/chaos/chaos_crt_alloc_hook.cpp +++ b/src/tests/chaos/chaos_crt_alloc_hook.cpp @@ -7,10 +7,8 @@ // NULL. VLD must count exactly the blocks that were allocated and leaked. In // a release CRT the hook is not called, and only the plain leaks count. -#include "chaos_common.h" +#include "chaos_ledger.h" #include -#include -#include "vld.h" namespace { @@ -23,6 +21,14 @@ __declspec(thread) int t_inHook = 0; __declspec(thread) void* t_moving = NULL; __declspec(thread) void* t_tracked = NULL; +// Tags: 1 hook malloc, 2 grown raw block, 3 zeroed raw block, 4 moving block, +// 5 worker malloc. +void Leak(void* block, LONG tag) +{ + InterlockedIncrement(&g_leaked); + chaos::RecordLeak(block, tag); +} + int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigned char*, int) { if (type != _HOOK_ALLOC || blockUse != _NORMAL_BLOCK || t_inHook) @@ -33,7 +39,7 @@ int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigne if (inner != NULL) { if (call % 11 == 0) - InterlockedIncrement(&g_leaked); + Leak(inner, 1); else free(inner); } @@ -55,7 +61,7 @@ int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigne if (grown != NULL) { if (call % 4 == 0) - InterlockedIncrement(&g_leaked); + Leak(grown, 2); else HeapFree(heap, 0, grown); } @@ -78,8 +84,9 @@ int __cdecl AllocHook(int type, void*, size_t, int blockUse, long, const unsigne // Zero-filled, which looks like the header of a freed CRT block. if (call % 4 == 2) { - if (HeapAlloc(heap, HEAP_ZERO_MEMORY, 64) != NULL) - InterlockedIncrement(&g_leaked); + void* zeroed = HeapAlloc(heap, HEAP_ZERO_MEMORY, 64); + if (zeroed != NULL) + Leak(zeroed, 3); } break; } @@ -109,12 +116,12 @@ DWORD WINAPI Worker(LPVOID p) block = moved; } if (random.Below(25) == 0) - InterlockedIncrement(&g_leaked); + Leak(block, 5); else free(block); } if (t_moving != NULL) - InterlockedIncrement(&g_leaked); + Leak(t_moving, 4); if (t_tracked != NULL) HeapFree(GetProcessHeap(), 0, t_tracked); return 0; @@ -140,9 +147,14 @@ int main() if (counted != (SIZE_T)g_leaked) { char message[128]; + chaos::DescribeMissingLeaks(); sprintf_s(message, "leaked %ld blocks (%ld allocations vetoed) but VLD counts %zu", g_leaked, g_vetoed, counted); chaos::Fail(message); } + + // Heap blocks allocated inside the hook are reported at their own address. + chaos::SetPhase("reporting"); + chaos::Check(chaos::DescribeMissingLeaks() == 0, "the report misplaces leaked blocks"); VLDMarkAllLeaksAsReported(); chaos::Pass(); return 0; diff --git a/src/tests/chaos/chaos_ledger.h b/src/tests/chaos/chaos_ledger.h new file mode 100644 index 00000000..e5d54b34 --- /dev/null +++ b/src/tests/chaos/chaos_ledger.h @@ -0,0 +1,117 @@ +// chaos_ledger.h - records the blocks a chaos test leaks on purpose, and on a +// miscount lists the ones VLD does not report. + +#pragma once + +#include "chaos_common.h" +#include +#include "vld.h" + +namespace chaos +{ +const LONG LEDGER_SIZE = 8192; + +struct LedgerEntry +{ + void* volatile block; + volatile LONG tag; +}; + +inline LedgerEntry* Ledger() +{ + static LedgerEntry entries[LEDGER_SIZE]; + return entries; +} + +inline volatile LONG& LedgerCount() +{ + static volatile LONG count = 0; + return count; +} + +// The tag says where the block came from; it is printed if the block is missed. +inline void RecordLeak(void* block, LONG tag) +{ + LONG slot = InterlockedIncrement(&LedgerCount()) - 1; + if (slot < LEDGER_SIZE) + { + Ledger()[slot].tag = tag; + Ledger()[slot].block = block; + } +} + +inline void** ReportedBlocks() +{ + static void* blocks[LEDGER_SIZE * 2]; + return blocks; +} + +inline volatile LONG& ReportedCount() +{ + static volatile LONG count = 0; + return count; +} + +inline int __cdecl CollectReportedBlock(int, wchar_t* message, int*) +{ + const wchar_t* at = wcsstr(message, L"---------- Block "); + if (at != NULL) + { + at = wcsstr(at, L" at 0x"); + if (at != NULL) + { + ULONG_PTR address = (ULONG_PTR)_wcstoui64(at + 6, NULL, 16); + LONG slot = InterlockedIncrement(&ReportedCount()) - 1; + if (slot < LEDGER_SIZE * 2) + ReportedBlocks()[slot] = (void*)address; + } + } + return 1; +} + +// Reports the leaks through a collecting hook and prints every recorded block +// the report does not list, with its tag and first bytes. Returns how many +// are missing. Other report hooks must be removed first, or they may swallow +// the report. A CRT block is listed at its data, at most 64 bytes past the +// heap block. +inline int DescribeMissingLeaks() +{ + InterlockedExchange(&ReportedCount(), 0); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, CollectReportedBlock); + VLDReportLeaks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, CollectReportedBlock); + LONG reported = min(ReportedCount(), LEDGER_SIZE * 2); + LONG recorded = min(LedgerCount(), LEDGER_SIZE); + char line[256]; + sprintf_s(line, "diagnostic report lists %ld blocks, %ld recorded\n", reported, recorded); + Write(line); + int missing = 0; + for (LONG i = 0; i < recorded; i++) + { + const LedgerEntry& entry = Ledger()[i]; + bool found = false; + for (LONG j = 0; j < reported && !found; j++) + found = (ULONG_PTR)entry.block - (ULONG_PTR)ReportedBlocks()[j] <= 64; + if (found) + continue; + if (++missing > 40) + continue; + const unsigned char* bytes = (const unsigned char*)entry.block; + int length = sprintf_s(line, "missing #%ld tag %ld at %p:", i, entry.tag, bytes); + __try + { + for (int b = 0; b < 16; b++) + length += sprintf_s(line + length, _countof(line) - length, " %02X", bytes[b]); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + length += sprintf_s(line + length, _countof(line) - length, " (not readable)"); + } + sprintf_s(line + length, _countof(line) - length, "\n"); + Write(line); + } + sprintf_s(line, "%d blocks missing from the diagnostic report\n", missing); + Write(line); + return missing; +} +} diff --git a/src/tests/chaos/chaos_unload_report.cpp b/src/tests/chaos/chaos_unload_report.cpp index 8bb58143..e4f2d14b 100644 --- a/src/tests/chaos/chaos_unload_report.cpp +++ b/src/tests/chaos/chaos_unload_report.cpp @@ -6,8 +6,7 @@ // or another address. Reporters report, count and resolve the whole time. // Afterwards every leaked block must still be counted. -#include "chaos_common.h" -#include "vld.h" +#include "chaos_ledger.h" namespace { @@ -17,8 +16,6 @@ const int REPORTERS = 3; const int MAX_LEAKS = 4000; volatile LONG g_stop = 0; volatile LONG g_leaked = 0; -void* volatile g_blocks[MAX_LEAKS]; -volatile LONG g_blockThreads[MAX_LEAKS]; typedef void* (*HelperMalloc_t)(size_t); @@ -27,66 +24,6 @@ int __cdecl SwallowHook(int, wchar_t*, int*) return 1; } -// Addresses of the blocks a diagnostic report lists. -void* g_reported[MAX_LEAKS * 2]; -volatile LONG g_reportedCount = 0; - -int __cdecl CollectHook(int, wchar_t* message, int*) -{ - const wchar_t* at = wcsstr(message, L"---------- Block "); - if (at != NULL) - { - at = wcsstr(at, L" at 0x"); - if (at != NULL) - { - ULONG_PTR address = (ULONG_PTR)_wcstoui64(at + 6, NULL, 16); - LONG slot = InterlockedIncrement(&g_reportedCount) - 1; - if (slot < (LONG)_countof(g_reported)) - g_reported[slot] = (void*)address; - } - } - return 1; -} - -// Lists the leaked blocks that VLD does not report, to find out why it misses them. -void DescribeMissingBlocks() -{ - VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); - VLDSetReportHook(VLD_RPTHOOK_INSTALL, CollectHook); - VLDReportLeaks(); - VLDSetReportHook(VLD_RPTHOOK_REMOVE, CollectHook); - LONG reported = min(g_reportedCount, (LONG)_countof(g_reported)); - char line[256]; - sprintf_s(line, "diagnostic report lists %ld blocks\n", reported); - chaos::Write(line); - int missing = 0; - for (LONG i = 0; i < g_leaked && i < MAX_LEAKS; i++) - { - bool found = false; - for (LONG j = 0; j < reported && !found; j++) - found = (ULONG_PTR)g_blocks[i] - (ULONG_PTR)g_reported[j] <= 64; - if (found) - continue; - if (++missing > 40) - continue; - const unsigned char* bytes = (const unsigned char*)g_blocks[i]; - int length = sprintf_s(line, "missing #%ld thread %ld at %p:", i, g_blockThreads[i], bytes); - __try - { - for (int b = 0; b < 16; b++) - length += sprintf_s(line + length, _countof(line) - length, " %02X", bytes[b]); - } - __except (EXCEPTION_EXECUTE_HANDLER) - { - length += sprintf_s(line + length, _countof(line) - length, " (not readable)"); - } - sprintf_s(line + length, _countof(line) - length, "\n"); - chaos::Write(line); - } - sprintf_s(line, "%d blocks missing from the diagnostic report\n", missing); - chaos::Write(line); -} - DWORD WINAPI Loader(LPVOID p) { chaos::Random random((unsigned)(INT_PTR)p * 53 + 11); @@ -107,8 +44,7 @@ DWORD WINAPI Loader(LPVOID p) } void* block = helperMalloc(16 + random.Below(200)); chaos::Check(block != NULL, "HelperMalloc failed"); - g_blocks[index - 1] = block; - g_blockThreads[index - 1] = (LONG)(INT_PTR)p; + chaos::RecordLeak(block, (LONG)(INT_PTR)p); } FreeLibrary(helper); } @@ -161,7 +97,8 @@ int main() UINT counted = VLDGetLeaksCount(); if (counted != (UINT)g_leaked) { - DescribeMissingBlocks(); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::DescribeMissingLeaks(); char message[96]; sprintf_s(message, "leaked %ld blocks but VLD counts %u", g_leaked, counted); chaos::Fail(message); From d5461510fa4622bc0e7ef10a29c42f2c4102a323 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 09:30:20 -0800 Subject: [PATCH 70/91] Read the CRT header of a reported block only if it is classified as a CRT block reportLeaks read the CRT header and printed the CRT allocation ID whenever the block was mapped with the CRT flag, so a small heap block allocated inside a CRT allocation, next to a guard page, was counted but skipped by the report. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/vld.cpp b/src/vld.cpp index 270c5a93..b35f9a89 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -2211,8 +2211,9 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S LPCVOID address = block; SIZE_T size = info->size; + const bool crtBlock = isDebugCrtAlloc(block, info); - if (isDebugCrtAlloc( block, info )) { + if (crtBlock) { // This block is allocated to a CRT heap, so the block has a CRT // memory block header pretended to it. int blockUse = getCrtBlockUse( block, info->ucrt, info->crtGuessed ); @@ -2245,7 +2246,7 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S // A block that can no longer be read is being freed. #ifdef _DEBUG SIZE_T crtRequest = 0; - if (info->debugCrtAlloc) { + if (crtBlock) { crtdbgblockheader_t crtheader; if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) continue; @@ -2271,7 +2272,7 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S SIZE_T blockLeaksCount = 1; Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", info->serialNumber, address, size); #ifdef _DEBUG - if (info->debugCrtAlloc) + if (crtBlock) Report(L" CRT Alloc ID: %Iu\n", crtRequest); #endif assert(info->callStack); From 62af29248a8bab3c188a68391607f84c47d994e4 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 10:00:57 -0800 Subject: [PATCH 71/91] chaos tests - allocate and leak from a new handler of failing allocations chaos_new_handler makes operator new and malloc (new mode 1) fail, and the new handler allocates, leaks CRT and heap blocks and asks for a retry while the failing CRT allocation is in progress. VLD must count every leaked block and report it at its own address. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_new_handler.cpp | 153 ++++++++++++++++++++++++++ 2 files changed, 154 insertions(+) create mode 100644 src/tests/chaos/chaos_new_handler.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index b71455b6..25848ad2 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -925,6 +925,7 @@ set(VLD_CHAOS_TESTS chaos_heaplock_report chaos_cotaskmem chaos_crt_alloc_hook + chaos_new_handler ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_new_handler.cpp b/src/tests/chaos/chaos_new_handler.cpp new file mode 100644 index 00000000..3d97dc75 --- /dev/null +++ b/src/tests/chaos/chaos_new_handler.cpp @@ -0,0 +1,153 @@ +// chaos_new_handler.cpp - a new handler that allocates, leaks and retries, +// called from inside operator new and malloc allocations that fail. +// +// With _set_new_mode(1) malloc also calls the handler. The handler runs while +// the failing CRT allocation is in progress, before VLD has mapped anything +// for it. It allocates and leaks CRT and heap blocks, asks for a retry once, +// then gives up, so operator new throws and malloc returns NULL. VLD must +// count every leaked block and report it at its own address. + +#include "chaos_ledger.h" +#include +#include +#include + +namespace +{ +const int THREADS = 6; +const int ROUNDS = 300; +volatile LONG g_leaked = 0; +volatile LONG g_handled = 0; +volatile LONG g_thrown = 0; +__declspec(thread) int t_retries = 0; + +// More than the address space, but small enough that the CRT tries the heap. +#ifdef _WIN64 +const size_t HUGE_SIZE = (size_t)1 << 50; +#else +const size_t HUGE_SIZE = 0x7FFF0000; +#endif + +// Tags: 1 handler malloc, 2 handler new[], 3 handler heap block, 4 worker +// malloc, 5 worker new. +void Leak(void* block, LONG tag) +{ + InterlockedIncrement(&g_leaked); + chaos::RecordLeak(block, tag); +} + +int __cdecl NewHandler(size_t) +{ + LONG call = InterlockedIncrement(&g_handled); + void* block = malloc(40); + if (block != NULL) + { + if (call % 5 == 0) + Leak(block, 1); + else + free(block); + } + char* array = new (std::nothrow) char[24]; + if (array != NULL) + { + if (call % 7 == 0) + Leak(array, 2); + else + delete[] array; + } + HANDLE heap = GetProcessHeap(); + void* raw = HeapAlloc(heap, 0, 48); + if (raw != NULL) + { + if (call % 3 == 0) + Leak(raw, 3); + else + HeapFree(heap, 0, raw); + } + if (++t_retries >= 2) + return 0; + return 1; +} + +DWORD WINAPI Worker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 37 + 13); + for (int round = 0; round < ROUNDS; round++) + { + // The handler asks for one retry per failing allocation; operator new + // and malloc in new mode 1 each loop over it. + t_retries = 0; + switch (random.Below(4)) + { + case 0: + try + { + char* never = new char[HUGE_SIZE]; + chaos::Fail("a huge operator new succeeded"); + delete[] never; + } + catch (const std::bad_alloc&) + { + InterlockedIncrement(&g_thrown); + } + break; + case 1: + chaos::Check(malloc(HUGE_SIZE) == NULL, "a huge malloc succeeded"); + break; + case 2: + { + void* block = malloc(1 + random.Below(300)); + if (block != NULL) + { + if (random.Below(10) == 0) + Leak(block, 4); + else + free(block); + } + break; + } + default: + { + int* value = new int(round); + if (random.Below(10) == 0) + Leak(value, 5); + else + delete value; + break; + } + } + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("failing allocations through an allocating new handler"); + _PNH previous = _set_new_handler(NewHandler); + int previousMode = _set_new_mode(1); + chaos::RunThreads(THREADS, Worker); + _set_new_mode(previousMode); + _set_new_handler(previous); + + chaos::SetPhase("counting"); + chaos::Check(g_handled > 0, "the new handler was never called"); + chaos::Check(g_thrown > 0, "operator new never threw"); + SIZE_T counted = VLDGetLeaksCount() - base; + if (counted != (SIZE_T)g_leaked) + { + char message[128]; + chaos::DescribeMissingLeaks(); + sprintf_s(message, "leaked %ld blocks (%ld handler calls) but VLD counts %zu", g_leaked, g_handled, counted); + chaos::Fail(message); + } + + chaos::SetPhase("reporting"); + chaos::Check(chaos::DescribeMissingLeaks() == 0, "the report misplaces leaked blocks"); + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} From f209447e09a354d68cc5946c0bd454e1eb09a7c4 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 10:07:09 -0800 Subject: [PATCH 72/91] chaos_new_handler - guard the handler against reentry and make every huge request fail The handler's own allocations can fail and call it again, and other threads can reach it, so it only runs once per thread at a time and only on workers. On x86 the request is 0xFFF00000, which no 32-bit address space can hold, passed at run time so that new[] compiles. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_new_handler.cpp | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/tests/chaos/chaos_new_handler.cpp b/src/tests/chaos/chaos_new_handler.cpp index 3d97dc75..b8096d17 100644 --- a/src/tests/chaos/chaos_new_handler.cpp +++ b/src/tests/chaos/chaos_new_handler.cpp @@ -20,12 +20,14 @@ volatile LONG g_leaked = 0; volatile LONG g_handled = 0; volatile LONG g_thrown = 0; __declspec(thread) int t_retries = 0; +__declspec(thread) bool t_worker = false; +__declspec(thread) bool t_inHandler = false; // More than the address space, but small enough that the CRT tries the heap. #ifdef _WIN64 -const size_t HUGE_SIZE = (size_t)1 << 50; +volatile size_t g_hugeSize = (size_t)1 << 50; #else -const size_t HUGE_SIZE = 0x7FFF0000; +volatile size_t g_hugeSize = 0xFFF00000; #endif // Tags: 1 handler malloc, 2 handler new[], 3 handler heap block, 4 worker @@ -38,6 +40,10 @@ void Leak(void* block, LONG tag) int __cdecl NewHandler(size_t) { + // The handler's own allocations can fail and call it again. + if (!t_worker || t_inHandler) + return 0; + t_inHandler = true; LONG call = InterlockedIncrement(&g_handled); void* block = malloc(40); if (block != NULL) @@ -64,6 +70,7 @@ int __cdecl NewHandler(size_t) else HeapFree(heap, 0, raw); } + t_inHandler = false; if (++t_retries >= 2) return 0; return 1; @@ -72,6 +79,7 @@ int __cdecl NewHandler(size_t) DWORD WINAPI Worker(LPVOID p) { chaos::Random random((unsigned)(INT_PTR)p * 37 + 13); + t_worker = true; for (int round = 0; round < ROUNDS; round++) { // The handler asks for one retry per failing allocation; operator new @@ -82,7 +90,7 @@ DWORD WINAPI Worker(LPVOID p) case 0: try { - char* never = new char[HUGE_SIZE]; + char* never = new char[g_hugeSize]; chaos::Fail("a huge operator new succeeded"); delete[] never; } @@ -92,7 +100,7 @@ DWORD WINAPI Worker(LPVOID p) } break; case 1: - chaos::Check(malloc(HUGE_SIZE) == NULL, "a huge malloc succeeded"); + chaos::Check(malloc(g_hugeSize) == NULL, "a huge malloc succeeded"); break; case 2: { From 33e6ad26b58075846795204288dfb8f1587461b8 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 10:10:23 -0800 Subject: [PATCH 73/91] chaos tests - allocate and leak from an IMallocSpy inside COM task allocations chaos_malloc_spy registers a malloc spy that puts every COM task block behind a header of its own and allocates and leaks CRT and heap blocks from PostAlloc and PostRealloc. VLD must count every leaked block and report it next to the pointer the application holds. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/CMakeLists.txt | 1 + src/tests/chaos/chaos_malloc_spy.cpp | 175 +++++++++++++++++++++++++++ 2 files changed, 176 insertions(+) create mode 100644 src/tests/chaos/chaos_malloc_spy.cpp diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 25848ad2..68fcccdb 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -926,6 +926,7 @@ set(VLD_CHAOS_TESTS chaos_cotaskmem chaos_crt_alloc_hook chaos_new_handler + chaos_malloc_spy ) function(set_chaos_output_dir TARGET_NAME) diff --git a/src/tests/chaos/chaos_malloc_spy.cpp b/src/tests/chaos/chaos_malloc_spy.cpp new file mode 100644 index 00000000..2a334051 --- /dev/null +++ b/src/tests/chaos/chaos_malloc_spy.cpp @@ -0,0 +1,175 @@ +// chaos_malloc_spy.cpp - an IMallocSpy that moves every COM task block behind +// a header of its own, and allocates and leaks from inside the allocations it +// watches. +// +// VLD hooks CoTaskMemAlloc and CoTaskMemRealloc. The spy runs inside them: +// PostAlloc and PostRealloc allocate CRT and heap blocks while the COM +// allocation is still in progress, and the pointer the application gets is +// 16 bytes past the heap block. VLD must count every leaked block and report +// it next to the pointer the application holds. + +#include "chaos_ledger.h" +#include +#include + +#pragma comment(lib, "ole32.lib") + +namespace +{ +const int THREADS = 6; +const int ROUNDS = 300; +const SIZE_T HEADER = 16; +volatile LONG g_leaked = 0; +volatile LONG g_spied = 0; +__declspec(thread) bool t_worker = false; +__declspec(thread) bool t_inSpy = false; + +// Tags: 1 spy malloc, 2 spy heap block, 3 spy new, 4 worker COM block. +void Leak(void* block, LONG tag) +{ + InterlockedIncrement(&g_leaked); + chaos::RecordLeak(block, tag); +} + +void AllocateInsideSpy() +{ + if (!t_worker || t_inSpy) + return; + t_inSpy = true; + LONG call = InterlockedIncrement(&g_spied); + void* block = malloc(32); + if (block != NULL) + { + if (call % 6 == 0) + Leak(block, 1); + else + free(block); + } + HANDLE heap = GetProcessHeap(); + void* raw = HeapAlloc(heap, 0, 48); + if (raw != NULL) + { + if (call % 4 == 0) + Leak(raw, 2); + else + HeapFree(heap, 0, raw); + } + if (call % 9 == 0) + Leak(new int((int)call), 3); + t_inSpy = false; +} + +void* Behind(void* request, BOOL spied) +{ + return request != NULL && spied ? (BYTE*)request - HEADER : request; +} + +class Spy : public IMallocSpy +{ +public: + STDMETHODIMP QueryInterface(REFIID riid, void** object) + { + if (riid == IID_IUnknown || riid == IID_IMallocSpy) + { + *object = static_cast(this); + return S_OK; + } + *object = NULL; + return E_NOINTERFACE; + } + // The spy is a static object; COM may hold it past main. + STDMETHODIMP_(ULONG) AddRef() { return 2; } + STDMETHODIMP_(ULONG) Release() { return 1; } + + STDMETHODIMP_(SIZE_T) PreAlloc(SIZE_T request) { return request + HEADER; } + STDMETHODIMP_(void*) PostAlloc(void* actual) + { + if (actual == NULL) + return NULL; + memset(actual, 0x5A, HEADER); + AllocateInsideSpy(); + return (BYTE*)actual + HEADER; + } + STDMETHODIMP_(void*) PreFree(void* request, BOOL spied) { return Behind(request, spied); } + STDMETHODIMP_(void) PostFree(BOOL) {} + STDMETHODIMP_(SIZE_T) PreRealloc(void* request, SIZE_T size, void** newRequest, BOOL spied) + { + *newRequest = Behind(request, spied); + if (size == 0 || (request != NULL && !spied)) + return size; + return size + HEADER; + } + STDMETHODIMP_(void*) PostRealloc(void* actual, BOOL spied) + { + if (actual == NULL || !spied) + return actual; + AllocateInsideSpy(); + return (BYTE*)actual + HEADER; + } + STDMETHODIMP_(void*) PreGetSize(void* request, BOOL spied) { return Behind(request, spied); } + STDMETHODIMP_(SIZE_T) PostGetSize(SIZE_T actual, BOOL spied) { return spied && actual >= HEADER ? actual - HEADER : actual; } + STDMETHODIMP_(void*) PreDidAlloc(void* request, BOOL spied) { return Behind(request, spied); } + STDMETHODIMP_(int) PostDidAlloc(void*, BOOL, int actual) { return actual; } + STDMETHODIMP_(void) PreHeapMinimize() {} + STDMETHODIMP_(void) PostHeapMinimize() {} +}; + +Spy g_spy; + +DWORD WINAPI Worker(LPVOID p) +{ + chaos::Random random((unsigned)(INT_PTR)p * 41 + 7); + t_worker = true; + for (int round = 0; round < ROUNDS; round++) + { + void* block = random.Below(2) ? CoTaskMemAlloc(1 + random.Below(300)) : CoTaskMemRealloc(NULL, 1 + random.Below(300)); + chaos::Check(block != NULL, "a COM task allocation failed"); + if (random.Below(2)) + { + void* moved = CoTaskMemRealloc(block, 1 + random.Below(2000)); + chaos::Check(moved != NULL, "a COM task reallocation failed"); + block = moved; + } + if (random.Below(15) == 0) + { + Leak(block, 4); + continue; + } + if (random.Below(2)) + CoTaskMemFree(block); + else + chaos::Check(CoTaskMemRealloc(block, 0) == NULL, "CoTaskMemRealloc to zero bytes returned a block"); + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(25000); + chaos::Check(SUCCEEDED(CoInitializeEx(NULL, COINIT_MULTITHREADED)), "CoInitializeEx failed"); + SIZE_T base = VLDGetLeaksCount(); + + chaos::SetPhase("COM task memory through an allocating malloc spy"); + chaos::Check(SUCCEEDED(CoRegisterMallocSpy(&g_spy)), "CoRegisterMallocSpy failed"); + chaos::RunThreads(THREADS, Worker); + // Revoking waits for the spied blocks, and some are leaked. + CoRevokeMallocSpy(); + + chaos::SetPhase("counting"); + chaos::Check(g_spied > 0, "the spy never allocated"); + SIZE_T counted = VLDGetLeaksCount() - base; + if (counted != (SIZE_T)g_leaked) + { + char message[128]; + chaos::DescribeMissingLeaks(); + sprintf_s(message, "leaked %ld blocks (%ld spy calls) but VLD counts %zu", g_leaked, g_spied, counted); + chaos::Fail(message); + } + + chaos::SetPhase("reporting"); + chaos::Check(chaos::DescribeMissingLeaks() == 0, "the report misplaces leaked blocks"); + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} From 02b018fdfe2b9a2e62d366163fcd2be70722ead5 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 10:18:47 -0800 Subject: [PATCH 74/91] chaos_malloc_spy - give a reallocated block from before the spy a header COM treats a reallocated block as spied even if it was allocated before the spy, so freeing it stepped back over a header it did not have. The spy now adds the header on such a reallocation and moves the data behind it; the test reallocates and frees a block from before the spy. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_malloc_spy.cpp | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/tests/chaos/chaos_malloc_spy.cpp b/src/tests/chaos/chaos_malloc_spy.cpp index 2a334051..44e69d42 100644 --- a/src/tests/chaos/chaos_malloc_spy.cpp +++ b/src/tests/chaos/chaos_malloc_spy.cpp @@ -23,6 +23,8 @@ volatile LONG g_leaked = 0; volatile LONG g_spied = 0; __declspec(thread) bool t_worker = false; __declspec(thread) bool t_inSpy = false; +__declspec(thread) SIZE_T t_reallocSize = 0; +__declspec(thread) bool t_reallocAddsHeader = false; // Tags: 1 spy malloc, 2 spy heap block, 3 spy new, 4 worker COM block. void Leak(void* block, LONG tag) @@ -95,14 +97,18 @@ class Spy : public IMallocSpy STDMETHODIMP_(SIZE_T) PreRealloc(void* request, SIZE_T size, void** newRequest, BOOL spied) { *newRequest = Behind(request, spied); - if (size == 0 || (request != NULL && !spied)) - return size; - return size + HEADER; + // COM treats the result as spied even if the block was not, so a block + // without a header gets one and its data moves behind it. + t_reallocSize = size; + t_reallocAddsHeader = request != NULL && !spied; + return size == 0 ? 0 : size + HEADER; } - STDMETHODIMP_(void*) PostRealloc(void* actual, BOOL spied) + STDMETHODIMP_(void*) PostRealloc(void* actual, BOOL) { - if (actual == NULL || !spied) - return actual; + if (actual == NULL) + return NULL; + if (t_reallocAddsHeader) + memmove((BYTE*)actual + HEADER, actual, t_reallocSize); AllocateInsideSpy(); return (BYTE*)actual + HEADER; } @@ -151,7 +157,14 @@ int main() SIZE_T base = VLDGetLeaksCount(); chaos::SetPhase("COM task memory through an allocating malloc spy"); + BYTE* early = (BYTE*)CoTaskMemAlloc(64); + chaos::Check(early != NULL, "CoTaskMemAlloc failed"); + memset(early, 0x3C, 64); chaos::Check(SUCCEEDED(CoRegisterMallocSpy(&g_spy)), "CoRegisterMallocSpy failed"); + // A block from before the spy is reallocated and freed through it. + early = (BYTE*)CoTaskMemRealloc(early, 128); + chaos::Check(early != NULL && early[0] == 0x3C && early[63] == 0x3C, "reallocating a block from before the spy lost its data"); + CoTaskMemFree(early); chaos::RunThreads(THREADS, Worker); // Revoking waits for the spied blocks, and some are leaked. CoRevokeMallocSpy(); From 7ade148c1c34a3fdeba5e1854cf26b74cef16a16 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 10:18:48 -0800 Subject: [PATCH 75/91] chaos_ledger - match reported blocks one to one and show what VLD knows about a missed block A reported block could satisfy several recorded blocks within 64 bytes and hide a missed one. Each reported block now matches one recorded block, at the same address first. For a missed block the diagnostics print its call stack if VLD still tracks it, to tell a skipped leak from one VLD never saw. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_ledger.h | 54 ++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 6 deletions(-) diff --git a/src/tests/chaos/chaos_ledger.h b/src/tests/chaos/chaos_ledger.h index e5d54b34..e403beaf 100644 --- a/src/tests/chaos/chaos_ledger.h +++ b/src/tests/chaos/chaos_ledger.h @@ -69,11 +69,38 @@ inline int __cdecl CollectReportedBlock(int, wchar_t* message, int*) return 1; } +typedef const wchar_t* (*AllocationCallstack_t)(void* alloc, BOOL showInternalFrames); + +// Prints what VLD knows about a block the report misses: its call stack if VLD +// still tracks it, which tells a skipped leak from one VLD never saw. +inline void DescribeTrackedBlock(void* block) +{ + HMODULE vld = NULL; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCWSTR)&VLDReportLeaks, &vld); + AllocationCallstack_t callstack = vld != NULL ? + (AllocationCallstack_t)GetProcAddress(vld, "VldInternalGetAllocationCallstack") : NULL; + if (callstack == NULL) + return; + const wchar_t* stack = callstack(block, TRUE); + if (stack == NULL) + { + Write(" not tracked by VLD\n"); + return; + } + char text[1024]; + int length = WideCharToMultiByte(CP_UTF8, 0, stack, -1, text, sizeof(text) - 1, NULL, NULL); + text[length > 0 ? length : 0] = '\0'; + Write(" tracked, call stack:\n"); + Write(text); + Write("\n"); +} + // Reports the leaks through a collecting hook and prints every recorded block // the report does not list, with its tag and first bytes. Returns how many // are missing. Other report hooks must be removed first, or they may swallow -// the report. A CRT block is listed at its data, at most 64 bytes past the -// heap block. +// the report. A reported block is matched to one recorded block only: at the +// same address first, then up to 64 bytes before it (a CRT or other header). inline int DescribeMissingLeaks() { InterlockedExchange(&ReportedCount(), 0); @@ -85,14 +112,27 @@ inline int DescribeMissingLeaks() char line[256]; sprintf_s(line, "diagnostic report lists %ld blocks, %ld recorded\n", reported, recorded); Write(line); + static bool used[LEDGER_SIZE * 2]; + static bool matched[LEDGER_SIZE]; + memset(used, 0, sizeof(used)); + memset(matched, 0, sizeof(matched)); + for (int pass = 0; pass < 2; pass++) + { + for (LONG i = 0; i < recorded; i++) + { + for (LONG j = 0; j < reported && !matched[i]; j++) + { + ULONG_PTR offset = (ULONG_PTR)Ledger()[i].block - (ULONG_PTR)ReportedBlocks()[j]; + if (!used[j] && (pass == 0 ? offset == 0 : offset <= 64)) + used[j] = matched[i] = true; + } + } + } int missing = 0; for (LONG i = 0; i < recorded; i++) { const LedgerEntry& entry = Ledger()[i]; - bool found = false; - for (LONG j = 0; j < reported && !found; j++) - found = (ULONG_PTR)entry.block - (ULONG_PTR)ReportedBlocks()[j] <= 64; - if (found) + if (matched[i]) continue; if (++missing > 40) continue; @@ -109,6 +149,8 @@ inline int DescribeMissingLeaks() } sprintf_s(line + length, _countof(line) - length, "\n"); Write(line); + if (missing <= 8) + DescribeTrackedBlock(entry.block); } sprintf_s(line, "%d blocks missing from the diagnostic report\n", missing); Write(line); From b472a2da9b46fb7ea998bd57b7a2f60d3e32e415 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 10:38:31 -0800 Subject: [PATCH 76/91] chaos_heap_flags - inspect a fixed-size heap instead of the process heap A gate hang dump showed one HeapWalk call on the process heap spinning for 24 s in RtlpWalkLFHBlock on Windows Server 2022, with no VLD frame on any stack: low-fragmentation heap blocks change without the heap lock. Fixed-size heaps never get the LFH, so the allocation traffic and the walk, compact and validate calls now use one. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_heap_flags.cpp | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/tests/chaos/chaos_heap_flags.cpp b/src/tests/chaos/chaos_heap_flags.cpp index 06da1d0e..7a3a86f4 100644 --- a/src/tests/chaos/chaos_heap_flags.cpp +++ b/src/tests/chaos/chaos_heap_flags.cpp @@ -13,11 +13,15 @@ namespace { const DWORD RUN_MS = 2500; volatile LONG g_stop = 0; +// Fixed-size heaps never get the low-fragmentation heap, whose blocks change +// without the heap lock; walking one that other threads use can spin inside a +// single HeapWalk call on Windows Server 2022. +HANDLE g_heap = NULL; DWORD WINAPI Allocator(LPVOID p) { chaos::Random random((unsigned)(INT_PTR)p * 31 + 7); - HANDLE heap = GetProcessHeap(); + HANDLE heap = g_heap; void* slots[16] = { 0 }; while (!InterlockedCompareExchange(&g_stop, 0, 0)) { @@ -52,7 +56,7 @@ DWORD WINAPI Allocator(LPVOID p) DWORD WINAPI Inspector(LPVOID p) { - HANDLE heap = GetProcessHeap(); + HANDLE heap = g_heap; bool walk = ((INT_PTR)p % 2) == 0; while (!InterlockedCompareExchange(&g_stop, 0, 0)) { @@ -60,8 +64,6 @@ DWORD WINAPI Inspector(LPVOID p) { if (HeapLock(heap)) { - // Bounded: on Windows Server 2022 a walk of a heap whose LFH - // other threads keep changing can take tens of seconds. PROCESS_HEAP_ENTRY entry = { 0 }; int entries = 0; ULONGLONG deadline = GetTickCount64() + 100; @@ -166,8 +168,11 @@ int main() chaos::Check(VLDGetLeaksCount() == base, "a freed zero-size block is still counted"); chaos::SetPhase("heap inspection under allocation traffic"); + g_heap = HeapCreate(0, 0, 32 * 1024 * 1024); + chaos::Check(g_heap != NULL, "HeapCreate of a fixed-size heap failed"); chaos::RunThreads(7, Worker); chaos::Check(VLDGetLeaksCount() == base, "allocation traffic with heap inspection left leaks"); + HeapDestroy(g_heap); chaos::Pass(); return 0; } From 6a9bfe1ad43ee6bfa485ac786bac8e5d06565a77 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 11:02:11 -0800 Subject: [PATCH 77/91] chaos_heaplock_report - wait for the report hook instead of a fixed time Report hooks run once VLD has built the whole report and released its lock, and a report of the many leaks the lockers make can take longer than the 2 s phase on a busy gate agent (x86 Debug, 'the report hook was never called'). The hook phase now runs until the hook is called, failing only after 15 s more. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_heaplock_report.cpp | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/src/tests/chaos/chaos_heaplock_report.cpp b/src/tests/chaos/chaos_heaplock_report.cpp index 44544f7f..1a97ecf7 100644 --- a/src/tests/chaos/chaos_heaplock_report.cpp +++ b/src/tests/chaos/chaos_heaplock_report.cpp @@ -13,6 +13,7 @@ namespace { const DWORD PHASE_MS = 2000; +const DWORD PROGRESS_MS = 15000; volatile LONG g_stop = 0; volatile LONG g_leaked = 0; volatile LONG g_hookCalls = 0; @@ -61,7 +62,11 @@ DWORD WINAPI Reporter(LPVOID) return 0; } -void RunPhase(const char* phase) +// Runs the phase for PHASE_MS, and then until *progress is nonzero: the hook +// sees a report only after VLD has built all of it, and a report of many +// leaks can take longer than PHASE_MS on a busy machine. Fails if there is +// still no progress after PROGRESS_MS. +void RunPhase(const char* phase, volatile LONG* progress) { chaos::SetPhase(phase); InterlockedExchange(&g_stop, 0); @@ -72,6 +77,11 @@ void RunPhase(const char* phase) chaos::Check(threads[i] != NULL, "CreateThread failed"); } Sleep(PHASE_MS); + ULONGLONG deadline = GetTickCount64() + PROGRESS_MS; + while (progress != NULL && InterlockedCompareExchange(progress, 0, 0) == 0 && GetTickCount64() < deadline) + { + Sleep(50); + } InterlockedExchange(&g_stop, 1); WaitForMultipleObjects(5, threads, TRUE, INFINITE); for (int i = 0; i < 5; i++) @@ -88,10 +98,10 @@ int main() VLDMarkAllLeaksAsReported(); VLDSetReportOptions(VLD_OPT_REPORT_TO_DEBUGGER, NULL); - RunPhase("reporting to the debugger while lockers allocate under HeapLock"); + RunPhase("reporting to the debugger while lockers allocate under HeapLock", NULL); VLDSetReportHook(VLD_RPTHOOK_INSTALL, AllocatingHook); - RunPhase("an allocating report hook while lockers allocate under HeapLock"); + RunPhase("an allocating report hook while lockers allocate under HeapLock", &g_hookCalls); chaos::Check(g_hookCalls > 0, "the report hook was never called"); chaos::SetPhase("counting"); From b3275144b2b352081774127411f62b16a7191386 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 11:18:29 -0800 Subject: [PATCH 78/91] getaddrinfo_missing_free_test - count only the test thread's leaks The test compares leak counts after getaddrinfo with and without freeaddrinfo, with system DLLs not ignored. The DNS client allocates on its own threads at any time, so a baseline that caught such allocations could tie with the missing-free count (2 vs 2 on ARM64). The addrinfo results are allocated on the calling thread, so only its leaks are counted. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- .../getaddrinfo_missing_free_test.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp index 8611268d..45130cac 100644 --- a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp +++ b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp @@ -42,6 +42,8 @@ class TestGetAddrInfoMissingFree : public ::testing::Test // loaded, this should produce 0 new leaks. // 3. Test: call getaddrinfo WITHOUT freeaddrinfo. VLD should track the // unreleased addrinfo allocation, producing more leaks than baseline. +// Only this thread's leaks count: the DNS client allocates on threads of its +// own at any time. TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) { // Step 1: warm up - trigger system DLL loading and mark those leaks. @@ -71,7 +73,7 @@ TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) ASSERT_EQ(0, rc); ASSERT_NE(static_cast(NULL), result); freeaddrinfo(result); - leaks_with_free = static_cast(VLDGetLeaksCount()); + leaks_with_free = static_cast(VLDGetThreadLeaksCount(GetCurrentThreadId())); } VLDMarkAllLeaksAsReported(); @@ -88,7 +90,7 @@ TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) ASSERT_EQ(0, rc); ASSERT_NE(static_cast(NULL), leaked_result); // Intentionally NOT calling freeaddrinfo(leaked_result). - leaks_without_free = static_cast(VLDGetLeaksCount()); + leaks_without_free = static_cast(VLDGetThreadLeaksCount(GetCurrentThreadId())); } EXPECT_GT(leaks_without_free, leaks_with_free) From 03df1f0406940588fedc69bc8d59b57fe3eb96be Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 11:26:52 -0800 Subject: [PATCH 79/91] chaos_unload_report - record whether VLD patched the helper copy a leak came from On ARM64 the blocks the test misses are not tracked by VLD at all. After every LoadLibrary the loader counts the helper's imports that point into VLD and tags its leaks with the result, and a miscount reports how many loads were not patched. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_unload_report.cpp | 43 ++++++++++++++++++++++++- 1 file changed, 42 insertions(+), 1 deletion(-) diff --git a/src/tests/chaos/chaos_unload_report.cpp b/src/tests/chaos/chaos_unload_report.cpp index e4f2d14b..10ae53b4 100644 --- a/src/tests/chaos/chaos_unload_report.cpp +++ b/src/tests/chaos/chaos_unload_report.cpp @@ -18,6 +18,38 @@ volatile LONG g_stop = 0; volatile LONG g_leaked = 0; typedef void* (*HelperMalloc_t)(size_t); +volatile LONG g_loads = 0; +volatile LONG g_unpatchedLoads = 0; + +// Counts the helper's imports, other than those of VLD itself, that VLD +// patched: zero means its allocations bypass VLD. Recorded with every leak to +// tell a missed block of an unpatched copy from one VLD skipped. +LONG CountPatchedImports(HMODULE module) +{ + HMODULE vld = NULL; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCWSTR)&VLDReportLeaks, &vld); + char vldName[MAX_PATH] = { 0 }; + GetModuleFileNameA(vld, vldName, MAX_PATH); + const char* vldBase = strrchr(vldName, '\\') != NULL ? strrchr(vldName, '\\') + 1 : vldName; + BYTE* base = (BYTE*)module; + IMAGE_NT_HEADERS* nt = (IMAGE_NT_HEADERS*)(base + ((IMAGE_DOS_HEADER*)base)->e_lfanew); + IMAGE_DATA_DIRECTORY dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + LONG patched = 0; + for (IMAGE_IMPORT_DESCRIPTOR* d = (IMAGE_IMPORT_DESCRIPTOR*)(base + dir.VirtualAddress); dir.VirtualAddress != 0 && d->Name != 0; d++) + { + if (_stricmp((const char*)(base + d->Name), vldBase) == 0) + continue; + for (IMAGE_THUNK_DATA* t = (IMAGE_THUNK_DATA*)(base + d->FirstThunk); t->u1.Function != 0; t++) + { + HMODULE target = NULL; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCWSTR)t->u1.Function, &target) && target == vld) + patched++; + } + } + return patched; +} int __cdecl SwallowHook(int, wchar_t*, int*) { @@ -33,6 +65,12 @@ DWORD WINAPI Loader(LPVOID p) chaos::Check(helper != NULL, "LoadLibrary(chaos_helper_dll) failed"); HelperMalloc_t helperMalloc = (HelperMalloc_t)GetProcAddress(helper, "HelperMalloc"); chaos::Check(helperMalloc != NULL, "HelperMalloc not found"); + // Tag: loader index, plus 100 if this copy of the helper is patched. + bool patched = CountPatchedImports(helper) > 0; + InterlockedIncrement(&g_loads); + if (!patched) + InterlockedIncrement(&g_unpatchedLoads); + LONG tag = (LONG)(INT_PTR)p + (patched ? 100 : 0); int count = 1 + random.Below(4); for (int i = 0; i < count; i++) { @@ -44,7 +82,7 @@ DWORD WINAPI Loader(LPVOID p) } void* block = helperMalloc(16 + random.Below(200)); chaos::Check(block != NULL, "HelperMalloc failed"); - chaos::RecordLeak(block, (LONG)(INT_PTR)p); + chaos::RecordLeak(block, tag); } FreeLibrary(helper); } @@ -99,6 +137,9 @@ int main() { VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); chaos::DescribeMissingLeaks(); + char loads[96]; + sprintf_s(loads, "%ld of %ld helper loads were not patched by VLD\n", g_unpatchedLoads, g_loads); + chaos::Write(loads); char message[96]; sprintf_s(message, "leaked %ld blocks but VLD counts %u", g_leaked, counted); chaos::Fail(message); From 06a09c9ca17a381964ec5024616d97607e791377 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 11:49:14 -0800 Subject: [PATCH 80/91] chaos_ledger - match a block to the nearest report before it A block 16 bytes past its heap block (a malloc spy header) could take the report of a neighbor just before it, which left the neighbor unmatched and failed chaos_malloc_spy on ARM64 although every block was reported. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_ledger.h | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/tests/chaos/chaos_ledger.h b/src/tests/chaos/chaos_ledger.h index e403beaf..0970f16a 100644 --- a/src/tests/chaos/chaos_ledger.h +++ b/src/tests/chaos/chaos_ledger.h @@ -120,12 +120,25 @@ inline int DescribeMissingLeaks() { for (LONG i = 0; i < recorded; i++) { + // Exact first, then the nearest report before the block, so that a + // block cannot take the report of a neighbor just before it. + LONG best = -1; + ULONG_PTR bestOffset = 65; for (LONG j = 0; j < reported && !matched[i]; j++) { ULONG_PTR offset = (ULONG_PTR)Ledger()[i].block - (ULONG_PTR)ReportedBlocks()[j]; - if (!used[j] && (pass == 0 ? offset == 0 : offset <= 64)) - used[j] = matched[i] = true; + if (used[j]) + continue; + if (pass == 0 ? offset == 0 : offset < bestOffset) + { + best = j; + bestOffset = offset; + if (pass == 0) + break; + } } + if (best >= 0) + used[best] = matched[i] = true; } } int missing = 0; From 41d8b4775be9ea5d6e9fea647fd89aac557cafd7 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 11:49:14 -0800 Subject: [PATCH 81/91] getaddrinfo_missing_free_test - use the smallest of three baselines The DNS client still allocates on the calling thread now and then after the warm-up, so a single baseline round could tie with the missing-free round (2 vs 2 on ARM64). Extra allocations can only raise the missing-free count, so the smallest baseline keeps the check strict. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- .../getaddrinfo_missing_free_test.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp index 45130cac..8ba200a5 100644 --- a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp +++ b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp @@ -10,6 +10,7 @@ // leak counts rather than checking for zero. #include +#include #include #include #include "vld.h" @@ -60,8 +61,11 @@ TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) } VLDMarkAllLeaksAsReported(); - // Step 2: baseline - getaddrinfo WITH freeaddrinfo after DLLs loaded. - int leaks_with_free; + // Step 2: baseline - getaddrinfo WITH freeaddrinfo after DLLs loaded. The + // DNS client sometimes still allocates on this thread, so the baseline is + // the smallest of a few rounds. + int leaks_with_free = INT_MAX; + for (int round = 0; round < 3; round++) { struct addrinfo hints; struct addrinfo* result = NULL; @@ -73,9 +77,11 @@ TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) ASSERT_EQ(0, rc); ASSERT_NE(static_cast(NULL), result); freeaddrinfo(result); - leaks_with_free = static_cast(VLDGetThreadLeaksCount(GetCurrentThreadId())); + int leaks = static_cast(VLDGetThreadLeaksCount(GetCurrentThreadId())); + if (leaks < leaks_with_free) + leaks_with_free = leaks; + VLDMarkAllLeaksAsReported(); } - VLDMarkAllLeaksAsReported(); // Step 3: test - getaddrinfo WITHOUT freeaddrinfo. int leaks_without_free; From 82b5e6b3f443f53c4f50a8cd15b8f3d524d1c65b Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 12:00:42 -0800 Subject: [PATCH 82/91] Replay module load/unload events onto the RefreshModules snapshot RefreshModules builds a new module set and swaps it in, which discarded updates made by concurrent loader notifications during the refresh. A stale or excluded entry could then cover a newly loaded module so its allocations were not tracked. Loads and unloads seen while a refresh is in progress are now recorded and replayed onto the new set before the swap; if recording fails the stale snapshot is dropped. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/vld.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++++++++++- src/vldint.h | 16 +++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/src/vld.cpp b/src/vld.cpp index b35f9a89..21032c54 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -446,6 +446,11 @@ VisualLeakDetector::VisualLeakDetector () m_curAlloc = 0; m_maxAlloc = 0; m_loadedModules = new ModuleSet(); + m_refreshDepth = 0; + m_moduleEventsLost = false; + m_moduleEvents = NULL; + m_moduleEventCount = 0; + m_moduleEventCapacity = 0; m_optionsLock.Initialize(); m_modulesLock.Initialize(); m_selfTestFile = __FILE__; @@ -810,6 +815,7 @@ VisualLeakDetector::~VisualLeakDetector () delete m_deferredHeaps; } delete m_loadedModules; + delete [] m_moduleEvents; delete m_ignoreFunctions; { @@ -2725,6 +2731,15 @@ VOID VisualLeakDetector::RefreshModules() ModuleSet* newmodules = new ModuleSet(); newmodules->reserve(MODULE_SET_RESERVE); + { + // The loader notification can register and unregister modules while + // the new set is built; record them to replay on it. + CriticalSectionLocker<> cs(m_modulesLock); + if (m_refreshDepth++ == 0) { + m_moduleEventCount = 0; + m_moduleEventsLost = false; + } + } { // dbghelp is not thread safe; other threads resolve symbols under // g_DbgHelp. @@ -2740,8 +2755,21 @@ VOID VisualLeakDetector::RefreshModules() attachToLoadedModules(newmodules); } - // Start using the new set of loaded modules. + // Start using the new set of loaded modules, once it has every load and + // unload since the refresh started: without them it can lack a module + // loaded meanwhile, or keep the entry of one unloaded meanwhile at the + // addresses of another, whose allocations would then be misclassified. CriticalSectionLocker<> cs(m_modulesLock); + for (size_t i = 0; i < m_moduleEventCount; i++) + applyModuleEvent(newmodules, m_moduleEvents[i]); + bool eventsLost = m_moduleEventsLost; + if (--m_refreshDepth == 0) + m_moduleEventCount = 0; + if (eventsLost) { + // The current set, which the notification keeps up to date, is better. + delete newmodules; + return; + } ModuleSet* oldmodules = m_loadedModules; m_loadedModules = newmodules; @@ -2760,6 +2788,51 @@ VOID VisualLeakDetector::RefreshModules() delete oldmodules; } +// recordModuleEvent - Records a module load or unload for RefreshModules to +// replay, if a refresh is in progress. Call with m_modulesLock held. +VOID VisualLeakDetector::recordModuleEvent(bool loaded, const moduleinfo_t& info) +{ + if (m_refreshDepth == 0 || m_moduleEventsLost) + return; + if (m_moduleEventCount == m_moduleEventCapacity) { + size_t capacity = m_moduleEventCapacity == 0 ? 64 : m_moduleEventCapacity * 2; + moduleevent_t* events = new moduleevent_t[capacity]; + if (events == NULL) { + m_moduleEventsLost = true; + return; + } + for (size_t i = 0; i < m_moduleEventCount; i++) + events[i] = m_moduleEvents[i]; + delete [] m_moduleEvents; + m_moduleEvents = events; + m_moduleEventCapacity = capacity; + } + m_moduleEvents[m_moduleEventCount].loaded = loaded; + m_moduleEvents[m_moduleEventCount].info = info; + m_moduleEventCount++; +} + +// applyModuleEvent - Applies a recorded load or unload to a module set: the +// entries overlapping the module go, and a loaded module is inserted. A load +// keeps the symbols state of an entry for the same address range. +VOID VisualLeakDetector::applyModuleEvent(ModuleSet* modules, const moduleevent_t& event) +{ + UINT32 symbolsLoaded = 0; + while (true) { + ModuleSet::Iterator it = modules->find(event.info); + if (it == modules->end()) + break; + if ((*it).addrLow == event.info.addrLow && (*it).addrHigh == event.info.addrHigh) + symbolsLoaded = (*it).flags & VLD_MODULE_SYMBOLSLOADED; + modules->erase(it); + } + if (event.loaded) { + moduleinfo_t info = event.info; + info.flags |= symbolsLoaded; + modules->insert(info); + } +} + VOID VisualLeakDetector::PatchCurrentModule(HMODULE module) { if (m_options & VLD_OPT_VLDOFF) @@ -2914,6 +2987,7 @@ VOID VisualLeakDetector::RegisterLoadedModule(HMODULE module, PCWSTR fullPath, P m_loadedModules->erase(existing); } m_loadedModules->insert(moduleinfo); + recordModuleEvent(true, moduleinfo); } // UnregisterLoadedModule - Removes a module from m_loadedModules when the @@ -2948,6 +3022,7 @@ VOID VisualLeakDetector::UnregisterLoadedModule(HMODULE module, ULONG sizeOfImag break; m_loadedModules->erase(it); } + recordModuleEvent(false, key); cs.Leave(); // Cached symbols of the module could name code loaded at its addresses later. diff --git a/src/vldint.h b/src/vldint.h index 091fc595..b6790588 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -179,6 +179,13 @@ struct moduleinfo_t { // ModuleSets store information about modules loaded in the process. typedef Set ModuleSet; +// A module load or unload seen by the loader notification while a refresh of +// the module set is in progress; the refresh replays these on its new set. +struct moduleevent_t { + bool loaded; + moduleinfo_t info; +}; + typedef Set ReportHookSet; #define MAX_REPORT_HOOKS 64 @@ -344,6 +351,8 @@ class VisualLeakDetector : public IMalloc //////////////////////////////////////////////////////////////////////////////// VOID attachToLoadedModules (ModuleSet *newmodules); UINT32 getModuleState(ModuleSet::Iterator& it, UINT32 &moduleFlags); + VOID recordModuleEvent(bool loaded, const moduleinfo_t& info); + static VOID applyModuleEvent(ModuleSet* modules, const moduleevent_t& event); LPWSTR buildSymbolSearchPath(); BOOL GetIniFilePath(LPTSTR lpPath, SIZE_T cchPath); VOID configure (); @@ -443,6 +452,13 @@ class VisualLeakDetector : public IMalloc SIZE_T m_maxDataDump; // Maximum number of user-data bytes to dump for each leaked block. UINT32 m_maxTraceFrames; // Maximum number of frames per stack trace for each leaked block. CriticalSection m_modulesLock; // Protects accesses to the "loaded modules" ModuleSet. + // Loads and unloads seen while RefreshModules builds a new module set, + // in order. Protected by m_modulesLock. + size_t m_refreshDepth; + bool m_moduleEventsLost; + moduleevent_t *m_moduleEvents; + size_t m_moduleEventCount; + size_t m_moduleEventCapacity; CriticalSection m_optionsLock; // Serializes access to the heap and block maps. UINT32 m_options; // Configuration options. IgnoreFunctionsSet *m_ignoreFunctions; // Contains information about all the functions that needs to be ignored. From 6f06484804d0d8d849487f2e520abc9afce3171e Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 13:58:53 -0800 Subject: [PATCH 83/91] dtor_suppression_test: stop forcing all modules into leak detection ForceIncludeModules = * made VLD track system modules, so on the first run of the x86 exe from a new folder the allocations apphelp's shim engine still holds at exit were reported and the test failed. The test only needs the exe, which VLD tracks because it imports vld.h. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/dtor_suppression_test/vld.ini | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tests/dtor_suppression_test/vld.ini b/src/tests/dtor_suppression_test/vld.ini index 3fb0b990..4bc6fbf0 100644 --- a/src/tests/dtor_suppression_test/vld.ini +++ b/src/tests/dtor_suppression_test/vld.ini @@ -11,7 +11,9 @@ [Options] VLD = on AggregateDuplicates = no -ForceIncludeModules = * +; Only the test exe: forcing system modules in would report what they hold at +; exit (e.g. apphelp's shim engine on an exe's first run from a new folder). +ForceIncludeModules = MaxDataDump = MaxTraceFrames = ReportEncoding = ascii From f2e0f19534adb906b324fd188ee61716ae30a80e Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 14:36:56 -0800 Subject: [PATCH 84/91] chaos tests: start workers together so none starves the stopper A gate hang dump of chaos_api_storm showed a worker looping on VLDRefreshModules, which holds the loader lock, while the other workers - including the only one that stops the run - waited for that lock to finish starting. RunThreads now releases the workers only once all have started, and the main thread fails the test if the stopping worker has not stopped the run in time instead of hanging until the watchdog. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_api_storm.cpp | 2 +- src/tests/chaos/chaos_common.h | 47 +++++++++++++++++++++- src/tests/chaos/chaos_heap_churn.cpp | 2 +- src/tests/chaos/chaos_heap_flags.cpp | 2 +- src/tests/chaos/chaos_report_hook_race.cpp | 2 +- src/tests/chaos/chaos_report_options.cpp | 2 +- src/tests/chaos/chaos_thread_churn.cpp | 2 +- 7 files changed, 51 insertions(+), 8 deletions(-) diff --git a/src/tests/chaos/chaos_api_storm.cpp b/src/tests/chaos/chaos_api_storm.cpp index 55f525f6..0bf3f955 100644 --- a/src/tests/chaos/chaos_api_storm.cpp +++ b/src/tests/chaos/chaos_api_storm.cpp @@ -108,7 +108,7 @@ int main() SIZE_T base = VLDGetLeaksCount(); chaos::SetPhase("API storm with allocation traffic"); - chaos::RunThreads(10, Worker); + chaos::RunThreads(10, Worker, &g_stop, RUN_MS + 2000); chaos::SetPhase("tracking after the storm"); VLDGlobalEnable(); diff --git a/src/tests/chaos/chaos_common.h b/src/tests/chaos/chaos_common.h index b75310ad..ce243209 100644 --- a/src/tests/chaos/chaos_common.h +++ b/src/tests/chaos/chaos_common.h @@ -216,20 +216,63 @@ struct Random unsigned int Below(unsigned int n) { return Next() % n; } }; -inline void RunThreads(int count, LPTHREAD_START_ROUTINE routine) +struct RunThreadsStart +{ + LPTHREAD_START_ROUTINE routine; + volatile LONG started; + HANDLE go; +}; + +struct RunThreadsArg +{ + RunThreadsStart* start; + INT_PTR index; +}; + +inline DWORD WINAPI RunThreadsTrampoline(LPVOID p) +{ + RunThreadsArg* arg = (RunThreadsArg*)p; + InterlockedIncrement(&arg->start->started); + WaitForSingleObject(arg->start->go, INFINITE); + return arg->start->routine((LPVOID)arg->index); +} + +inline void RunThreads(int count, LPTHREAD_START_ROUTINE routine, volatile LONG* stop = NULL, DWORD stopAfterMs = INFINITE) { HANDLE threads[64]; + RunThreadsArg args[64]; Check(count <= 64, "too many threads"); + RunThreadsStart start = { routine, 0, CreateEventW(NULL, TRUE, FALSE, NULL) }; + Check(start.go != NULL, "CreateEvent failed"); for (int i = 0; i < count; i++) { - threads[i] = CreateThread(NULL, 0, routine, (LPVOID)(INT_PTR)i, 0, NULL); + args[i].start = &start; + args[i].index = i; + threads[i] = CreateThread(NULL, 0, RunThreadsTrampoline, &args[i], 0, NULL); Check(threads[i] != NULL, "CreateThread failed"); } + // Starting a thread takes the loader lock, which a worker calling + // VLDRefreshModules in a loop can keep for itself; so no worker runs until + // all have started. + while (InterlockedCompareExchange(&start.started, 0, 0) < count) + { + Sleep(1); + } + SetEvent(start.go); + // Backstop for a worker that stops the others but cannot get to it; that + // worker not having stopped the run by then is a failure. + bool stopperLate = false; + if (WaitForMultipleObjects(count, threads, TRUE, stopAfterMs) == WAIT_TIMEOUT && stop != NULL) + { + stopperLate = InterlockedExchange(stop, 1) == 0; + } WaitForMultipleObjects(count, threads, TRUE, INFINITE); for (int i = 0; i < count; i++) { CloseHandle(threads[i]); } + CloseHandle(start.go); + Check(!stopperLate, "the stopping worker did not stop the run in time"); } inline void Pass() diff --git a/src/tests/chaos/chaos_heap_churn.cpp b/src/tests/chaos/chaos_heap_churn.cpp index f07b70fe..7616331e 100644 --- a/src/tests/chaos/chaos_heap_churn.cpp +++ b/src/tests/chaos/chaos_heap_churn.cpp @@ -82,7 +82,7 @@ int main() VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowReport); chaos::SetPhase("heap create/alloc/destroy churn with leak counts"); - chaos::RunThreads(9, Worker); + chaos::RunThreads(9, Worker, &g_stop, RUN_MS + 2000); VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowReport); chaos::SetPhase("final count"); diff --git a/src/tests/chaos/chaos_heap_flags.cpp b/src/tests/chaos/chaos_heap_flags.cpp index 7a3a86f4..8b75b4e0 100644 --- a/src/tests/chaos/chaos_heap_flags.cpp +++ b/src/tests/chaos/chaos_heap_flags.cpp @@ -170,7 +170,7 @@ int main() chaos::SetPhase("heap inspection under allocation traffic"); g_heap = HeapCreate(0, 0, 32 * 1024 * 1024); chaos::Check(g_heap != NULL, "HeapCreate of a fixed-size heap failed"); - chaos::RunThreads(7, Worker); + chaos::RunThreads(7, Worker, &g_stop, RUN_MS + 2000); chaos::Check(VLDGetLeaksCount() == base, "allocation traffic with heap inspection left leaks"); HeapDestroy(g_heap); chaos::Pass(); diff --git a/src/tests/chaos/chaos_report_hook_race.cpp b/src/tests/chaos/chaos_report_hook_race.cpp index 883fa5a0..456541ee 100644 --- a/src/tests/chaos/chaos_report_hook_race.cpp +++ b/src/tests/chaos/chaos_report_hook_race.cpp @@ -84,7 +84,7 @@ int main() } chaos::SetPhase("hook install/remove racing VLDReportLeaks"); - chaos::RunThreads(6, Worker); + chaos::RunThreads(6, Worker, &g_stop, RUN_MS + 2000); chaos::SetPhase("cleanup"); for (int i = 0; i < 4; i++) diff --git a/src/tests/chaos/chaos_report_options.cpp b/src/tests/chaos/chaos_report_options.cpp index 23d89a3c..e9655201 100644 --- a/src/tests/chaos/chaos_report_options.cpp +++ b/src/tests/chaos/chaos_report_options.cpp @@ -135,7 +135,7 @@ int main() VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwitchingHook); chaos::SetPhase("switching the destination while threads report"); - chaos::RunThreads(6, Worker); + chaos::RunThreads(6, Worker, &g_stop, RUN_MS + 2000); chaos::SetPhase("cleanup"); VLDSetReportOptions(VLD_OPT_REPORT_TO_STDOUT, NULL); diff --git a/src/tests/chaos/chaos_thread_churn.cpp b/src/tests/chaos/chaos_thread_churn.cpp index 29a38372..807db369 100644 --- a/src/tests/chaos/chaos_thread_churn.cpp +++ b/src/tests/chaos/chaos_thread_churn.cpp @@ -106,7 +106,7 @@ int main() chaos::SetPhase("thread churn with allocating thread attach/detach, DLL loads and leak counts"); setThreadChurn(1); - chaos::RunThreads(8, Worker); + chaos::RunThreads(8, Worker, &g_stop, RUN_MS + 2000); setThreadChurn(0); // Threads still alive that attached during the churn (thread pool and From bcc516b07dbba888a3efbe5fef395f224b242775 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 14:36:56 -0800 Subject: [PATCH 85/91] corruption: exit the heap mismatch death test before the bad free After VLD reports the mismatch the free still reaches the wrong heap. Sometimes that raises an exception with the heap lock held, and gtest's SEH handling deadlocks starting a thread that needs that lock, hanging the test. The report hook now ends the child once VLD dumps the deallocation call stack, and the test requires that exit code. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/corruption/corruption.cpp | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/tests/corruption/corruption.cpp b/src/tests/corruption/corruption.cpp index d882ad70..ad48ccc7 100644 --- a/src/tests/corruption/corruption.cpp +++ b/src/tests/corruption/corruption.cpp @@ -3,6 +3,9 @@ #include "stdafx.h" #include "Tests.h" +#define WIN32_LEAN_AND_MEAN +#include +#include // This hooks vld into this app #include "vld.h" @@ -17,7 +20,21 @@ enum CorruptionType int __cdecl ReportHook(int /*reportHook*/, wchar_t *message, int* /*returnValue*/) { + static bool deallocationStack = false; fwprintf(stderr, L"%s", message); + // Exit once VLD dumps the deallocation call stack (its first frame), before + // the mismatched free reaches the heap: corrupting it can raise an exception + // with the heap lock held, and gtest's SEH handling then deadlocks starting + // a thread that needs that lock. + if (wcsstr(message, L"Deallocation Call stack.") != NULL) + { + deallocationStack = true; + } + else if (deallocationStack && wcschr(message, L'!') != NULL) + { + fflush(stderr); + TerminateProcess(GetCurrentProcess(), 3); + } return 1; } @@ -56,7 +73,7 @@ TEST(CorruptionDeathTest, HeapMismatch) VLDSetReportHook(VLD_RPTHOOK_INSTALL, ReportHook); TestCorruption(eHeapMismatch); VLDSetReportHook(VLD_RPTHOOK_REMOVE, ReportHook); - }, IgnoreExitCode, "CRITICAL ERROR!: VLD reports that memory was allocated in one heap and freed in another."); + }, testing::ExitedWithCode(3), "CRITICAL ERROR!: VLD reports that memory was allocated in one heap and freed in another."); } int main(int argc, char **argv) { From 8e755f29d46411a7ee61efa1fa10defb83de5259 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 16:07:29 -0800 Subject: [PATCH 86/91] chaos_ledger: describe report blocks no recorded leak matches Prints each unmatched report block with its size, first bytes, the modules its first pointers point into and VLD's allocation call stack, so an extra block can be identified, not just counted. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_ledger.h | 52 +++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/src/tests/chaos/chaos_ledger.h b/src/tests/chaos/chaos_ledger.h index 0970f16a..2144025f 100644 --- a/src/tests/chaos/chaos_ledger.h +++ b/src/tests/chaos/chaos_ledger.h @@ -52,6 +52,12 @@ inline volatile LONG& ReportedCount() return count; } +inline SIZE_T* ReportedSizes() +{ + static SIZE_T sizes[LEDGER_SIZE * 2]; + return sizes; +} + inline int __cdecl CollectReportedBlock(int, wchar_t* message, int*) { const wchar_t* at = wcsstr(message, L"---------- Block "); @@ -60,10 +66,14 @@ inline int __cdecl CollectReportedBlock(int, wchar_t* message, int*) at = wcsstr(at, L" at 0x"); if (at != NULL) { - ULONG_PTR address = (ULONG_PTR)_wcstoui64(at + 6, NULL, 16); + wchar_t* end = NULL; + ULONG_PTR address = (ULONG_PTR)_wcstoui64(at + 6, &end, 16); LONG slot = InterlockedIncrement(&ReportedCount()) - 1; if (slot < LEDGER_SIZE * 2) + { ReportedBlocks()[slot] = (void*)address; + ReportedSizes()[slot] = end != NULL && end[0] == L':' ? (SIZE_T)_wcstoui64(end + 1, NULL, 10) : 0; + } } } return 1; @@ -167,6 +177,46 @@ inline int DescribeMissingLeaks() } sprintf_s(line, "%d blocks missing from the diagnostic report\n", missing); Write(line); + int extra = 0; + for (LONG j = 0; j < reported; j++) + { + if (used[j] || ++extra > 8) + continue; + const unsigned char* bytes = (const unsigned char*)ReportedBlocks()[j]; + int length = sprintf_s(line, "unrecorded block in the report at %p (%Iu bytes):", bytes, ReportedSizes()[j]); + __try + { + for (int b = 0; b < 32; b++) + length += sprintf_s(line + length, _countof(line) - length, " %02X", bytes[b]); + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + length += sprintf_s(line + length, _countof(line) - length, " (not readable)"); + } + sprintf_s(line + length, _countof(line) - length, "\n"); + Write(line); + for (int w = 0; w < 4; w++) + { + ULONG_PTR value = 0; + __try + { + value = ((const ULONG_PTR*)bytes)[w]; + } + __except (EXCEPTION_EXECUTE_HANDLER) + { + break; + } + HMODULE module = NULL; + wchar_t name[MAX_PATH]; + if (value != 0 && GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCWSTR)value, &module) && + GetModuleFileNameW(module, name, MAX_PATH) != 0) + { + sprintf_s(line, " word %d = %ls+0x%Ix\n", w, wcsrchr(name, L'\\') != NULL ? wcsrchr(name, L'\\') + 1 : name, value - (ULONG_PTR)module); + Write(line); + } + } + DescribeTrackedBlock(ReportedBlocks()[j]); + } return missing; } } From 2ce16a6d68aa79dfde29bd05bf801fcf9a39b6b0 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 16:07:29 -0800 Subject: [PATCH 87/91] chaos_malloc_spy: start the workers one by one Released together, the workers contend for COM's spy lock at once; Windows then allocates the lock's debug record inside a CoTaskMemAlloc call and VLD charges it to that call as a leak. RunThreads can now start workers without the barrier, which this test uses. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/tests/chaos/chaos_common.h | 4 ++-- src/tests/chaos/chaos_malloc_spy.cpp | 5 ++++- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/tests/chaos/chaos_common.h b/src/tests/chaos/chaos_common.h index ce243209..64662721 100644 --- a/src/tests/chaos/chaos_common.h +++ b/src/tests/chaos/chaos_common.h @@ -237,12 +237,12 @@ inline DWORD WINAPI RunThreadsTrampoline(LPVOID p) return arg->start->routine((LPVOID)arg->index); } -inline void RunThreads(int count, LPTHREAD_START_ROUTINE routine, volatile LONG* stop = NULL, DWORD stopAfterMs = INFINITE) +inline void RunThreads(int count, LPTHREAD_START_ROUTINE routine, volatile LONG* stop = NULL, DWORD stopAfterMs = INFINITE, bool together = true) { HANDLE threads[64]; RunThreadsArg args[64]; Check(count <= 64, "too many threads"); - RunThreadsStart start = { routine, 0, CreateEventW(NULL, TRUE, FALSE, NULL) }; + RunThreadsStart start = { routine, 0, CreateEventW(NULL, TRUE, !together, NULL) }; Check(start.go != NULL, "CreateEvent failed"); for (int i = 0; i < count; i++) { diff --git a/src/tests/chaos/chaos_malloc_spy.cpp b/src/tests/chaos/chaos_malloc_spy.cpp index 44e69d42..4a586759 100644 --- a/src/tests/chaos/chaos_malloc_spy.cpp +++ b/src/tests/chaos/chaos_malloc_spy.cpp @@ -165,7 +165,10 @@ int main() early = (BYTE*)CoTaskMemRealloc(early, 128); chaos::Check(early != NULL && early[0] == 0x3C && early[63] == 0x3C, "reallocating a block from before the spy lost its data"); CoTaskMemFree(early); - chaos::RunThreads(THREADS, Worker); + // Workers start one by one: started together they contend for COM's spy + // lock at once, and the lock's debug record Windows then allocates inside + // the COM call is reported as a leak of that call. + chaos::RunThreads(THREADS, Worker, NULL, INFINITE, false); // Revoking waits for the spied blocks, and some are leaked. CoRevokeMallocSpy(); From c260c2086315d651625760d0da2e4df28c1b0747 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 16:29:56 -0800 Subject: [PATCH 88/91] Create VLD's critical sections without debug info Windows allocates a critical section's debug info from the process heap the first time the section is contended. A thread that held the heap lock (HeapLock) and waited for a VLD section then deadlocked with the thread that owned another VLD section and needed the heap to contend for this one, as seen in chaos_heaplock_report under x64 emulation on ARM64. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/criticalsection.h | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/criticalsection.h b/src/criticalsection.h index 1a295fc5..4276d7cc 100644 --- a/src/criticalsection.h +++ b/src/criticalsection.h @@ -13,7 +13,12 @@ class CriticalSection { m_ownerThreadId = 0; __try { - InitializeCriticalSection(&m_critRegion); + // Without debug info: Windows otherwise allocates it from the process + // heap the first time the section is contended, which deadlocks when + // another thread holds the heap lock (HeapLock) and waits for this + // section. + if (!InitializeCriticalSectionEx(&m_critRegion, 0, CRITICAL_SECTION_NO_DEBUG_INFO)) + InitializeCriticalSection(&m_critRegion); } __except (GetExceptionCode() == STATUS_NO_MEMORY ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { assert(FALSE); } From be5e4e3bb4d2a26e9effbffd2ef502925a3a15ac Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 18:19:56 -0800 Subject: [PATCH 89/91] Print a leak query's report output after releasing the query lock The report output queued while g_heapMapLock was held was printed - and user report hooks run - before g_leakQueryLock was released, so a hook waiting on a thread that queries leaks deadlocked. HeapMapLock can now be left without printing, so the query prints once it holds no VLD lock. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- src/utility.h | 11 +++++++++-- src/vld.cpp | 4 +++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/utility.h b/src/utility.h index 667bbfcd..d69af370 100644 --- a/src/utility.h +++ b/src/utility.h @@ -202,11 +202,18 @@ class HeapMapLock bool IsOwnedByCurrentThread () { return m_lock.IsOwnedByCurrentThread(); } void Leave () { - deferredreport_t* report = m_lock.IsOwnedOnceByCurrentThread() ? TakeDeferredReport() : NULL; - m_lock.Leave(); + deferredreport_t* report = LeaveTakingReport(); if (report != NULL) PrintDeferredReport(report); } + // Leaves without printing; the caller prints the returned output once it + // holds no other VLD lock either. + deferredreport_t* LeaveTakingReport () + { + deferredreport_t* report = m_lock.IsOwnedOnceByCurrentThread() ? TakeDeferredReport() : NULL; + m_lock.Leave(); + return report; + } private: CriticalSection m_lock; diff --git a/src/vld.cpp b/src/vld.cpp index 21032c54..6a57241c 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -3266,8 +3266,10 @@ class LeakSymbolsHeapMapLock { m_vld.endBlockWalk(); if (!m_nested) { - g_heapMapLock.Leave(); + deferredreport_t* report = g_heapMapLock.LeaveTakingReport(); g_leakQueryLock.Leave(); + if (report != NULL) + PrintDeferredReport(report); } } From 629c029a2e5e2eead377431932f63d0b9ce0581b Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Thu, 12 Nov 2026 18:22:53 -0800 Subject: [PATCH 90/91] getaddrinfo_missing_free_test: check the leaked block, not leak counts The DNS client allocates on the test thread at any time, so comparing this thread's leak counts with and without freeaddrinfo still failed now and then on ARM64. The test now asks VLD whether it tracks the block getaddrinfo returns, and that the unfreed one is a leak of this thread. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- .../getaddrinfo_missing_free_test.cpp | 99 +++++++++---------- 1 file changed, 45 insertions(+), 54 deletions(-) diff --git a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp index 8ba200a5..89ea22af 100644 --- a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp +++ b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp @@ -38,73 +38,64 @@ class TestGetAddrInfoMissingFree : public ::testing::Test // // Strategy: // 1. Warm up: call getaddrinfo+freeaddrinfo to trigger system DLL loading. -// Mark all one-time init leaks as reported. -// 2. Baseline: call getaddrinfo+freeaddrinfo again. Since DLLs are already -// loaded, this should produce 0 new leaks. -// 3. Test: call getaddrinfo WITHOUT freeaddrinfo. VLD should track the -// unreleased addrinfo allocation, producing more leaks than baseline. -// Only this thread's leaks count: the DNS client allocates on threads of its -// own at any time. +// 2. Baseline: VLD tracks the block getaddrinfo returns. +// 3. Test: call getaddrinfo WITHOUT freeaddrinfo. VLD still tracks the +// block, as a leak of this thread. +// Leak counts are not compared: the DNS client allocates on this thread and +// on threads of its own at any time. +typedef const wchar_t* (*AllocationCallstack_t)(void* alloc, BOOL showInternalFrames); + +static AllocationCallstack_t GetAllocationCallstack() +{ + HMODULE vld = NULL; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + (LPCWSTR)&VLDMarkAllLeaksAsReported, &vld); + return vld != NULL ? (AllocationCallstack_t)GetProcAddress(vld, "VldInternalGetAllocationCallstack") : NULL; +} + +static struct addrinfo* ResolveLocalhost() +{ + struct addrinfo hints; + struct addrinfo* result = NULL; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + int rc = getaddrinfo("localhost", "80", &hints, &result); + EXPECT_EQ(0, rc); + return rc == 0 ? result : NULL; +} + TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) { + AllocationCallstack_t callstack = GetAllocationCallstack(); + ASSERT_NE(static_cast(NULL), callstack); + // Step 1: warm up - trigger system DLL loading and mark those leaks. - { - struct addrinfo hints; - struct addrinfo* warmup = NULL; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - int rc = getaddrinfo("localhost", "80", &hints, &warmup); - if (rc == 0 && warmup != NULL) - freeaddrinfo(warmup); - } + struct addrinfo* warmup = ResolveLocalhost(); + if (warmup != NULL) + freeaddrinfo(warmup); VLDMarkAllLeaksAsReported(); - // Step 2: baseline - getaddrinfo WITH freeaddrinfo after DLLs loaded. The - // DNS client sometimes still allocates on this thread, so the baseline is - // the smallest of a few rounds. - int leaks_with_free = INT_MAX; + // Step 2: baseline - VLD tracks the block getaddrinfo returns. for (int round = 0; round < 3; round++) { - struct addrinfo hints; - struct addrinfo* result = NULL; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - int rc = getaddrinfo("localhost", "80", &hints, &result); - ASSERT_EQ(0, rc); + struct addrinfo* result = ResolveLocalhost(); ASSERT_NE(static_cast(NULL), result); + EXPECT_NE(static_cast(NULL), callstack(result, FALSE)) + << "VLD does not track the block getaddrinfo returned."; freeaddrinfo(result); - int leaks = static_cast(VLDGetThreadLeaksCount(GetCurrentThreadId())); - if (leaks < leaks_with_free) - leaks_with_free = leaks; VLDMarkAllLeaksAsReported(); } // Step 3: test - getaddrinfo WITHOUT freeaddrinfo. - int leaks_without_free; - { - struct addrinfo hints; - struct addrinfo* leaked_result = NULL; - memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_INET; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - int rc = getaddrinfo("localhost", "80", &hints, &leaked_result); - ASSERT_EQ(0, rc); - ASSERT_NE(static_cast(NULL), leaked_result); - // Intentionally NOT calling freeaddrinfo(leaked_result). - leaks_without_free = static_cast(VLDGetThreadLeaksCount(GetCurrentThreadId())); - } - - EXPECT_GT(leaks_without_free, leaks_with_free) - << "Expected more leaks when freeaddrinfo is NOT called. " - << "Leaks with freeaddrinfo: " << leaks_with_free - << ", leaks without freeaddrinfo: " << leaks_without_free - << ". VLD should detect the missing freeaddrinfo as an " - << "additional tracked allocation."; + struct addrinfo* leaked_result = ResolveLocalhost(); + ASSERT_NE(static_cast(NULL), leaked_result); + // Intentionally NOT calling freeaddrinfo(leaked_result). + EXPECT_NE(static_cast(NULL), callstack(leaked_result, FALSE)) + << "VLD should detect the missing freeaddrinfo: it does not track the block getaddrinfo returned."; + EXPECT_GT(VLDGetThreadLeaksCount(GetCurrentThreadId()), 0u) + << "VLD should count the block getaddrinfo returned as a leak of this thread."; VLDMarkAllLeaksAsReported(); } From 1118ed76a4c4bf800ed8e6fdda64f6c38f1dfe26 Mon Sep 17 00:00:00 2001 From: Andrei Porumb Date: Fri, 13 Nov 2026 22:21:14 -0800 Subject: [PATCH 91/91] Address PR 74 review comments, with a regression test per testable comment Product fixes: - A symbol cache miss no longer latches a call stack's startup decision or its resolved text; a partial rendering is resolved again once its frames are cached. Earlier renderings stay alive with the call stack, since VldInternalGetAllocationResolveResults hands them out. - Hooks preserve the thread's last error (getTls and CaptureContext). - An unopenable report file falls back to debugger output. - Ordinal names are handled when matching GetProcAddress requests. - ValidateHeapFree reports print after g_heapMapLock is released; call stack resolution no longer uses static scratch buffers. - Blocks are read with ReadProcessMemory, so unreadable or guard pages raise no exceptions; a CRT block whose header the application made inaccessible is still counted and reported. - DumpMemoryW does not read past the block; NULL checks after VLD's new in the symbol cache. - VLDSetReportOptions callers are serialized. - StackWalkMethod=safe fallbacks to RtlCaptureStackBackTrace are counted and reported once. - Docs: report hook locking and the 64 hook limit; stale comments fixed. Tests and pipeline: - New src/tests/review74 tests, each failing without its fix. - Chaos tests: permanent hook checked after churn, a CRT header guess that changes between queries, paced leakers and enabled moves in realloc_reuse. - getaddrinfo_missing_free_test comments and name match what it checks. - Failed job attempts publish their build under a per-attempt artifact name. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: d251f4de-84a5-4357-87c1-0d7158123d9f --- build/templates/build-arch.yml | 11 +- src/callstack.cpp | 174 +++++++++++++----- src/callstack.h | 20 +- src/tests/CMakeLists.txt | 52 ++++++ src/tests/chaos/chaos_fake_crt_header.cpp | 19 ++ src/tests/chaos/chaos_realloc_reuse.cpp | 26 ++- src/tests/chaos/chaos_report_hook_race.cpp | 13 +- .../getaddrinfo_missing_free_test.cpp | 12 +- src/tests/review74/review_common.h | 124 +++++++++++++ .../review74/review_crt_noaccess_leak.cpp | 60 ++++++ src/tests/review74/review_last_error.cpp | 73 ++++++++ .../review74/review_proc_name_address.cpp | 45 +++++ .../review74/review_report_file_fallback.cpp | 41 +++++ .../review74/review_report_options_race.cpp | 74 ++++++++ .../review74/review_symbol_cache_latch.cpp | 83 +++++++++ .../review_unreadable_no_exception.cpp | 73 ++++++++ .../review74/review_validate_heapfree.cpp | 92 +++++++++ src/tests/review74/vld.ini | 16 ++ src/utility.cpp | 7 +- src/vld.cpp | 114 +++++++++--- src/vld.h | 11 +- src/vldint.h | 1 + 22 files changed, 1033 insertions(+), 108 deletions(-) create mode 100644 src/tests/review74/review_common.h create mode 100644 src/tests/review74/review_crt_noaccess_leak.cpp create mode 100644 src/tests/review74/review_last_error.cpp create mode 100644 src/tests/review74/review_proc_name_address.cpp create mode 100644 src/tests/review74/review_report_file_fallback.cpp create mode 100644 src/tests/review74/review_report_options_race.cpp create mode 100644 src/tests/review74/review_symbol_cache_latch.cpp create mode 100644 src/tests/review74/review_unreadable_no_exception.cpp create mode 100644 src/tests/review74/review_validate_heapfree.cpp create mode 100644 src/tests/review74/vld.ini diff --git a/build/templates/build-arch.yml b/build/templates/build-arch.yml index f3e04b95..b203e0cc 100644 --- a/build/templates/build-arch.yml +++ b/build/templates/build-arch.yml @@ -133,7 +133,16 @@ steps: - task: PublishPipelineArtifact@1 displayName: 'Publish ${{ parameters.arch }}${{ parameters.artifactSuffix }} build' - condition: succeededOrFailed() + condition: succeeded() inputs: targetPath: 'build_${{ parameters.arch }}' artifact: 'build_${{ parameters.arch }}${{ parameters.artifactSuffix }}' + +# Artifact names cannot be reused, so each failed attempt publishes under its +# own name and "Rerun failed jobs" can still publish. +- task: PublishPipelineArtifact@1 + displayName: 'Publish ${{ parameters.arch }}${{ parameters.artifactSuffix }} failed build' + condition: failed() + inputs: + targetPath: 'build_${{ parameters.arch }}' + artifact: 'build_${{ parameters.arch }}${{ parameters.artifactSuffix }}_failed_attempt$(System.JobAttempt)' diff --git a/src/callstack.cpp b/src/callstack.cpp index b45ab90b..15577a81 100644 --- a/src/callstack.cpp +++ b/src/callstack.cpp @@ -76,7 +76,8 @@ static WCHAR* duplicateString(LPCWSTR source) { size_t length = wcslen(source) + 1; WCHAR* copy = new WCHAR[length]; - wcscpy_s(copy, length, source); + if (copy != NULL) + wcscpy_s(copy, length, source); return copy; } @@ -107,7 +108,11 @@ VOID CallStack::cacheSymbols (const Set& programCounters) generation = g_symbolCacheGeneration; } + // VLD's new returns NULL when its heap is exhausted; a symbol that + // cannot be cached is shown as an address. cachedsymbol_t* symbol = new cachedsymbol_t; + if (symbol == NULL) + return; IMAGEHLP_LINE64 sourceInfo = { 0 }; sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64); { @@ -129,10 +134,10 @@ VOID CallStack::cacheSymbols (const Set& programCounters) } CriticalSectionLocker<> cs(g_symbolCacheLock); - if (generation == g_symbolCacheGeneration) { + if (symbol->functionName != NULL && generation == g_symbolCacheGeneration) { if (g_symbolCache == NULL) g_symbolCache = new SymbolCache; - if (g_symbolCache->find(programCounter) == g_symbolCache->end()) { + if (g_symbolCache != NULL && g_symbolCache->find(programCounter) == g_symbolCache->end()) { g_symbolCache->insert(programCounter, symbol); continue; } @@ -221,6 +226,7 @@ CallStack::CallStack () m_resolved = NULL; m_resolvedCapacity = 0; m_resolvedLength = 0; + m_superseded = NULL; } // Destructor - Frees all memory allocated to the CallStack. @@ -237,12 +243,23 @@ CallStack::~CallStack () } delete [] m_resolved; + freeSuperseded(); m_resolved = NULL; m_resolvedCapacity = 0; m_resolvedLength = 0; } +VOID CallStack::freeSuperseded () +{ + while (m_superseded != NULL) { + superseded_t* next = m_superseded->next; + delete [] m_superseded->text; + delete m_superseded; + m_superseded = next; + } +} + CallStack* CallStack::Create() { CallStack* result = NULL; @@ -345,15 +362,17 @@ VOID CallStack::clear () delete [] m_resolved; m_resolved = NULL; } + freeSuperseded(); + m_status &= ~CALLSTACK_STATUS_PARTIAL; m_resolvedCapacity = 0; m_resolvedLength = 0; } // getFunctionName - Names the function of a program counter from the symbol // cache. If the cache does not have it, asks dbghelp, or uses the address on -// a thread that owns g_heapMapLock. +// a thread that owns g_heapMapLock and sets cacheMiss. LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement64, - SYMBOL_INFO* functionInfo) + SYMBOL_INFO* functionInfo, bool& cacheMiss) { displacement64 = 0; { @@ -371,6 +390,7 @@ LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement6 CriticalSectionLocker locker(g_DbgHelp); return getFunctionName(programCounter, displacement64, functionInfo, locker); } + cacheMiss = true; auto result = fmt::format_to_n(functionInfo->Name, MAX_SYMBOL_NAME_LENGTH - 1, L"" ADDRESSCPPFORMAT, programCounter); *result.out = L'\0'; return functionInfo->Name; @@ -378,9 +398,10 @@ LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement6 // getLine - Finds the source line of a program counter in the symbol cache. If // the cache does not have it, asks dbghelp, except on a thread that owns -// g_heapMapLock. sourceInfo->FileName points to fileName on success. +// g_heapMapLock, which sets cacheMiss. sourceInfo->FileName points to +// fileName on success. BOOL CallStack::getLine(SIZE_T programCounter, DWORD& displacement, IMAGEHLP_LINEW64* sourceInfo, - LPWSTR fileName, DWORD fileNameSize) + LPWSTR fileName, DWORD fileNameSize, bool& cacheMiss) { { CriticalSectionLocker<> cs(g_symbolCacheLock); @@ -397,8 +418,10 @@ BOOL CallStack::getLine(SIZE_T programCounter, DWORD& displacement, IMAGEHLP_LIN } } } - if (usesSymbolCacheOnly()) + if (usesSymbolCacheOnly()) { + cacheMiss = true; return FALSE; + } #if defined(_M_ARM64) if (VldArm64InTeardownReport()) return FALSE; @@ -538,6 +561,10 @@ bool CallStack::isLeakSuppressed() } BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 }; + // A frame missing from the symbol cache is named by its address, which can + // hide a CRT startup or ignored function: such an answer holds for this + // query only, and the stack is examined again next time. + bool cacheMiss = false; // Iterate through each frame in the call stack. for (UINT32 frame = 0; frame < m_size; frame++) { @@ -553,13 +580,13 @@ bool CallStack::isLeakSuppressed() } DWORD64 displacement64; - LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer); + LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, cacheMiss); - m_status |= isCrtStartupFunction(functionName); - if (m_status & CALLSTACK_STATUS_STARTUPCRT) { - return true; - } else if (m_status & CALLSTACK_STATUS_NOTSTARTUPCRT) { - return false; + UINT startup = isCrtStartupFunction(functionName); + if (startup != 0) { + if (!cacheMiss) + m_status |= startup; + return (startup & CALLSTACK_STATUS_STARTUPCRT) != 0; } if (isIgnoreFunction(functionName)) { @@ -567,7 +594,8 @@ bool CallStack::isLeakSuppressed() } } - m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; + if (!cacheMiss) + m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; return false; } @@ -587,9 +615,7 @@ bool CallStack::isLeakSuppressed() // void CallStack::dump(BOOL showInternalFrames) { - if (!m_resolved) { - resolve(showInternalFrames); - } + resolve(showInternalFrames); // The stack was reoslved already if (m_resolved) { @@ -618,7 +644,12 @@ int CallStack::resolve(BOOL showInternalFrames) // already resolved, no need to do it again // resolving twice may report an incorrect module for the stack frames // if the memory was leaked in a dynamic library that was already unloaded. - return 0; + // A stack resolved while some of its symbols were missing from the + // cache is resolved again once the cache has them all. The earlier + // text lives as long as the CallStack: GetAllocationResolveResults + // has handed it out. + if (!(m_status & CALLSTACK_STATUS_PARTIAL) || !areFramesCached()) + return 0; } if (m_status & CALLSTACK_STATUS_STARTUPCRT) { @@ -640,22 +671,33 @@ int CallStack::resolve(BOOL showInternalFrames) bool skipStartupLeaks = !!(g_vld.GetOptions() & VLD_OPT_SKIP_CRTSTARTUP_LEAKS); - // Use static here to increase performance, and avoid heap allocs. - // It's thread safe because of g_heapMapLock lock. - static WCHAR stack_line[MAXREPORTLENGTH + 1] = L""; + // Not static: a ValidateHeapFree report resolves outside g_heapMapLock. + struct ScratchBuffers { + WCHAR* stackLine; + WCHAR* fileName; + ScratchBuffers() : stackLine(new WCHAR[MAXREPORTLENGTH + 1]), fileName(new WCHAR[MAX_PATH * 4]) {} + ~ScratchBuffers() { delete [] stackLine; delete [] fileName; } + } scratch; + if (scratch.stackLine == NULL || scratch.fileName == NULL) + return 0; + WCHAR* stack_line = scratch.stackLine; + const size_t stackLineLength = MAXREPORTLENGTH + 1; + WCHAR* fileName = scratch.fileName; + const size_t fileNameLength = MAX_PATH * 4; + stack_line[0] = L'\0'; bool isPrevFrameInternal = false; DWORD NumChars = 0; - static WCHAR fileName[MAX_PATH * 4]; - const size_t max_line_length = MAXREPORTLENGTH + 1; - m_resolvedCapacity = m_size * max_line_length; - const size_t allocedBytes = m_resolvedCapacity * sizeof(WCHAR); - m_resolved = new WCHAR[m_resolvedCapacity]; - if (m_resolved) { - ZeroMemory(m_resolved, allocedBytes); - } + const int textCapacity = m_size * (MAXREPORTLENGTH + 1); + WCHAR* text = new WCHAR[textCapacity]; + if (text == NULL) + return 0; + ZeroMemory(text, textCapacity * sizeof(WCHAR)); + int textLength = 0; // Iterate through each frame in the call stack. + bool cacheMiss = false; + UINT startup = m_status & (CALLSTACK_STATUS_STARTUPCRT | CALLSTACK_STATUS_NOTSTARTUPCRT); for (UINT32 frame = 0; frame < m_size; frame++) { // Try to get the source file and line number associated with @@ -666,23 +708,24 @@ int CallStack::resolve(BOOL showInternalFrames) DWORD64 displacement64; BYTE symbolBuffer[sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE]; - LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer); + LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, cacheMiss); if (skipStartupLeaks) { - if (!(m_status & (CALLSTACK_STATUS_STARTUPCRT | CALLSTACK_STATUS_NOTSTARTUPCRT))) { - m_status |= isCrtStartupFunction(functionName); + if (startup == 0) { + startup = isCrtStartupFunction(functionName); + // Kept only if it was decided with every symbol at hand; see + // isLeakSuppressed. + if (!cacheMiss) + m_status |= startup; } - if (m_status & CALLSTACK_STATUS_STARTUPCRT) { - delete[] m_resolved; - m_resolved = NULL; - m_resolvedCapacity = 0; - m_resolvedLength = 0; + if (startup & CALLSTACK_STATUS_STARTUPCRT) { + delete[] text; return 0; } } DWORD displacement = 0; - BOOL foundline = getLine(programCounter, displacement, &sourceInfo, fileName, _countof(fileName)); + BOOL foundline = getLine(programCounter, displacement, &sourceInfo, fileName, fileNameLength, cacheMiss); bool isFrameInternal = false; if (foundline && !showInternalFrames) { @@ -694,27 +737,42 @@ int CallStack::resolve(BOOL showInternalFrames) // show one allocation function for context if (NumChars > 0 && !isFrameInternal && isPrevFrameInternal) { - m_resolvedLength += NumChars; - if (m_resolved) { - wcsncat_s(m_resolved, m_resolvedCapacity, stack_line, NumChars); - } + textLength += NumChars; + wcsncat_s(text, textCapacity, stack_line, NumChars); } isPrevFrameInternal = isFrameInternal; if (!foundline) displacement = (DWORD)displacement64; NumChars = resolveFunction( programCounter, foundline ? &sourceInfo : NULL, - displacement, functionName, stack_line, _countof( stack_line )); + displacement, functionName, stack_line, stackLineLength); if (NumChars > 0 && !isFrameInternal) { - m_resolvedLength += NumChars; - if (m_resolved) { - wcsncat_s(m_resolved, m_resolvedCapacity, stack_line, NumChars); - } + textLength += NumChars; + wcsncat_s(text, textCapacity, stack_line, NumChars); } } // end for loop - m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; + if (m_resolved != NULL) { + superseded_t* superseded = new superseded_t; + if (superseded == NULL) { + delete [] text; + return unresolvedFunctionsCount; + } + superseded->text = m_resolved; + superseded->next = m_superseded; + m_superseded = superseded; + } + m_resolved = text; + m_resolvedCapacity = textCapacity; + m_resolvedLength = textLength; + if (cacheMiss) { + m_status |= CALLSTACK_STATUS_PARTIAL; + } + else { + m_status &= ~CALLSTACK_STATUS_PARTIAL; + m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; + } return unresolvedFunctionsCount; } @@ -726,7 +784,20 @@ const WCHAR* CallStack::getResolvedCallstack( BOOL showinternalframes ) bool CallStack::needsSymbols() const { - return m_resolved == NULL && !(m_status & CALLSTACK_STATUS_STARTUPCRT); + return (m_resolved == NULL || (m_status & CALLSTACK_STATUS_PARTIAL)) && !(m_status & CALLSTACK_STATUS_STARTUPCRT); +} + +// areFramesCached - Checks that the symbol cache has every frame. +bool CallStack::areFramesCached() const +{ + CriticalSectionLocker<> cs(g_symbolCacheLock); + if (g_symbolCache == NULL) + return false; + for (UINT32 frame = 0; frame < m_size; frame++) { + if (g_symbolCache->find((*this)[frame]) == g_symbolCache->end()) + return false; + } + return true; } // push_back - Pushes a frame's program counter onto the CallStack. Pushes are @@ -995,6 +1066,8 @@ ULONG CallStack::captureBackTrace (UINT32 maxdepth, const context_t& context) // Longest wait for g_DbgHelp, in milliseconds. static const ULONGLONG DBGHELP_WAIT_MS = 100; +volatile LONG g_safeStackWalkFallbacks = 0; + // enterDbgHelp - Enters g_DbgHelp, giving up after DBGHELP_WAIT_MS. The caller // can hold a heap lock (HeapLock) that the owner of g_DbgHelp waits for, // since dbghelp allocates from the process heap; waiting forever would @@ -1064,6 +1137,7 @@ VOID SafeCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) // Not under g_heapMapLock: a thread holding g_DbgHelp can be loading a DLL // for dbghelp, waiting for a loader owner that waits for g_heapMapLock. if (!enterDbgHelp()) { + InterlockedIncrement(&g_safeStackWalkFallbacks); captureBackTrace(maxdepth, context); return; } diff --git a/src/callstack.h b/src/callstack.h index 126af20b..0cbce269 100644 --- a/src/callstack.h +++ b/src/callstack.h @@ -38,6 +38,9 @@ template class Set; #define MAX_SYMBOL_NAME_LENGTH 256 // Maximum symbol name length that we will allow. Longer names will be truncated. #define MAX_SYMBOL_NAME_SIZE ((MAX_SYMBOL_NAME_LENGTH * sizeof(WCHAR)) - 1) +// Number of safe stack walks that fell back to RtlCaptureStackBackTrace. +extern volatile LONG g_safeStackWalkFallbacks; + //////////////////////////////////////////////////////////////////////////////// // // The CallStack Class @@ -96,7 +99,8 @@ class CallStack virtual DWORD getHashValue() const = 0; virtual VOID getStackTrace (UINT32 maxdepth, const context_t& context) = 0; bool isLeakSuppressed(); - // False once the stack is resolved or known to be a CRT startup stack. + // False once the stack is resolved with all its symbols or known to be a + // CRT startup stack. bool needsSymbols() const; // Symbols of call stack frames are looked up by dbghelp only outside @@ -122,6 +126,7 @@ class CallStack #define CALLSTACK_STATUS_INCOMPLETE 0x1 // If set, the stack trace stored in this CallStack appears to be incomplete. #define CALLSTACK_STATUS_STARTUPCRT 0x2 // If set, the stack trace is startup CRT. #define CALLSTACK_STATUS_NOTSTARTUPCRT 0x4 // If set, the stack trace is not startup CRT. +#define CALLSTACK_STATUS_PARTIAL 0x8 // If set, m_resolved shows frames whose symbols were missing from the cache as addresses. // The chunk list is made of a linked list of Chunks. struct chunk_t { @@ -142,15 +147,24 @@ class CallStack int m_resolvedCapacity; int m_resolvedLength; + // Earlier renderings of a stack resolved again; see resolve. + struct superseded_t { + WCHAR* text; + superseded_t* next; + }; + superseded_t* m_superseded; + VOID freeSuperseded (); + bool isInternalModule( const PWSTR filename ) const; UINT isCrtStartupFunction( LPCWSTR functionName ) const; bool isIgnoreFunction(LPCWSTR functionName) const; static LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, - SYMBOL_INFO* functionInfo); + SYMBOL_INFO* functionInfo, bool& cacheMiss); static LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker); static BOOL getLine(SIZE_T programCounter, DWORD& displacement, IMAGEHLP_LINEW64* sourceInfo, - LPWSTR fileName, DWORD fileNameSize); + LPWSTR fileName, DWORD fileNameSize, bool& cacheMiss); + bool areFramesCached() const; DWORD resolveFunction(SIZE_T programCounter, IMAGEHLP_LINEW64* sourceInfo, DWORD displacement, LPCWSTR functionName, LPWSTR stack_line, DWORD stackLineSize) const; diff --git a/src/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 68fcccdb..d5d700e0 100644 --- a/src/tests/CMakeLists.txt +++ b/src/tests/CMakeLists.txt @@ -978,3 +978,55 @@ add_vld_test(chaos_longname_dll set_chaos_output_dir(chaos_longname_dll) set_target_properties(chaos_longname_dll PROPERTIES OUTPUT_NAME "chaos_longname_012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789end") add_dependencies(chaos_long_frame chaos_longname_dll) + +# ============================================================================ +# review74 - one test per PR #74 review comment, in their own output directory +# with their own vld.ini. +# ============================================================================ +set(VLD_REVIEW74_TESTS + review_symbol_cache_latch + review_last_error + review_report_file_fallback + review_proc_name_address + review_validate_heapfree + review_crt_noaccess_leak + review_report_options_race + review_unreadable_no_exception +) + +# The tests share one directory, so one target copies their runtime files; +# a copy per test would race in a parallel build. +set(REVIEW74_DIR "${CMAKE_BINARY_DIR}/bin/$/review74") +add_custom_target(review74_runtime + COMMAND ${CMAKE_COMMAND} -E make_directory "${REVIEW74_DIR}" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_CURRENT_SOURCE_DIR}/review74/vld.ini" + "${REVIEW74_DIR}/vld.ini" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "$" + "${REVIEW74_DIR}/$" + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "${CMAKE_SOURCE_DIR}/setup/dbghelp/${DBGHELP_ARCH}/dbghelp.dll" + "${REVIEW74_DIR}/dbghelp.dll" + DEPENDS vld + COMMENT "Copying review74 vld.ini, VLD DLL, and dbghelp.dll" +) + +foreach(REVIEW_TEST ${VLD_REVIEW74_TESTS}) + add_vld_test(${REVIEW_TEST} + SOURCES review74/${REVIEW_TEST}.cpp + HEADERS review74/review_common.h chaos/chaos_common.h + ) + set_target_properties(${REVIEW_TEST} PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin/$/review74" + RUNTIME_OUTPUT_DIRECTORY_DEBUG "${CMAKE_BINARY_DIR}/bin/Debug/review74" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${CMAKE_BINARY_DIR}/bin/Release/review74" + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${CMAKE_BINARY_DIR}/bin/RelWithDebInfo/review74" + RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL "${CMAKE_BINARY_DIR}/bin/MinSizeRel/review74" + ) + add_dependencies(${REVIEW_TEST} review74_runtime) + set_tests_properties(${REVIEW_TEST} PROPERTIES + TIMEOUT 150 + FAIL_REGULAR_EXPRESSION "FAIL:|Visual Leak Detector detected [0-9]+ memory leak") +endforeach() + diff --git a/src/tests/chaos/chaos_fake_crt_header.cpp b/src/tests/chaos/chaos_fake_crt_header.cpp index bfbd71ec..54fd6250 100644 --- a/src/tests/chaos/chaos_fake_crt_header.cpp +++ b/src/tests/chaos/chaos_fake_crt_header.cpp @@ -55,6 +55,25 @@ int main() chaos::Fail(message); } + chaos::SetPhase("a header that changes between queries"); + void* changing = malloc(BLOCK_SIZE); + chaos::Check(changing != NULL, "malloc failed"); + memset(changing, 0, BLOCK_SIZE); + FakeHeader* header = (FakeHeader*)changing; + header->use = 1; + header->size = BLOCK_SIZE - sizeof(FakeHeader) - 4; + memset(header->gap, 0xFD, sizeof(header->gap)); + UINT before = VLDGetLeaksCount(); + header->use = 0; + UINT after = VLDGetLeaksCount(); + if (before != _countof(USES) + 1 || after != before) + { + char message[128]; + sprintf_s(message, "counted %u leaks, then %u after the fake header changed; expected %d", before, after, (int)_countof(USES) + 1); + chaos::Fail(message); + } + free(changing); + chaos::SetPhase("cleanup"); for (int i = 0; i < _countof(USES); i++) { diff --git a/src/tests/chaos/chaos_realloc_reuse.cpp b/src/tests/chaos/chaos_realloc_reuse.cpp index 778ce9cb..db7af949 100644 --- a/src/tests/chaos/chaos_realloc_reuse.cpp +++ b/src/tests/chaos/chaos_realloc_reuse.cpp @@ -3,10 +3,11 @@ // // The heap frees the old block inside the real realloc, before VLD forgets // the old address, so another thread can be handed that address first. Movers -// reallocate blocks that VLD does not track, or tracked ones while VLD is -// disabled for the thread, through every reallocation API to a larger size -// so they move; leakers keep every block they allocate. Each leaker's count -// must match exactly. +// reallocate blocks that VLD does not track, tracked ones while VLD is +// disabled for the thread, and tracked ones with VLD enabled, through every +// reallocation API to a larger size so they move; leakers keep every block +// they allocate, spread over the whole run. Each leaker's count must match +// exactly. #include "chaos_common.h" #include "vld.h" @@ -74,16 +75,18 @@ DWORD WINAPI Mover(LPVOID p) while (!InterlockedCompareExchange(&g_stop, 0, 0)) { Api api = (Api)random.Below(API_COUNT); - bool untracked = random.Below(2) == 0; + unsigned mode = random.Below(3); + bool untracked = mode == 0; + bool disabledMove = mode == 1; if (untracked) VLDDisable(); void* block = Allocate(api); if (untracked) VLDRestore(); - else + else if (disabledMove) VLDDisable(); void* moved = Reallocate(api, block, 4096 + random.Below(4096)); - if (!untracked) + if (disabledMove) VLDRestore(); Free(api, moved != NULL ? moved : block); } @@ -93,11 +96,16 @@ DWORD WINAPI Mover(LPVOID p) DWORD WINAPI LeakerThread(LPVOID p) { Leaker* leaker = (Leaker*)p; + ULONGLONG start = GetTickCount64(); while (!InterlockedCompareExchange(&g_stop, 0, 0) && leaker->kept < MAX_KEPT) { + ULONGLONG elapsed = GetTickCount64() - start; + if ((ULONGLONG)leaker->kept * RUN_MS >= (ULONGLONG)MAX_KEPT * elapsed) + { + Sleep(1); + continue; + } leaker->blocks[leaker->kept++] = malloc(SIZE); - if ((leaker->kept & 15) == 0) - Sleep(0); } return 0; } diff --git a/src/tests/chaos/chaos_report_hook_race.cpp b/src/tests/chaos/chaos_report_hook_race.cpp index 456541ee..01cf503c 100644 --- a/src/tests/chaos/chaos_report_hook_race.cpp +++ b/src/tests/chaos/chaos_report_hook_race.cpp @@ -1,7 +1,7 @@ // chaos_report_hook_race.cpp - report hooks installed and removed while other // threads print leak reports. // -// VLDSetReportHook changes the hook set under VLD's options lock; every +// VLDSetReportHook changes the hook set under g_reportHooksLock; every // printed report line walks that set. A leak report running concurrently with // hook installs/removals must neither crash nor lose the permanent hook. @@ -13,6 +13,7 @@ namespace const DWORD RUN_MS = 3000; volatile LONG g_stop = 0; volatile LONG g_leakedLines = 0; +volatile LONG g_permanentLines = 0; template int __cdecl Hook(int, wchar_t* message, int*) @@ -28,7 +29,7 @@ int __cdecl PermanentHook(int, wchar_t* message, int*) { if (message != NULL && wcsstr(message, L"Leak Hash") != NULL) { - InterlockedIncrement(&g_leakedLines); + InterlockedIncrement(&g_permanentLines); } return 1; } @@ -86,13 +87,17 @@ int main() chaos::SetPhase("hook install/remove racing VLDReportLeaks"); chaos::RunThreads(6, Worker, &g_stop, RUN_MS + 2000); + chaos::SetPhase("permanent hook after churn"); + InterlockedExchange(&g_permanentLines, 0); + VLDReportLeaks(); + chaos::Check(InterlockedCompareExchange(&g_permanentLines, 0, 0) >= 4, "the permanent hook was lost during churn"); + chaos::SetPhase("cleanup"); for (int i = 0; i < 4; i++) { free(leaks[i]); } - VLDSetReportHook(VLD_RPTHOOK_REMOVE, PermanentHook); - chaos::Check(InterlockedCompareExchange(&g_leakedLines, 0, 0) > 0, "no leak report reached the permanent hook"); + chaos::Check(VLDSetReportHook(VLD_RPTHOOK_REMOVE, PermanentHook) == 0, "remove failed"); chaos::Pass(); return 0; } diff --git a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp index 89ea22af..f8338525 100644 --- a/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp +++ b/src/tests/getaddrinfo_missing_free_test/getaddrinfo_missing_free_test.cpp @@ -3,14 +3,14 @@ // // This test runs in its own process so DLL loading state is clean. // It first warms up getaddrinfo (triggering system DLL one-time init), -// then compares leak counts with and without freeaddrinfo. +// then checks that VLD tracks the block getaddrinfo returns and counts it +// as a leak of this thread when freeaddrinfo is not called. // // The vld.ini for this test has an empty IgnoreModulesList, so system DLL -// false positives are visible. The test accounts for this by comparing -// leak counts rather than checking for zero. +// allocations are tracked too. Leak counts are not compared: the DNS client +// allocates on this thread and on threads of its own at any time. #include -#include #include #include #include "vld.h" @@ -41,8 +41,6 @@ class TestGetAddrInfoMissingFree : public ::testing::Test // 2. Baseline: VLD tracks the block getaddrinfo returns. // 3. Test: call getaddrinfo WITHOUT freeaddrinfo. VLD still tracks the // block, as a leak of this thread. -// Leak counts are not compared: the DNS client allocates on this thread and -// on threads of its own at any time. typedef const wchar_t* (*AllocationCallstack_t)(void* alloc, BOOL showInternalFrames); static AllocationCallstack_t GetAllocationCallstack() @@ -66,7 +64,7 @@ static struct addrinfo* ResolveLocalhost() return rc == 0 ? result : NULL; } -TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) +TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoIsTrackedAsLeak) { AllocationCallstack_t callstack = GetAllocationCallstack(); ASSERT_NE(static_cast(NULL), callstack); diff --git a/src/tests/review74/review_common.h b/src/tests/review74/review_common.h new file mode 100644 index 00000000..0003c787 --- /dev/null +++ b/src/tests/review74/review_common.h @@ -0,0 +1,124 @@ +// review_common.h - helpers for the review74 tests. +// +// Each review74 test checks one PR #74 review comment and fails without its +// fix. Tests that need a separate process start a copy of themselves with +// "--child " and check its exit code or its debugger output. + +#pragma once + +#include "../chaos/chaos_common.h" + +namespace review +{ +// Returns the child mode of this process, or NULL in the parent. +inline const wchar_t* ChildMode() +{ + int argc = 0; + LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); + if (argv == NULL || argc != 3 || wcscmp(argv[1], L"--child") != 0) + { + return NULL; + } + return argv[2]; +} + +inline bool StartChild(const wchar_t* mode, DWORD creationFlags, PROCESS_INFORMATION& process) +{ + wchar_t exe[MAX_PATH]; + wchar_t commandLine[MAX_PATH + 64]; + GetModuleFileNameW(NULL, exe, _countof(exe)); + swprintf_s(commandLine, L"\"%s\" --child %s", exe, mode); + STARTUPINFOW startup = { sizeof(startup) }; + ZeroMemory(&process, sizeof(process)); + return CreateProcessW(exe, commandLine, NULL, NULL, FALSE, creationFlags, NULL, NULL, &startup, &process) != FALSE; +} + +// Runs a copy of this test in the given child mode and returns its exit code. +inline DWORD RunChild(const wchar_t* mode, DWORD timeoutMs) +{ + PROCESS_INFORMATION process; + chaos::Check(StartChild(mode, 0, process), "could not start the child process"); + CloseHandle(process.hThread); + if (WaitForSingleObject(process.hProcess, timeoutMs) == WAIT_TIMEOUT) + { + TerminateProcess(process.hProcess, 99); + WaitForSingleObject(process.hProcess, INFINITE); + } + DWORD exitCode = 0; + GetExitCodeProcess(process.hProcess, &exitCode); + CloseHandle(process.hProcess); + return exitCode; +} + +// Runs a copy of this test under this process as its debugger and collects +// what it sends to the debugger (OutputDebugString). Returns its exit code. +inline DWORD RunChildUnderDebugger(const wchar_t* mode, wchar_t* text, size_t textSize, DWORD timeoutMs) +{ + PROCESS_INFORMATION process; + chaos::Check(StartChild(mode, DEBUG_ONLY_THIS_PROCESS, process), "could not start the child process"); + size_t length = 0; + text[0] = L'\0'; + ULONGLONG deadline = GetTickCount64() + timeoutMs; + DWORD exitCode = 99; + for (;;) + { + DEBUG_EVENT event; + if (!WaitForDebugEvent(&event, 1000)) + { + if (GetTickCount64() > deadline) + { + TerminateProcess(process.hProcess, 99); + } + continue; + } + DWORD status = DBG_CONTINUE; + switch (event.dwDebugEventCode) + { + case OUTPUT_DEBUG_STRING_EVENT: + { + const OUTPUT_DEBUG_STRING_INFO& info = event.u.DebugString; + BYTE buffer[8192]; + SIZE_T bytes = info.nDebugStringLength * (info.fUnicode ? sizeof(WCHAR) : 1); + if (bytes > sizeof(buffer)) + bytes = sizeof(buffer); + SIZE_T read = 0; + if (ReadProcessMemory(process.hProcess, info.lpDebugStringData, buffer, bytes, &read) && read > 0) + { + for (SIZE_T i = 0; i < (info.fUnicode ? read / sizeof(WCHAR) : read) && length + 1 < textSize; i++) + { + WCHAR c = info.fUnicode ? ((WCHAR*)buffer)[i] : (WCHAR)buffer[i]; + if (c != L'\0') + text[length++] = c; + } + text[length] = L'\0'; + } + break; + } + case EXCEPTION_DEBUG_EVENT: + // The loader's initial breakpoint is expected; anything else is + // left to the child. + if (event.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT && + event.u.Exception.ExceptionRecord.ExceptionCode != 0x4000001F) // STATUS_WX86_BREAKPOINT + status = DBG_EXCEPTION_NOT_HANDLED; + break; + case CREATE_PROCESS_DEBUG_EVENT: + if (event.u.CreateProcessInfo.hFile != NULL) + CloseHandle(event.u.CreateProcessInfo.hFile); + break; + case LOAD_DLL_DEBUG_EVENT: + if (event.u.LoadDll.hFile != NULL) + CloseHandle(event.u.LoadDll.hFile); + break; + case EXIT_PROCESS_DEBUG_EVENT: + exitCode = event.u.ExitProcess.dwExitCode; + break; + } + ContinueDebugEvent(event.dwProcessId, event.dwThreadId, status); + if (event.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) + break; + } + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + return exitCode; +} +} diff --git a/src/tests/review74/review_crt_noaccess_leak.cpp b/src/tests/review74/review_crt_noaccess_leak.cpp new file mode 100644 index 00000000..d45f039e --- /dev/null +++ b/src/tests/review74/review_crt_noaccess_leak.cpp @@ -0,0 +1,60 @@ +// review_crt_noaccess_leak.cpp - PR #74 review comment on vld.cpp:2156. +// +// A leaked debug CRT block whose header page the application made +// inaccessible is still a leak: VLD must count and report it, like a heap +// block it cannot read, not drop it as freed. Only Debug builds have debug CRT +// blocks; elsewhere the block is a plain heap block, counted either way. + +#include "review_common.h" +#include "vld.h" +#include + +namespace +{ +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} +} + +int main() +{ + chaos::StartWatchdog(30000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + VLDMarkAllLeaksAsReported(); + + chaos::SetPhase("leaking a large CRT block"); + // Large enough for the heap to give it pages of its own. + const size_t size = 1024 * 1024; + BYTE* data = (BYTE*)malloc(size); + chaos::Check(data != NULL, "malloc failed"); + memset(data, 0x5A, size); + // Looks up the block's symbols now, so that the queries below need no + // allocation that could touch the heap's pages around the block. + chaos::Check(VLDGetLeaksCount() == 1, "the CRT block is not counted"); + + chaos::SetPhase("making the page with the block's header inaccessible"); + SYSTEM_INFO si; + GetSystemInfo(&si); +#ifdef _DEBUG + BYTE* first = data - 1; +#else + // No header; the heap can give the block a page of its own, so the byte + // before it can be on a page that is not even committed. + BYTE* first = data; +#endif + BYTE* page = (BYTE*)((UINT_PTR)first & ~((UINT_PTR)si.dwPageSize - 1)); + DWORD old = 0; + chaos::Check(VirtualProtect(page, si.dwPageSize, PAGE_NOACCESS, &old) != FALSE, "VirtualProtect failed"); + UINT counted = VLDGetLeaksCount(); + UINT reported = VLDReportLeaks(); + VirtualProtect(page, si.dwPageSize, old, &old); + + chaos::Check(counted == 1, "VLDGetLeaksCount dropped a CRT block whose header is not readable"); + chaos::Check(reported == 1, "VLDReportLeaks dropped a CRT block whose header is not readable"); + free(data); + chaos::Check(VLDGetLeaksCount() == 0, "the freed block is still counted"); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_last_error.cpp b/src/tests/review74/review_last_error.cpp new file mode 100644 index 00000000..bc11b095 --- /dev/null +++ b/src/tests/review74/review_last_error.cpp @@ -0,0 +1,73 @@ +// review_last_error.cpp - PR #74 review comment on vld.cpp:1703. +// +// VLD's hooks must leave the thread's last error alone: code such as +// "if (!ReadFile(...)) { free(buffer); return GetLastError(); }" must see the +// error of the call that failed, not the 0 that TlsGetValue stores on success. + +#include "review_common.h" +#include "vld.h" +#include + +namespace +{ +void CheckPreserved(DWORD expected, const char* message) +{ + chaos::Check(GetLastError() == expected, message); +} +} + +int main() +{ + chaos::StartWatchdog(20000); + VLDMarkAllLeaksAsReported(); + + // Each call runs on a fresh thread too, whose TLS VLD creates on first use. + for (int pass = 0; pass < 2; pass++) + { + chaos::SetPhase("HeapAlloc and HeapFree"); + SetLastError(ERROR_HANDLE_EOF); + void* block = HeapAlloc(GetProcessHeap(), 0, 32); + CheckPreserved(ERROR_HANDLE_EOF, "HeapAlloc changed the last error"); + chaos::Check(block != NULL, "HeapAlloc failed"); + SetLastError(ERROR_ACCESS_DENIED); + HeapFree(GetProcessHeap(), 0, block); + CheckPreserved(ERROR_ACCESS_DENIED, "HeapFree changed the last error"); + + chaos::SetPhase("malloc and free"); + SetLastError(ERROR_BROKEN_PIPE); + void* crtBlock = malloc(48); + CheckPreserved(ERROR_BROKEN_PIPE, "malloc changed the last error"); + chaos::Check(crtBlock != NULL, "malloc failed"); + SetLastError(ERROR_FILE_NOT_FOUND); + free(crtBlock); + CheckPreserved(ERROR_FILE_NOT_FOUND, "free changed the last error"); + + chaos::SetPhase("HeapReAlloc"); + void* moved = HeapAlloc(GetProcessHeap(), 0, 16); + chaos::Check(moved != NULL, "HeapAlloc failed"); + SetLastError(ERROR_SHARING_VIOLATION); + moved = HeapReAlloc(GetProcessHeap(), 0, moved, 64 * 1024); + CheckPreserved(ERROR_SHARING_VIOLATION, "HeapReAlloc changed the last error"); + chaos::Check(moved != NULL, "HeapReAlloc failed"); + HeapFree(GetProcessHeap(), 0, moved); + + if (pass == 0) + { + HANDLE thread = CreateThread(NULL, 0, [](LPVOID) -> DWORD { + SetLastError(ERROR_INVALID_DATA); + void* block = HeapAlloc(GetProcessHeap(), 0, 24); + if (GetLastError() != ERROR_INVALID_DATA) + chaos::Fail("the first allocation of a thread changed the last error"); + HeapFree(GetProcessHeap(), 0, block); + return 0; + }, NULL, 0, NULL); + chaos::Check(thread != NULL, "CreateThread failed"); + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); + } + } + + chaos::Check(VLDGetLeaksCount() == 0, "a freed block is still counted"); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_proc_name_address.cpp b/src/tests/review74/review_proc_name_address.cpp new file mode 100644 index 00000000..b6e443ef --- /dev/null +++ b/src/tests/review74/review_proc_name_address.cpp @@ -0,0 +1,45 @@ +// review_proc_name_address.cpp - PR #74 review comment on vld.cpp:2535. +// +// GetProcAddress takes a name or an ordinal; a value above 0xFFFF is a name. +// On 64-bit Windows a name can sit at an address whose bits 16-31 are zero +// (0x0000000100001234), which HIWORD alone mistakes for an ordinal. VLD must +// still hand out its replacement for such a name. + +#include "review_common.h" +#include "vld.h" + +namespace +{ +typedef LPVOID (WINAPI *HeapAlloc_t)(HANDLE, DWORD, SIZE_T); +} + +int main() +{ + chaos::StartWatchdog(20000); +#ifdef _WIN64 + chaos::SetPhase("placing a name at an address with bits 16-31 zero"); + const SIZE_T size = 64 * 1024; + char* page = NULL; + for (ULONG_PTR high = 1; high < 0x8000 && page == NULL; high++) + { + page = (char*)VirtualAlloc((LPVOID)(high << 32), size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + } + chaos::Check(page != NULL, "no 4 GB aligned address is free"); + char* name = page + 0x1234; + strcpy_s(name, 32, "HeapAlloc"); + chaos::Check(((ULONG_PTR)name >> 16 & 0xFFFF) == 0 && (ULONG_PTR)name > 0xFFFF, "the name is not where it should be"); + + chaos::SetPhase("allocating through the HeapAlloc found by that name"); + HeapAlloc_t heapAlloc = (HeapAlloc_t)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), name); + chaos::Check(heapAlloc != NULL, "GetProcAddress failed"); + VLDMarkAllLeaksAsReported(); + void* block = heapAlloc(GetProcessHeap(), 0, 40); + chaos::Check(block != NULL, "HeapAlloc failed"); + chaos::Check(VLDGetLeaksCount() == 1, "a block from HeapAlloc found by a name at that address is not tracked"); + HeapFree(GetProcessHeap(), 0, block); + chaos::Check(VLDGetLeaksCount() == 0, "the freed block is still counted"); + VirtualFree(page, 0, MEM_RELEASE); +#endif + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_report_file_fallback.cpp b/src/tests/review74/review_report_file_fallback.cpp new file mode 100644 index 00000000..9cbdb721 --- /dev/null +++ b/src/tests/review74/review_report_file_fallback.cpp @@ -0,0 +1,41 @@ +// review_report_file_fallback.cpp - PR #74 review comment on vld.cpp:3728. +// +// With the report going to a file only, a file that cannot be opened must not +// silence the report: the warning says it goes to the debugger, and it must. +// The parent runs the child as its debugger and collects what it outputs. + +#include "review_common.h" +#include "vld.h" + +namespace +{ +int Child() +{ + VLDMarkAllLeaksAsReported(); + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, L"Z:\\review74\\no such directory\\report.txt"); + void* leak = HeapAlloc(GetProcessHeap(), 0, 40); + if (leak == NULL) + return 2; + memcpy(leak, "REVIEW74-MARKER", 16); + VLDReportLeaks(); + VLDMarkAllLeaksAsReported(); + return 0; +} +} + +int main() +{ + if (review::ChildMode() != NULL) + return Child(); + + chaos::StartWatchdog(60000); + chaos::SetPhase("running the child under this process as its debugger"); + static wchar_t text[256 * 1024]; + DWORD exitCode = review::RunChildUnderDebugger(L"report", text, _countof(text), 50000); + chaos::Check(exitCode == 0, "the child failed"); + chaos::Check(wcsstr(text, L"Couldn't open report file") != NULL, + "the debugger did not get the warning that the report file could not be opened"); + chaos::Check(wcsstr(text, L"REVIEW74") != NULL, "the debugger did not get the leak report"); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_report_options_race.cpp b/src/tests/review74/review_report_options_race.cpp new file mode 100644 index 00000000..27782ded --- /dev/null +++ b/src/tests/review74/review_report_options_race.cpp @@ -0,0 +1,74 @@ +// review_report_options_race.cpp - PR #74 review comment on vld.cpp:3674. +// +// VLDSetReportOptions is one operation: when two threads race it, the report +// file VLDGetReportFilename names must be the file the report goes to. + +#include "review_common.h" +#include "vld.h" +#include + +namespace +{ +const int ROUNDS = 1000; +// Only the last calls of a round decide which file is current, so each round +// is one call per thread, started together. +const int SETS_PER_THREAD = 1; + +wchar_t g_paths[2][MAX_PATH]; + +DWORD WINAPI Setter(LPVOID p) +{ + const wchar_t* path = g_paths[(INT_PTR)p]; + for (int i = 0; i < SETS_PER_THREAD; i++) + { + VLDSetReportOptions(VLD_OPT_REPORT_TO_FILE, path); + } + return 0; +} + +long FileSize(const wchar_t* path) +{ + WIN32_FILE_ATTRIBUTE_DATA data; + if (!GetFileAttributesExW(path, GetFileExInfoStandard, &data)) + return -1; + return (long)data.nFileSizeLow; +} +} + +int main() +{ + chaos::StartWatchdog(120000); + wchar_t dir[MAX_PATH]; + GetTempPathW(_countof(dir), dir); + swprintf_s(g_paths[0], L"%sreview74_race_%lu_a.txt", dir, GetCurrentProcessId()); + swprintf_s(g_paths[1], L"%sreview74_race_%lu_b.txt", dir, GetCurrentProcessId()); + VLDMarkAllLeaksAsReported(); + + for (int round = 0; round < ROUNDS; round++) + { + chaos::SetPhase("racing VLDSetReportOptions"); + chaos::RunThreads(2, Setter); + + chaos::SetPhase("reporting to the file VLD names"); + wchar_t named[MAX_PATH] = L""; + VLDGetReportFilename(named); + int index = _wcsicmp(named, g_paths[0]) == 0 ? 0 : _wcsicmp(named, g_paths[1]) == 0 ? 1 : -1; + chaos::Check(index >= 0, "VLDGetReportFilename names neither file"); + void* leak = HeapAlloc(GetProcessHeap(), 0, 16); + chaos::Check(leak != NULL, "HeapAlloc failed"); + VLDReportLeaks(); + VLDMarkAllLeaksAsReported(); + HeapFree(GetProcessHeap(), 0, leak); + // Closes the report file, flushing it. + VLDSetReportOptions(VLD_OPT_REPORT_TO_STDOUT, NULL); + char message[512]; + sprintf_s(message, "round %d: VLDGetReportFilename names file %c (%ld bytes) but the report went to file %c (%ld bytes)", + round, 'a' + index, FileSize(g_paths[index]), 'b' - index, FileSize(g_paths[1 - index])); + chaos::Check(FileSize(g_paths[index]) > 0 && FileSize(g_paths[1 - index]) == 0, message); + } + + DeleteFileW(g_paths[0]); + DeleteFileW(g_paths[1]); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_symbol_cache_latch.cpp b/src/tests/review74/review_symbol_cache_latch.cpp new file mode 100644 index 00000000..0a954c9c --- /dev/null +++ b/src/tests/review74/review_symbol_cache_latch.cpp @@ -0,0 +1,83 @@ +// review_symbol_cache_latch.cpp - PR #74 review comment on callstack.cpp:374. +// +// A leak query that finds a frame missing from the symbol cache while it holds +// g_heapMapLock gets the frame's address instead of its name. That must not +// decide anything for good. Here a thread that loads and unloads a DLL empties +// the cache while a query looks at fresh leaks of a function listed in +// IgnoreFunctionsList; once the unloads stop, none of them may count. + +#include "review_common.h" +#include "vld.h" + +namespace +{ +const int ROUNDS = 4; +const int LEAKS_PER_ROUND = 25000; + +volatile LONG g_stop = 0; +volatile LONG g_unloads = 0; + +#pragma optimize("", off) +extern "C" __declspec(noinline) void* ReviewIgnoredLeaker() +{ + void* block = HeapAlloc(GetProcessHeap(), 0, 16); + return block; +} +#pragma optimize("", on) + +DWORD WINAPI Churn(LPVOID) +{ + while (InterlockedCompareExchange(&g_stop, 0, 0) == 0) + { + HMODULE module = LoadLibraryW(L"msimg32.dll"); + if (module != NULL) + FreeLibrary(module); + InterlockedIncrement(&g_unloads); + } + return 0; +} +} + +int main() +{ + chaos::StartWatchdog(120000); + VLDMarkAllLeaksAsReported(); + chaos::Check(GetModuleHandleW(L"msimg32.dll") == NULL, "msimg32.dll is already loaded; pick another DLL"); + + // A query marks an ignored leak as reported the first time it looks at + // it, so every round leaks blocks no query has seen yet, then queries them + // once while the DLL loads and unloads. + for (int round = 0; round < ROUNDS; round++) + { + chaos::SetPhase("leaking from an ignored function"); + for (int i = 0; i < LEAKS_PER_ROUND; i++) + { + chaos::Check(ReviewIgnoredLeaker() != NULL, "HeapAlloc failed"); + } + + chaos::SetPhase("querying while a DLL loads and unloads"); + InterlockedExchange(&g_stop, 0); + LONG unloads = InterlockedCompareExchange(&g_unloads, 0, 0); + HANDLE churn = CreateThread(NULL, 0, Churn, NULL, 0, NULL); + chaos::Check(churn != NULL, "CreateThread failed"); + while (InterlockedCompareExchange(&g_unloads, 0, 0) < unloads + 2) + { + Sleep(1); + } + VLDGetLeaksCount(); + InterlockedExchange(&g_stop, 1); + WaitForSingleObject(churn, INFINITE); + CloseHandle(churn); + } + + chaos::SetPhase("querying after the unloads stopped"); + char message[512]; + UINT leaks = VLDGetLeaksCount(); + sprintf_s(message, "%u leaks of the ignored function are counted after %d queries raced %ld unloads", + leaks, ROUNDS, g_unloads); + chaos::Check(leaks == 0, message); + + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_unreadable_no_exception.cpp b/src/tests/review74/review_unreadable_no_exception.cpp new file mode 100644 index 00000000..b3ff97f4 --- /dev/null +++ b/src/tests/review74/review_unreadable_no_exception.cpp @@ -0,0 +1,73 @@ +// review_unreadable_no_exception.cpp - PR #74 review comment on vld.cpp:2020. +// +// VLD reads leaked blocks while it holds g_heapMapLock. A block the +// application made unreadable must not raise an exception there: the +// application's vectored handlers run before VLD's __except, under VLD's lock, +// and a guard page raises an exception VLD does not handle at all. + +#include "review_common.h" +#include "vld.h" + +namespace +{ +volatile LONG g_exceptions = 0; + +LONG CALLBACK CountExceptions(PEXCEPTION_POINTERS info) +{ + DWORD code = info->ExceptionRecord->ExceptionCode; + if (code == EXCEPTION_ACCESS_VIOLATION || code == EXCEPTION_GUARD_PAGE) + InterlockedIncrement(&g_exceptions); + return EXCEPTION_CONTINUE_SEARCH; +} + +int __cdecl SwallowHook(int, wchar_t*, int*) +{ + return 1; +} + +void CheckLeak(DWORD protection, const char* what) +{ + chaos::SetPhase(what); + const SIZE_T size = 64 * 1024; + BYTE* block = (BYTE*)HeapAlloc(GetProcessHeap(), 0, size); + chaos::Check(block != NULL, "HeapAlloc failed"); + chaos::Check(VLDGetLeaksCount() == 1, "the block is not counted"); + SYSTEM_INFO si; + GetSystemInfo(&si); + BYTE* page = (BYTE*)(((UINT_PTR)block + 2 * si.dwPageSize) & ~((UINT_PTR)si.dwPageSize - 1)); + DWORD old = 0; + chaos::Check(VirtualProtect(page, si.dwPageSize, protection, &old) != FALSE, "VirtualProtect failed"); + + InterlockedExchange(&g_exceptions, 0); + UINT counted = VLDGetLeaksCount(); + UINT reported = VLDReportLeaks(); + LONG exceptions = InterlockedCompareExchange(&g_exceptions, 0, 0); + + VirtualProtect(page, si.dwPageSize, old, &old); + chaos::Check(counted == 1 && reported == 1, "the leak is not counted and reported"); + chaos::Check(exceptions == 0, "reading the unreadable block raised an exception in the application"); + VLDMarkAllLeaksAsReported(); + HeapFree(GetProcessHeap(), 0, block); +} +} + +int main() +{ + chaos::StartWatchdog(30000); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, SwallowHook); + UINT options = VLDGetOptions(); + // Dumps the whole block, across the unreadable page. + VLDSetOptions(options, 64 * 1024, 64); + VLDMarkAllLeaksAsReported(); + PVOID handler = AddVectoredExceptionHandler(1, CountExceptions); + chaos::Check(handler != NULL, "AddVectoredExceptionHandler failed"); + + CheckLeak(PAGE_NOACCESS, "a leak with a PAGE_NOACCESS page"); + CheckLeak(PAGE_READWRITE | PAGE_GUARD, "a leak with a PAGE_GUARD page"); + + RemoveVectoredExceptionHandler(handler); + VLDSetOptions(options, 256, 64); + VLDSetReportHook(VLD_RPTHOOK_REMOVE, SwallowHook); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/review_validate_heapfree.cpp b/src/tests/review74/review_validate_heapfree.cpp new file mode 100644 index 00000000..f20e3d56 --- /dev/null +++ b/src/tests/review74/review_validate_heapfree.cpp @@ -0,0 +1,92 @@ +// review_validate_heapfree.cpp - PR #74 review comment on vld.cpp:1715. +// +// With ValidateHeapFree, freeing a block on a heap other than its own makes +// VLD print both call stacks. They must name the functions, which needs +// dbghelp, so VLD must print them without holding g_heapMapLock. +// +// The child frees a block on the wrong heap; its report hook exits with 3 +// once both stacks named their function, before the free reaches the heap. + +#include "review_common.h" +#include "vld.h" + +namespace +{ +wchar_t g_report[64 * 1024]; +size_t g_length = 0; +// Messages since the deallocation stack's "Call Stack:" heading; VLD prints a +// whole call stack in one message. +int g_afterDeallocationHeading = -1; + +int __cdecl Hook(int, wchar_t* message, int*) +{ + size_t length = wcslen(message); + if (g_length + length + 1 < _countof(g_report)) + { + memcpy(g_report + g_length, message, length * sizeof(wchar_t)); + g_length += length; + g_report[g_length] = L'\0'; + } + const wchar_t* deallocation = wcsstr(g_report, L"Deallocation Call stack."); + if (deallocation == NULL) + return 1; + if (g_afterDeallocationHeading < 0) + { + if (wcsstr(message, L"Call Stack:") != NULL) + g_afterDeallocationHeading = 0; + return 1; + } + const wchar_t* allocation = wcsstr(g_report, L"Allocation Call stack."); + const wchar_t* allocator = wcsstr(g_report, L"ReviewAllocOnHeap"); + bool allocationNamed = allocation != NULL && allocator != NULL && allocation < allocator && allocator < deallocation; + bool deallocationNamed = wcsstr(deallocation, L"ReviewFreeOnOtherHeap") != NULL; + TerminateProcess(GetCurrentProcess(), !allocationNamed ? 4 : !deallocationNamed ? 5 : 3); + return 1; +} + +#pragma optimize("", off) +__declspec(noinline) void* ReviewAllocOnHeap(HANDLE heap) +{ + void* block = HeapAlloc(heap, 0, 64); + return block; +} + +__declspec(noinline) void ReviewFreeOnOtherHeap(HANDLE heap, void* block) +{ + HeapFree(heap, 0, block); +} +#pragma optimize("", on) + +int Child() +{ + VLDSetOptions(VLDGetOptions() | VLD_OPT_VALIDATE_HEAPFREE, 64, 32); + VLDSetReportHook(VLD_RPTHOOK_INSTALL, Hook); + HANDLE heapA = HeapCreate(0, 0, 0); + HANDLE heapB = HeapCreate(0, 0, 0); + if (heapA == NULL || heapB == NULL) + return 2; + void* block = ReviewAllocOnHeap(heapA); + if (block == NULL) + return 2; + ReviewFreeOnOtherHeap(heapB, block); + // The hook did not see both stacks named. + TerminateProcess(GetCurrentProcess(), 5); + return 5; +} +} + +int main() +{ + if (review::ChildMode() != NULL) + return Child(); + + chaos::StartWatchdog(60000); + chaos::SetPhase("freeing a block on the wrong heap in a child"); + DWORD exitCode = review::RunChild(L"heapfree", 50000); + char message[512]; + sprintf_s(message, "the child exited with %lu: 3 means both stacks were printed with function names, 4 that the " + "allocation stack was not, 5 that the deallocation stack was not", exitCode); + chaos::Check(exitCode == 3, message); + chaos::Pass(); + return 0; +} diff --git a/src/tests/review74/vld.ini b/src/tests/review74/vld.ini new file mode 100644 index 00000000..13b2ae26 --- /dev/null +++ b/src/tests/review74/vld.ini @@ -0,0 +1,16 @@ +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Visual Leak Detector - Initialization/Configuration File (test config) +;; +;; Shared by the review74 tests. ReviewIgnoredLeaker is the function +;; review_symbol_cache_latch leaks from; no other test uses that name. +;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +[Options] +VLD = on +ReportTo = stdout +StackWalkMethod = fast +SkipCrtStartupLeaks = yes +AggregateDuplicates = no +IgnoreFunctionsList = ReviewIgnoredLeaker diff --git a/src/utility.cpp b/src/utility.cpp index e2a04fed..8536f0d4 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -212,9 +212,10 @@ VOID DumpMemoryW (LPCVOID address, SIZE_T size) BYTE byte = ((PBYTE)address)[byteIndex]; FormatHexByte(byte, formatBuf); wcsncpy_s(hexDump + hexIndex, HEXDUMPLINELENGTH - hexIndex, formatBuf, 4); - if (((byteIndex % 2) == 0) && ((byteIndex + 1) < dumpLen)) { - // On every even byte, print one character. - WORD word = ((PWORD)address)[byteIndex / 2]; + if ((byteIndex % 2) == 0) { + // On every even byte, print one character. An odd size ends + // with a lone byte; the copy being dumped stops there. + WORD word = ((byteIndex + 1) < size) ? ((PWORD)address)[byteIndex / 2] : (WORD)byte; if ((word == 0x0000) || (word == 0x0020)) { unidump[uniIndex] = L'.'; } diff --git a/src/vld.cpp b/src/vld.cpp index 6a57241c..3e8288d3 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -452,6 +452,7 @@ VisualLeakDetector::VisualLeakDetector () m_moduleEventCount = 0; m_moduleEventCapacity = 0; m_optionsLock.Initialize(); + m_reportOptionsLock.Initialize(); m_modulesLock.Initialize(); m_selfTestFile = __FILE__; m_selfTestLine = 0; @@ -776,6 +777,11 @@ VisualLeakDetector::~VisualLeakDetector () Report(L"Largest number used: %Iu bytes.\n", m_maxAlloc); Report(L"Total allocations: %Iu bytes.\n", m_totalAlloc); } + LONG fallbacks = InterlockedCompareExchange(&g_safeStackWalkFallbacks, 0, 0); + if (fallbacks != 0) { + Report(L"WARNING: Visual Leak Detector: %ld call stacks were captured with the fast method because the symbol handler was busy; their Leak Hash can differ from the same stack captured with the safe method.\n", + fallbacks); + } } #if defined(_M_ARM64) @@ -857,6 +863,7 @@ VisualLeakDetector::~VisualLeakDetector () HeapDestroy(g_vldHeap); m_optionsLock.Delete(); + m_reportOptionsLock.Delete(); m_modulesLock.Delete(); m_tlsLock.Delete(); g_heapMapLock.Delete(); @@ -1518,6 +1525,8 @@ SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, S } // gettls - Obtains the thread local storage structure for the calling thread. +// Keeps the thread's last error, which TlsGetValue clears on success: the +// hooks call this between the application's calls. // // Return Value: // @@ -1526,6 +1535,7 @@ SIZE_T VisualLeakDetector::eraseDuplicates (const BlockMap::Iterator &element, S // tls_t* VisualLeakDetector::getTls () { + DWORD lastError = GetLastError(); // Get the pointer to this thread's thread local storage structure. tls_t* tls = (tls_t*)TlsGetValue(m_tlsIndex); assert(GetLastError() == ERROR_SUCCESS); @@ -1555,6 +1565,7 @@ tls_t* VisualLeakDetector::getTls () TlsSetValue(m_tlsIndex, tls); } + SetLastError(lastError); return tls; } @@ -1739,17 +1750,30 @@ VOID VisualLeakDetector::unmapBlock (HANDLE heap, LPCVOID mem, const context_t & bool diff = other_heap != heap; // Check indeed if the other heap is different if (alloc_block && alloc_block->callStack && diff) { + // Printing needs dbghelp to name the frames, and the debugger + // break must come after it, so both happen without + // g_heapMapLock; another thread can free the block meanwhile, + // so what the message needs is copied first. + SIZE_T serialNumber = alloc_block->serialNumber; + SIZE_T size = alloc_block->size; + DWORD threadId = alloc_block->threadId; + CallStack* alloc_stack = CallStack::Create(); + for (UINT32 frame = 0; frame < alloc_block->callStack->size(); frame++) + alloc_stack->push_back((*alloc_block->callStack)[frame]); + cs.Leave(); + Report(L"CRITICAL ERROR!: VLD reports that memory was allocated in one heap and freed in another.\nThis will result in a corrupted heap.\nAllocation Call stack.\n"); - Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", alloc_block->serialNumber, mem, alloc_block->size); - Report(L" TID: %u\n", alloc_block->threadId); + Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", serialNumber, mem, size); + Report(L" TID: %u\n", threadId); Report(L" Call Stack:\n"); - alloc_block->callStack->dump(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); + alloc_stack->dump(m_options & VLD_OPT_TRACE_INTERNAL_FRAMES); + delete alloc_stack; // Now we need a way to print the current callstack at this point: CallStack* stack_here = CallStack::Create(); stack_here->getStackTrace(m_maxTraceFrames, context); Report(L"Deallocation Call stack.\n"); - Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", alloc_block->serialNumber, mem, alloc_block->size); + Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", serialNumber, mem, size); Report(L" Call Stack:\n"); stack_here->dump(FALSE); // Now it should be safe to delete our temporary callstack @@ -2005,21 +2029,30 @@ VOID VisualLeakDetector::reportConfig () // readTrackedBlock - Copies bytes of a tracked block. A reallocation frees the // old block before VLD remaps it, so a walk under g_heapMapLock can meet a -// block whose memory is already gone. +// block whose memory is already gone, and an application can make a live +// block unreadable. ReadProcessMemory fails on such memory where a plain +// read would raise an exception, which the application's vectored handlers +// and a debugger would see first, while VLD holds its lock. // // Return Value: // -// false if the block can no longer be read. +// false if the block cannot be read. // static bool readTrackedBlock (LPVOID dest, LPCVOID block, SIZE_T size) { - __try { - memcpy(dest, block, size); - return true; - } - __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + SIZE_T read = 0; + return ReadProcessMemory(g_currentProcess, block, dest, size, &read) && read == size; +} + +// isLiveUnreadableBlock - Tells a block that cannot be read because the +// application protected its pages, which is still allocated, from one whose +// memory is gone. +static bool isLiveUnreadableBlock (LPCVOID block) +{ + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery(block, &mbi, sizeof(mbi)) != sizeof(mbi)) return false; - } + return mbi.State == MEM_COMMIT; } // hasCrtNoMansLand - Checks the no-man's land the debug CRT writes on both @@ -2088,8 +2121,8 @@ bool VisualLeakDetector::isDebugCrtAlloc( LPCVOID block, blockinfo_t* info ) } // A guessed block without a consistent header is a heap block that was - // allocated while a CRT allocation was in progress. A block that cannot - // be read is being freed, which getCrtBlockUse reports for CRT blocks. + // allocated while a CRT allocation was in progress. getCrtBlockUse tells + // a block that cannot be read apart. if (info->debugCrtAlloc && info->crtGuessed) { BYTE first; if (readTrackedBlock(&first, block, sizeof(first)) && !hasCrtHeader(block, info->size, info->ucrt)) @@ -2153,13 +2186,14 @@ SIZE_T VisualLeakDetector::getLeaksCount (heapinfo_t* heapinfo, DWORD threadId) int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt, bool guessed) { - // A block that can no longer be read is being freed. + // A block that cannot be read is being freed, unless the application made + // its pages inaccessible; then it is a leak like any other. int use; if (!ucrt) { crtdbgblockheader_t crtheader; if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) - return CRT_USE_FREE; + return isLiveUnreadableBlock(block) ? CRT_USE_NORMAL : CRT_USE_FREE; use = crtheader.use; if (guessed && (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL)) { if (!hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) @@ -2170,7 +2204,7 @@ int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt, bool guessed) { crtdbgblockheaderucrt_t crtheader; if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) - return CRT_USE_FREE; + return isLiveUnreadableBlock(block) ? CRT_USE_NORMAL : CRT_USE_FREE; use = crtheader.use; if (guessed && (CRT_USE_TYPE(use) == CRT_USE_FREE || CRT_USE_TYPE(use) == CRT_USE_INTERNAL)) { if (!hasCrtNoMansLand(block, crtheader.gap, sizeof(crtheader), crtheader.size)) @@ -2239,6 +2273,11 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S // we'll include in the report. address = CRTDBGBLOCKDATA(block); size = getCrtBlockSize(block, info->ucrt); + if (size == 0 && info->size > (SIZE_T)((LPCBYTE)address - (LPCBYTE)block) + GAPSIZE) { + // The header cannot be read; the heap block's size tells the + // data's. + size = info->size - ((LPCBYTE)address - (LPCBYTE)block) - GAPSIZE; + } } if (m_options & VLD_OPT_SKIP_CRTSTARTUP_LEAKS) { @@ -2248,15 +2287,18 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S } } - // A report hook may free the block, so read it before the first Report. - // A block that can no longer be read is being freed. + // A block that cannot be read is being freed, unless the application + // made its pages inaccessible. #ifdef _DEBUG SIZE_T crtRequest = 0; + bool crtHeaderRead = false; if (crtBlock) { crtdbgblockheader_t crtheader; - if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) + crtHeaderRead = readTrackedBlock(&crtheader, block, sizeof(crtheader)); + if (crtHeaderRead) + crtRequest = crtheader.request; + else if (!isLiveUnreadableBlock(block)) continue; - crtRequest = crtheader.request; } #endif SIZE_T dumpSize = (m_maxDataDump < size) ? m_maxDataDump : size; @@ -2278,8 +2320,10 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S SIZE_T blockLeaksCount = 1; Report(L"---------- Block %Iu at " ADDRESSFORMAT L": %Iu bytes ----------\n", info->serialNumber, address, size); #ifdef _DEBUG - if (crtBlock) + if (crtBlock && crtHeaderRead) Report(L" CRT Alloc ID: %Iu\n", crtRequest); + else if (crtBlock) + Report(L" CRT Alloc ID: (not readable)\n"); #endif assert(info->callStack); if (m_options & VLD_OPT_AGGREGATE_DUPLICATES) { @@ -2531,8 +2575,10 @@ static UINT_PTR exportOrdinal (HMODULE module, LPCSTR name) // static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPCSTR procname) { - bool entryIsOrdinal = HIWORD(patchentry->importName) == 0; - bool requestIsOrdinal = HIWORD(procname) == 0; + // GetProcAddress's own test: a name is any value above 0xFFFF. HIWORD looks + // at bits 16-31 only, which are zero for some 64-bit addresses too. + bool entryIsOrdinal = IS_INTRESOURCE(patchentry->importName); + bool requestIsOrdinal = IS_INTRESOURCE(procname); if (entryIsOrdinal && requestIsOrdinal) return (UINT_PTR)patchentry->importName == (UINT_PTR)procname; if (!entryIsOrdinal && !requestIsOrdinal) @@ -3156,7 +3202,8 @@ VOID VisualLeakDetector::collectLeakFrames (Set& frames, DWORD threadI // While a thread walks the heap and block maps under g_heapMapLock, code it // runs can free or reallocate tracked blocks or destroy heaps on the same -// thread: report hooks and dbghelp callbacks. Erasing map entries would break +// thread: an application's vectored exception handler sees the exceptions +// dbghelp raises and handles internally. Erasing map entries would break // the walk (Tree::erase moves the successor's contents) and deleting a block's // information would pull it from under the walk, so such changes are deferred // to the end of the outermost walk. Call with g_heapMapLock held. @@ -3232,7 +3279,8 @@ VOID VisualLeakDetector::endBlockWalk () // missing after that is shown as an address. g_leakQueryLock keeps a second // caller from holding g_heapMapLock while it waits for g_DbgHelp, which a // caching thread holds. A query from a thread that already owns -// g_heapMapLock (e.g. a report hook) caches nothing and takes no lock. +// g_heapMapLock (e.g. from a vectored exception handler) caches nothing and +// takes no lock. class LeakSymbolsHeapMapLock { public: @@ -3644,6 +3692,10 @@ void VisualLeakDetector::SetReportOptions(UINT32 option_mask, CONST WCHAR *filen return; } + // One setter at a time, so that the file installed last is the one + // m_reportFilePath names. No allocation hook takes this lock, so it can be + // held while files are opened and closed. + CriticalSectionLocker<> setter(m_reportOptionsLock); WCHAR path[MAX_PATH]; UINT32 options; { @@ -3735,6 +3787,7 @@ VOID VisualLeakDetector::setReportDestination(LPCWSTR path, UINT32 options) // to a file opened for binary writing. FILE* file = NULL; if (_wfopen_s(&file, path, isUnicode ? L"wb" : L"w") != 0 || file == NULL) { + SwapReportFile(NULL, ascii, TRUE, toStdout); Report(L"WARNING: Visual Leak Detector: Couldn't open report file for writing: %s\n" L" The report will be sent to the debugger instead.\n", path); return; @@ -3746,7 +3799,6 @@ VOID VisualLeakDetector::setReportDestination(LPCWSTR path, UINT32 options) WCHAR bom = BOM; fwrite(&bom, sizeof(WCHAR), 1, file); } - // Another thread may have set a file meanwhile. previous = SwapReportFile(file, isUnicode ? unicode : ascii, toDebugger, toStdout); if (previous != NULL) fclose(previous); @@ -3891,6 +3943,14 @@ CaptureContext::~CaptureContext() { if (!m_bFirst) return; + // The hooked function's last error must reach its caller; the module and + // stack lookups below can change it. + struct LastErrorKeeper { + DWORD error; + LastErrorKeeper() : error(GetLastError()) {} + ~LastErrorKeeper() { SetLastError(error); } + } keeper; + #if defined(_M_ARM64) // [ARM64 process-exit teardown hang fix] Mirror the allocation-hook guards // (see VisualLeakDetector::_HeapAlloc): when leak detection is disabled on diff --git a/src/vld.h b/src/vld.h index 3ac63a4a..8f56c597 100644 --- a/src/vld.h +++ b/src/vld.h @@ -302,9 +302,11 @@ __declspec(dllimport) VLD_BOOL VLDGetModulesList(wchar_t *modules, VLD_UINT size __declspec(dllimport) void VLDSetReportOptions(VLD_UINT option_mask, const wchar_t *filename); // VLDSetReportHook - Installs or uninstalls a client-defined reporting function by hooking it -// into the C run-time debug reporting process (debug version only). Hooks run on the -// reporting thread after VLD releases its internal locks, so a hook may allocate and -// call VLD. +// into the C run-time debug reporting process (debug version only). Hooks get leak reports +// on the reporting thread after VLD releases its internal locks, so a hook may allocate and +// call VLD then. Warnings VLD prints while it loads module symbols (for example about a +// module without symbols) still reach hooks with VLD's internal locks held; a hook must +// not call VLD for those. // // mode: The action to take: VLD_RPTHOOK_INSTALL or VLD_RPTHOOK_REMOVE. // @@ -312,7 +314,8 @@ __declspec(dllimport) void VLDSetReportOptions(VLD_UINT option_mask, const wchar // // Return Value: // -// int: 0 if success. +// int: 0 if success, -1 if VLD is off, the mode is not valid, or 64 hooks are already +// installed. // __declspec(dllimport) int VLDSetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook); diff --git a/src/vldint.h b/src/vldint.h index b6790588..dba08b62 100644 --- a/src/vldint.h +++ b/src/vldint.h @@ -460,6 +460,7 @@ class VisualLeakDetector : public IMalloc size_t m_moduleEventCount; size_t m_moduleEventCapacity; CriticalSection m_optionsLock; // Serializes access to the heap and block maps. + CriticalSection m_reportOptionsLock; // Serializes SetReportOptions. UINT32 m_options; // Configuration options. IgnoreFunctionsSet *m_ignoreFunctions; // Contains information about all the functions that needs to be ignored.