;FASM STANDARD LIBRARY
;Win32 memory routines for use with FASMLIB heap manager

;you can replace src/win32/mem.inc with this file, to use FASMLIB heap manager
;instead of Heap*** Win32API functions. Useful to test heap manager on win32,
;but with this way VirtualAlloc often cannot enlarge block enough

NEED_HEAP_MANAGER equ 1

HEAP_MAX_SIZE = 1024 * 1024 * 1024  ; = 1GB address space.


uglobal
  __heap_start dd ?
endg


initialize InitHeapManager
.info SYSTEM_INFO
begin
        invoke  VirtualAlloc, 0, HEAP_MAX_SIZE, MEM_RESERVE, PAGE_READWRITE
        test    eax, eax
        jz      .error

        mov     [__heap_start], eax
        return

.error:
        int3
        return

endp



proc mem.alloc_heap, .size
begin
        push    ecx edx

        invoke  VirtualAlloc, [__heap_start], [.size], MEM_COMMIT, PAGE_EXECUTE_READWRITE
        test    eax, eax
        jz      .error_VirtualAlloc

        clc
        pop     edx ecx
        return

.error_VirtualAlloc:
        mov     eax, ERR_OUT_OF_MEM
        stc
        pop     edx ecx
        return
endp




proc mem.free_heap, .block, .size
begin
        push    ecx edx eax

        invoke  VirtualFree, [.block], [.size], MEM_DECOMMIT
        test    eax, eax
        jz      .error

        clc
.r:
        pop     eax edx ecx
        return

.error: stc
        mov     dword [esp], ERR_UNKNOWN
        jmp     .r
endp



proc mem.realloc_heap, .heapptr, .newsize, .oldsize
begin
        push    ecx edx

        invoke  VirtualAlloc, [.heapptr], [.newsize], MEM_COMMIT, PAGE_EXECUTE_READWRITE
        test    eax,eax
        jz      .error_GlobalReAlloc

.rnc:   clc
        pop     edx ecx
        return

.error_GlobalReAlloc:
        mov     eax, ERR_OUT_OF_MEM
        stc
        pop     edx ecx
        return
endp
