diff --git a/build/templates/build-arch.yml b/build/templates/build-arch.yml index aff8535f..b203e0cc 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 }})' @@ -118,9 +128,21 @@ 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: 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 39ff1bbe..15577a81 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; @@ -50,6 +50,150 @@ extern DbgHelp g_DbgHelp; extern "C" bool VldArm64InTeardownReport(void); #endif +// 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; +// 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) +{ + size_t length = wcslen(source) + 1; + WCHAR* copy = new WCHAR[length]; + if (copy != NULL) + wcscpy_s(copy, length, source); + return copy; +} + +static bool usesSymbolCacheOnly() +{ + 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; + ULONG generation; + { + CriticalSectionLocker<> cs(g_symbolCacheLock); + if (g_symbolCache != NULL && g_symbolCache->find(programCounter) != g_symbolCache->end()) + continue; + 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); + { + 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 (symbol->functionName != NULL && generation == g_symbolCacheGeneration) { + if (g_symbolCache == NULL) + g_symbolCache = new SymbolCache; + if (g_symbolCache != NULL && 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; + g_symbolCacheGeneration++; + } + 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 // template @@ -82,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. @@ -98,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; @@ -206,12 +362,80 @@ 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 and sets cacheMiss. +LPCWSTR CallStack::getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + SYMBOL_INFO* functionInfo, bool& cacheMiss) +{ + 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); + } + 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; +} + +// 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, 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, bool& cacheMiss) +{ + { + 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()) { + cacheMiss = true; + 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); @@ -306,7 +530,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; } @@ -332,11 +560,11 @@ 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); + // 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++) { @@ -352,13 +580,13 @@ bool CallStack::isLeakSuppressed() } DWORD64 displacement64; - LPCWSTR functionName = getFunctionName(programCounter, displacement64, (SYMBOL_INFO*)&symbolBuffer, locker); + 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)) { @@ -366,7 +594,8 @@ bool CallStack::isLeakSuppressed() } } - m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; + if (!cacheMiss) + m_status |= CALLSTACK_STATUS_NOTSTARTUPCRT; return false; } @@ -386,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) { @@ -417,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) { @@ -439,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; - CriticalSectionLocker locker(g_DbgHelp); - 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 @@ -465,31 +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, locker); + 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; } } - // 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 - foundline = g_DbgHelp.SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo, locker); + BOOL foundline = getLine(programCounter, displacement, &sourceInfo, fileName, fileNameLength, cacheMiss); bool isFrameInternal = false; if (foundline && !showInternalFrames) { @@ -501,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; } @@ -531,6 +782,24 @@ const WCHAR* CallStack::getResolvedCallstack( BOOL showinternalframes ) return m_resolved; } +bool CallStack::needsSymbols() const +{ + 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 // always appended to the back of the chunk list (aka the "top" chunk). // @@ -762,12 +1031,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 @@ -786,8 +1060,44 @@ 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; + +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 +// 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 () +{ + // 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) { + 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' @@ -824,6 +1134,15 @@ 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()) { + InterlockedIncrement(&g_safeStackWalkFallbacks); + captureBackTrace(maxdepth, context); + return; + } + CriticalSectionLocker locker(g_DbgHelp, CriticalSectionLocker::Adopt()); + count++; push_back(CONTEXT_IPREG(context)); @@ -848,9 +1167,6 @@ VOID SafeCallStack::getStackTrace (UINT32 maxdepth, const context_t& context) frame.AddrFrame.Mode = AddrModeFlat; frame.Virtual = TRUE; - CriticalSectionLocker<> cs(g_heapMapLock); - CriticalSectionLocker locker(g_DbgHelp); - // Walk the stack. while (count < maxdepth) { count++; diff --git a/src/callstack.h b/src/callstack.h index 80c58894..0cbce269 100644 --- a/src/callstack.h +++ b/src/callstack.h @@ -32,10 +32,15 @@ #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) +// Number of safe stack walks that fell back to RtlCaptureStackBackTrace. +extern volatile LONG g_safeStackWalkFallbacks; + //////////////////////////////////////////////////////////////////////////////// // // The CallStack Class @@ -90,20 +95,38 @@ 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(); + // 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 + // 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. #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 { @@ -124,11 +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; - LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, - SYMBOL_INFO* functionInfo, CriticalSectionLocker& locker) const; + static LPCWSTR getFunctionName(SIZE_T programCounter, DWORD64& displacement64, + 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, 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/criticalsection.h b/src/criticalsection.h index 983145ba..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); } @@ -37,6 +42,18 @@ class CriticalSection return m_ownerThreadId == GetCurrentThreadId(); } + // Unlike IsLockedByCurrentThread, stays true after a nested Leave. + bool IsOwnedByCurrentThread() + { + 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() { @@ -71,6 +88,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/tests/CMakeLists.txt b/src/tests/CMakeLists.txt index 55624ce2..d5d700e0 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) # ============================================================================ @@ -846,3 +887,146 @@ 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 + chaos_report_hook_race + chaos_long_frame + chaos_hook_reenter + chaos_thread_churn + chaos_crt_matrix + chaos_heap_churn + chaos_api_storm + chaos_aggregate_threads + chaos_hook_heap_ops + chaos_heap_flags + chaos_exit_pressure + chaos_report_options + chaos_realloc_reuse + chaos_fake_crt_header + chaos_crt_odd_apis + chaos_unload_report + chaos_alloc_throw + chaos_fibers + chaos_option_extremes + chaos_many_leaks + chaos_proc_ordinal + chaos_noaccess_leak + chaos_aligned_new + chaos_heaplock + chaos_heaplock_report + chaos_cotaskmem + chaos_crt_alloc_hook + chaos_new_handler + chaos_malloc_spy +) + +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() + +# 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) + +# ============================================================================ +# 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_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/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; +} 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; +} diff --git a/src/tests/chaos/chaos_api_storm.cpp b/src/tests/chaos/chaos_api_storm.cpp new file mode 100644 index 00000000..0bf3f955 --- /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, &g_stop, RUN_MS + 2000); + + 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/tests/chaos/chaos_common.h b/src/tests/chaos/chaos_common.h new file mode 100644 index 00000000..64662721 --- /dev/null +++ b/src/tests/chaos/chaos_common.h @@ -0,0 +1,283 @@ +// 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 +#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. Uses +// no CRT, whose locks the hung or crashed threads may hold. +inline void Fail(const char* message, UINT exitCode = 1) +{ + Write("FAIL: "); + Write(message); + Write(" (phase: "); + Write(Phase()); + Write(")\n"); + 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; +} + +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) + { + 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; } +}; + +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, bool together = true) +{ + HANDLE threads[64]; + RunThreadsArg args[64]; + Check(count <= 64, "too many threads"); + RunThreadsStart start = { routine, 0, CreateEventW(NULL, TRUE, !together, NULL) }; + Check(start.go != NULL, "CreateEvent failed"); + for (int i = 0; i < count; i++) + { + 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() +{ + StopWatchdog(); + Write("CHAOS PASS\n"); +} +} 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; +} 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..a4c8fc89 --- /dev/null +++ b/src/tests/chaos/chaos_crt_alloc_hook.cpp @@ -0,0 +1,161 @@ +// 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_ledger.h" +#include + +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; +__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) + return TRUE; + t_inHook = 1; + LONG call = InterlockedIncrement(&g_calls); + void* inner = malloc(24); + if (inner != NULL) + { + if (call % 11 == 0) + Leak(inner, 1); + 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; + + // 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) + Leak(grown, 2); + 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) + { + void* zeroed = HeapAlloc(heap, HEAP_ZERO_MEMORY, 64); + if (zeroed != NULL) + Leak(zeroed, 3); + } + break; + } + 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++) + { + if (t_tracked == NULL) + t_tracked = HeapAlloc(GetProcessHeap(), 0, 128); + 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) + Leak(block, 5); + else + free(block); + } + if (t_moving != NULL) + Leak(t_moving, 4); + if (t_tracked != NULL) + HeapFree(GetProcessHeap(), 0, t_tracked); + 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]; + 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_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_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; +} 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; +} 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..54fd6250 --- /dev/null +++ b/src/tests/chaos/chaos_fake_crt_header.cpp @@ -0,0 +1,84 @@ +// 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("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++) + { + free(blocks[i]); + } + chaos::Pass(); + return 0; +} 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; +} diff --git a/src/tests/chaos/chaos_heap_churn.cpp b/src/tests/chaos/chaos_heap_churn.cpp new file mode 100644 index 00000000..7616331e --- /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, &g_stop, RUN_MS + 2000); + + 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; +} diff --git a/src/tests/chaos/chaos_heap_flags.cpp b/src/tests/chaos/chaos_heap_flags.cpp new file mode 100644 index 00000000..8b75b4e0 --- /dev/null +++ b/src/tests/chaos/chaos_heap_flags.cpp @@ -0,0 +1,178 @@ +// 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; +// 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 = g_heap; + 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 = g_heap; + 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; + ULONGLONG deadline = GetTickCount64() + 100; + while (HeapWalk(heap, &entry) && entries < 100000) + { + entries++; + if (GetTickCount64() > deadline || InterlockedCompareExchange(&g_stop, 0, 0)) + { + break; + } + } + 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 == 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; + 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"); + g_heap = HeapCreate(0, 0, 32 * 1024 * 1024); + chaos::Check(g_heap != NULL, "HeapCreate of a fixed-size heap failed"); + 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(); + return 0; +} 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_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; +} diff --git a/src/tests/chaos/chaos_heaplock_report.cpp b/src/tests/chaos/chaos_heaplock_report.cpp new file mode 100644 index 00000000..1a97ecf7 --- /dev/null +++ b/src/tests/chaos/chaos_heaplock_report.cpp @@ -0,0 +1,123 @@ +// 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; +const DWORD PROGRESS_MS = 15000; +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; +} + +// 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); + 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); + 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++) + { + 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", NULL); + + VLDSetReportHook(VLD_RPTHOOK_INSTALL, AllocatingHook); + 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"); + 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; +} diff --git a/src/tests/chaos/chaos_helper_dll.cpp b/src/tests/chaos/chaos_helper_dll.cpp new file mode 100644 index 00000000..effff9f4 --- /dev/null +++ b/src/tests/chaos/chaos_helper_dll.cpp @@ -0,0 +1,107 @@ +// 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 volatile LONG g_threadChurnLive = 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); +} + +// 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) + { + 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) + { + 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) + { + void* block = TlsGetValue(g_tlsIndex); + if (block != NULL) + { + free(block); + InterlockedDecrement(&g_threadChurnLive); + } + TlsSetValue(g_tlsIndex, NULL); + } + break; + } + return TRUE; +} 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..45dbf239 --- /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 reports. +// +// 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. +// 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/tests/chaos/chaos_hook_reenter.cpp b/src/tests/chaos/chaos_hook_reenter.cpp new file mode 100644 index 00000000..81accfc4 --- /dev/null +++ b/src/tests/chaos/chaos_hook_reenter.cpp @@ -0,0 +1,70 @@ +// chaos_hook_reenter.cpp - a report hook that allocates, frees and queries VLD +// while VLD reports. +// +// 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 +#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/tests/chaos/chaos_ledger.h b/src/tests/chaos/chaos_ledger.h new file mode 100644 index 00000000..2144025f --- /dev/null +++ b/src/tests/chaos/chaos_ledger.h @@ -0,0 +1,222 @@ +// 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 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 "); + if (at != NULL) + { + at = wcsstr(at, L" at 0x"); + if (at != NULL) + { + 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; +} + +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 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); + 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); + 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++) + { + // 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]) + 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; + for (LONG i = 0; i < recorded; i++) + { + const LedgerEntry& entry = Ledger()[i]; + if (matched[i]) + 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); + if (missing <= 8) + DescribeTrackedBlock(entry.block); + } + 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; +} +} 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 diff --git a/src/tests/chaos/chaos_malloc_spy.cpp b/src/tests/chaos/chaos_malloc_spy.cpp new file mode 100644 index 00000000..4a586759 --- /dev/null +++ b/src/tests/chaos/chaos_malloc_spy.cpp @@ -0,0 +1,191 @@ +// 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; +__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) +{ + 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); + // 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) + { + if (actual == NULL) + return NULL; + if (t_reallocAddsHeader) + memmove((BYTE*)actual + HEADER, actual, t_reallocSize); + 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"); + 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); + // 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(); + + 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; +} 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; +} diff --git a/src/tests/chaos/chaos_new_handler.cpp b/src/tests/chaos/chaos_new_handler.cpp new file mode 100644 index 00000000..b8096d17 --- /dev/null +++ b/src/tests/chaos/chaos_new_handler.cpp @@ -0,0 +1,161 @@ +// 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; +__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 +volatile size_t g_hugeSize = (size_t)1 << 50; +#else +volatile size_t g_hugeSize = 0xFFF00000; +#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) +{ + // 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) + { + 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); + } + t_inHandler = false; + if (++t_retries >= 2) + return 0; + return 1; +} + +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 + // and malloc in new mode 1 each loop over it. + t_retries = 0; + switch (random.Below(4)) + { + case 0: + try + { + char* never = new char[g_hugeSize]; + chaos::Fail("a huge operator new succeeded"); + delete[] never; + } + catch (const std::bad_alloc&) + { + InterlockedIncrement(&g_thrown); + } + break; + case 1: + chaos::Check(malloc(g_hugeSize) == 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; +} 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/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; +} 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/tests/chaos/chaos_realloc_reuse.cpp b/src/tests/chaos/chaos_realloc_reuse.cpp new file mode 100644 index 00000000..db7af949 --- /dev/null +++ b/src/tests/chaos/chaos_realloc_reuse.cpp @@ -0,0 +1,166 @@ +// 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 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" +#include +#include + +#pragma comment(lib, "ole32.lib") + +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]; + +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); + unsigned mode = random.Below(3); + bool untracked = mode == 0; + bool disabledMove = mode == 1; + if (untracked) + VLDDisable(); + void* block = Allocate(api); + if (untracked) + VLDRestore(); + else if (disabledMove) + VLDDisable(); + void* moved = Reallocate(api, block, 4096 + random.Below(4096)); + if (disabledMove) + VLDRestore(); + Free(api, moved != NULL ? moved : block); + } + return 0; +} + +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); + } + 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/tests/chaos/chaos_report_hook_race.cpp b/src/tests/chaos/chaos_report_hook_race.cpp new file mode 100644 index 00000000..01cf503c --- /dev/null +++ b/src/tests/chaos/chaos_report_hook_race.cpp @@ -0,0 +1,103 @@ +// chaos_report_hook_race.cpp - report hooks installed and removed while other +// threads print leak reports. +// +// 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. + +#include "chaos_common.h" +#include "vld.h" + +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*) +{ + 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_permanentLines); + } + 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, &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]); + } + chaos::Check(VLDSetReportHook(VLD_RPTHOOK_REMOVE, PermanentHook) == 0, "remove failed"); + chaos::Pass(); + return 0; +} diff --git a/src/tests/chaos/chaos_report_options.cpp b/src/tests/chaos/chaos_report_options.cpp new file mode 100644 index 00000000..e9655201 --- /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, &g_stop, RUN_MS + 2000); + + 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/tests/chaos/chaos_thread_churn.cpp b/src/tests/chaos/chaos_thread_churn.cpp new file mode 100644 index 00000000..807db369 --- /dev/null +++ b/src/tests/chaos/chaos_thread_churn.cpp @@ -0,0 +1,136 @@ +// 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, &g_stop, RUN_MS + 2000); + 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); + } + // Their attach blocks stay allocated past the exit report. + VLDMarkAllLeaksAsReported(); + chaos::Pass(); + return 0; +} diff --git a/src/tests/chaos/chaos_unload_report.cpp b/src/tests/chaos/chaos_unload_report.cpp new file mode 100644 index 00000000..10ae53b4 --- /dev/null +++ b/src/tests/chaos/chaos_unload_report.cpp @@ -0,0 +1,158 @@ +// 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_ledger.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); +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*) +{ + 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"); + // 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++) + { + LONG index = InterlockedIncrement(&g_leaked); + if (index > MAX_LEAKS) + { + InterlockedDecrement(&g_leaked); + break; + } + void* block = helperMalloc(16 + random.Below(200)); + chaos::Check(block != NULL, "HelperMalloc failed"); + chaos::RecordLeak(block, tag); + } + 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) + { + 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); + } + 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; +} 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/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) { 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 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..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,11 +3,12 @@ // // 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 @@ -37,66 +38,62 @@ 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. -TEST_F(TestGetAddrInfoMissingFree, MissingFreeAddrInfoProducesMoreLeaks) +// 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. +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, MissingFreeAddrInfoIsTrackedAsLeak) +{ + 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. - int leaks_with_free; + // 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); - leaks_with_free = static_cast(VLDGetLeaksCount()); + VLDMarkAllLeaksAsReported(); } - 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(VLDGetLeaksCount()); - } - - 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(); } 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..933cdbd5 --- /dev/null +++ b/src/tests/heapmaplock_deadlock_test/heapmaplock_deadlock_test.cpp @@ -0,0 +1,172 @@ +// 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, 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 +#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; +HANDLE g_thread = NULL; + +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) + { + 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 in VLDGetLeaksCount while dbghelp loaded symbols\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. + // 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); + g_thread = CreateThread(NULL, 0, NewThread, NULL, 0, NULL); + if (g_thread == NULL) + { + 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); + HMODULE version = LoadLibraryW(L"version.dll"); + InterlockedExchange(&g_inLoadLibrary, 0); + if (version != NULL) + FreeLibrary(version); + 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(); + if (g_thread != NULL) + { + WaitForSingleObject(g_thread, INFINITE); + CloseHandle(g_thread); + } + 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 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 5680ac92..8536f0d4 100644 --- a/src/utility.cpp +++ b/src/utility.cpp @@ -33,6 +33,8 @@ // 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) @@ -42,12 +44,23 @@ 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. #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 @@ -129,8 +142,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; @@ -198,12 +210,12 @@ 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. - 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'.'; } @@ -1017,7 +1029,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; } @@ -1193,11 +1205,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; } @@ -1216,19 +1244,18 @@ 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)) { 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); @@ -1245,10 +1272,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); @@ -1265,6 +1294,101 @@ 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; + size_t dropped; // Messages lost because the queue could not grow. +}; +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; + 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; + 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. 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; + 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; +} + +// 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. // @@ -1280,13 +1404,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'; @@ -1456,50 +1592,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..d69af370 100644 --- a/src/utility.h +++ b/src/utility.h @@ -32,12 +32,13 @@ 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 +#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. @@ -172,6 +173,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 (); @@ -180,6 +182,42 @@ 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 = 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; +}; #ifndef NDEBUG #define DbgPrint(x) Print(x) #define DbgReport(...) Report(__VA_ARGS__) @@ -191,8 +229,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 2324e717..3e8288d3 100644 --- a/src/vld.cpp +++ b/src/vld.cpp @@ -51,7 +51,10 @@ 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. ReportHookSet* g_pReportHooks; DbgHelp g_DbgHelp; ImageDirectoryEntries g_Ide; @@ -326,9 +329,9 @@ 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; HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); if (ntdll) @@ -422,6 +425,9 @@ VisualLeakDetector::VisualLeakDetector () LoaderLock ll; g_heapMapLock.Initialize(); + g_leakQueryLock.Initialize(); + g_symbolCacheLock.Initialize(); + g_reportHooksLock.Initialize(); g_vldHeap = HeapCreate(0x0, 0, 0); g_vldHeapLock.Initialize(); g_pReportHooks = new ReportHookSet; @@ -429,13 +435,24 @@ 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; 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_reportOptionsLock.Initialize(); m_modulesLock.Initialize(); m_selfTestFile = __FILE__; m_selfTestLine = 0; @@ -461,7 +478,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 @@ -502,9 +519,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)) { @@ -758,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) @@ -783,7 +807,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) { @@ -792,8 +816,12 @@ VisualLeakDetector::~VisualLeakDetector () delete blockmap; } delete m_heapMap; + delete m_deferredBlocks; + delete m_deferredCallStacks; + delete m_deferredHeaps; } delete m_loadedModules; + delete [] m_moduleEvents; delete m_ignoreFunctions; { @@ -810,32 +838,47 @@ 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; + CallStack::clearSymbolCache(); checkInternalMemoryLeaks(); } 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; } + CallStack::clearSymbolCache(); HeapDestroy(g_vldHeap); m_optionsLock.Delete(); + m_reportOptionsLock.Delete(); m_modulesLock.Delete(); m_tlsLock.Delete(); g_heapMapLock.Delete(); + g_leakQueryLock.Delete(); + g_symbolCacheLock.Delete(); + g_reportHooksLock.Delete(); g_vldHeapLock.Delete(); if (m_tlsIndex != TLS_OUT_OF_INDEXES) { 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. @@ -1141,6 +1184,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; } @@ -1400,11 +1479,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; @@ -1414,7 +1496,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) { @@ -1424,7 +1506,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()) @@ -1441,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: // @@ -1449,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); @@ -1474,9 +1561,11 @@ tls_t* VisualLeakDetector::getTls () tls->oldFlags = 0x0; tls->threadId = threadId; tls->blockWithoutGuard = NULL; + tls->blockSerial = 0; TlsSetValue(m_tlsIndex, tls); } + SetLastError(lastError); return tls; } @@ -1507,10 +1596,14 @@ 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; blockinfo->debugCrtAlloc = debugcrtalloc; + blockinfo->crtGuessed = false; blockinfo->ucrt = ucrt; if (SIZE_MAX - m_totalAlloc > size) @@ -1524,8 +1617,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()); @@ -1541,6 +1635,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 = { (*heapit).second, mem, info }; + m_deferredBlocks->insert(deferred); + const_cast&>(*blockit).second = blockinfo; + return; + } delete info; blockmap->erase(blockit); blockmap->insert(mem, blockinfo); @@ -1559,7 +1662,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; @@ -1568,11 +1671,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); } @@ -1594,8 +1707,23 @@ 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); 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 != 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. - 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 @@ -1622,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 @@ -1648,6 +1789,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 = { (*heapit).second, mem, info }; + m_deferredBlocks->insert(deferred); + return; + } delete info; blockmap->erase(blockit); } @@ -1665,7 +1813,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 @@ -1676,6 +1824,10 @@ 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()) { + deferUnmapHeap(heap, heapinfo); + return; + } for (BlockMap::Iterator blockit = blockmap->begin(); blockit != blockmap->end(); ++blockit) { m_curAlloc -= (*blockit).second->size; delete (*blockit).second; @@ -1714,12 +1866,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; } @@ -1751,7 +1903,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) @@ -1775,6 +1930,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. // @@ -1836,17 +2027,80 @@ 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, 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 cannot be read. +// +static bool readTrackedBlock (LPVOID dest, LPCVOID block, SIZE_T size) +{ + 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 +// 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) +{ + 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; +} + +// 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 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->crtGuessed = true; info->ucrt = false; } } @@ -1854,17 +2108,26 @@ 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->crtGuessed = true; info->ucrt = true; } } } + // A guessed block without a consistent header is a heap block that was + // 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)) + return false; + } return info->debugCrtAlloc; } @@ -1897,7 +2160,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 || @@ -1921,66 +2184,47 @@ 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) +int VisualLeakDetector::getCrtBlockUse(LPCVOID block, bool ucrt, bool guessed) { + // 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 = (crtdbgblockheader_t*)block; - return crtheader->use; + crtdbgblockheader_t crtheader; + if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) + 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)) + use = CRT_USE_NORMAL; + } } else { - crtdbgblockheaderucrt_t* crtheader = (crtdbgblockheaderucrt_t*)block; - return crtheader->use; + crtdbgblockheaderucrt_t crtheader; + if (!readTrackedBlock(&crtheader, block, sizeof(crtheader))) + 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)) + use = CRT_USE_NORMAL; + } } + return use; } 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; } } @@ -2007,11 +2251,12 @@ 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 ); + 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 || @@ -2028,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) { @@ -2037,6 +2287,31 @@ SIZE_T VisualLeakDetector::reportLeaks (heapinfo_t* heapinfo, bool &firstLeak, S } } + // 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; + crtHeaderRead = readTrackedBlock(&crtheader, block, sizeof(crtheader)); + if (crtHeaderRead) + crtRequest = crtheader.request; + else if (!isLiveUnreadableBlock(block)) + continue; + } +#endif + SIZE_T dumpSize = (m_maxDataDump < size) ? m_maxDataDump : size; + LPBYTE dumpData = NULL; + if (dumpSize != 0) { + dumpData = new BYTE[dumpSize]; + if (!readTrackedBlock(dumpData, address, dumpSize)) { + // A live block can have pages the application made inaccessible. + delete [] dumpData; + dumpData = NULL; + } + } + // 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"); @@ -2045,18 +2320,16 @@ 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) - { - crtdbgblockheader_t* crtheader = (crtdbgblockheader_t*)block; - Report(L" CRT Alloc ID: %Iu\n", crtheader->request); - assert(size == getCrtBlockSize(block, info->ucrt)); - } + 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) { // 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 @@ -2078,15 +2351,19 @@ 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(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"); } @@ -2121,7 +2398,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) @@ -2267,6 +2544,67 @@ 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 the name is exported with that ordinal. +// +static bool matchesProcName (HMODULE module, const patchentry_t* patchentry, LPCSTR procname) +{ + // 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) + return strcmp(patchentry->importName, procname) == 0; + if (requestIsOrdinal) + return exportOrdinal(module, patchentry->importName) == (UINT_PTR)procname; + 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 @@ -2304,20 +2642,9 @@ 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)) { + saveOriginal(patchentry, original); + return (FARPROC)patchentry->replacement; } patchentry++; } @@ -2372,20 +2699,9 @@ 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)) { + saveOriginal(patchentry, original); + return (FARPROC)patchentry->replacement; } patchentry++; } @@ -2462,6 +2778,19 @@ 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. + 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. @@ -2472,15 +2801,84 @@ 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; + // 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; } +// 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) @@ -2635,6 +3033,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 @@ -2669,6 +3068,11 @@ 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. + CallStack::clearSymbolCache(); } // Find the information for the module that initiated this reallocation. @@ -2753,6 +3157,177 @@ bool VisualLeakDetector::isFunctionIgnored(LPCWSTR functionName) return g_vld.m_ignoreFunctions->find(functioninfo) != g_vld.m_ignoreFunctions->end(); } +// Leak counting and reporting resolve call stacks while holding g_heapMapLock, +// 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. +// +// - heap (IN): Only leaks in this heap, or in all heaps if NULL. +// +// Return Value: +// +// None. +// +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) + continue; + 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 || !info->callStack->needsSymbols()) + continue; + if (threadId != ((DWORD)-1) && info->threadId != threadId) + continue; + for (UINT32 frame = 0; frame < info->callStack->size(); frame++) + frames.insert((*info->callStack)[frame]); + } + } +} + +// 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: 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. +VOID VisualLeakDetector::beginBlockWalk () +{ + if (m_blockWalkDepth++ == 0) + m_blockWalkThreadId = GetCurrentThreadId(); +} + +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) + 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); + 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()) { + 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(); + deferredheap_t deferred = *it; + m_deferredHeaps->erase(it); + 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; + } +} + +// 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. from a vectored exception handler) caches nothing and +// takes no lock. +class LeakSymbolsHeapMapLock +{ +public: + LeakSymbolsHeapMapLock(VisualLeakDetector& vld, bool loadSymbols, DWORD threadId = (DWORD)-1, HANDLE heap = NULL) + : m_vld(vld), m_nested(g_heapMapLock.IsOwnedByCurrentThread()) + { + if (!m_nested) { +#if defined(_M_ARM64) + // 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 frames; + vld.collectLeakFrames(frames, threadId, heap); + if (attempt == maxAttempts || CallStack::areSymbolsCached(frames)) + break; + g_heapMapLock.Leave(); + CallStack::cacheSymbols(frames); + } + } + m_vld.beginBlockWalk(); + } + + ~LeakSymbolsHeapMapLock() + { + m_vld.endBlockWalk(); + if (!m_nested) { + deferredreport_t* report = g_heapMapLock.LeaveTakingReport(); + g_leakQueryLock.Leave(); + if (report != NULL) + PrintDeferredReport(report); + } + } + +private: + VisualLeakDetector& m_vld; + const bool m_nested; + LeakSymbolsHeapMapLock(const LeakSymbolsHeapMapLock&); + LeakSymbolsHeapMapLock& operator=(const LeakSymbolsHeapMapLock&); +}; + SIZE_T VisualLeakDetector::GetLeaksCount() { if (m_options & VLD_OPT_VLDOFF) { @@ -2762,7 +3337,7 @@ SIZE_T VisualLeakDetector::GetLeaksCount() 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); @@ -2781,7 +3356,7 @@ SIZE_T VisualLeakDetector::GetThreadLeaksCount(DWORD 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); @@ -2800,7 +3375,7 @@ SIZE_T VisualLeakDetector::ReportLeaks( ) // 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) { @@ -2821,7 +3396,7 @@ SIZE_T VisualLeakDetector::ReportThreadLeaks( DWORD 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) { @@ -2833,6 +3408,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) { @@ -2841,7 +3451,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); @@ -2858,7 +3468,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); @@ -3042,7 +3652,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; @@ -3082,34 +3692,38 @@ 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 )) + // 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; { - 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_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; } - 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; - } + setReportDestination((options & VLD_OPT_REPORT_TO_FILE) ? path : NULL, options); } int VisualLeakDetector::SetReportHook(int mode, VLD_REPORT_HOOK pfnNewHook) @@ -3118,9 +3732,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; } @@ -3132,50 +3757,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. - - //Close the previous report file if needed. - if (m_reportFile) { - fclose(m_reportFile); - m_reportFile = NULL; - } + 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 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) { + 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", 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); } + 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 @@ -3209,18 +3836,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; @@ -3252,14 +3875,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, 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(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. @@ -3282,14 +3903,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; @@ -3324,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 @@ -3338,18 +3965,35 @@ 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; } #endif BOOL excluded = IsExcludedModule(); + 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. 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(); 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, @@ -3368,21 +4012,48 @@ 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); + 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 + // 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) { +void CaptureContext::Set(HANDLE heap, LPVOID mem, LPVOID newmem, SIZE_T size, SIZE_T serial) { + if (m_tls->blockWithoutGuard != NULL && mem != NULL && + (m_tls->heap != heap || m_tls->blockWithoutGuard != mem || m_tls->newBlockWithoutGuard != newmem)) { + 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; + 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 + // 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; 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 @@ -3432,7 +4103,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/vld.h b/src/vld.h index 8912c34c..8f56c597 100644 --- a/src/vld.h +++ b/src/vld.h @@ -302,7 +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). +// 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. // @@ -310,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/vld_hooks.cpp b/src/vld_hooks.cpp index a2992d03..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); @@ -288,14 +288,24 @@ 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) || !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.unmapMovedBlock(heap, mem, serial, context_); + } + return newmem; + } 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; @@ -307,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; { @@ -320,13 +331,22 @@ 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.unmapMovedBlock(heap, mem, serial, context_); + } + return newmem; + } 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 f916bf48..dba08b62 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. @@ -127,10 +128,28 @@ 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. 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; } + 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 std::basic_string, vldallocator > vldstring; // This structure stores information, primarily the virtual address range, about @@ -160,12 +179,21 @@ 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 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; @@ -186,12 +214,14 @@ 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; 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: @@ -207,7 +237,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(); @@ -215,8 +245,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, bool nested); void Reset(); private: tls_t *m_tls; @@ -319,29 +351,40 @@ 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 (); 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); 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: 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); + 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 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); 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; int resolveStacks(heapinfo_t* heapinfo); // Static functions (callbacks) @@ -354,7 +397,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(); @@ -393,6 +436,12 @@ 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. + 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. @@ -403,7 +452,15 @@ 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. + CriticalSection m_reportOptionsLock; // Serializes SetReportOptions. UINT32 m_options; // Configuration options. IgnoreFunctionsSet *m_ignoreFunctions; // Contains information about all the functions that needs to be ignored. @@ -412,7 +469,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.