崩溃转储格式设计:没有段头的转储文件,和一个不告诉你「已经截断了」的回溯

5 阅读22分钟

崩溃转储格式设计:没有段头的转储文件,和一个不告诉你「已经截断了」的回溯

转储不是「打印一下栈」

设备在现场崩了。你拿到什么,决定了你能不能定位。

最低配的做法是打一行日志:「segfault at 0x1234」。信息量约等于零——你知道崩了,不知道在哪、为什么、当时在干什么。

中等配置是 backtrace() 打一串函数名。这有用,但只在「崩溃原因明显」的时候有用。

真正的转储格式要回答五个问题:

问题需要的数据
崩在哪条指令?PC 寄存器
怎么走到这里的?完整调用链(不是截断的)
当时在操作什么数据?通用寄存器(参数)、栈内容
其他任务在干什么?所有任务的栈快照
这份转储是完整的吗?段头 + 长度 + 校验和

现网框架的情况有点特殊:它没有进程级的 core dump,取而代之的是「硬件现场取证」——把协处理器的寄存器、DM 内存打包成 tar,FTP 上传。

这个反差本身值得说:

一个把「崩溃」理解成「硬件出问题了」的系统,绕开了进程级 core dump。

所以本文分两部分:

  • 框架层的崩溃捕获(osp_dbg.c):只有 backtrace() 的符号文本,没有寄存器、没有栈、没有校验
  • 设计一个真正的转储格式:段头、寄存器段、多任务快照、版本兼容

实测七件事,其中两件是「当前实现」的硬缺陷,五件是「设计一个格式时」必须解决的工程问题。

现状:只有符号文本

osp_dbg.c:386-402:

static void osp_dbg_trace_self(void)
{
    void *trace[100] = {0};
    int trace_size = 0;
    char **messages = NULL;
    int  i = 0;

    trace_size = backtrace(trace, 100);
    messages = (char **)backtrace_symbols(trace, trace_size);

    for (i = 0; i < trace_size; ++i)
    {
       osp_dbg_out(CMD_DEBUG_LEVEL, "[bt] %s\n", messages[i]);
    }

    return;
}

这段代码有五处问题,逐个数:

  1. 只存符号文本,栈的原始字节丢了
  2. messages 从不 free(backtrace_symbols 用 malloc 分配)
  3. messages 不判 NULL(分配失败时直接解引用)
  4. 固定 100 帧,且不报告截断
  5. 信号处理函数收了 ucontext_t* 但完全不用

第 5 条最可惜。看 osp_dbg.c:355-371 和 :411-428:

static void osp_dbg_signal_action_trace(int nr, siginfo_t *info, void *void_context)
{ ... }                                          /* void_context 未使用 */

static void osp_dbg_signal_action_except(int nr, siginfo_t *info, void *void_context)
{
    TASK_STATE(CURRENT_TASKID) = TASK_SUSPEND;
    osp_dbg_call_deathbed_func();
    ...
}                                                /* void_context 未使用 */

三个信号处理函数全部忽略 void_context。

而 void_context 就是 ucontext_t *——里面装着崩溃瞬间的完整寄存器组。sigaction 注册时用了 SA_SIGINFO(osp_dbg.c:441),所以这个参数是有效的。

系统把最有价值的数据递到你手上,你把它扔了。

设计段头:让它能被校验

一个没有段头的二进制文件,和一堆随机字节没有区别。所以第一件事是段头。

struct dump_hdr {
    U32 magic;          /* 'OSPD' / 'OSPE'      */
    U32 version;        /* 1 or 2               */
    U32 hdr_size;       /* sizeof(dump_hdr)     */
    U32 section_count;  /* number of sections   */
    U32 total_len;      /* whole file length    */
    U32 crc32;          /* CRC of the payload   */
    U64 timestamp;      /* when the dump was taken */
};
/* sizeof(struct dump_hdr) = 32 bytes */

六个字段,各管一件事:

字段作用省了会怎样
magic确认「这是一个转储文件」无法区分文件和垃圾
version确认「能不能解析」新版文件被旧工具误读
hdr_size「头部多长,负载从哪开始」无法向后兼容
section_count「有几个段」无法遍历
total_len「文件应该多长」截断检测不了
crc32「内容对不对」位翻转检测不了

