diff --git a/lib/app_report/services/app_crash_session.dart b/lib/app_report/services/app_crash_session.dart index b979e51179..58252873dd 100644 --- a/lib/app_report/services/app_crash_session.dart +++ b/lib/app_report/services/app_crash_session.dart @@ -2,6 +2,7 @@ import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:otzaria/app_report/services/unclean_exit_detector.dart'; +import 'package:otzaria/app_report/services/windows_exit_evidence.dart'; import 'package:otzaria/core/error_log_file.dart'; import 'package:otzaria/core/startup_timeline.dart'; @@ -21,13 +22,23 @@ abstract class AppCrashSession { static Future detectAndStartSession({ required String version, UncleanExitDetector? detector, + void Function()? onSessionScanDone, + WindowsExitEvidenceReader? readWindowsExit, }) async { if (!isSupported) return null; - final active = - detector ?? UncleanExitDetector(processStartedAt: processStartTime()); - final candidate = await active.detectPreviousCrash(); - await active.startSession(version: version); - return candidate; + final UncleanExitDetector active; + final ({CrashCandidate? candidate, SessionLock? unmatchedSession}) scan; + try { + active = + detector ?? UncleanExitDetector(processStartedAt: processStartTime()); + scan = await active.scanPreviousExit(); + await active.startSession(version: version); + } finally { + onSessionScanDone?.call(); + } + final session = scan.unmatchedSession; + if (session == null || readWindowsExit == null) return scan.candidate; + return active.corroborateWindowsExit(session, read: readWindowsExit); } /// מועמד לתקיעה שהשתחררה בהפעלה הנוכחית, לפי רשומת `App hang` האחרונה. diff --git a/lib/app_report/services/session_context_snapshot.dart b/lib/app_report/services/session_context_snapshot.dart index 3b8f54fa45..02e583b896 100644 --- a/lib/app_report/services/session_context_snapshot.dart +++ b/lib/app_report/services/session_context_snapshot.dart @@ -3,6 +3,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; +import 'package:flutter/semantics.dart'; import 'package:otzaria/app_report/services/unclean_exit_detector.dart'; import 'package:otzaria/core/diagnostics/developer_diagnostics.dart'; import 'package:otzaria/core/error_log_file.dart'; @@ -43,7 +44,10 @@ class SessionContextSnapshot { /// התמונה רק אם נשמרה בהפעלה [session]. בלי נעילה (ANR) אין זיהוי אמין /// של ההפעלה: מספר תהליך עלול להיות בשימוש חוזר, וזמן יציאה אינו זמן התחלה. - Future?> previousFor(SessionLock? session) async { + Future?> previousFor( + SessionLock? session, { + DateTime? before, + }) async { if (session == null) return null; final snapshot = await previous; if (snapshot == null) return null; @@ -51,10 +55,24 @@ class SessionContextSnapshot { final matches = snapshot['pid'] == session.pid && savedAt != null && - !savedAt.isBefore(session.startedAt); + !savedAt.isBefore(session.startedAt) && + (before == null || !savedAt.isAfter(before)); return matches ? snapshot : null; } + /// הקשר הקודם והראיה התמציתית של מערכת ההפעלה, אם נמצאה. + Future?> previousForIncident( + CrashCandidate candidate, + ) async { + final event = candidate.windowsExit; + final snapshot = await previousFor( + candidate.previousSession, + before: event?.occurredAt, + ); + if (event == null) return snapshot; + return {...?snapshot, 'windowsExit': event.toJson()}; + } + /// מתחיל לשמור. פעם אחת לתהליך. Future start() async { if (_started) return; @@ -123,5 +141,8 @@ class SessionContextSnapshot { 'context': DeveloperDiagnostics.instance.contextProvider?.call() ?? const {}, 'searches': ActiveLexicalSearches.instance.collect(), + 'accessibility': { + 'semanticsEnabled': SemanticsBinding.instance.semanticsEnabled, + }, }; } diff --git a/lib/app_report/services/unclean_exit_detector.dart b/lib/app_report/services/unclean_exit_detector.dart index 8adaf27151..0bb9dc500e 100644 --- a/lib/app_report/services/unclean_exit_detector.dart +++ b/lib/app_report/services/unclean_exit_detector.dart @@ -8,6 +8,7 @@ import 'package:flutter/foundation.dart'; import 'package:otzaria/app_report/repository/error_log_blocks.dart'; import 'package:otzaria/app_report/services/breakpad_envelope.dart'; import 'package:otzaria/app_report/services/minidump_signature.dart'; +import 'package:otzaria/app_report/services/windows_exit_evidence.dart'; import 'package:otzaria/core/error_log_file.dart'; import 'package:otzaria_report_contract/otzaria_report_contract.dart'; import 'package:path/path.dart' as p; @@ -20,16 +21,19 @@ class SessionLock { required this.pid, required this.version, required this.startedAt, + this.windowsCreationFileTime, }); final int pid; final String version; final DateTime startedAt; + final int? windowsCreationFileTime; Map toJson() => { 'pid': pid, 'version': version, 'startedAt': startedAt.toUtc().toIso8601String(), + 'windowsCreationFileTime': ?windowsCreationFileTime, }; static SessionLock? tryParse(String content) { @@ -38,11 +42,15 @@ class SessionLock { if (json is! Map) return null; final pid = json['pid']; final startedAt = DateTime.tryParse('${json['startedAt']}'); - if (pid is! int || startedAt == null) return null; + if (pid is! int || pid <= 0 || startedAt == null) return null; + final fileTime = json['windowsCreationFileTime']; return SessionLock( pid: pid, version: '${json['version'] ?? ''}', startedAt: startedAt, + windowsCreationFileTime: fileTime is int && fileTime > 0 + ? fileTime + : null, ); } catch (_) { return null; @@ -63,6 +71,7 @@ class CrashCandidate { required this.hasMinidump, this.minidump, this.minidumpSignature, + this.windowsExit, this.kind = CrashIncidentKind.crash, }) : hangDuration = null, details = null, @@ -81,7 +90,8 @@ class CrashCandidate { hasStartupStall = false, hasMinidump = false, minidump = null, - minidumpSignature = null; + minidumpSignature = null, + windowsExit = null; final CrashIncidentKind kind; @@ -112,6 +122,8 @@ class CrashCandidate { /// חתימת [minidump] גם כש-[signature] נלקחה מרשומה ב-errors.txt. final CrashSignature? minidumpSignature; + + final WindowsExitEvidence? windowsExit; } /// מזהה יציאה לא נקייה של ההפעלה הקודמת. לוגיקה בלבד — הקריאה מהעלייה @@ -162,6 +174,9 @@ class UncleanExitDetector { pid: _currentPid, version: version, startedAt: _processStartedAt, + windowsCreationFileTime: Platform.isWindows && _currentPid == pid + ? await _currentWindowsCreationFileTime() + : null, ); final file = File(lockPath); await file.parent.create(recursive: true); @@ -206,7 +221,12 @@ class UncleanExitDetector { /// מחזיר מועמד לקריסה רק כשנשארה נעילה של תהליך שאינו חי, ויש ראיה לקריסה: /// רשומת שגיאה מאז תחילתו, `Startup stall`, או minidump של Sentry. /// נעילת עלייה מכסה תהליך שמת לפני שכתב את `session.lock`. - Future detectPreviousCrash() async { + Future detectPreviousCrash() async => + (await scanPreviousExit()).candidate; + + /// משאיר את הנעילה האחרונה לבדיקה משלימה אחרי רישום ההפעלה הנוכחית. + Future<({CrashCandidate? candidate, SessionLock? unmatchedSession})> + scanPreviousExit() async { for (final dir in _sentryDirs ?? defaultSentryDatabaseDirs()) { await pruneRecoveredMinidumps(dir); } @@ -221,15 +241,16 @@ class UncleanExitDetector { if (lock != null && (lock.pid == _currentPid || _isStillRunning(lock))) { lock = null; } + final sessions = [?lock, ...abandoned]; // הוותיקה מכולן: רשומות של כל ההפעלות שלא נסגרו נכנסות לבדיקה. - final previous = [?lock, ...abandoned].fold( + final previous = sessions.fold( null, (oldest, next) => oldest == null || next.startedAt.isBefore(oldest.startedAt) ? next : oldest, ); - if (previous == null) return null; + if (previous == null) return (candidate: null, unmatchedSession: null); final blocks = await _errorBlocksSince( previous.startedAt, @@ -247,23 +268,66 @@ class UncleanExitDetector { final evidence = blocks .where((b) => b.isCrashEvidence || unrecoveredHang(b)) .toList(); - if (evidence.isEmpty && !dump.found) return null; + if (evidence.isEmpty && !dump.found) { + final latest = sessions.reduce( + (a, b) => a.startedAt.isAfter(b.startedAt) ? a : b, + ); + return ( + candidate: null, + unmatchedSession: latest.startedAt.isBefore(_processStartedAt) + ? latest + : null, + ); + } final newestDump = dump.newest; final dumpSignature = newestDump == null ? null : await readMinidumpSignature(newestDump); + return ( + candidate: CrashCandidate( + previousSession: previous, + entries: blocks, + signature: evidence.isNotEmpty + ? evidence.last.signature + : dumpSignature, + hasStartupStall: hasStall, + hasMinidump: dump.found, + minidump: newestDump, + minidumpSignature: dumpSignature, + kind: evidence.isNotEmpty && evidence.last.isAppHang + ? CrashIncidentKind.hang + : CrashIncidentKind.crash, + ), + unmatchedSession: null, + ); + } + + /// מגבש מועמד רק כשהמערכת תיעדה את סיום אותו מופע. + Future corroborateWindowsExit( + SessionLock session, { + WindowsExitEvidenceReader read = readWindowsExitEvidence, + }) async { + final creationFileTime = session.windowsCreationFileTime; + if (creationFileTime == null) return null; + final event = await read( + session.pid, + creationFileTime, + session.startedAt, + _processStartedAt, + ); + if (event == null) return null; + final code = event.exceptionCode; return CrashCandidate( - previousSession: previous, - entries: blocks, - signature: evidence.isNotEmpty ? evidence.last.signature : dumpSignature, - hasStartupStall: hasStall, - hasMinidump: dump.found, - minidump: newestDump, - minidumpSignature: dumpSignature, - kind: evidence.isNotEmpty && evidence.last.isAppHang - ? CrashIncidentKind.hang - : CrashIncidentKind.crash, + previousSession: session, + entries: const [], + signature: code == null + ? null + : CrashSignature(exceptionType: code, frames: const []), + hasStartupStall: false, + hasMinidump: false, + kind: event.isHang ? CrashIncidentKind.hang : CrashIncidentKind.crash, + windowsExit: event, ); } @@ -447,6 +511,20 @@ class UncleanExitDetector { /// זמן יצירת התהליך ב-Windows (GetProcessTimes), או null. static DateTime? defaultProcessCreatedAt(int processId) { if (!Platform.isWindows) return null; + final ticks = _windowsProcessCreationFileTime(processId); + return ticks == null + ? null + : DateTime.utc(1601).add(Duration(microseconds: ticks ~/ 10)); + } + + static Future? _windowsCreationOfCurrentProcess; + + static Future _currentWindowsCreationFileTime() => + _windowsCreationOfCurrentProcess ??= Isolate.run( + () => _windowsProcessCreationFileTime(pid), + ).timeout(const Duration(seconds: 2), onTimeout: () => null); + + static int? _windowsProcessCreationFileTime(int processId) { final handle = OpenProcess( PROCESS_QUERY_LIMITED_INFORMATION, false, @@ -464,8 +542,7 @@ class UncleanExitDetector { ).value) { return null; } - final ticks = (times.ref.dwHighDateTime << 32) | times.ref.dwLowDateTime; - return DateTime.utc(1601).add(Duration(microseconds: ticks ~/ 10)); + return (times.ref.dwHighDateTime << 32) | times.ref.dwLowDateTime; } finally { calloc.free(times); handle.value.close(); diff --git a/lib/app_report/services/windows_exit_evidence.dart b/lib/app_report/services/windows_exit_evidence.dart new file mode 100644 index 0000000000..8ec350bdab --- /dev/null +++ b/lib/app_report/services/windows_exit_evidence.dart @@ -0,0 +1,218 @@ +import 'dart:ffi'; +import 'dart:io'; +import 'dart:isolate'; + +import 'package:ffi/ffi.dart'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; +import 'package:win32/win32.dart'; +import 'package:xml/xml.dart'; + +/// ראיה מיומן Application של Windows, בלי הטקסט הגולמי של האירוע. +class WindowsExitEvidence { + const WindowsExitEvidence({ + required this.eventId, + required this.occurredAt, + this.exceptionCode, + }); + + final int eventId; + final DateTime occurredAt; + final String? exceptionCode; + + bool get isHang => eventId == 1002; + + Map toJson() => { + 'eventId': eventId, + 'occurredAt': occurredAt.toUtc().toIso8601String(), + 'exceptionCode': ?exceptionCode, + }; +} + +typedef WindowsExitEvidenceReader = + Future Function( + int processId, + int creationFileTime, + DateTime from, + DateTime until, + ); + +/// מחפש אירוע של אותו מופע בדיוק. הקריאה ל-Windows רצה ב-isolate. +Future readWindowsExitEvidence( + int processId, + int creationFileTime, + DateTime from, + DateTime until, +) async { + if (!Platform.isWindows || !from.isBefore(until)) return null; + final executable = p.basename(Platform.resolvedExecutable); + if (executable.contains("'")) return null; + return Isolate.run( + () => _findEvent(executable, processId, creationFileTime, from, until), + ).timeout(const Duration(seconds: 4), onTimeout: () => null); +} + +WindowsExitEvidence? _findEvent( + String executable, + int processId, + int creationFileTime, + DateTime from, + DateTime until, +) { + final deadline = Stopwatch()..start(); + final channel = 'Application'.toPcwstr(); + final xpath = + ("*[System[((Provider[@Name='Application Error'] and EventID=1000) or " + "(Provider[@Name='Application Hang'] and EventID=1002)) and " + "TimeCreated[@SystemTime>='${from.toUtc().toIso8601String()}' and " + "@SystemTime<='${until.toUtc().toIso8601String()}']]] " + "and *[EventData[Data[@Name='AppName']='$executable']]") + .toPcwstr(); + final event = calloc(); + final returned = calloc(); + final bufferUsed = calloc(); + final propertyCount = calloc(); + var query = 0; + try { + query = EvtQuery( + null, + channel, + xpath, + EvtQueryChannelPath | EvtQueryReverseDirection, + ).value; + if (query == 0) return null; + for (var i = 0; i < 32; i++) { + final remaining = 3000 - deadline.elapsedMilliseconds; + if (remaining <= 0 || + !EvtNext(EVT_HANDLE(query), 1, event, remaining, 0, returned).value || + returned.value != 1) { + return null; + } + final handle = EVT_HANDLE(event.value); + try { + final xml = _renderEvent(handle, bufferUsed, propertyCount); + if (xml == null) continue; + final evidence = parseWindowsExitEvent( + xml, + executable: executable, + processId: processId, + creationFileTime: creationFileTime, + from: from, + until: until, + ); + if (evidence != null) return evidence; + } finally { + EvtClose(handle); + } + } + return null; + } finally { + if (query != 0) EvtClose(EVT_HANDLE(query)); + malloc.free(channel); + malloc.free(xpath); + calloc.free(event); + calloc.free(returned); + calloc.free(bufferUsed); + calloc.free(propertyCount); + } +} + +String? _renderEvent( + EVT_HANDLE handle, + Pointer bufferUsed, + Pointer propertyCount, +) { + bufferUsed.value = 0; + EvtRender( + null, + handle, + EvtRenderEventXml, + 0, + null, + bufferUsed, + propertyCount, + ); + final bytes = bufferUsed.value; + if (bytes < 2 || bytes > 64 * 1024) return null; + final buffer = calloc(bytes); + try { + if (!EvtRender( + null, + handle, + EvtRenderEventXml, + bytes, + buffer, + bufferUsed, + propertyCount, + ).value) { + return null; + } + return buffer.cast().toDartString(length: bufferUsed.value ~/ 2 - 1); + } finally { + calloc.free(buffer); + } +} + +@visibleForTesting +WindowsExitEvidence? parseWindowsExitEvent( + String xml, { + required String executable, + required int processId, + required int creationFileTime, + required DateTime from, + required DateTime until, +}) { + final XmlElement event; + try { + event = XmlDocument.parse(xml).rootElement; + } on XmlException { + return null; + } + if (event.name.local != 'Event') return null; + final system = event.getElement('System'); + final eventId = int.tryParse(system?.getElement('EventID')?.innerText ?? ''); + final provider = system?.getElement('Provider')?.getAttribute('Name'); + final expectedProvider = switch (eventId) { + 1000 => 'Application Error', + 1002 => 'Application Hang', + _ => null, + }; + if (expectedProvider == null || provider != expectedProvider) return null; + final time = DateTime.tryParse( + system?.getElement('TimeCreated')?.getAttribute('SystemTime') ?? '', + ); + if (time == null || time.isBefore(from) || !time.isBefore(until)) return null; + + final payload = event.getElement('EventData'); + if (payload == null) return null; + String? field(String key) => payload + .findElements('Data') + .where((data) => data.getAttribute('Name') == key) + .singleOrNull + ?.innerText + .trim(); + + final startField = eventId == 1000 ? 'ProcessCreationTime' : 'StartTime'; + if (field('AppName')?.toLowerCase() != executable.toLowerCase() || + _parseHex(field('ProcessId')) != processId || + _parseHex(field(startField)) != creationFileTime) { + return null; + } + final code = eventId == 1000 ? _parseHex(field('ExceptionCode')) : null; + return WindowsExitEvidence( + eventId: eventId!, + occurredAt: time, + exceptionCode: code != null && code >= 0 && code <= 0xffffffff + ? '0x${code.toRadixString(16).padLeft(8, '0')}' + : null, + ); +} + +int? _parseHex(String? value) { + if (value == null) return null; + final digits = value.toLowerCase(); + return int.tryParse( + digits.startsWith('0x') ? digits.substring(2) : digits, + radix: 16, + ); +} diff --git a/lib/app_report/view/crash_prompt_dialog.dart b/lib/app_report/view/crash_prompt_dialog.dart index d503430134..8e0bc8f3e0 100644 --- a/lib/app_report/view/crash_prompt_dialog.dart +++ b/lib/app_report/view/crash_prompt_dialog.dart @@ -90,9 +90,8 @@ class CrashPromptDialog extends StatefulWidget { static AppReportCollector collectorFor(CrashCandidate candidate) => AppReportCollector( includeCurrentContext: !candidate.occurredInPreviousRun, - previousRunContext: () => SessionContextSnapshot.instance.previousFor( - candidate.previousSession, - ), + previousRunContext: () => + SessionContextSnapshot.instance.previousForIncident(candidate), ); static const String title = 'אוצריא נסגרה באופן לא צפוי'; diff --git a/lib/main.dart b/lib/main.dart index fcef19029d..94208a59f2 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -31,6 +31,7 @@ import 'package:otzaria/app_report/services/app_crash_session.dart'; import 'package:otzaria/app_report/services/app_report_service.dart'; import 'package:otzaria/app_report/services/crash_report_decision.dart'; import 'package:otzaria/app_report/services/crash_report_flow.dart'; +import 'package:otzaria/app_report/services/windows_exit_evidence.dart'; import 'package:otzaria/app_report/services/input_focus_diagnostics.dart'; import 'package:otzaria/app_report/services/session_context_snapshot.dart'; import 'package:otzaria/app_report/services/unclean_exit_detector.dart'; @@ -1127,15 +1128,20 @@ Future _runDeferredCrashCheck() async { try { final candidate = await AppCrashSession.detectAndStartSession( version: ErrorLogFile.appVersion, - ).whenComplete(_markCrashScanDone); + onSessionScanDone: _markCrashScanDone, + readWindowsExit: + Platform.isWindows && + CrashReportFlow.currentMode() != AppCrashReportMode.never + ? readWindowsExitEvidence + : null, + ); if (candidate == null) return; await CrashReportFlow( showPrompt: showCrashPromptOnNavigator, collector: AppReportCollector( includeCurrentContext: false, - previousRunContext: () => SessionContextSnapshot.instance.previousFor( - candidate.previousSession, - ), + previousRunContext: () => + SessionContextSnapshot.instance.previousForIncident(candidate), ), ).handle(candidate); } catch (error, stackTrace) { diff --git a/test/app_report/session_context_snapshot_test.dart b/test/app_report/session_context_snapshot_test.dart index ed5778fbc9..47f900a1ae 100644 --- a/test/app_report/session_context_snapshot_test.dart +++ b/test/app_report/session_context_snapshot_test.dart @@ -4,9 +4,12 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/app_report/services/session_context_snapshot.dart'; import 'package:otzaria/app_report/services/unclean_exit_detector.dart'; +import 'package:otzaria/app_report/services/windows_exit_evidence.dart'; import 'package:path/path.dart' as p; void main() { + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + late Directory tmp; late String path; @@ -83,12 +86,47 @@ void main() { expect(await snapshot.previousFor(crashed), isNull); }); + test('צילום שנכתב אחרי אירוע הסיום אינו מצורף', () async { + final snapshot = saved(pid: 4242, at: '2026-11-15T23:00:00.000Z'); + expect( + await snapshot.previousFor( + crashed, + before: DateTime.utc(2026, 11, 15, 22, 50), + ), + isNull, + ); + }); + test('בלי נעילה (ANR): אין התאמה אמינה להפעלה', () async { final snapshot = saved(pid: 77, at: '2026-11-15T23:00:00.000Z'); expect(await snapshot.previousFor(null), isNull); }); }); + test('ראיית Windows מצורפת גם כשההפעלה לא הספיקה לשמור הקשר', () async { + final snapshot = SessionContextSnapshot(path: path); + final happenedAt = DateTime.utc(2026, 11, 15, 22, 6); + final candidate = CrashCandidate( + previousSession: SessionLock( + pid: 4242, + version: '1', + startedAt: DateTime.utc(2026, 11, 15, 22), + ), + entries: const [], + signature: null, + hasStartupStall: false, + hasMinidump: false, + windowsExit: WindowsExitEvidence(eventId: 1000, occurredAt: happenedAt), + ); + + expect(await snapshot.previousForIncident(candidate), { + 'windowsExit': { + 'eventId': 1000, + 'occurredAt': happenedAt.toIso8601String(), + }, + }); + }); + test('קובץ חסר או פגום: אין הקשר קודם', () async { expect(await SessionContextSnapshot(path: path).previous, isNull); File(path) @@ -97,6 +135,16 @@ void main() { expect(await SessionContextSnapshot(path: path).previous, isNull); }); + test('צילום ההפעלה שומר את מצב ה-Semantics שהיה פעיל בה', () async { + final handle = binding.ensureSemantics(); + try { + await SessionContextSnapshot(path: path).record(); + } finally { + handle.dispose(); + } + expect(readSaved()['accessibility'], {'semanticsEnabled': true}); + }); + test('נכתב מחדש רק כשהתוכן השתנה', () async { var screen = 'reading'; var tick = 0; diff --git a/test/app_report/unclean_exit_detector_test.dart b/test/app_report/unclean_exit_detector_test.dart index 126495a472..b63e98c2e9 100644 --- a/test/app_report/unclean_exit_detector_test.dart +++ b/test/app_report/unclean_exit_detector_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'dart:io'; @@ -6,6 +7,7 @@ import 'package:otzaria/app_report/services/app_crash_session.dart'; import 'package:otzaria/app_report/services/breakpad_envelope.dart'; import 'package:otzaria/app_report/services/crash_report_decision.dart'; import 'package:otzaria/app_report/services/unclean_exit_detector.dart'; +import 'package:otzaria/app_report/services/windows_exit_evidence.dart'; import 'package:otzaria/core/error_log_file.dart'; import 'package:otzaria/core/app_paths.dart'; import 'package:otzaria/core/startup_timeline.dart'; @@ -40,12 +42,17 @@ void main() { processStartedAt: thisStart, ); - void writeLock({int pid = 1000, DateTime? startedAt}) { + void writeLock({ + int pid = 1000, + DateTime? startedAt, + int? windowsCreationFileTime, + }) { File(p.join(logs.path, UncleanExitDetector.lockFileName)).writeAsStringSync( jsonEncode({ 'pid': pid, 'version': '0.9.97', 'startedAt': (startedAt ?? previousStart).toIso8601String(), + 'windowsCreationFileTime': ?windowsCreationFileTime, }), ); } @@ -119,6 +126,124 @@ void main() { expect(await detector().detectPreviousCrash(), isNull); }); + group('ראיה מיומן Windows אחרי יציאה שקטה', () { + const creationFileTime = 0x1dd641d4200f000; + final event = WindowsExitEvidence( + eventId: 1002, + occurredAt: previousStart.add(const Duration(minutes: 3)), + ); + + test('הנעילה החדשה נכתבת לפני שמתחילה קריאת היומן', () async { + writeLock(windowsCreationFileTime: creationFileTime); + final active = detector(); + final reading = Completer<(int, int, DateTime, DateTime)>(); + final result = Completer(); + var scanDone = false; + final pending = AppCrashSession.detectAndStartSession( + version: 'test', + detector: active, + onSessionScanDone: () => scanDone = true, + readWindowsExit: (pid, ticks, from, until) { + reading.complete((pid, ticks, from, until)); + return result.future; + }, + ); + expect( + await reading.future, + (1000, creationFileTime, previousStart, thisStart), + ); + expect(scanDone, isTrue); + final current = SessionLock.tryParse( + File(active.lockPath).readAsStringSync(), + ); + expect(current?.pid, 2000); + result.complete(event); + final candidate = await pending; + expect(candidate?.previousSession?.pid, 1000); + expect(candidate?.occurredInPreviousRun, isTrue); + expect(candidate?.isHang, isTrue); + expect(candidate?.windowsExit, same(event)); + expect(candidate?.hasMinidump, isFalse); + }); + + test('גם נעילת runner מהפעלה שנכשלה לפני החשיפה נבדקת', () async { + final active = detector(); + final startup = File(active.startupLockPath(1000)); + startup.writeAsStringSync( + jsonEncode( + SessionLock( + pid: 1000, + version: 'test', + startedAt: previousStart, + windowsCreationFileTime: creationFileTime, + ).toJson(), + ), + ); + final candidate = await AppCrashSession.detectAndStartSession( + version: 'test', + detector: active, + readWindowsExit: (_, _, _, _) async => WindowsExitEvidence( + eventId: 1000, + occurredAt: event.occurredAt, + exceptionCode: '0xc0000005', + ), + ); + expect(candidate?.isHang, isFalse); + expect(candidate?.windowsExit?.exceptionCode, '0xc0000005'); + expect(candidate?.signature?.exceptionType, '0xc0000005'); + expect(candidate?.signature?.frames, isEmpty); + expect(await startup.exists(), isFalse); + }); + + test('נעילה ישנה או תהליך חי אינם מספיקים לשאילתת היומן', () async { + Future unexpected( + int pid, + int ticks, + DateTime start, + DateTime until, + ) async => throw StateError('unexpected event query'); + + writeLock(); + expect( + await AppCrashSession.detectAndStartSession( + version: 'test', + detector: detector(), + readWindowsExit: unexpected, + ), + isNull, + ); + + writeLock(windowsCreationFileTime: creationFileTime); + expect( + await AppCrashSession.detectAndStartSession( + version: 'test', + detector: detector(alive: (_) => true), + readWindowsExit: unexpected, + ), + isNull, + ); + }); + + test('הראיה הקיימת בלוג מקבלת קדימות על פני שאילתת Windows', () async { + writeLock(windowsCreationFileTime: creationFileTime); + writeErrors( + entry( + 'Unhandled Error', + previousStart.add(const Duration(minutes: 2)), + body: 'Exception: StateError: failed', + ), + ); + final candidate = await AppCrashSession.detectAndStartSession( + version: 'test', + detector: detector(), + readWindowsExit: (_, _, _, _) async => + throw StateError('unexpected event query'), + ); + expect(candidate?.signature?.exceptionType, 'StateError'); + expect(candidate?.windowsExit, isNull); + }); + }); + test('תהליך שעדיין חי אינו קריסה', () async { writeLock(); writeErrors( diff --git a/test/app_report/windows_exit_evidence_test.dart b/test/app_report/windows_exit_evidence_test.dart new file mode 100644 index 0000000000..f0cc69fe35 --- /dev/null +++ b/test/app_report/windows_exit_evidence_test.dart @@ -0,0 +1,102 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/app_report/services/windows_exit_evidence.dart'; + +void main() { + final start = DateTime.utc(2026, 11, 20, 18); + final end = DateTime.utc(2026, 11, 20, 20); + const windowsFileTime = 0x1dd641d4200f000; + const expectedPid = 0x1ed0; + + String event({ + int id = 1000, + String? provider, + String application = 'otzaria.exe', + String pid = '0x1ed0', + String? creationTime = '0x1dd641d4200f000', + String exceptionCode = 'C0000005', + String time = '2026-11-20T19:00:00.1234567Z', + String additionalFields = '', + }) { + final startField = id == 1002 ? 'StartTime' : 'ProcessCreationTime'; + return ''' + + + + $id + + + private-host + + + $application + $pid + ${creationTime == null ? '' : '$creationTime'} + $exceptionCode + C:\\Users\\Private\\otzaria.exe + private-report-id + $additionalFields + + +'''; + } + + WindowsExitEvidence? parse(String xml) => parseWindowsExitEvent( + xml, + executable: 'Otzaria.exe', + processId: expectedPid, + creationFileTime: windowsFileTime, + from: start, + until: end, + ); + + test('ראיית קריסה מכילה רק מזהה אירוע, זמן וקוד חריגה', () { + final evidence = parse(event())!; + expect(evidence.isHang, isFalse); + expect(evidence.toJson(), { + 'eventId': 1000, + 'occurredAt': '2026-11-20T19:00:00.123456Z', + 'exceptionCode': '0xc0000005', + }); + }); + + test('Application Hang מזוהה לפי StartTime ואינו מדווח כקריסה', () { + final evidence = parse(event(id: 1002))!; + expect(evidence.isHang, isTrue); + expect(evidence.toJson(), { + 'eventId': 1002, + 'occurredAt': '2026-11-20T19:00:00.123456Z', + }); + }); + + test('PID שגוי נדחה גם כשה-PID של ספק האירוע תואם', () { + expect(parse(event(pid: '0x1ed1')), isNull); + }); + + test('PID ממוחזר, זמן יצירה חסר או שדה כפול אינם ראיה', () { + expect(parse(event(creationTime: '0x1dd641d4200f001')), isNull); + expect(parse(event(creationTime: null)), isNull); + expect( + parse(event(additionalFields: '0x1ed0')), + isNull, + ); + }); + + test('התאמת השם ועמידה בטווח הזמן נבדקות גם לאחר שאילתת Windows', () { + expect(parse(event(application: 'other-otzaria.exe')), isNull); + expect(parse(event(time: '2026-11-20T17:59:59.999999Z')), isNull); + expect(parse(event(time: end.toIso8601String())), isNull); + }); + + test('ספק או מזהה אירוע זר, או XML פגום, נדחים', () { + expect(parse(event(id: 1002, provider: 'Application Error')), isNull); + expect(parse(event(id: 1001)), isNull); + expect(parse(''), isNull); + }); + + test('טקסט במקום קוד חריגה מושמט', () { + expect( + parse(event(exceptionCode: 'private value'))?.exceptionCode, + isNull, + ); + }); +} diff --git a/test/windows/crash_record_test.cpp b/test/windows/crash_record_test.cpp index 9820104e0f..5dca68a370 100644 --- a/test/windows/crash_record_test.cpp +++ b/test/windows/crash_record_test.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -79,6 +80,25 @@ int wmain(int argc, wchar_t** argv) { const auto log = startup_watchdog::ErrorLogPath(); std::filesystem::create_directories(std::filesystem::path(log).parent_path()); + crash_record::g_started_at = crash_record::TimestampMs(); + crash_record::WriteStartupLock(0); + const auto startup_lock = std::filesystem::path(log).parent_path() / + (L"startup-" + std::to_wstring(GetCurrentProcessId()) + L".lock"); + std::ifstream startup_file(startup_lock); + std::string startup_json; + std::getline(startup_file, startup_json); + startup_file.close(); + FILETIME creation{}, exit{}, kernel{}, user{}; + Require(GetProcessTimes(GetCurrentProcess(), &creation, &exit, &kernel, &user), + "Cannot query test process creation time"); + const auto creation_ticks = + (static_cast(creation.dwHighDateTime) << 32) | + creation.dwLowDateTime; + Require(startup_json.find("\"windowsCreationFileTime\":" + + std::to_string(creation_ticks) + "}") != std::string::npos, + "Startup lock must contain the exact process creation FILETIME"); + std::filesystem::remove(startup_lock); + crash_record::g_wer.magic = CrashWerContext::kMagic; crash_record::g_wer.size = sizeof(CrashWerContext); wcscpy_s(crash_record::g_wer.log_path, log.c_str()); diff --git a/windows/runner/crash_record.cpp b/windows/runner/crash_record.cpp index 3ce09704b7..52f8f325ab 100644 --- a/windows/runner/crash_record.cpp +++ b/windows/runner/crash_record.cpp @@ -202,11 +202,17 @@ void CALLBACK WriteStartupLock(ULONG_PTR) { const DWORD pid = ::GetCurrentProcessId(); const std::wstring path = dir + L"\\startup-" + std::to_wstring(pid) + L".lock"; - char json[160]; + FILETIME creation{}, exit{}, kernel{}, user{}; + ::GetProcessTimes(::GetCurrentProcess(), &creation, &exit, &kernel, &user); + const auto creation_ticks = + (static_cast(creation.dwHighDateTime) << 32) | + creation.dwLowDateTime; + char json[192]; snprintf(json, sizeof(json), - "{\"pid\":%lu,\"version\":\"%s\",\"startedAt\":\"%s\"}", + "{\"pid\":%lu,\"version\":\"%s\",\"startedAt\":\"%s\"," + "\"windowsCreationFileTime\":%llu}", static_cast(pid), g_wer.version, - g_started_at.c_str()); + g_started_at.c_str(), creation_ticks); HANDLE file = ::CreateFileW(path.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) return;