幾種CRT函數的彙編實現

.data
.set ZERO , 0b00000000000000000000000000000000

strlen:
在這裏利用scasb命令,scasb將di指向的數據與al比較,repne表示重複掃描,如果不相等,則di遞增指向下一個數據,cx也遞減,如此重複,知道遇到結束符‘\0’爲止。代碼中利用eax存儲常值0與數據比較,利用ecx累計長度,由於累計後是負值,所以將其取正返回(拉長32位取反減一)

#asm_strlen(const char *data)
	__asm_strlen:
	
		pushl %ebp
		movl %esp , %ebp
	
		movl 8(%ebp) , %edi
		movl $-1 , %ecx
		movl $0 , %eax
	
		cld
		repne scasb
	
		orl $ZERO , %ecx
		notl %ecx
		decl %ecx
	
		movl %ebp , %esp
		popl %ebp
	
		movl %ecx , %eax
	
		ret

strncpy:

這裏利用lodsb和stosb兩個指令,前者將數據從si載入al,後者再將數據再從al存到di中,所以,將參數source的地址放入esi中,將參數dest的地址放入edi,然後進入循環,累減ecx(len),直到len複製完了跳出。

#asm_strncpy(char *dest , char *source , int len)
.global __asm_strncpy
	__asm_strncpy:
		
		pushl %ebp
		movl %esp , %ebp
		
		movl 16(%ebp) , %ecx
		movl 12(%ebp) , %esi
		movl 8(%ebp) , %edi
        
		movl %ecx , %ebx
		
		1:
		lodsb
	        stosb
		decl %ecx
		jne 1b
		
		movl %ebp , %esp
		popl %ebp
	    
		orl %ecx , %ecx
		jne 2
		
		ret
		2:
		subl %ecx , %ebx
		movl %ebx , %eax
	    ret

strchr:

這裏大部分和strlen一樣,只是將比較的內容改爲參數__c。
#asm_strchr( char *__s, int __c )
.global __asm_strchr
	__asm_strchr:
		
		pushl %ebp
		movl %esp , %ebp
		
		movl 12(%ebp) , %eax
		movl 8(%ebp) , %edi
		movl %edi , %ebx
		movl $-1 , %ecx
		
		cld
		repne scasb
		
		orl $ZERO , %ecx
		notl %ecx
		decl %ecx
		
		movl %ebp , %esp
		popl %ebp
		
		addl %ecx , %ebx
		#movl (%ebx) , %eax #return current char
	    movl %ebx , %eax # return string
		
		ret


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章