五种破坏的检测

写一个 384 字节的文件(32 字节头 + 352 字节负载),三个段:REGS(64) / TASKS(128) / BACKTRACE(64)。

wrote test.bin: 384 bytes total, 352 payload bytes, CRC = 0x45A9A1E3

-- test 1: the intact file --
      parser: header OK  magic=0x4F535044 version=1 sections=3 total_len=384 CRC=0x45A9A1E3
      parse result: 0 (ACCEPTED)
      timestamp read back: 0x0001A2B3C4D5E6F7
      section table:
        REGS         type=1 offset=128 length=64 crc=0xCBD9ECF0
        TASKS        type=2 offset=192 length=128 crc=0x2F1EADF9
        BACKTRACE    type=3 offset=320 length=64 crc=0x68727A57

-- test 2: corrupt ONE payload byte (offset 40 into the payload) --
      byte at file offset 72 changed 0x00 -> 0x01
      parser: CRC MISMATCH expected 0x45A9A1E3 got 0x8B60D5F4 -> reject
      parse result: -6 (REJECTED)
      => a single flipped bit anywhere in the payload is detected.

-- test 3: wrong magic --
      parser: BAD MAGIC 0xDEADBEEF (expected 0x4F535044 or 0x4F535045) -> reject
      parse result: -2 (REJECTED)

-- test 4: unsupported version --
      parser: UNSUPPORTED VERSION 7 -> reject
      parse result: -3 (REJECTED)

-- test 5: truncated file (the classic case a checksum must catch) --
      parser: total_len 384 > file size 192 -> reject (truncated)
      parse result: -5 (REJECTED)

五种破坏全部检出,各自有不同的错误码。

注意 test 5 用的是 total_len 而不是 CRC。截断的文件往往是「前 N 字节完整」,CRC 只覆盖剩下部分所以可能通过——长度检查才是截断的正解,CRC 检查的是内容。

寄存器段:为什么必须存原始寄存器

结构

ARM64 的寄存器组:

struct dump_regs {
    U64 x[31];     /* x0..x30        */
    U64 sp;        /* stack pointer  */
    U64 pc;        /* program counter*/
    U64 pstate;    /* processor state*/
};
/* sizeof = 272 bytes (34 fields) */

往返测试:

round-trip through a byte buffer:
  x[0]  written 0x1111000000000000  read 0x1111000000000000  OK
  x[30] written 0x2F2F1E1E1E1E1E1E  read 0x2F2F1E1E1E1E1E1E  OK
  sp    written 0x0007FFF0000FE000  read 0x0007FFF0000FE000  OK
  pc    written 0x00000000AAAA8000  read 0x00000000AAAA8000  OK
  pstate written 0x0000000000000605 read 0x0000000000000605  OK

  fields compared : 34
  matched         : 34
  mismatched      : 0
  match rate      : 100.00%

为什么不能只存符号文本

实验给出了五条理由,值得完整列出:

why the dump format MUST have a register section:
  1. A backtrace is a list of RETURN ADDRESSES.  Without the
     registers there is no way to tell a return address from a
     data value, so a corrupted stack produces a plausible but
     completely wrong call chain.
  2. pc tells you WHERE the crash happened.  The symbol text of
     backtrace() gives the call chain but the top frame may be
     missing (see EXP-4), so the faulting instruction is lost.
  3. sp tells you HOW MUCH STACK was used and lets a debugger
     unwind the frames itself, instead of trusting a truncated
     symbol table.
  4. x0..x30 carry the arguments of the crashing function.
     For an assert or a null-pointer dereference the faulting
     pointer is almost always in x0 or x1 -- and that is exactly
     the information the current code throws away.
  5. pstate tells you the exception level and the interrupt mask
     state, which distinguishes a deliberate abort from a
     hardware fault.

第 4 条最实用。 空指针解引用时,那个指针几乎总在 x0 或 x1。

所以「segfault at 0x1234」这句话里虽然没有「哪个变量是空指针」,但 x0 = 0x1234 就告诉你函数第一个参数是空。这是定位问题的关键一步,而当前实现把它扔了。

