Linux X86-64下编写汇编程序

最近对底层比较感兴趣,重新学习了汇编语言。主要从汇编的角度能够更好的理解程序的运行机制,便于以后对上面封装,抽象出的高级语言有个追本溯源的认识。下面是一个范例程序。

写程序之前我们需要先看看对应系统下的系统调用对应的立即数

[xxxxxxxx@localhost asmwork]$    cat /usr/include/asm/unistd_64.h
#define __NR_read 0
#define __NR_write 1
#define __NR_open 2
#define __NR_close 3
#define __NR_stat 4
#define __NR_fstat 5
#define __NR_lstat 6
#define __NR_poll 7
#define __NR_lseek 8
#define __NR_mmap 9
#define __NR_mprotect 10
#define __NR_munmap 11
#define __NR_brk 12
#define __NR_rt_sigaction 13
#define __NR_rt_sigprocmask 14
#define __NR_rt_sigreturn 15
#define __NR_ioctl 16
....
#define __NR_fork 57
#define __NR_vfork 58
#define __NR_execve 59
#define __NR_exit 60
...

global main

section .data
        query_string : db "Enter a character: "
        query_string_len : equ $ - query_string
        out_string : db "You hava input: "
        out_string_len : equ $ - out_string

section .bss
        in_char :    resw 4

section .text

main:
        mov rax, 1   ;syscall need this parameter, diaplay write
        mov rdi, 1           ; stdout
        mov rsi, query_string  ; syscall invoke return rsi to get string
        mov rdx, query_string_len ; get the string length from rdx
        syscall

        mov rax, 0   ;read 
        mov rdi, 0   ;stdin
        mov rsi, in_char
        mov rdx, 2
        syscall

        mov rax, 1
        mov rdi, 1
        mov rsi, out_string
        mov rdx, out_string_len
        syscall

        mov rax, 1
        mov rdi, 1
        mov rsi, in_char
        mov rdx, 2
        syscall
        mov rax, 1
        mov rdi, 1
        mov rsi, out_string
        mov rdx, out_string_len
        syscall

        mov rax, 1
        mov rdi, 1
        mov rsi, in_char
        mov rdx, 2
        syscall

        mov rax, 60
        mov rdi, 0
        syscall


          

下面编译运行

[xxxxxxxx@localhost asmwork]$ nasm -f elf64 test.asm
[xxxxxxxx@localhost asmwork]$  gcc -o test test.o


[xxxxxxxx@localhost asmwork]$ ./test
Enter a character: 4
You hava input: 4

猜你喜欢

转载自blog.csdn.net/atxxiang4/article/details/83187181