# 诊断 test_real_hello.exe 崩溃
# 使用 Windows 事件日志和调试工具

Write-Host "=== 诊断 test_real_hello.exe 崩溃 ===" -ForegroundColor Cyan

# 1. 检查文件是否存在
if (-not (Test-Path "test_real_hello.exe")) {
    Write-Host "❌ test_real_hello.exe 不存在，先生成..." -ForegroundColor Yellow
    .\target\release\ts-native.exe test_real_hello.ts
}

# 2. 使用 PowerShell 捕获异常
Write-Host "`n📊 尝试运行并捕获异常..." -ForegroundColor Cyan

try {
    $process = Start-Process -FilePath ".\test_real_hello.exe" -NoNewWindow -Wait -PassThru
    Write-Host "退出码: $($process.ExitCode)" -ForegroundColor Yellow
    
    if ($process.ExitCode -eq 0xC0000005) {
        Write-Host "`n❌ 检测到 ACCESS_VIOLATION (0xC0000005)" -ForegroundColor Red
        Write-Host "  这意味着程序访问了无效内存地址" -ForegroundColor Yellow
        Write-Host "`n可能的原因:" -ForegroundColor Cyan
        Write-Host "  1. 空指针解引用" -ForegroundColor White
        Write-Host "  2. 访问未分配的内存" -ForegroundColor White
        Write-Host "  3. 栈溢出" -ForegroundColor White
        Write-Host "  4. .pdata 节区异常处理数据不正确" -ForegroundColor White
    }
} catch {
    Write-Host "❌ 异常: $_" -ForegroundColor Red
}

# 3. 检查 Windows 事件日志
Write-Host "`n📋 检查 Windows 应用程序事件日志..." -ForegroundColor Cyan
$events = Get-WinEvent -FilterHashtable @{
    LogName='Application'
    Level=2
    StartTime=(Get-Date).AddMinutes(-5)
} -ErrorAction SilentlyContinue | Where-Object { $_.Message -match "test_real_hello" }

if ($events) {
    Write-Host "找到 $($events.Count) 个相关事件:" -ForegroundColor Yellow
    foreach ($event in $events) {
        Write-Host "`n时间: $($event.TimeCreated)" -ForegroundColor White
        Write-Host "消息: $($event.Message)" -ForegroundColor White
    }
} else {
    Write-Host "未找到相关事件日志" -ForegroundColor Yellow
}

# 4. 使用 dumpbin 检查 PE 结构
Write-Host "`n🔍 检查 PE 结构..." -ForegroundColor Cyan
$dumpbinPath = "C:\Program Files\Microsoft Visual Studio\2022\Professional\VC\Tools\MSVC\14.44.35207\bin\Hostx64\x64\dumpbin.exe"

if (Test-Path $dumpbinPath) {
    Write-Host "`n节区信息:" -ForegroundColor Cyan
    & $dumpbinPath /headers test_real_hello.exe 2>&1 | Select-String "SECTION HEADER" -Context 0,1 | Select-Object -First 10
    
    Write-Host "`n导入表:" -ForegroundColor Cyan
    & $dumpbinPath /imports test_real_hello.exe 2>&1 | Select-Object -First 20
}

Write-Host "`n✅ 诊断完成" -ForegroundColor Green