第 1 条最反直觉。 栈里混合着返回地址和普通数据。没有 sp/pc 作为锚点,你无法判断「栈上某个 8 字节值,是返回地址还是一个恰好落在代码段的整数」。

多任务快照:崩溃时其他任务在干什么

单任务转储只回答「谁崩了」,不回答「为什么崩」。很多崩溃是别的任务先破坏了共享状态,然后当前任务撞上了。

所以要存所有任务的栈快照:

struct task_sect_hdr {
    U32 task_id;
    U32 stack_size;
    U32 stack_crc32;
    U32 pad;
};
/* sizeof = 16 bytes */

实测 8 个任务(栈深 100..800 字节):

task_id  | stack_size  | crc32          | file offset
----------+--------------+----------------+-------------
100      | 100         | 0x7CC8939E       | 32
101      | 200         | 0x4A3B7A42       | 148
102      | 300         | 0xDB27E549       | 364
103      | 400         | 0x45BCA4B4       | 680
104      | 500         | 0xDA4F3862       | 1096
105      | 600         | 0x00886CED       | 1612
106      | 700         | 0x2D953E91       | 2228
107      | 800         | 0x5134497B       | 2944

total file size : 3760 bytes = header 32 + 128 sub-headers + 3600 bytes of stacks
  header overhead     : 32 bytes (0.9% of the file)
  per-task overhead   : 128 bytes (3.4% of the file)

读回后逐任务校验:

    task 100  stack_size=100  stored_crc=0x7CC8939E computed_crc=0x7CC8939E  OK
    ...
    task 107  stack_size=800  stored_crc=0x5134497B computed_crc=0x5134497B  OK
  all task CRCs valid : YES
  bytes consumed      : 3760 of 3760

开销只有 4.3%(32 + 128 字节 over 3760)。对一个几 KB 到几 MB 的转储文件,每个段存 CRC 的成本可以忽略,收益是「知道哪个段坏了」。

如果整个文件只有一个 CRC,坏了之后你不知道坏在哪一段,只能整份丢弃。分段 CRC 让你能部分恢复——比如 TASKS 段坏了但 REGS 段完好,还能看到崩溃点。

缺陷一:100 帧的截断是静默的

void *trace[100] 固定 100 帧。实测一个 500 层的调用栈:

applying the source's limit:
  stack depth            : 500 frames
  trace[] array size     : 100
  frames actually captured: 100
  frames LOST            : 400
  percentage lost        : 80.0%

the captured range is frames 0..99, i.e. func_500+0x00 ... func_401+0xB5
the LOST range is frames 100..499, i.e. func_400+0xBC ... func_001+0xA5

这里必须澄清一个容易搞反的点。

backtrace() 返回的数组从「调用 backtrace() 的那个函数」开始,向外展开。所以 trace[0] 是最内层(崩溃点附近),trace[99] 是第 99 层调用者。

所以「取前 100 帧」= 保留最内层 100 帧——这是对的。崩溃点和它的直接调用者是最有价值的信息,这个截断策略正确。

(实验程序在这一节的叙述文字说「保留了最外层 100 帧、丢掉了最内层 400 帧,方向反了」,但它自己列的 frame 0 : func_500 / frame 99 : func_401 明明是最内层——文字与数据矛盾,以数据为准。)

真正的问题是:截断是静默的。

  Note also that backtrace() on glibc walks the frame chain
  from the CURRENT frame downwards; the entry count is bounded
  by the array, so a deep stack is silently truncated with no
  indication that anything was dropped.

backtrace(trace, 100) 返回 100,你无法区分这两种情况:

  • 栈真的只有 100 层(完整)
  • 栈有 500 层,截断了 400 层

这个区别很重要:

情况含义
完整 100 帧调用链是完整的,看到的最外层就是 main
截断的 100 帧最外层 400 帧被丢了,你看到的「最外层」是假的

如果不加判断,你会以为 func_401 是启动路径上的某个函数,然后花时间去看一个与崩溃无关的调用点。

修法

backtrace() 没有「是否截断」的返回值,所以要自己加一帧的余量来判断:

#define BT_MAX 101                  /* 多要一帧 */
void *trace[BT_MAX];

trace_size = backtrace(trace, BT_MAX);

