前言
参考书籍:
王爽。汇编语言。北京:清华大学出版社, 2013:123-133
本人菜狗一枚,不敢咬文嚼字,只能站在巨人的肩膀上窥探一下未曾了解的世界。
程序取得所需空间的方法有两种:
- 在加载程序的时候为程序分配
- 程序在执行的过程中向系统申请
在代码段中使用数据
在程序中,定义希望处理的数据,这些数据在编译、连接过程中会作为程序的一部分写到可执行文件中,当可执行文件中的程序被加载入内存时,这些数据也同时被加载入内存中。于此同时,这些数据也就自然而然地获得了存储空间。
assume cs:code
code segment
; dw 即 "define word",定义字型数据
; dw 即可以用来定义数据,也可以用来开辟空间
; 由于定义在代码段中,所以它们的地址分别是 CS:0、CS:2、CS:4、CS:6、CS:8、CS:A、CS:C、CS:E
dw 0123h, 0456h, 0789h, 0abch, 0defh, 0fedh, 0cbah, 0987h
start:
mov bx, 0
mov ax, 0
mov cx, 8
s:
add ax, cs:[bx]
add bx, 2
loop s
mov ax, 4c00h
int 21h
code ends
; end 指令指明了程序的入口在标号 start 处
end start
在程序的第一条指令的前面加上一个标号 start,在伪指令 end 后面也出现了 start。
end 除了通知编译器程序结束外,还可以通知编译器程序的入口在什么地方。
end 标号指明程序入口,即设置 CS:IP。
在代码段中使用栈
在 cs:0 ~ cs:F 单元中定义数据,共 8 个字单元。
将 cs:10 ~ cs:2F 的内存空间当作栈使用,初始状态下栈为空,ss:sp 指向栈底 cs:30。
assume cs:codesg
codesg segment
dw 0123h, 0456h, 0789h, 0abch, 0defh, 0fedh, 0cbah, 0987h
dw 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
start:
mov ax, cs
mov ss, ax
mov sp, 30h
mov bx, 0
mov cx, 8
s:
push cs:[bx]
add bx, 2
loop s
mov bx, 0
mov cx, 8
s0:
pop cs:[bx]
add bx, 2
loop s0
mov ax, 4c00h
int 21h
codesg ends
end start
将数据、代码、栈放入不同的段
assume cs:code, ds:data, ss:stack
data segment
dw 0123h, 0456h, 0789h, 0abch, 0defh, 0fedh, 0cbah, 0987h
data ends
stack segment
dw 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
stack ends
code segment
start:
; 设置栈顶 ss:sp 指向 stack:20
mov ax, stack
mov ss, ax
mov sp, 20h
; ds:bx 指向 data 段中的第一个单元
mov ax, data
mov ds, ax
mov bx, 0
mov cx, 8
s:
push [bx]
add bx, 2
loop s
mov bx, 0
mov cx, 8
s0:
pop [bx]
add bx, 2
loop s0
mov ax, 4c00h
int 21h
code ends
end start