在64位系統下編譯32位彙編程式
阿新 • • 發佈:2019-01-02
#只是例子,計算2^3 + 5^2
.code32
.section .data
.section .text
.globl _start
_start:
pushl $3
pushl $2
call power
addl $8, %esp
pushl %eax
pushl $2
pushl $5
call power
addl $8, %esp
movl (%esp), %ebx
addl %eax, %ebx
movl $1, %eax
int $0x80
.type power, @function
power:
pushl %ebp
movl %esp, %ebp
movl 8(%ebp), %edx #x
movl 12(%ebp), %ecx #y
movl $1, %eax
loop:
cmpl $0, %ecx
jle loop_exit
imull %edx, %eax
decl %ecx
jmp loop
loop_exit:
movl %ebp, %esp
popl %ebp
ret
在64位環境下正常編譯,連結,執行時會出現錯誤.
movl %esp, %ebp
雖然是32位程式,但是在64位環境下執行,仍然使用的是%rsp,%rbp.
我們使用movl只複製了%rsp的低32位,導致之後rbp的取值是錯誤的.
於是,在彙編程式碼最上新增.code32
並且使用
as -m32 test.s -o test.o
ld -m elf_i386 test.o -o test