int truncated = 0;
if (trace_size == BT_MAX) {
    truncated = 1;
    trace_size = BT_MAX - 1;       /* 丢掉多余的一帧 */
}

/* 转储里必须记下这个标志 */
hdr.flags |= truncated ? DUMP_FLAG_BT_TRUNCATED : 0;

一帧的代价,换来「知道截断了」。

缺陷二:帧指针链在 -O2 下会断

这是栈回溯最根本的困难。

两种回溯策略:

  • chain:跟随 rbp 链。每个函数栈帧保存「调用者的 rbp」和「返回地址」,链是精确的。
  • scan:扫描整个栈,找出所有「看起来像返回地址」的值(落在代码段内的指针)。

实测:

=== case A: rbp is a proper frame pointer ===
  frame-pointer chain : 60 frames recovered (of 60 real)
  stack scan          : 12 candidate return addresses
  the chain is exact: 60 frames, and it establishes the ORDER.

=== case B: rbp is a general purpose register (-O2 default) ===
  frame-pointer chain : 2 frames recovered
  stack scan          : 12 candidate return addresses

60 帧塌成 2 帧。

原因:

The chain depends on every function SAVING AND RESTORING rbp.
With -fomit-frame-pointer (the default at -O2) the compiler
uses rbp as a general purpose register, so the chain is garbage.

-O2 默认开启 -fomit-frame-pointer——把一个通用寄存器(x86 的 rbp / ARM 的 x29)解放出来给编译器用。代价是栈帧之间不再有链。

  the chain collapses from 60 frames to 2: the first link
  works, the second one points into garbage and the walk stops.
  The unwind does not report an error -- it just returns a short
  list, and the caller has no way to tell that it is short.

「不报错,只是返回一个短列表」——这是第二个静默截断,而且比 100 帧那个更隐蔽:你连「应该有 60 帧」都不知道。

scan 策略能找到 12 个候选,但:

  the scan still finds 12 candidates, but it cannot tell which
  are real return addresses and which are pointers into the text
  segment, and it cannot establish the ORDER.

顺序丢失是致命的。调用链的价值一半在于「谁调用了谁」,只剩一个集合没有意义。

这对「转储格式」的启示

glibc 的 backtrace() 内部用链策略,链不可用时回退到 .eh_frame(.eh_frame 是编译器生成的展开表,-fasynchronous-unwind-tables 开启)。回退不一定成功。

所以:不要在崩溃时做展开。存原始数据,事后展开。

  The decisive point for the dump FORMAT: a format that stores
  the raw stack bytes AND the registers lets an offline tool try
  every strategy -- chain, .eh_frame, scan -- with full context.
  The current format stores only the symbol TEXT, so the stack
  bytes are gone and no strategy can be applied after the fact.
存什么事后能做什么
符号文本只能看,不能重算
符号文本 + 寄存器 + 栈字节可以试所有展开策略,可以换调试器,可以换符号表版本

「转储格式的价值在于保留足够的信息让事后分析成为可能」——这是本文最重要的一句话。转储不是给人看的报告,是给工具用的输入。

缺陷三:backtrace_symbols 返回 NULL 导致二次崩溃

    char **messages = backtrace_symbols(trace, trace_size);
    for (i = 0; i < trace_size; ++i)
    {
       osp_dbg_out(CMD_DEBUG_LEVEL, "[bt] %s\n", messages[i]);   /* 不判 NULL */
    }

backtrace_symbols 内部对每一帧 malloc 一个字符串。分配失败返回 NULL。

而崩溃时 malloc 失败的概率远高于平时:

  backtrace_symbols() allocates one string per frame and returns
  NULL when the allocation fails.  malloc() inside a signal
  handler is especially likely to fail, because the handler may
  be running on the very heap that is exhausted -- and on glibc
  malloc() is not async-signal-safe.

两个理由:

  1. 堆可能已经耗尽——而这正是崩溃的原因之一
  2. malloc 不是 async-signal-safe——在信号处理函数里调用它本身就是未定义行为(它可能正在被中断打断的地方持锁)

