CSC231 Buggy Code 1

From dftwiki3
Revision as of 10:02, 12 November 2012 by Thiebaut (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut 09:40, 9 November 2012 (EST)


The code below is buggy... can you explain why?

		section	.data
hexChars:	db	"0123456789ABCDEF"

		section	.text
		global	_start
_start:
		mov	al,0xf5
		and	al,0x0f		;al <-- 05
		mov	ebx, hexChars 	;ebx <-- address hexChars
		add	bl, al		;ebx <-- hexChars+05
		mov	al,[ebx]	;al <-- '5'

		call	printChar

;;; exit
		mov	ebx, 0
		mov	eax, 1
		int	0x80

;;;----------------------------------------------------
;;; printChar: prints char in al to screen
;;;----------------------------------------------------
		section	.data
pc_temp:	db	0
		section	.text
	
printChar:	pushad
		mov	[pc_temp],al     ;store char in string
		mov	eax, 4	         ;print string
		mov	ebx, 1
		mov	ecx, pc_temp
		mov	edx, 1
		int	0x80
	
		popad
		ret













Solution

You may have guessed that the culprit was the add instruction highlighted in the code below. The reason is that what we want is the 32-bit address of the character in the hexChars array, but we perform an 8-bit addition, between bl and al, hoping that ebx is the correct address. Unfortunately there might be a carry from the addition of al to bl that will not affect bh and the higher part of ebx...


		section	.data
hexChars:	db	"0123456789ABCDEF"

		section	.text
		global	_start
_start:
		mov	al,0xf5
		and	al,0x0f		;al <-- 05
		mov	ebx, hexChars 	;ebx <-- address hexChars
		add	bl, al		;ebx <-- hexChars+05
		mov	al,[ebx]	;al <-- '5'

		call	printChar

;;; exit
		mov	ebx, 0
		mov	eax, 1
		int	0x80

;;;----------------------------------------------------
;;; printChar: prints char in al to screen
;;;----------------------------------------------------
		section	.data
pc_temp:	db	0
		section	.text
	
printChar:	pushad
		mov	[pc_temp],al     ;store char in string
		mov	eax, 4	         ;print string
		mov	ebx, 1
		mov	ecx, pc_temp
		mov	edx, 1
		int	0x80
	
		popad
		ret