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
// ============================================================================
+38 -6
View File
@@ -161,14 +161,40 @@ namespace ANSCENTER {
// Time is converted to the user's local timezone and formatted
// using LOCALE_USER_DEFAULT (matches Event Viewer's display).
//
// If `clearAfterRead` is true, calls EvtClearLog on the entire
// Application channel after reading. WARNING: this wipes every
// event from every source in the Application log, not just
// ANSLogger entries — there is no per-event delete API in
// Windows. Requires Administrator privileges; without elevation
// the clear silently fails (events are still returned).
// clearAfterRead=true behaviour:
// * Calls EvtClearLog on the entire Application channel after
// reading. WARNING: this wipes every event from every source
// in the Application log, not just ANSLogger entries — there
// is no per-event delete API in Windows.
// * REQUIRES THE CALLING PROCESS TO BE ELEVATED (run as
// Administrator). Without elevation, EvtClearLog returns
// ERROR_ACCESS_DENIED (Win32 error 5) and the events remain
// in the log. The read still succeeds either way.
// * Failures are reported on stderr in the form
// "[ANSUtilities] EvtClearLog(Application) FAILED, GetLastError=N"
// and via DebugView under the "EVTLOG" tag. The C++ return
// value does NOT signal clear success — capture stderr or
// check Event Viewer afterwards to confirm.
[[nodiscard]] static std::string GetANSLoggerErrorEvents(bool clearAfterRead = false);
// Same as GetANSLoggerErrorEvents but only returns events that
// have NOT been returned by a previous call from this user
// account. The highest EventRecordID seen is persisted to
// HKCU\Software\ANSCENTER\ANSUtilities\EventLogWatermark\ANSLogger
// (REG_QWORD) and used as a Windows XPath filter
// (EventRecordID > N) on the next call. No admin needed for the
// skip mechanism — only for the optional clearAfterRead.
//
// Channel-clear handling: if Windows resets the Application
// channel's RecordID counter (typical after EvtClearLog), this
// function detects that the channel's current max RecordID is
// less than the stored watermark and resets the watermark to 0
// so no newly-written events are accidentally skipped.
//
// To force a re-read of all events, delete the registry value
// above and call again.
[[nodiscard]] static std::string GetANSLoggerErrorEventsSinceLastCall(bool clearAfterRead = false);
// Scan the local network for AIBOX / ANSVIS servers.
// Runs two strategies in parallel and merges results by IP:
// 1) UDP multicast probe to 230.50.200.150:58839 (with subnet
@@ -398,6 +424,12 @@ extern "C" ANSULT_API int ScanANSDevicesCpp(int timeoutMs, std::string& resultJ
extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle result);
extern "C" ANSULT_API int GetANSLoggerErrorEventsCpp(int clearAfterRead, std::string& result);
// Watermarked variant: only returns events not seen by previous calls.
// Watermark is stored in HKCU\Software\ANSCENTER\ANSUtilities\EventLogWatermark\ANSLogger
// (REG_QWORD). No admin needed for the skip; only for clearAfterRead.
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCall(int clearAfterRead, LStrHandle result);
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCallCpp(int clearAfterRead, std::string& result);
// Unicode conversion utilities for LabVIEW
extern "C" ANSULT_API int ANSConvertUTF8ToUTF16LE(const char* utf8Str, LStrHandle result, int includeBOM = 1);
extern "C" ANSULT_API int ANSDecodeJsonUnicodeToUTF16LE(const char* escapedStr, LStrHandle result);
+39
View File
@@ -3093,3 +3093,42 @@ extern "C" ANSULT_API int GetANSLoggerErrorEvents(int clearAfterRead, LStrHandle
}
catch (...) { return -1; }
}
// ---------------------------------------------------------------------------
// GetANSLoggerErrorEventsSinceLastCall — watermark-based incremental read.
// Stores highest EventRecordID seen in HKCU; subsequent calls return only
// newer events. No admin needed for the skip (only for clearAfterRead).
// ---------------------------------------------------------------------------
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCallCpp(int clearAfterRead, std::string& result) {
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCallCpp: clearAfterRead=%d", clearAfterRead);
try {
result = ANSCENTER::ANSUtilities::GetANSLoggerErrorEventsSinceLastCall(clearAfterRead != 0);
return 1;
}
catch (const std::exception& e) {
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCallCpp threw: %s", e.what());
result.clear();
return 0;
}
catch (...) {
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCallCpp threw unknown");
result.clear();
return 0;
}
}
extern "C" ANSULT_API int GetANSLoggerErrorEventsSinceLastCall(int clearAfterRead, LStrHandle result) {
ANS_DBG("ANSUTIL", "GetANSLoggerErrorEventsSinceLastCall: clearAfterRead=%d", clearAfterRead);
if (!result) return -1;
try {
std::string s;
GetANSLoggerErrorEventsSinceLastCallCpp(clearAfterRead, s);
int size = static_cast<int>(s.size());
MgErr error = DSSetHandleSize(result, sizeof(int32) + size * sizeof(uChar));
if (error != noErr) return -2;
(*result)->cnt = size;
if (size > 0) memcpy((*result)->str, s.data(), size);
return 1;
}
catch (...) { return -1; }
}