更多
更多

NASM汇编的"hello, world"

最近学了汇编语言,8086(发布1978年,16位),MASM汇编器。结果就是,特么的跟没学一样,完、全、搞、不、懂 _(:3」∠)_

毫无疑问汇编是很有用的,这就很尴尬了,也不能装懂,也没有兴趣,也没有那么多时间去折腾,索性,就放弃它了,应付过了考试就好。

但也想象征下的写一个 “hello, world” 来纪念一下,然而,没想到的是,就这一个 “hello, world” 我也搞不定,看来放弃它是正确的选择 ಥ_ಥ


因为我用Mac,所以MASM是用不了的,又因为不同的CPU,不同的汇编器,汇编的语法也不同,所以书本是没啥参考的了。

Mac自带NASM,使用它来汇编,使用ld来连接。

即使上网搜索也很难搞定NASM汇编的 “hello, world” ,最后通过用英文Google找到了相关代码。


Straight Line “hello, world”

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
; hello.asm - a "hello, world" program using NASM

; nasm -f macho hello.asm
;Assemble the above source to an object file, hello.o, in the Mach-O format.

; ld -o hello -e mystart hello.o
;Link the object file to produce the hello executable. (Calling this step "linking" when there is only one object file is a bit weird.)

; ./hello
;Run the executable.

; echo $?
;Check the exit status in Bash.


section .text

global mystart ; make the main function externally visible

mystart:

; 1 print "hello, world"

; 1a prepare the arguments for the system call to write
push dword mylen ; message length
push dword mymsg ; message to write
push dword 1 ; file descriptor value

; 1b make the system call to write
mov eax, 0x4 ; system call number for write
sub esp, 4 ; OS X (and BSD) system calls needs "extra space" on stack
int 0x80 ; make the actual system call

; 1c clean up the stack
add esp, 16 ; 3 args * 4 bytes/arg + 4 bytes extra space = 16 bytes

; 2 exit the program

; 2a prepare the argument for the sys call to exit
push dword 0 ; exit status returned to the operating system

; 2b make the call to sys call to exit
mov eax, 0x1 ; system call number for exit
sub esp, 4 ; OS X (and BSD) system calls needs "extra space" on stack
int 0x80 ; make the system call

; 2c no need to clean up the stack because no code here would executed: already exited

section .data

mymsg db "hello, Assembly Language! (。•ˇ‸ˇ•。) ... and, say goodbye. _(:3」∠)_", 0xa ; string with a carriage-return
mylen equ $-mymsg ; string length in bytes


汇编后缀为.asm, 注释为 ; (分号之后的一行内字符视为注释)

打开终端,(当前文件夹下, 或完整路径)

Assemble: nasm -f macho hello.asm

Link: ld -o hello -e mystart hello.o

Run: ./hello

其他说明直接看代码内注释。


hello, Assembly Language! (。•ˇ‸ˇ•。)

… …

and,

say goodbye. _(:3」∠)_




通过汇编的学习,更加深刻地认识到一些事:

  • 选对教材很重要

  • Google很重要

  • 英语很重要,用英文Google更重要

  • 不适合的不强求,该放弃的就得放弃 (/ _ ; )




//参考: