bloggerads

2013年3月5日 星期二

x86 Assembly (legacy Bios) 一些指令紀錄

4大Segment的暫存器組合 (參考WIKI x86 Assembly)

CS:IP (CS is Code Segment, IP is Instruction Pointer) points to the address where the processor will fetch the next byte of code.
SS:SP (SS is Stack Segment, SP is Stack Pointer) points to the address of the top of the stack, i.e. the most recently pushed byte.
DS:SI (DS is Data Segment, SI is Source Index) is often used to point to string data that is about to be copied to ES:DI.
ES:DI (ES is Extra Segment, DI is Destination Index) is typically used to point to the destination for a string copy, as mentioned above.

# FLAG register:

Overflow(bit 11)/Direction(bit 10)/Interrupt(bit 9)/Sign(bit 7)/Zero(bit 6)/Auxiliary Carry(bit 4)/Parity(bit 2)/Carry(bit 0)


# 操作Flag register 的指令:

STD  ;Set Direction Flag (STD sets the direction flag to 1, causing all subsequent string operations to decrement the index registers, (E)SI and/or (E)DI, on which they operate.)
CLD  ;Clear Direction Flag
STC  ;Set Carry Flag
CLC  ;Clear Carry Flag 
CLI   ;Clear Interrupt Flag
STI   ;Set Interrupts


# 一些在Bios常使用的指令

PUSHA ;(PUSH ALL):PUSH  ax,cx,dx,bx,sp,bp,si,di 
PUSHAD ;Push EAX, ECX, EDX, EBX, original ESP, EBP, ESI, and EDI PUSHF ; Save the CPU flags on the stack.
POPF   ;Restore the CPU flags from the stack.
POPA  ;(POP ALL):POP  di,si,bp,sp,bx,dx,cx,ax
RET    ;副程式結束,返回,即 pop ip  
RETF  ;遠程副程式結束,返回,即 pop cs 然後 pop ip   
MOVSB ;Move byte at address DS:(E)SI to address ES:(E)DI.

# 標記與跳躍 @F 或 @B (這段是參考小木偶的網頁,感謝他)

除了高階的流程控制之外,MASM 6.x 還接受一種特殊標記,@@:。這種標記是做為跳躍指令的目的地,要用 @@: 做為目的地的跳躍指令,必須配合 @f 或 @b 使用,前者是指往前跳躍,後者是往後跳躍,它們都只向前或向後跳躍到第一個 @@: 標記處。

例如有一個程式片段,是用來使一個佔用 16 個位元組的 key_buffer 陣列所有元素填上 0,一般會這樣寫:

+           mov   cx,16
+           lea     si,key_buffer
+  next: mov   byte ptr ss:[si],0
+           inc     si
+           loop   next

如果 next: 標記只有此處用到,那麼便可以用 @@: 代替,變成下面的程式:

+          mov   cx,16
+          lea     si,key_buffer
+  @@: mov   byte ptr ss:[si],0
+          inc     si
+          loop   @b