二次崩溃的路径

    messages[0] where messages == NULL
    -> the CPU computes the address 0x00000000 + 0*8 = 0x00000000
    -> the load reads from the NULL page
    -> on Linux with vm.mmap_min_addr = 65536 this raises
       SIGSEGV inside the SIGSEGV handler -> the process dies
       with no dump at all.

在 SIGSEGV 处理函数里再触发一次 SIGSEGV。

Linux 的默认行为是:如果信号在处理过程中再次触发同一个信号,且没有 SA_NODEFER,该信号被屏蔽,进程直接终止。所以:

  • 第一次崩溃的全部努力(deathbed 回调、栈打印)都可能还没写完

  • 进程死得干干净净,一个字节的转储都没有

      note that the C standard does not even guarantee the
      crash is at address 0: dereferencing NULL is UNDEFINED
      BEHAVIOUR, so the faulting address may be 0, 8, or
      something else entirely depending on the compiler's
      codegen and the CPU.
    

顺带:messages 从不 free

the leak that never happens:
    the return value of backtrace_symbols() is NEVER freed.
    backtrace_symbols() allocates with malloc(); the caller
    owns the result and must free() it.
    modelled: 100 crashes x 480 bytes of symbol text = 48000 bytes
    leaked per crash cycle.

100 帧 × 每帧约 480 字节符号文本 = 每次崩溃泄漏 48 KB。

单次崩溃不重启,泄漏无所谓。但如果信号处理函数重新挂载自己(很多实现这样做,为了捕获多次崩溃),就会持续泄漏。而泄漏又增加下次 malloc 失败的概率——两个 bug 互相放大。

缺陷四:文件名没有时间戳和序号

业务侧的转储文件名是固定的。

-- the source's naming scheme, 5 successive dumps --
  dump #1 : hpp_dump.tar.gz           <- written
  dump #2 : hpp_dump.tar.gz           <- OVERWRITES the previous one
  dump #3 : hpp_dump.tar.gz           <- OVERWRITES the previous one
  dump #4 : hpp_dump.tar.gz           <- OVERWRITES the previous one
  dump #5 : hpp_dump.tar.gz           <- OVERWRITES the previous one

  all 5 names are identical
  -> every dump replaces the previous one.  Only ONE crash
     report ever survives, and it is whichever crash happened
     LAST.  The first crash -- usually the one with the most
     useful context -- is the one that gets overwritten.

五次崩溃,只剩最后一份。

这个问题的恶劣之处:第一次崩溃信息量最大。第一次崩溃往往发生在「状态还干净」的时候,第二次、第三次崩溃可能是第一次崩溃留下的烂摊子导致的。你留住的恰恰是最没用的那一份。

加上时间戳和序号:

  dump #1 : hpp_dump_1767225643200_0001.tar.gz
  dump #2 : hpp_dump_1767225686400_0002.tar.gz
  dump #3 : hpp_dump_1767225729600_0003.tar.gz
  dump #4 : hpp_dump_1767225772800_0004.tar.gz
  dump #5 : hpp_dump_1767225816000_0005.tar.gz

  all 5 names are distinct.

命名要满足四条

  1. monotonically increasing sequence number, so the ORDER of
     the crashes is recoverable even if the timestamps are not
     trusted;
  2. a timestamp with enough resolution to separate two crashes
     that happen in the same second;
  3. the process id, so a crash of a different instance does not
     overwrite the previous one;
  4. no overwrite on upload: the FTP upload must use a unique
     remote name as well, otherwise the collision just moves
     from the local disk to the server.

四条都很实在,尤其第 4 条——本地名字唯一了,但 FTP 上传时用了固定远端名,碰撞只是从本地转移到了服务器。这是个很容易漏的环节。

第 1 条(序号)和第 2 条(时间戳)为什么都要?因为:

  • 设备可能没有 RTC,重启后时间回到 1970
  • 时间可能被 NTP 往回校
  • 序号是单调的,不受时钟影响

序号保证顺序,时间戳保证关联(和日志/告警对上),两者不能互相替代。

缺陷五:版本演进——magic 和 version 必须独立

格式一定会演进。加一个字段就得升版本。问题是:旧工具能不能读新文件?

实验设计了两版头:

v1 header: magic, version, hdr_size, section_count, total_len,
          crc32, timestamp                       (32 bytes)
