仍然是彙編和C混合編程的例子,這次用了gcc 和 NASM

仍然是彙編和C混合編程的例子,這次用了gcc 和 NASM

之所以選擇gcc和NASM,主要目的是在開發操作系統的時候,經常要用到幾種不同的彙編和C語言的編譯器,而NASM和GCC都是開源的,而且也配合的非常好,同時又是INTEL格式的彙編,相信會很合大家的胃口。

global __strlen, _str, _print
extern _ss, _printf

_str: db 'Good Luck!', 0 ;_str: db "Good Luck!", 0

_print: ; void print(char* s);
	push ebp
	mov ebp, esp

	mov ebx, [2 * 4 + esp]
	push ebx
	call __strlen
	add esp, 1 * 4
	
	push eax
	push dword [_ss]
	push ebx
	call _printf  ; printf("%s len = %d", ss, _strlen(ss));
	add esp, 3 * 4
	
	pop ebp
	ret

__strlen: ; int _strlen(char* s);
	push ebp
	mov ebp, esp
	push ebx
	push edi
	
	xor eax, eax
	mov ebx, [4 * 4 + esp]
	mov edi, ebx
	repne scasb
	sub edi, ebx
	dec edi
	mov eax, edi
	
	pop edi
	pop ebx
	pop ebp
	ret
#include <stdio.h>

int _strlen(char* s); //之所以是_strlen(),是因爲標準庫中有同名函數
extern char str;

char* ss = "%s ### len = %d";

void print(char* s);

int main(void) { 
	printf("%d\n", _strlen("1234567890"));
	printf("%d\n", _strlen(&str));
	print(ss);
}

 

 

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