在不具備gdb環境的類Linux系統開發板上調試段錯誤,大致定位出錯函數位置

在不具備gdb環境的類Linux系統開發板上調試段錯誤,大致定位出錯函數位置

在不具備gdb環境的類Linux系統開發板上調試段錯誤,大致定位出錯函數位置
理論知識就不講了,想了解的可以在搜索下“Linux下的段錯誤產生的原因及調試方法” 這篇文章,本文的內容基本是從那文章裏提取出來的。

1 初步步驟:
1)在你的代碼中添加如下代碼:

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void dump(int signo)
{
    void *array[30];
    size_t size;
    char **strings;
    size_t i;

    size = backtrace (array, 30);
    strings = backtrace_symbols (array, size);

    fprintf (stderr,"Obtained %zd stack frames.nm", size);

    for (i = 0; i < size; i++)
        fprintf (stderr,"%sn", strings[i]);

    free (strings);

    exit(0);
}

Debug_Printf_FrameInfos()
{
    signal(SIGSEGV, &dump);
}

2)
在你的mian函數中調用 Debug_Printf_FrameInfos(); 函數。
最好在mian函數的開頭。

3)編譯程序時  加   -g 選項

2:如何定位出錯函數地址
這裏以 test.c 爲例,來查找出錯函數地址

#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

void dump(int signo)
{
    void *array[30];
    size_t size;
    char **strings;
    size_t i;

    size = backtrace (array, 30);
    strings = backtrace_symbols (array, size);

    fprintf (stderr,"Obtained %zd stack frames.nm", size);

    for (i = 0; i <= size; i++)
        fprintf (stderr,"%s\n", strings[i]);

    free (strings);
    exit(0);
}

Debug_Printf_FrameInfos()
{
    signal(SIGSEGV, dump);
}

void c()
{
    * ((volatile char *) 0x0) = 0x999;
}
void b()
{
    c();
}
void a()
{
    b();
}
int main()
{
    Debug_Printf_FrameInfos();
    a();
    return 0;
}

該例程功能是
main()->a()->b()->c()->出錯。
 
a)編譯程序:     gcc -g test.c -o test
b)運行 test程序:   ./test

c)程序將打印如下信息:
Obtained 7 stack frames.nm./a.out [0x80484f3]
[0xffffe420]
./a.out [0x80485ad]
./a.out [0x80485b7]
./a.out [0x80485d4]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xdc) [0xb7dc4ebc]
./a.out [0x8048451]

d) objdump -d text > tmp
e)在tmp 中查找0x80485ad的地址,你會發現如下信息:
080485a5 <b>:
 80485a5:   55                      push   %ebp
 80485a6:   89 e5                   mov    %esp,%ebp
 80485a8:   e8 eb ff ff ff          call   8048598 <c>
 80485ad:   5d                      pop    %ebp
 80485ae:   c3                      ret

其中:
 80485ad:   5d                      pop    %ebp
是調用( call   8048598 <c>)c函數後的地址, 雖然沒有直接定位到C函數,但已經定位到B了,這在大型的程序中確是非常有用的。
(本例程的結果可能會隨着C庫的不同而不同)

 

發佈了5 篇原創文章 · 獲贊 3 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章