在写驱动程序或者优化程序的时候,我门可能会使用到汇编语言,为了理解汇编语言,我们先看看下面这个简单的例子:
#this is in a file first.s
.global main
main:
movl $20, %eax
movl $10, $ebx
ret
$20, %eax 意思是,将20拷贝到寄存器eax 中。
使用GNU C 的-S 选项,我们可以生成汇编代码,举个例子:
int main(){
int x = 10;
int y = 15;
return 0;
}
我们使用-S选项来编译一下
它生成的汇编代码文件simple.s长这个样子:
.file "simpole.c"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $10, -4(%rbp)
movl $15, -8(%rbp)
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
举这个例子的目的是为了让大家在一定程度上了解汇编语言,我们可以看到x, 和y的初始化过程,还有,大量用到了esp(stack 指针), ebp(base 指针)。每条指令后面的l 表明我们的操作符号作用于32位的操作数上面。寄存器用%表示。比如:
movl $10, -4(%ebp)
意思是将10 移动到ebp-4这个位置。
我们来看另外一个将C语言转换成汇编语言的例子:
#include <stdio.h>
int main()
{
printf("hello world\n");
return 0;
}
汇编代码:
.file "hello.c"
.section .rodata
.LC0:
.string "hello world"
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $.LC0, %edi
call puts
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (GNU) 4.8.2 20140120 (Red Hat 4.8.2-16)"
.section .note.GNU-stack,"",@progbits