# 提取 kernel32.dll 导出函数
# 使用简单的字符串搜索方法

$dllPath = "C:\Windows\System32\kernel32.dll"
$outputFile = "kernel32_functions_list.txt"

# 读取 DLL 二进制文件
$bytes = [System.IO.File]::ReadAllBytes($dllPath)

# 搜索导出函数名（简单启发式方法）
# 这种方法不完美，但能快速找到大部分函数

Write-Host "🔍 正在扫描 kernel32.dll..." -ForegroundColor Cyan

# 使用 dumpbin 如果可用
$dumpbinPaths = @(
    "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Tools\MSVC\*\bin\Hostx64\x64\dumpbin.exe",
    "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\*\bin\Hostx64\x64\dumpbin.exe"
)

$dumpbin = $null
foreach ($path in $dumpbinPaths) {
    $found = Get-ChildItem -Path $path -ErrorAction SilentlyContinue | Select-Object -First 1
    if ($found) {
        $dumpbin = $found.FullName
        break
    }
}

if ($dumpbin) {
    Write-Host "✅ 找到 dumpbin: $dumpbin" -ForegroundColor Green
    
    # 使用 dumpbin 提取导出函数
    & $dumpbin /exports $dllPath | Out-File -FilePath "kernel32_dumpbin_output.txt" -Encoding UTF8
    
    # 解析输出
    $functions = @()
    $inExports = $false
    
    Get-Content "kernel32_dumpbin_output.txt" | ForEach-Object {
        if ($_ -match "Summary") {
            $inExports = $false
        }
        if ($inExports -and $_ -match '\d+\s+\d+\s+[0-9A-F]+\s+[0-9A-F]+\s+(\w+)') {
            $functions += $matches[1]
        }
        if ($_ -match "ordinal.*name") {
            $inExports = $true
        }
    }
    
    Write-Host "`n✅ 找到 $($functions.Count) 个导出函数`n" -ForegroundColor Green
    
    # 输出为 Rust 格式
    $functions | Sort-Object | ForEach-Object {
        Write-Output "    `"$_`".to_string(),"
    } | Out-File -FilePath "kernel32_rust_vec.txt" -Encoding UTF8
    
    # 输出纯文本列表
    $functions | Sort-Object | Out-File -FilePath $outputFile -Encoding UTF8
    
    Write-Host "📄 已保存到:" -ForegroundColor Yellow
    Write-Host "  - $outputFile (纯文本)" -ForegroundColor Yellow
    Write-Host "  - kernel32_rust_vec.txt (Rust vec 格式)" -ForegroundColor Yellow
} else {
    Write-Host "❌ 未找到 dumpbin 工具" -ForegroundColor Red
    Write-Host "`n请安装 Visual Studio Build Tools 或使用以下替代方法:" -ForegroundColor Yellow
    Write-Host "  1. 在线查看: https://learn.microsoft.com/en-us/windows/win32/apiindex/windows-api-list" -ForegroundColor Yellow
    Write-Host "  2. 使用 objdump: objdump -p C:\Windows\System32\kernel32.dll" -ForegroundColor Yellow
    Write-Host "  3. 使用 Python pefile 库" -ForegroundColor Yellow
}
