///hello world!!!
///that piece of crap, i mean, code assumes that the memory starting address is on ix
///and the memory ending adress are on iy(both provided by kernel)
///
///code assumes that when api calls a function the parameters are store in BC, DE, HL ...
///code assumes that when we return something to api, we return in HL
memstarth: defs 0
memstartl: defs 0
memendh: defs 0
memendl: defs 0
mmapladdrh: defs 0
mmapladdrl: defs 0
ld (memstarth),ixh ;putting start memory adress on ram
ld (memstartl),ixl ;assuming that its on ix
ld (memendh),iyh ;putting end memory adress on ram
ld (memendl),iyl ;assuming that its on iy
ld (mmapladdrh),iyh ;putting end memory adress on ram
ld (mmapladdrl),iyl ;assuming that its on iy
malloc:
ld ixh,(memendh) ;get the last available memory address
ld ixl,(memendl)
ld iyh,(ix+1) ;get the last header address from MM
ld iyl,(ix+2)
ld h,(iy) ;get the size of last chunk
ld l,(iy+1)
add iy,hl ;get the first free address on memory
add iy,4
or a
sbc ix,iy ;get the free memory size
ld hl,6 ;fill DE with header size and MM registry size
add bc,hl ;get the amout of memory neded
or a
ld hl,0 ;prepare to exit n' return false case the memory is not enough
sbc ix,bc ;see if the free memory is enough to exec malloc
jr nc,mmap ;test if memory is enogh, if yes, jump to memory maping routine
ret
///remember that mmap starts at the end of memory and come back word by word
mmap:
ld ixh,(memendh) ;get the last available memory address
ld ixl,(memendl)
dec ix
dec ix
ld (memendh),ixh ;save new memory last available address
ld (memendl),ixl
ld (ix+1),iyh ;save mmap record
ld (ix+2),iyl
ld hl,de
ld (iy),h ;save the size in the header
inc iy
ld (iy),l
inc iy
ld (iy),KERNEL_CurTaskID ;put the app id on the header
inc iy
ld (iy),0 ;clear our extra header byte
inc iy
ld hl,iy; ;put the memory starting address on hl to return to app
ret