; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: Dynamic memory management library. Linux part.
;
;  Target OS: Linux
;
;  Dependencies:
;
;  Notes: Uses libc (malloc etc.) heap management functions.
;_________________________________________________________________________________________

uses libc

body GetMem
begin
        push    ebx ecx edx esi edi

        mov     ebx, [.size]
        add     ebx, 3
        and     bl, $fc          ; align to dword.

        cinvoke malloc, ebx
        test    eax, eax
        jz      .error
        push    eax

        cld
        mov     edi, eax
        mov     ecx, ebx
        shr     ecx, 2
        xor     eax, eax
        rep stosd

        pop     eax
        clc
        pop     edi esi edx ecx ebx
        return

.error:
        stc
        pop     edi esi edx ecx ebx
        return

endp



body FreeMem
begin
        cmp     [.ptr], 0
        je      @f
        pushad
        cinvoke free, [.ptr]
        popad
@@:
        return
endp




body ResizeMem
begin
        push    ebx ecx edx esi edi

        mov     ebx, [.newsize]
        add     ebx, 3
        and     bl, $fc          ; align to dword.

        cinvoke realloc, [.ptr], ebx
        test    eax, eax
        jz      .error

        clc
        pop     edi esi edx ecx ebx
        return

.error:
        stc
        pop     edi esi edx ecx ebx
        return
endp




if used SpaceAllocate & ~ used GetMem
initialize ReserveAddressSpace
begin
        mov     eax, sys_brk
        xor     ebx, ebx
        int     $80
        mov     [_MemoryFreeSpace], eax
        return
endp
end if


body SpaceAllocate
begin
        push ebx
        mov     eax, sys_brk
        mov     ebx, [_MemoryFreeSpace]
        add     ebx, [.size]
        int     $80
        pop  ebx
        return
endp