汇编语言学习[2018-05-09],第 3 天
简单的汇编程序
汇编程序有各块组成,常用的3个块如下
- The data section
- The bss section
- The text section
The data section
带初始化值数据块,可定义在程序块的后面,最好是定义在程序的最前面,方便阅读和维护,对于汇编程序是可选块
The bss section
不带初始化值数据库,必须定义在程序块前面,通常用于缓冲区定义,对于汇编程序是可选块
The text section
程序块,对于汇编程序是必选块
定义块
``` 汇编代码
.section .data
.section .bss
.section .text
```
汇编语言的main函数
汇编语言的程序执行入口只有_start标记,相对于java或c中的main函数,也可以将_start标记替换成main标记,在程序编译连接时,使用ld -emain来指定程序入口
汇编程序hello word
``` 汇编代码
#cpuid.s Sample program to extract the processor Vendor ID
.section .data
output: .ascii "The processor Vendor ID is 'xxxxxxxxxxxx'\n"
.section .text
.globl _start
_start:
movl $0, %eax
cpuid
movl $output, %edi
movl %ebx, 28(%edi)
movl %edx, 32(%edi)
movl %ecx, 36(%edi)
movl $4, %eax
movl $1, %ebx
movl $output, %ecx
movl $42, %edx
int $0x80
movl $1, %eax
movl $0, %ebx
int $0x80
```
代码中int $0x80是使用了Linux的系统调用,系统调用是需要设置以下寄存器作为调用参数:
- EAX contains the system call value.
- EBX contains the file descriptor to write to.
- ECX contains the start of the string.
- EDX contains the length of the string.
编译和执行汇编程序
$ as -o cpuid.o cpuid.as
$ ld -o cpuid cpuid.o
$ ./cpuid
汇编语言可以直接使用c的编译器gcc进行编译和连接
$ gcc -o cpuid cpuid.s
注意:使用gcc编译汇编程序时,汇编语言的程序执行入口,必须使用main标记,同时源程序文件的扩展名必须是.s
会员程序的debug
使用gdb工具进行dubug,需要debug时,需要重新编译连接程序,编译时使用-gstabs参数
$ as -gstabs -o cpuid.o cpuid.as
$ ld -o cpuid cpuid.o
$ gdb cpuid
(gdb) break *_start
(gdb) next
(gdb) next
(gdb) step
(gdb) step
(gdb) cont
(gdb) info registers
(gdb) print /d
rbx(gdb)print/t
r
b
x
(
g
d
b
)
p
r
i
n
t
/
t
rbx
(gdb) print /x $rbx
(gdb) x /42cb &output
(gdb) quit
在汇编程序中使用C语言的函数库
``` 汇编代码
#cpuid2.s View the CPUID Vendor ID string using C library calls
.code32
.section .data
output:.asciz "The processor Vendor ID is '%s'\n"
.section .bss
.lcomm buffer, 12
.section .text
.globl main
main:
movl $0, %eax
cpuid
movl $buffer, %edi
movl %ebx, (%edi)
movl %edx, 4(%edi)
movl %ecx, 8(%edi)
pushl $buffer
pushl $output
call printf
addl $8, %esp
pushl $0
call exit
```
使用call指令,调用c函数库,使用pushl进行函数参数压栈
使用gcc 编译连接:
$ gcc -o cpuid2 cpuid2.s
$ ./cpuid2
注意:我使用的环境是centos7-64位系统,做上面使用c函数库的代码时会有问题,需要安装gcc 32位的工具和包,进行以下check,如果没有安装32的工具或包,请补充安装
$ yum list glibc
$ yum list glibc-devel
$ yum list libgcc