Here is another version:
; ###################################################### ;
; cmdAllocateBuffer - Allocates zero buffer of specified size
;
; Usage:
; ------------------------------------------
; ; this will create new buffer of LIST_SIZE size.
; ------------------------------------------
; mov rcx,qword LIST_SIZE
; call cmdAllocateBuffer
;
; Returns, pointer to buffer, returned in rax.
;
; ###################################################### ;
cmdAllocateBuffer:
mov qword [rsp+8*1],rcx ; buffer size
sub rsp,qword 8*5
call malloc
cmp rax,qword 0
jne .gotMem
add rsp,qword 8*5
ret
.gotMem:
mov r8,qword [rsp+8*5+8*1]
mov qword [rsp+8*5+8*1],rax
mov rdx,qword 0
mov rcx,rax
call memset
mov rax,qword [rsp+8*5+8*1]
add rsp,qword 8*5
ret
; ###################################################### ;
; cmdReadFileIntoBuffer - Reads file data into buffer
;
; Usage:
; mov rcx,qword addressOfFilename
; call cmdReadFileIntoBuffer
;
; Returns address of buffer into rax.
; Returns buffer len into rcx.
; Clear's carry on success.
; Set's carry on failure.
;
; ###################################################### ;
cmdReadFileIntoBuffer:
mov qword [rsp+8*1],rcx; filename
mov qword [rsp+8*2],qword 0; (tmp) store file handle
mov qword [rsp+8*3],qword 0; (tmp) store file size
mov qword [rsp+8*4],qword 0; (tmp) store buffer address
sub rsp,qword 8*5
cmp rcx,qword 0
jne .gotSomeFileName
add rsp,qword 8*5
stc
ret
.gotSomeFileName:
mov qword [rsp+8*4],qword "rb"
lea rdx,[rsp+8*4]
call fopen
cmp rax,qword 0
jne .fileOpened
add rsp,qword 8*5
stc
ret
.fileOpened:
mov qword [rsp+8*5+8*2],rax
mov rcx,rax
xor rdx,rdx
mov r8,qword 2
call fseek
cmp rax,qword 0
je .fseekSuccessEnd
mov rcx,qword [rsp+8*5+8*2]
call fclose
add rsp,qword 8*5
stc
ret
.fseekSuccessEnd:
mov rcx,qword [rsp+8*5+8*2]
call ftell
cmp rax,qword 0
jne .ftellSuccess
mov rcx,qword [rsp+8*5+8*2]
call fclose
add rsp,qword 8*5
stc
ret
.ftellSuccess:
mov qword [rsp+8*5+8*3],rax
mov rcx,rax
call cmdAllocateBuffer
cmp rax,qword 0
jne .gotBuffer
mov rcx,qword [rsp+8*5+8*2]
call fclose
add rsp,qword 8*5
stc
ret
.gotBuffer:
mov qword [rsp+8*5+8*4],rax
mov rcx,qword [rsp+8*5+8*2]
xor rdx,rdx
mov r8,qword 0
call fseek
cmp rax,qword 0
je .fseekSuccessStart
mov rcx,qword [rsp+8*5+8*2]
call fclose
mov rcx,qword [rsp+8*5+8*4]
call free
add rsp,qword 8*5
stc
ret
.fseekSuccessStart:
mov rcx,qword [rsp+8*5+8*4]
mov rdx,qword 1
mov r8,qword [rsp+8*5+8*3]
mov r9,qword [rsp+8*5+8*2]
call fread
cmp rax,qword [rsp+8*5+8*3]
je .freadSuccess
mov rcx,qword [rsp+8*5+8*2]
call fclose
mov rcx,qword [rsp+8*5+8*4]
call free
add rsp,qword 8*5
stc
ret
.freadSuccess:
mov rcx,qword [rsp+8*5+8*2]
call fclose
mov rax,qword [rsp+8*5+8*4]
mov rcx,qword [rsp+8*5+8*3]
add rsp,qword 8*5
clc
ret
Define file access into stack:
...
mov qword [rsp+8*4],qword "rb"
lea rdx,[rsp+8*4]
call fopen
...