If gdb is connected to your application, you can get a backtrace at any time. However, it is also possible to get a backtrace at runtime, without having a debugger connected.
In the kernel, simply call the function dump_stack() anywhere in the kernel. This generates the same format of backtrace that is output if the kernel panics:
Stack: (0x87685ec0 to 0x87686000) 5ec0: 84006256 87685ed0 87f306e0 84307340 84004744 87685ed8 84076f5a 87685ef8 5ee0: 87685f78 000000d0 00414038 00001000 87f306e0 84307340 87685f78 8709f724 5f00: 87f30700 00000000 00000000 386d43b6 2e7ddb00 00000000 00000000 8408d176 5f20: 87685f3c 87685f78 00001000 8709f724 fffffffb 84076e6a 844a2300 00414038 5f40: 8405d6f6 87685f60 00400d68 fffffff7 87685f78 00001000 00414038 8709f724 5f60: 8405db62 87685f78 00001000 00414038 8709f724 87685f44 00000000 00000000 5f80: 00000000 840078f8 00400ba8 00000514 00000000 00000021 0000004c 8405db24 5fa0: 00000000 00000450 00413690 00000003 00000003 00414038 00001000 00000000 5fc0: 00001000 00001000 00414038 00000003 00400ba8 00400d68 00400ba8 7bc3eca4 5fe0: 296097f4 0040225a 00008101 2967b7d8 00000000 00001000 0000004c 00000160 Call trace: [<84006256>] dump_stack+0xe/0x1c [<84004744>] show_cpuinfo+0x24/0x258 [<84076f5a>] seq_read+0xf0/0x27e [<8408d176>] proc_reg_read+0x7e/0xb0 [<84076e6a>] seq_read+0x0/0x27e [<8405d6f6>] vfs_read+0x6e/0xf8 [<8405db62>] sys_read+0x3e/0x78 [<840078f8>] syscall_call+0xa/0xe [<8405db24>] sys_read+0x0/0x78
A note about kernel backtraces: because the sh architecture does not put return addresses at a fixed offset from the stack pointer, they are generated by scanning the entire stack for values that correspond to addresses in kernel or module text sections. This means that although the backtrace is complete, it may also contain some "false positive" entries which do not correspond to real stack frames.
To generate a backtrace in user mode, the backtrace() function from the C library can be used. For example:
#include <execinfo.h> #define BACKTRACE_SIZ 64 void show_backtrace (void) { void *array[BACKTRACE_SIZ]; size_t size, i; char **strings; size = backtrace(array, BACKTRACE_SIZ); strings = backtrace_symbols(array, size); for (i = 0; i < size; i++) { printf("%p : %s\n", array[i], strings[i]); } free(strings); // malloced by backtrace_symbols }
In this case, any call to the function show_backtrace() will print an accurate backtrace. The "false positives" issue with kernel backtraces does not apply in this case.
For the backtrace() support to work correctly, the application must be compiled with -funwind-tables and linked with -rdynamic.