.

loop指令用ecx來控制迴圈次數,loop label,相當於如下兩條指令:
dec ecx
jne label
如下是使用loop指令的一個示例程式:

section .data

	EditBuff: db 'abcdefghijklm',10
	BUFFERLEN equ $-EditBuff
	FILLCHR	  equ 35 ;'#'
	
section .text

WriteStr:
	push eax		; Save pertinent registers
	push ebx
	mov eax,4		; Specify sys_write call
	mov ebx,1		; Specify File Descriptor 1: Stdout
	int 80H			; Make the kernel call
	pop ebx			; Restore pertinent registers
	pop eax
	ret			; Go home
	
	global	_start
_start:
	nop
	
	mov ecx,EditBuff		
	mov edx,BUFFERLEN	
	call WriteStr
	
	mov edi,EditBuff
	mov ecx,BUFFERLEN-1
	mov al,FILLCHR
DoChar: stosb	; Note that there's no REP prefix!
	loop DoChar	; Go back & do another char until ECX goes to 0
				
	mov ecx,EditBuff		
	mov edx,BUFFERLEN	
	call WriteStr

Exit:	mov eax,1		; Code for Exit Syscall
	mov ebx,0		; Return a code of zero	
	int 80H			; Make kernel call

程式分析:
    mov edi,EditBuff //edi = EditBuff
    mov ecx,BUFFERLEN-1 //ecx= BUFFERLEN-1,這樣可以不覆蓋最後一個換行符
    mov al,FILLCHR //al = ‘#’
DoChar: stosb //用al中的值填充edi
    loop DoChar //ecx=ecx-1,如果ecx不等於0,跳轉到DoChar。

makefile檔案內容:

loopdemo: loopdemo.o
	ld -o loopdemo loopdemo.o
loopdemo.o: loopdemo.asm
	nasm -f elf -g -F stabs loopdemo.asm -l loopdemo.lst

測試:

[[email protected] loopdemo]# make
nasm -f elf -g -F stabs loopdemo.asm -l loopdemo.lst
ld -o loopdemo loopdemo.o
[[email protected] loopdemo]# ./loopdemo 
abcdefghijklm
#############