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

來源:互聯網
上載者:User
在不具備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個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.