iT邦幫忙

0

在linux中看gcc產生出來的組合語言

環境:linux使用者直接用終端機即可,windows使用者可用WSL或是建一個linux的虛擬機

先開啟一個c語言檔

$ vim test.c

在檔案內輸入:

void set_to_87(int *p)
{
    *p = 87;
}

方法一

  1. 先產生一個object file(2進位的格式)
gcc -Og -c test.c 
  1. 再用objdump去觀看組合言(解讀2進位的test.o,轉換成文字)
objdump -d test.o

輸出:

test.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <set_to_87>:
   0:   c7 07 57 00 00 00       movl   $0x57,(%rdi)
   6:   c3                      retq   

方法二

直接讓gcc產生出組合語言:

gcc -Og -S test.c 

這時會產生出test.s(文字檔)

cat test.s

輸出

        .file   "test.c"
        .text
        .globl  set_to_87
        .type   set_to_87, @function
set_to_87:
.LFB0:
        .cfi_startproc
        movl    $87, (%rdi)
        ret
        .cfi_endproc
.LFE0:
        .size   set_to_87, .-set_to_87
        .ident  "GCC: (Debian 10.2.1-6) 10.2.1 20210110"
        .section        .note.GNU-stack,"",@progbits

解讀組合語言

void set_to_87(int *p)
{
    *p = 87;
}
test.o:     file format elf64-x86-64


Disassembly of section .text:

0000000000000000 <set_to_87>:
   0:   c7 07 57 00 00 00       movl   $0x57,(%rdi)
   6:   c3                      retq   

可以看到指令只有兩個,這個functio被呼叫時,p的值會放在register%rdi

movl   $0x57,(%rdi)

就是把0x57(87)放到%rdi所指向的記憶體位置的意思

retq

則是return的意思


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言