Prevent OOM

This commit is contained in:
2026-06-18 05:55:31 +10:00
parent ebba70b9d9
commit b3436a61ee
44 changed files with 1797 additions and 66 deletions
+173 -8
View File
@@ -1312,7 +1312,7 @@ namespace ANSCENTER
return result;
}
// ====================================================================
// GetANSLoggerErrorEvents
// GetANSLoggerErrorEvents / GetANSLoggerErrorEventsSinceLastCall
//
// Reads every Error-level event written by the "ANSLogger" source in
// the Application channel using the modern winevt API. Events are
@@ -1322,14 +1322,98 @@ namespace ANSCENTER
//
// DebugView: filter "[EVTLOG]".
// ====================================================================
std::string ANSUtilities::GetANSLoggerErrorEvents(bool clearAfterRead) {
// XPath: Provider name "ANSLogger" AND Level 2 (EVENTLOG_ERROR_TYPE).
// Forward direction keeps chronological insertion order so output
// matches a fresh "oldest first" scroll through Event Viewer.
constexpr const wchar_t* kQuery =
L"*[System[Provider[@Name='ANSLogger'] and Level=2]]";
EVT_HANDLE hResults = EvtQuery(nullptr, L"Application", kQuery,
// ---- Watermark helpers (HKCU, no admin needed) ----------------------
static constexpr const wchar_t* kWatermarkRegKey =
L"Software\\ANSCENTER\\ANSUtilities\\EventLogWatermark";
static constexpr const wchar_t* kWatermarkValueName = L"ANSLogger";
static uint64_t ReadAnsLoggerWatermark() {
HKEY hKey = nullptr;
if (RegOpenKeyExW(HKEY_CURRENT_USER, kWatermarkRegKey, 0,
KEY_READ, &hKey) != ERROR_SUCCESS) {
return 0;
}
uint64_t value = 0;
DWORD size = sizeof(value), type = 0;
LONG rc = RegQueryValueExW(hKey, kWatermarkValueName, nullptr,
&type, reinterpret_cast<LPBYTE>(&value),
&size);
RegCloseKey(hKey);
return (rc == ERROR_SUCCESS && type == REG_QWORD) ? value : 0;
}
static void WriteAnsLoggerWatermark(uint64_t value) {
HKEY hKey = nullptr;
if (RegCreateKeyExW(HKEY_CURRENT_USER, kWatermarkRegKey, 0,
nullptr, REG_OPTION_NON_VOLATILE, KEY_WRITE,
nullptr, &hKey, nullptr) != ERROR_SUCCESS) {
ANS_DBG("EVTLOG", "watermark RegCreateKey failed err=%lu",
GetLastError());
return;
}
LONG rc = RegSetValueExW(hKey, kWatermarkValueName, 0, REG_QWORD,
reinterpret_cast<const BYTE*>(&value),
sizeof(value));
if (rc != ERROR_SUCCESS) {
ANS_DBG("EVTLOG", "watermark RegSetValue failed err=%ld", rc);
}
RegCloseKey(hKey);
}
// Extracts <EventRecordID>NNN</EventRecordID> from a rendered event XML.
// Returns 0 if not present (shouldn't happen — every Windows event has one).
static uint64_t ExtractRecordIdFromXml(const std::wstring& xml) {
auto open = xml.find(L"<EventRecordID>");
if (open == std::wstring::npos) return 0;
open += 15; // length of "<EventRecordID>"
auto close = xml.find(L"</EventRecordID>", open);
if (close == std::wstring::npos) return 0;
std::wstring numStr = xml.substr(open, close - open);
return std::wcstoull(numStr.c_str(), nullptr, 10);
}
// Returns the RecordID of the most recently written event in `channel`.
// Used to detect channel clears: if our stored watermark > channelMax,
// the channel was cleared and the new event counter restarted at 1, so
// we must reset our watermark or risk skipping all new events.
static uint64_t GetChannelMaxRecordId(const wchar_t* channel) {
EVT_HANDLE hQuery = EvtQuery(nullptr, channel, nullptr,
EvtQueryChannelPath | EvtQueryReverseDirection);
if (!hQuery) return 0;
EVT_HANDLE hEvent = nullptr;
DWORD returned = 0;
uint64_t maxId = 0;
if (EvtNext(hQuery, 1, &hEvent, 1000, 0, &returned) && returned > 0) {
std::vector<wchar_t> buf(4096);
DWORD used = 0, propCount = 0;
BOOL ok = EvtRender(nullptr, hEvent, EvtRenderEventXml,
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
buf.data(), &used, &propCount);
if (!ok && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
buf.resize(used / sizeof(wchar_t) + 1);
ok = EvtRender(nullptr, hEvent, EvtRenderEventXml,
static_cast<DWORD>(buf.size() * sizeof(wchar_t)),
buf.data(), &used, &propCount);
}
if (ok) maxId = ExtractRecordIdFromXml(std::wstring(buf.data()));
EvtClose(hEvent);
}
EvtClose(hQuery);
return maxId;
}
// ---- Shared implementation -----------------------------------------
// Runs `query` against the Application channel, formats events as
// "<DD/MM/YYYY h:mm:ss tt>: <event data>\n"
// and optionally clears the channel afterwards. If trackWatermark is
// true, also persists the highest EventRecordID seen to HKCU on return.
static std::string ReadAnsLoggerEventsImpl(const wchar_t* query,
bool clearAfterRead,
bool trackWatermark)
{
EVT_HANDLE hResults = EvtQuery(nullptr, L"Application", query,
EvtQueryChannelPath | EvtQueryForwardDirection);
if (!hResults) {
ANS_DBG("EVTLOG", "EvtQuery failed err=%lu", GetLastError());
@@ -1337,6 +1421,7 @@ namespace ANSCENTER
}
std::string out;
uint64_t highestRecordId = 0;
constexpr DWORD kBatch = 64;
EVT_HANDLE events[kBatch];
DWORD returned = 0;
@@ -1367,6 +1452,15 @@ namespace ANSCENTER
}
std::wstring xml(buf.data());
// Track the highest RecordID we've seen this call so we can
// persist it as the new watermark on exit. Done before the
// continue-on-malformed-XML paths below so an unrenderable
// event still advances the watermark.
if (trackWatermark) {
uint64_t rid = ExtractRecordIdFromXml(xml);
if (rid > highestRecordId) highestRecordId = rid;
}
// ---- TimeCreated SystemTime='2026-05-18T11:52:07.123Z' ----
// EvtRender produces either single- or double-quoted attrs
// depending on Windows version, so handle both.
@@ -1462,18 +1556,89 @@ namespace ANSCENTER
}
EvtClose(hResults);
// Persist watermark BEFORE clearing — once EvtClearLog succeeds,
// future events restart at RecordID 1, and we'd never see them
// again if the watermark stayed at e.g. 547.
// Special case: if clear is also going to succeed, the new
// watermark is irrelevant (we'll reset on next call via the
// GetChannelMaxRecordId check), so writing it here is harmless.
if (trackWatermark && highestRecordId > 0) {
WriteAnsLoggerWatermark(highestRecordId);
ANS_DBG("EVTLOG", "watermark updated to %llu", highestRecordId);
}
if (clearAfterRead) {
// Clears the entire Application channel — see header warning.
// DIAGNOSTIC: also print to stderr so callers without DebugView
// can see what's going on. Common failure codes:
// 5 ERROR_ACCESS_DENIED — process is not elevated
// 1314 ERROR_PRIVILEGE_NOT_HELD — token missing SeSecurityPriv
// 87 ERROR_INVALID_PARAMETER — channel name wrong
if (!EvtClearLog(nullptr, L"Application", nullptr, 0)) {
DWORD e = GetLastError();
ANS_DBG("EVTLOG", "EvtClearLog failed err=%lu (need admin)", e);
std::fprintf(stderr,
"[ANSUtilities] EvtClearLog(Application) FAILED, "
"GetLastError=%lu (5=AccessDenied, 1314=PrivNotHeld)\n", e);
} else {
ANS_DBG("EVTLOG", "EvtClearLog: Application channel cleared");
std::fprintf(stderr,
"[ANSUtilities] EvtClearLog(Application) OK\n");
// Clear succeeded → counter resets to 1, so our watermark
// is stale. Reset it now so the next call doesn't skip
// legitimate new events whose RecordID < old watermark.
if (trackWatermark) {
WriteAnsLoggerWatermark(0);
ANS_DBG("EVTLOG", "watermark reset to 0 after clear");
}
}
}
return out;
}
// ---- Public: full read, no skip ------------------------------------
std::string ANSUtilities::GetANSLoggerErrorEvents(bool clearAfterRead) {
// XPath: Provider name "ANSLogger" AND Level 2 (EVENTLOG_ERROR_TYPE).
// Forward direction keeps chronological insertion order so output
// matches a fresh "oldest first" scroll through Event Viewer.
return ReadAnsLoggerEventsImpl(
L"*[System[Provider[@Name='ANSLogger'] and Level=2]]",
clearAfterRead,
/*trackWatermark=*/false);
}
// ---- Public: incremental read using HKCU watermark -----------------
std::string ANSUtilities::GetANSLoggerErrorEventsSinceLastCall(bool clearAfterRead) {
uint64_t watermark = ReadAnsLoggerWatermark();
// Channel-clear detection: if the channel's current max RecordID
// is lower than our stored watermark, the log was cleared (by us
// or by something else like Event Viewer's "Clear Log") and the
// counter restarted at 1. Reset the watermark so we don't skip
// events 1..watermark that are actually fresh.
uint64_t channelMax = GetChannelMaxRecordId(L"Application");
if (channelMax > 0 && watermark > channelMax) {
ANS_DBG("EVTLOG", "watermark reset: stored=%llu channelMax=%llu "
"(channel was cleared externally)",
watermark, channelMax);
watermark = 0;
WriteAnsLoggerWatermark(0);
}
// Embed the watermark in the XPath so Windows does the filtering;
// we never see events <= watermark, which is more efficient than
// post-filtering thousands of events on the client side.
wchar_t queryBuf[256];
swprintf_s(queryBuf, _countof(queryBuf),
L"*[System[Provider[@Name='ANSLogger'] and Level=2 and "
L"(EventRecordID>%llu)]]",
watermark);
ANS_DBG("EVTLOG", "GetANSLoggerErrorEventsSinceLastCall watermark=%llu",
watermark);
return ReadAnsLoggerEventsImpl(queryBuf, clearAfterRead,
/*trackWatermark=*/true);
}
} // namespace ANSCENTER
// ============================================================================