You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写脚本自动执行GDB崩溃分析流程并生成报告?

自动GDB崩溃分析脚本实现(Ubuntu 20.04)

下面提供两种可行的实现方案,帮你自动完成GDB加载程序、触发崩溃分析并生成报告的全流程:

方案一:Shell + GDB脚本组合(轻量易维护)

1. 编写GDB命令脚本(auto_analyze.gdb)

这个脚本定义GDB需要执行的操作逻辑:

# 加载你的Python崩溃分析程序(替换为实际绝对路径)
source /home/your_user/path/to/your_analysis_script.py

# 根据输入文件执行目标程序
if "${INPUT_FILE}" != ""
    run < ${INPUT_FILE}
else
    run
end

# 仅当程序崩溃停止时执行分析命令
if $_is_stopped
    analyze
end

quit

2. 编写Shell执行脚本(auto_crash_analyzer.sh)

负责接收参数、替换GDB脚本变量并调用GDB:

#!/bin/bash

# 参数校验
if [ $# -lt 1 ]; then
    echo "用法: $0 <目标程序路径> [崩溃触发输入文件路径]"
    exit 1
fi

TARGET=$1
INPUT=${2:-""}
REPORT="crash_report_$(date +%Y%m%d_%H%M%S).txt"

# 替换GDB脚本中的占位变量,执行GDB并导出报告
sed "s/\${INPUT_FILE}/${INPUT}/" auto_analyze.gdb | gdb -batch -x - "${TARGET}" > "${REPORT}"

echo "分析报告已生成: ${REPORT}"

使用方式

  1. 给Shell脚本添加可执行权限:
chmod +x auto_crash_analyzer.sh
  1. 运行脚本:
# 无输入文件的情况
./auto_crash_analyzer.sh ./your_target_app

# 带崩溃输入文件的情况
./auto_crash_analyzer.sh ./your_target_app ./crash_input.txt

方案二:纯Python脚本(适合Python生态集成)

如果需要和现有Python工具链整合,用Python脚本实现更灵活:

#!/usr/bin/env python3
import subprocess
import sys
from datetime import datetime

def main():
    # 参数校验
    if len(sys.argv) < 2:
        print("用法: python3 auto_analyze.py <目标程序路径> [崩溃触发输入文件路径]")
        sys.exit(1)

    target = sys.argv[1]
    input_file = sys.argv[2] if len(sys.argv) > 2 else ""
    report_path = f"crash_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"

    # 构建GDB执行命令序列
    gdb_commands = [
        # 替换为你的Python分析脚本绝对路径
        "source /home/your_user/path/to/your_analysis_script.py",
    ]

    # 添加运行命令(处理输入文件)
    if input_file:
        gdb_commands.append(f"run < {input_file}")
    else:
        gdb_commands.append("run")

    # 崩溃时执行分析并退出
    gdb_commands.extend([
        "if $_is_stopped",
        "    analyze",
        "end",
        "quit"
    ])

    # 调用GDB并捕获输出
    result = subprocess.run(
        ["gdb", "-batch", "-ex", "\n".join(gdb_commands), target],
        capture_output=True,
        text=True
    )

    # 写入报告文件
    with open(report_path, "w") as f:
        f.write(result.stdout)
        if result.stderr:
            f.write("\n--- GDB 错误输出 ---\n")
            f.write(result.stderr)

    print(f"分析报告已生成: {report_path}")

if __name__ == "__main__":
    main()

使用方式

  1. 替换脚本中的Python分析程序路径
  2. 运行脚本:
python3 auto_analyze.py ./your_target_app ./crash_input.txt

关键注意事项

  • 务必使用绝对路径指定你的Python分析脚本,避免GDB因工作目录问题找不到文件
  • GDB内置变量$_is_stopped用于判断程序是否因崩溃停止,确保只有崩溃时才执行analyze
  • -batch参数让GDB以非交互模式运行,执行完所有命令后自动退出
  • 报告文件用时间戳命名,避免覆盖历史分析结果

内容的提问来源于stack exchange,提问作者Monere Morgul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 21:05:37