title: How to get a call stack backtrace? (deeply embedded, no library support)
body: <p>I want my exception handlers and debug functions to be able to print call stack backtraces, basically just like the backtrace() library function in glibc. Unfortunately, my C library (Newlib) doesn't provide such a call. </p>
  
  <p>I've got something like this:</p>
  
  <pre><code>#include &lt;unwind.h&gt // GCC's internal unwinder, part of libgcc
  _Unwind_Reason_Code trace_fcn(_Unwind_Context *ctx, void *d)
  {
      int *depth = (int*)d;
      printf("\t#%d: program counter at %08x\n", *depth, _Unwind_GetIP(ctx));
      (*depth)++;
      return _URC_NO_REASON;
  }
  
  void print_backtrace_here()
  {
      int depth = 0;
      _Unwind_Backtrace(&trace_fcn, &depth);
  }
  </code></pre>
  
  <p>which basically works but the resulting traces aren't always complete. For example, if I do</p>
  
  <pre><code>int func3() { print_backtrace_here(); return 0; }
  int func2() { return func3(); }
  int func1() { return func2(); }
  int main()  { return func1(); }</code></pre>
  
  <p>the backtrace only shows func3() and main(). (This is obv. a toy example, but I have checked the disassembly and confirmed that these functions are all here in full and not optimized out or inlined.)</p>
  
  <p><strong>Update:</strong> I tried this backtrace code on the old ARM7 system but with the same (or at least, as equivalent as possible) compiler options and linker script and it prints a correct, full backtrace (i.e. func1 and func2 aren't missing) and indeed it even backtraces up past main into the boot initialization code. So presumably the problem isn't with the linker script or compiler options. (Also, confirmed from disassembly that no frame pointer is used in this ARM7 test either). </p>
  
  <p>The code is compiled with -fomit-frame-pointer, but my platform (bare metal ARM Cortex M3) defines an ABI that does not use a frame pointer anyway. (A previous version of this system used the old APCS ABI on ARM7 with forced stack frames and frame pointer, and an backtrace like the one <a href="http://csg.lbl.gov/pipermail/vxwexplo/2004-February/004397.html" rel="noreferrer">here</a>, which worked perfectly). </p>
  
  <p>The whole system is compiled with -fexception, which ensures the necessary metadata that _Unwind uses is included in the ELF file. (_Unwind is designed for exception handling I think). </p>
  
  <p>So, my question is:
  <strong>Is there a "standard", accepted way of getting reliable backtraces in embedded systems using GCC?</strong></p>
  
  <p>I don't mind having to mess around with the linker scripts and crt0 code if necessary, but don't want to have to make any chances to the toolchain itself. </p>
  
  <p>Thanks!</p>