2019-11-29 10:14:17 +03:00
|
|
|
module builtin
|
|
|
|
|
2019-12-04 11:46:09 +03:00
|
|
|
const (
|
2021-03-24 21:39:59 +03:00
|
|
|
mem_prot = Mm_prot(int(Mm_prot.prot_read) | int(Mm_prot.prot_write))
|
2020-04-23 06:16:10 +03:00
|
|
|
mem_flags = Map_flags(int(Map_flags.map_private) | int(Map_flags.map_anonymous))
|
|
|
|
page_size = u64(Linux_mem.page_size)
|
2019-12-04 11:46:09 +03:00
|
|
|
)
|
|
|
|
|
2019-11-29 10:14:17 +03:00
|
|
|
pub fn mm_pages(size u64) u32 {
|
2021-03-24 21:39:59 +03:00
|
|
|
pages := (size + u64(4) + page_size) / page_size
|
2019-11-29 10:14:17 +03:00
|
|
|
return u32(pages)
|
|
|
|
}
|
|
|
|
|
2020-04-23 06:16:10 +03:00
|
|
|
pub fn mm_alloc(size u64) (byteptr, Errno) {
|
2019-11-29 10:14:17 +03:00
|
|
|
pages := mm_pages(size)
|
2021-03-24 21:39:59 +03:00
|
|
|
n_bytes := u64(pages * u32(Linux_mem.page_size))
|
2019-11-29 10:14:17 +03:00
|
|
|
|
|
|
|
a, e := sys_mmap(0, n_bytes, mem_prot, mem_flags, -1, 0)
|
|
|
|
if e == .enoerror {
|
2020-04-22 21:12:30 +03:00
|
|
|
mut ap := &int(a)
|
2019-11-29 10:14:17 +03:00
|
|
|
*ap = pages
|
2021-03-24 21:39:59 +03:00
|
|
|
return byteptr(a + 4), e
|
2019-11-29 10:14:17 +03:00
|
|
|
}
|
|
|
|
return byteptr(0), e
|
|
|
|
}
|
|
|
|
|
2020-04-23 06:16:10 +03:00
|
|
|
pub fn mm_free(addr byteptr) Errno {
|
2021-03-24 21:39:59 +03:00
|
|
|
ap := &int(addr - 4)
|
2020-04-23 06:16:10 +03:00
|
|
|
size := u64(*ap) * u64(Linux_mem.page_size)
|
2019-11-29 10:14:17 +03:00
|
|
|
|
2019-12-01 11:27:36 +03:00
|
|
|
return sys_munmap(ap, size)
|
|
|
|
}
|
2019-11-29 10:14:17 +03:00
|
|
|
|
2019-12-01 11:27:36 +03:00
|
|
|
pub fn mem_copy(dest0 voidptr, src0 voidptr, n int) voidptr {
|
|
|
|
mut dest := byteptr(dest0)
|
|
|
|
src := byteptr(src0)
|
2021-03-24 21:39:59 +03:00
|
|
|
for i in 0 .. n {
|
2019-12-01 11:27:36 +03:00
|
|
|
dest[i] = src[i]
|
|
|
|
}
|
|
|
|
return dest0
|
2019-11-29 10:14:17 +03:00
|
|
|
}
|
2019-12-08 13:44:52 +03:00
|
|
|
|
2020-08-09 12:22:11 +03:00
|
|
|
[unsafe]
|
2019-12-08 13:44:52 +03:00
|
|
|
pub fn malloc(n int) byteptr {
|
|
|
|
if n < 0 {
|
|
|
|
panic('malloc(<0)')
|
|
|
|
}
|
|
|
|
|
|
|
|
ptr, e := mm_alloc(u64(n))
|
|
|
|
assert e == .enoerror
|
|
|
|
assert !isnil(ptr)
|
|
|
|
return ptr
|
|
|
|
}
|
|
|
|
|
2020-08-09 12:22:11 +03:00
|
|
|
[unsafe]
|
2019-12-08 13:44:52 +03:00
|
|
|
pub fn free(ptr voidptr) {
|
|
|
|
assert mm_free(ptr) == .enoerror
|
|
|
|
}
|