v2 header: the same fields PLUS flags and build_id (40 bytes)
v2 magic  : 0x4F535045 ('OSPE'), v1 magic : 0x4F535044 ('OSPD')

策略一:拒绝未知版本

-- strategy 1: the old parser REJECTS an unknown version --
  the old parser reads: magic=0x4F535045 version=2 hdr_size=40
  magic is 0x4F535045 -> REJECTED (unknown magic)
  version is 2 -> REJECTED (unknown version)
  => the old parser rejects the file cleanly and refuses to
     guess.

干净、安全。代价是旧工具读不了任何新转储——现场设备升级了固件,工程师手上的工具就得跟着升级。

策略二:跳过不认识的字段(这个实现是错的)

-- strategy 2: the old parser SKIPS the unknown fields --
  the old parser reads the first 32 bytes as a v1 header.
  it sees version = 2, which it does not know, BUT it can
  still locate the payload, because hdr_size (40) and
  total_len (104) are self-describing.
  -> the payload starts at offset 40, which is PAST the end of
     the v2 header (40 bytes).  So the old parser would read
     the payload from the WRONG offset and compute a CRC over
     the wrong bytes.
  the CRC check then FAILS, and the file is rejected -- by
  accident rather than by design.

「靠 CRC 失败来拒绝」是偶然,不是设计。 如果 CRC 碰巧对上(概率 2^-32,但更可能是「新字段恰好不影响 CRC 覆盖范围」),就会用错误的数据继续跑。

策略三:让 hdr_size 自描述

-- the design that actually works --
  hdr_size = 40 -> the payload starts at offset 40
  CRC over [offset 40, 104) = 0x100ECE8C, stored = 0x100ECE8C -> MATCH
  a v1 reader that honours hdr_size reads the payload
  correctly and ignores flags and build_id.

关键设计:

    magic     : identifies the file format, never changes
    version   : the schema version, bumped on every change
    hdr_size  : the size of THIS header, so a reader can skip
                any extra fields it does not understand
    payload_offset = hdr_size  -> the reader seeks to hdr_size

三条规则:

  1. magic 标识「文件格式」,永不变。v1 和 v2 是同一个格式的不同版本,magic 应该相同。
  2. version 标识「schema 版本」,每次变更都升。
  3. payload_offset = hdr_size,让读取方知道负载从哪开始,与版本无关。

实验里的 v2 用了新 magic(0x4F535045),这是个设计错误——它让 magic 承担了版本区分的职责,导致「识别格式」和「识别版本」两件事混在一起。正确做法是 magic 不变,只用 version + hdr_size 区分。

加字段时的两条规则

变更类型做法旧工具能否读
在头部末尾加字段升 version,改 hdr_size✅ 能(按 hdr_size 跳过)
在段表中加新段类型加一个 type,放入新段✅ 能(不认识的 type 就跳过)
修改已有字段的语义必须换 magic❌ 不能(明确拒绝)

「只增不改」 是格式演进的黄金规则。字段语义变了就必须当作新格式。

一份可用的转储格式

把上面的教训收成一个文件布局:

+----------------------------------+  0
| dump_hdr (32 或 40 字节)          |
|   magic, version, hdr_size,      |
|   section_count, total_len,      |
|   crc32(payload), timestamp      |
+----------------------------------+  hdr_size
| section_table[section_count]     |
|   每项: type, offset, length,    |
|         crc32                    |
+----------------------------------+  段表末尾
| SEG 1: REGS                      |
|   dump_regs { x[31], sp, pc,     |
|               pstate }  (272 B)  |
+----------------------------------+
| SEG 2: TASKS                     |
|   task_sect_hdr[task_count]      |
|   每项: task_id, stack_size,     |
|         crc32, pad   (16 B)      |
|   各任务的栈字节                  |
+----------------------------------+
| SEG 3: BACKTRACE                 |
|   原始栈字节 + sp/pc 锚点         |
|   (不是符号文本!)              |
+----------------------------------+
| SEG 4: FLAGS                     |
|   bt_truncated / heap_exhausted  |
|   / assert_vs_fault              |
+----------------------------------+

