I am reversing an SRAM driver, mostly for learning how to reverse, but also so that I can emulate the hardware later on.
It is going very well, but there is a piece of code, that I do not really understand. It is a character device driver and the function I am having problems with is the 'write' function in a 'struct file_operations'. The following is all the code up to the point I am having problems with:
Code: Select all
;Prototype:
; size_t sram_write(struct file *file, <-- Passed in EAX
; const char __user * data, <-- Passed in EDX
; size_t len, <-- Passed in ECX
; loff_t * offset) <-- Passed as first stack variable
;Set up stack frame
push ebp
mov ebp, esp
sub esp, 14h
;Now EBX, ESI and EDI are stored.
;They are restored before returning from this function
mov [ebp-0ch], ebx ;Save EBX for later restoration
mov [ebp-08h], esi ;Save ESI for later restoration
mov [ebp-04h], edi ;Save EDI for later restoration
;Now make sure that write does not extend available size
mov eax, ds:size ;'ds:size' contains total size of memory
mov edi, [ebp+8] ;Put 'offset' into EDI
mov [ebp-10h], edx ;Store 'data' pointer
mov esi, [edi] ;Read low 32 bits offset into ESI (high 32 bits are ignored)
sub eax, esi ;EAX = ds:size - *offset = Space left in memory relative to offset
cmp eax, ecx ;Compare space left to 'len'
mov ds:aux_pos, eax ;Store space left
jb short too_short ;If len > space left go to too_short
magic_happens:
mov edx, esp ;Put stack pointer into EDX
mov ebx, ecx ;Put 'len' into EBX
mov eax, [ebp-10h] ;Put 'data' pointer into EAX
and edx, 0ffffe000h ;???? WHY ?????
add eax, ebx ;EAX = data + len = end of data
sbb ecx, ecx ;Subtract with borrow...WHY ????
cmp [edx+18h], eax ;Compare obscured address with end of data...WHY ??
sbb ecx, 0 ;???
test ecx, ecx ;Set flags for ECX...but why ??
jnz short err1
;Here starts the actual writing...not so interesting to my problem
;....
xor ebx, ebx
jmp end
err1:
mov [esp], offset str2;Format string: "<4>Cannot read from write-call-buffer\n"
xor ebx, ebx
call printk
jmp short end
too_short:
mov [esp], offset str1;Format string on stack: "<4>Limiting write to available memory\n"
call printk
mov ecx, ds:aux_pos ;Put available memory size into ECX
jmp short magic_happens
end:
mov eax, ebx ;Set return value
mov esi, [ebp-08h] ;Restore ESI
mov ebx, [ebp-0ch] ;Restore EBX
mov edi, [ebp-04h] ;Restore EDI
;Tear down stack frame
mov esp, ebp
pop ebp
ret
Code: Select all
mov edx, esp
cmp [edx+18h], eax
Code: Select all
mov edx, esp
and edx, 0ffffe000h
cmp [edx+18h], eax
And what do the two SBB instructions do ?
Best,
Robert