操作`ucontext_t`的正确方法是什么?

时间:2013-09-20 09:55:39

标签: c callstack ucontext

Redis 的源代码,在文件 src / debug.c 中,它使用backtrace()来记录调用堆栈。在这些操作中,我注意到getMcontextEip(),在Linux中似乎是这样的:

  static void *getMcontextEip(ucontext_t *uc) {
    /* Linux */
  #if defined(__i386__)
    return (void*) uc->uc_mcontext.gregs[14]; /* Linux 32 */
  #elif defined(__X86_64__) || defined(__x86_64__)
    return (void*) uc->uc_mcontext.gregs[16]; /* Linux 64 */
  #elif defined(__ia64__)                     /* Linux IA64 */
    return (void*) uc->uc_mcontext.sc_ip;
  #endif
  }

所有这些背后的机制是:当有信号(即SIGFPE)时,它将被捕获并尝试将调用堆栈记录到文件:

void log_stack_trace(ucontext_t *uc) {
    void *trace[100];
    int fd = open(file);
    int trace_size = backtrace(trace, 100); /* get call stack */

    /* overwrite sigaction with caller's address */
    if (getMcontextEip(uc) != NULL)
        trace[1] = getMcontextEip(uc);

    backtrace_symbols_fd(trace, trace_size, fd); /* log to file */
}

来自评论,我们知道它的目的是用调用者的地址覆盖sigaction ,但有没有提示这样做?我模拟了一个SIGFPE信号,并在GDB中对其进行了调试,ucontext_t似乎是这样的:

(gdb) p *uc
$6 = {
  uc_flags = 0, 
  uc_link = 0x0, 
  uc_stack = {
    ss_sp = 0x0, 
    ss_flags = 2, 
    ss_size = 0
  }, 
  uc_mcontext = {
    gregs = {51, 0, 123, 123, 0, 0, -1073745320, -1073745376, -1208258560, 0, -1073745852, 5, 0, 0, 134514547, 115, 2163270, -1073745376, 123}, 
    fpregs = 0xbfffefb0, 
    oldmask = 0, 
    cr2 = 0
  }, 
  uc_sigmask = {
    __val = {0, 0, 44472, 8441088, 0, 0, 4294902655, 4294901760, 4294967295, 0 <repeats 23 times>}
  }, 
  __fpregs_mem = {
    cw = 0, 
    sw = 0, 
    tag = 895, 
    ipoff = 0, 
    cssel = 0, 
    dataoff = 0, 
    datasel = 0, 
    _st = {{
        significand = {0, 0, 8064, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }, {
        significand = {0, 0, 0, 0}, 
        exponent = 0
      }}, 
    status = 0
  }
}

getMcontextEip中,它只返回i386平台上的uc->uc_mcontext.gregs[14],为什么会这样做?为什么 14 而不是其他人(有19个元素)?

1 个答案:

答案 0 :(得分:1)

我认为“14”是EIP寄存器,因此当前指令指针(也就是程序计数器)是您收到信号时需要知道调用堆栈位置的起点。

您可能会发现V8如何将其用于其采样分析器: http://code.google.com/p/v8/source/browse/branches/bleeding_edge/src/sampler.cc?spec=svn16109&r=16109