Wednesday, July 21, 2010

Malloc with a glitch

Let's look at some assembly code:
; alloc memory
C_06B4 PROC NEAR
SHR BX,1
SHR BX,1
SHR BX,1
SHR BX,1
MOV AH,48h
INT 21h
MOV BX,AX
MOV AX,1
JB C_06C9
XOR AX,AX
C_06C9:
RET
C_06B4 ENDP

The first thing you noticed was the mythical INT 21h, didn't you ? Back in the ol'times, this was how the system calls were performed.
Register AH contains the number of the system call, in our case 48h (h for hexadecimal) which stands for Allocate Memory, and take as sole parameter the number of paragraphs in register BX. And that's funny because its value is not set inside this function, but just shifted by 4 bits to the right, (i.e dividing it by 16). Yes, you got it, when calling this function, you just have to set BX to the desired amount of memory, in bytes.
Let's go back to the 48h system call; upon its returns, the carry flag should be checked.
if reset, the call is a success, and AX contains the segment register of the allocated zone.
if set, there has been an error.

With all this knowledge, you are now able to understand what the last part of our function is doing:
In case of error, it sets AX to 0, and you're fckd.
In case of success, to 1, and you can then use the content of BX which is the allocated segment's address.

Yeah, I know, I'm not really good with the explanations. Anyway, just think of it as a kind of malloc (with a glitch though, can you find it ?).

It's not a really interesting function, but it is used a lot in LORI_init ... a bigger piece that will be discussed on the next post !

No comments: