#include "logging.h" #include #include #include #include namespace { HANDLE g_log = INVALID_HANDLE_VALUE; CRITICAL_SECTION g_cs; bool g_cs_inited = false; void ensure_cs() { if (!g_cs_inited) { InitializeCriticalSection(&g_cs); g_cs_inited = true; } } void write_line(const char* s, size_t len) { if (g_log == INVALID_HANDLE_VALUE) return; DWORD written = 0; WriteFile(g_log, s, (DWORD)len, &written, nullptr); } } namespace leakfix { void log_init(const char* path) { ensure_cs(); EnterCriticalSection(&g_cs); if (g_log != INVALID_HANDLE_VALUE) { LeaveCriticalSection(&g_cs); return; } g_log = CreateFileA(path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); SetFilePointer(g_log, 0, nullptr, FILE_END); LeaveCriticalSection(&g_cs); logf("===== leakfix.dll loaded (pid=%lu) =====", GetCurrentProcessId()); } void log_close() { ensure_cs(); EnterCriticalSection(&g_cs); if (g_log != INVALID_HANDLE_VALUE) { CloseHandle(g_log); g_log = INVALID_HANDLE_VALUE; } LeaveCriticalSection(&g_cs); } void logf(const char* fmt, ...) { ensure_cs(); char buf[1024]; SYSTEMTIME st; GetLocalTime(&st); int n = std::snprintf(buf, sizeof(buf), "[%04d-%02d-%02d %02d:%02d:%02d.%03d] ", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond, st.wMilliseconds); va_list ap; va_start(ap, fmt); int m = std::vsnprintf(buf + n, sizeof(buf) - n - 2, fmt, ap); va_end(ap); if (m < 0) m = 0; int total = n + m; if (total >= (int)sizeof(buf) - 1) total = sizeof(buf) - 2; buf[total] = '\n'; buf[total + 1] = '\0'; EnterCriticalSection(&g_cs); write_line(buf, (size_t)total + 1); LeaveCriticalSection(&g_cs); // Also forward to debugger if attached OutputDebugStringA(buf); } } // namespace leakfix