四条设计决定:

  1. 存原始栈字节,不存符号文本。符号在事后用 addr2line / gdb 解,可以在另一台机器、用另一个版本的符号表做。
  2. 每个段有独立 CRC。一个段坏了不影响其他段。
  3. FLAGS 段显式记录「哪些信息不完整」。截断、堆耗尽、展开失败——这些「元信息」和数据一样重要。
  4. payload_offset 恒等于 hdr_size。向后兼容的唯一可靠机制。

七个缺陷汇总

#位置 / 设计缺陷后果
1osp_dbg.c:394messages 不判 NULL二次崩溃,转储全丢
2osp_dbg.c:394messages 从不 free每次崩溃泄漏 48 KB
3osp_dbg.c:391固定 100 帧且不报截断不知调用链是否完整
4全部信号处理函数忽略 ucontext_t*寄存器全丢,崩溃点无法确定
5转储格式无段头、无 magic/version/CRC截断与位翻转无法检出
6业务侧文件名无时间戳无序号只剩最后一次崩溃
7转储内容无多任务快照看不出「谁先破坏了共享状态」

第 1 和第 4 并列最严重:一个让转储完全丢失,一个让转储失去定位能力。

工程落地清单

  1. 信号处理函数必须用 ucontext_t*。系统把崩溃瞬间的寄存器递给你,不用就是浪费。SA_SIGINFO 已经注册了,参数就在那里。

  2. backtrace_symbols 的返回值必须判 NULL 并用完 free。在信号处理函数里调 malloc 本身就不安全,要判空;返回的数组是 malloc 的,要 free。

  3. 更彻底:崩溃时不展开符号。存原始栈字节 + 寄存器,事后离线展开。这样信号处理函数里没有 malloc、没有动态内存。

  4. 截断必须显式记录。多要一帧判断是否装满,把 bt_truncated 写进转储的 flags 段。

  5. 转储文件必须有段头:magic + version + hdr_size + section_count + total_len + crc32。缺一个就少一种检测能力。

  6. 每个段独立 CRC。整份一个 CRC 只能判断「全坏」,分段 CRC 能判断「哪段坏」,支持部分恢复。

  7. payload_offset = hdr_size,不要用固定的 sizeof(struct)。这是向后兼容的唯一可靠机制。

  8. magic 标识格式(永不变),version 标识 schema(每次升)。两件事不要混在一个字段里。

  9. 格式演进遵守「只增不改」。加字段升版本、改语义换 magic。

  10. 文件名要带时间戳 + 单调序号 + pid。序号保证顺序(不依赖时钟),时间戳保证关联,pid 隔离多实例。

  11. FTP 上传的远端文件名也要唯一。否则碰撞只是从本地转移到服务器。

  12. 存多任务快照。崩溃常常是「别的任务先破坏了共享状态」,单任务转储看不出这个。

  13. 信号处理函数里只调 async-signal-safe 的函数。malloc、printf、free 都不在列表里。要写文件用 write,要格式化用栈上的 snprintf。

附:实验环境

项值
编译器MinGW gcc 8.1.0(i686,32 位)
主机Windows,12 逻辑核
源码基线私有工程 platform/osp_nocompile/osp_dbg.c(595 行)
实验程序e28_dump.c(8 节)

沙箱适配说明:

源码机制沙箱实现原因
ucontext_t 寄存器捕获dump_regs 结构体往返读写验证MinGW 无 ucontext_t、无 sigaction
真实 backtrace()模拟 500 层调用栈 + 复刻 100 帧上限无跨平台 backtrace_symbols
帧指针链 vs 扫描两种策略的等价模型同上
backtrace_symbols 返回 NULL检查并报告(不真崩)避免实验程序崩溃
CRC32真实计算纯算法,与平台无关
段头解析真实实现文件 I/O 完全真实

如实修正:EXP-4 的实验程序叙述文字称「保留了最外层 100 帧、丢掉了最内层 400 帧,方向反了」,但其自身数据(frame 0 : func_500 … frame 99 : func_401)显示保留的是最内层 100 帧。以数据为准:截断方向是对的,真正的缺陷是「截断不被告知」。

声明:所有产品名、模块代号、业务语义均已脱敏,文中仅讨论通用 Linux C 编程与崩溃分析。源码引用保留原始行号以便对照。