Files
zerorigin-toolbox/internal/platform/windows/crashguard.go
T
zerorigin2019 0a1c1e82ea chore: 初始化仓库(零源工具箱 0.1.0 基线)
- Go 主进程 cmd/zerorigin(托盘常驻 + 触发器/规则/动作引擎)
- Wails v3 设置进程 cmd/settings(独立 module)
- 监督进程 cmd/watchdog(-supervise 异常重启)
- 构建脚本 build.bat / NSIS 安装包 deploy/、便携版 portable/
- 架构与 MVP 计划文档 docs/、阶段 0-4 验收记录 deploy/acceptance-0-4.md
2026-08-05 00:42:45 +08:00

184 lines
6.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package windows
// crashguard.go — 进程级崩溃捕获(取证)。
//
// 目标:主进程是托盘常驻程序(-H windowsgui,无控制台)。一旦发生
// 未被 recover 的 Go panic,或 C 层原生异常(access violation 等),
// 进程会静默消失,无任何证据。本模块提供三道防线:
//
// 1. AddVectoredExceptionHandler(VEH):捕获原生异常(access violation、
// illegal instruction、stack overflow 等),将异常代码/地址写入崩溃日志。
// ⚠️ 必须用 VEH 而非 SetUnhandledExceptionFilter:Go runtime 在 Windows
// 上会安装自己的异常处理链,SetUnhandledExceptionFilter 可能永不被调用。
// 2. crash.log 与 app.log / heartbeat 配合,可在进程消失后判定死因:
// 有崩溃记录 → 自身崩溃;无崩溃记录且心跳停止但无 bye → 被外部强杀。
// 3. Go panic(runtime panic,不触发 VEH)→ 必须靠各 goroutine 的
// defer recover 调用 LogGoPanic 记录(见各调用点)。
import (
"fmt"
"os"
"path/filepath"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
)
var (
crashKernel32 = syscall.NewLazyDLL("kernel32.dll")
procSetUnhandledExceptionFilter2 = crashKernel32.NewProc("SetUnhandledExceptionFilter")
procAddVectoredExceptionHandler = crashKernel32.NewProc("AddVectoredExceptionHandler")
procCreateFileW2 = crashKernel32.NewProc("CreateFileW")
procWriteFile2 = crashKernel32.NewProc("WriteFile")
procCloseHandle2 = crashKernel32.NewProc("CloseHandle")
procGetCurrentProcessId2 = crashKernel32.NewProc("GetCurrentProcessId")
procSetFilePointer = crashKernel32.NewProc("SetFilePointer")
)
// EXCEPTION_CONTINUE_SEARCH:不吞异常,继续查找处理程序(进程最终退出)。
const exceptionContinueSearch = 0x80000001
// exceptionRecord 对应 EXCEPTION_RECORD(仅取所需字段,保持布局兼容)。
type exceptionRecord struct {
code uint32
flags uint32
outerRecord uintptr
addr uintptr
numParams uint32
params [15]uintptr
}
// exceptionPointers 对应 EXCEPTION_POINTERS。
type exceptionPointers struct {
record *exceptionRecord
ctx uintptr
}
var (
crashGuardInstalled atomic.Bool
crashLogPathVal string
crashCallbackPtr uintptr // 回调指针必须保持存活(GC 安全)
crashVehPtr uintptr
crashMu sync.Mutex
)
// InstallCrashGuard 安装崩溃捕获。logPath 为崩溃日志文件路径
// (如 %LOCALAPPDATA%\ZerOriginTool\logs\crash.log)。幂等。
func InstallCrashGuard(logPath string) {
if crashGuardInstalled.Swap(true) {
return
}
if logPath == "" {
return
}
if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
return
}
crashLogPathVal = logPath
// VEH(首选):Go runtime 安装自己的异常链会覆盖 SetUnhandledExceptionFilter,
// VEH 是链式的、可共存,且先于 SEH 触发。
crashVehPtr = syscall.NewCallback(vehHandler)
procAddVectoredExceptionHandler.Call(1, crashVehPtr)
// SEH 兜底(部分场景仍有效)。
crashCallbackPtr = syscall.NewCallback(crashHandler)
procSetUnhandledExceptionFilter2.Call(crashCallbackPtr)
}
// vehHandler 为 AddVectoredExceptionHandler 回调(LONG CALLBACK)。
// 记录异常后返回 EXCEPTION_CONTINUE_SEARCH,交给后续处理(含 Go runtime 与默认流程)。
func vehHandler(ep uintptr) uintptr {
defer func() { _ = recover() }() // 尽力而为,绝不让记录动作再次崩溃
code := uint32(0)
addr := uintptr(0)
if ep != 0 {
rec := (*exceptionPointers)(unsafe.Pointer(ep))
if rec != nil && rec.record != nil {
code = rec.record.code
addr = rec.record.addr
}
}
// 只记录"会终止进程"的严重异常码,减少 Go runtime 正常处理异常时的噪音。
switch code {
case 0xC0000005, // access violation
0xC000001D, // illegal instruction
0xC00000FD, // stack overflow
0xC0000096, // privileged instruction
0xC0000008, // invalid handle
0xC000013A, // ctrl+C (console)
0xC0000142, // DLL init failed
0xC0000409, // fail fast
0xE06D7363: // MSVC C++ exception
pid, _, _ := procGetCurrentProcessId2.Call()
line := fmt.Sprintf("native-crash code=0x%08X addr=0x%X pid=%d ts=%s\n",
code, addr, uint32(pid), time.Now().Format("2006-01-02T15:04:05.000-07:00"))
appendCrashLog(line)
}
return exceptionContinueSearch
}
// crashHandler 为 SetUnhandledExceptionFilter 回调(LONG CALLBACK)。
// 记录异常信息后返回 EXCEPTION_CONTINUE_SEARCH,让系统走默认崩溃流程。
func crashHandler(ep uintptr) uintptr {
defer func() { _ = recover() }() // 尽力而为,绝不让记录动作再次崩溃
code := uint32(0)
addr := uintptr(0)
if ep != 0 {
rec := (*exceptionPointers)(unsafe.Pointer(ep))
if rec != nil && rec.record != nil {
code = rec.record.code
addr = rec.record.addr
}
}
pid, _, _ := procGetCurrentProcessId2.Call()
line := fmt.Sprintf("native-crash code=0x%08X addr=0x%X pid=%d ts=%s\n",
code, addr, uint32(pid), time.Now().Format("2006-01-02T15:04:05.000-07:00"))
appendCrashLog(line)
return exceptionContinueSearch
}
// LogGoPanic 供各 goroutine 的 recover 兜底调用:把 Go panic 信息写入崩溃日志。
func LogGoPanic(where string, r any, stack []byte) {
defer func() { _ = recover() }()
line := fmt.Sprintf("go-panic %s value=%v pid=%d ts=%s\n%s\n",
where, r, os.Getpid(), time.Now().Format("2006-01-02T15:04:05.000-07:00"), stack)
appendCrashLog(line)
}
// CrashLogPath 返回崩溃日志路径(未安装时为 "")。
func CrashLogPath() string {
return crashLogPathVal
}
// appendCrashLog 追加一行到崩溃日志(纯 Win32 写入,崩溃线程上避免 Go 文件层)。
func appendCrashLog(line string) {
crashMu.Lock()
defer crashMu.Unlock()
if crashLogPathVal == "" {
return
}
p, err := syscall.UTF16PtrFromString(crashLogPathVal)
if err != nil {
return
}
// CREATE_ALWAYS(2) | OPEN_ALWAYS(4):使用 OPEN_ALWAYS 追加。
h, _, _ := procCreateFileW2.Call(
uintptr(unsafe.Pointer(p)),
0xC0000000, // GENERIC_READ | GENERIC_WRITE
0x00000001, // FILE_SHARE_READ
0,
0x00000004, // OPEN_ALWAYS
0x00000080, // FILE_ATTRIBUTE_NORMAL
0)
if h == 0 || h == ^uintptr(0) {
return
}
// 定位到文件尾:SetFilePointer 与 GetFileSize 组合。
procSetFilePointer.Call(h, 0, 0, 2) // FILE_END
b := []byte(line)
var written uint32
procWriteFile2.Call(h, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(unsafe.Pointer(&written)), 0)
procCloseHandle2.Call(h)
}