编写汇编函数需要三步
1.定义输入值
使用寄存器
使用全局变量
使用堆栈
2.定义函数处理
call func1
.type func1, @function
func1:
...
ret
3.定义输出值
结果放到寄存器中
结果放到全局内存位置中
按照C 样式传递数据值:使用堆栈,无需担心破坏寄存器值或全局变量值
返回值定义
32位结果EAX
64位结果EDX:EAX
浮点数 FPU的ST(0)
示例
pushl %eax ;function(int x1,int x ,int x3)的第3个参数x3
pushl %ebx ;function(x1,x2,x3)的第2个参数x2
pushl %ecx ;function(x1,x2,x3)的第1个参数x1
call function
addl $12, %esp ;清除堆栈
function:
pushl %ebp ;保存EBP的值
movl %esp, %ebp ;设置新的EBP值
subl $8, %esp ;为局部变量留出空间
...
movl %ebp, %esp
popl %ebp
ret
使用独立的函数文件
area.s
;area.s - The areacircumference function
.section .text
.type area, @function
.globl area
area:
pushl %ebp
movl %esp, %ebp
subl $4, %esp
fldpi
filds 8(%ebp)
fmul %st(0), %st(0)
fmulp %st(0), %st(1)
fstps -4(%ebp)
movl -4(%ebp), %eax
movl %ebp, %esp
popl %ebp
ret
;functest4.s - An example of using external functions
.section .data
precision:
.byte 0x7f, 0x00
.section .bss
.lcomm result, 4
.section .text
.globl _start
_start:
nop
finit
fldcw precision
pushl $10
call area
addl $4, %esp
movl %eax, result
pushl $2
call area
addl $4, %esp
movl %eax, result
pushl $120
call area
addl $4, %esp
movl %eax, result
movl $1, %eax
movl $0, %ebx ;系统调用
int $0x80
编译
as -gstabs -o area.o area.s
as -gstabs -o func4.o functest4.s
ld -o func4 area.o func4.o