0%

nasm例子

nasm例子

assembly_nasm_example.asm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
section .data
text db "Hello, world!",10

section .text
global _start

_start:
mov rax, 1
mov rdi, 1
mov rsi, text
mov rdx, 14
syscall

mov rax, 60
mov rdi, 0
syscall

try_sasm_3.asm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
SECTION .data                           
msg db 'Hello World!', 0Ah ; 换行Windows, dos用0Dh和0Ah; Unix和Linux舍去0Dh, 只用0Ah

SECTION .text
global _main
_main:
mov ebp, esp; for correct debugging
mov eax, msg
call strlen

mov edx, eax
mov ecx, msg
mov ebx, 1
mov eax, 4 ; SYS_WRITE 4
int 80h

mov ebx, 0
mov eax, 1 ; SYS_EXIT 1
int 80h


strlen:
push ebx ; find strlen of msg
mov ebx, eax

nextchar:
cmp byte [eax], 0 ; \0
jz finished ; finished
inc eax
jmp nextchar ; nextchar

finished:
sub eax, ebx ; strlen: eax = eax - ebx
pop ebx
ret

try_sasm_4.asm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
;-------------------Hello World Program(include)--------------------
; nasm -f elf helloworld-inc.asm
; ld -m elf_i386 helloworld-inc.o -o helloworld-inc
; ./helloworld-inc
;-------------------------------------------------------------------

SECTION .data
msg1 db 'Hello World!', 0Ah, 0h ; 换行Windows, dos用0Dh和0Ah; Unix和Linux舍去0Dh, 只用0Ah
msg2 db 'Hello NASM!', 0Ah, 0h

SECTION .text
global _main

_main:
mov eax, msg1
call sprint ; sprint

mov eax, msg2
call sprint

call quit ; exit


;-------------------Hello World Program(include)--------------------
;-------------------------------------------------------------------


;------------------------------------------
; int slen(String message)
slen:
push ebx
mov ebx, eax

nextchar:
cmp byte [eax], 0
jz finished
inc eax
jmp nextchar

finished:
sub eax, ebx
pop ebx
ret

;------------------------------------------
; void sprint(String message)
sprint:
push edx
push ecx
push ebx
push eax
call slen ; slen

mov edx, eax
pop eax

mov ecx, eax
mov ebx, 1
mov eax, 4
int 80h

pop ebx
pop ecx
pop edx
ret

;------------------------------------------
; void exit()
quit:
mov ebx, 0
mov eax, 1
int 80h
ret

try_sasm_5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
section	.text
global _main ;must be declared for linker (ld)

_main:
mov ebp, esp ;for correct debugging ;tell linker entry point
mov edx, 9 ;message length
mov ecx, stars;message to write
mov ebx, 1 ;file descriptor (stdout)
mov eax, 4 ;system call number (sys_write)
int 0x80 ;call kernel

mov eax, 1 ;system call number (sys_exit)
int 0x80 ;call kernel

section .data
stars times 9 db '*'