1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/builtin/linux_bare/mm_bare.v

59 lines
1.1 KiB
V
Raw Normal View History

module builtin
const (
mem_prot = Mm_prot(int(Mm_prot.prot_read) | int(Mm_prot.prot_write))
mem_flags = Map_flags(int(Map_flags.map_private) | int(Map_flags.map_anonymous))
page_size = u64(Linux_mem.page_size)
)
pub fn mm_pages(size u64) u32 {
pages := (size + u64(4) + page_size) / page_size
return u32(pages)
}
2021-04-05 21:21:46 +03:00
pub fn mm_alloc(size u64) (&byte, Errno) {
pages := mm_pages(size)
n_bytes := u64(pages * u32(Linux_mem.page_size))
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)
*ap = pages
2021-04-05 21:21:46 +03:00
return &byte(a + 4), e
}
2021-04-05 21:21:46 +03:00
return &byte(0), e
}
2021-04-05 21:21:46 +03:00
pub fn mm_free(addr &byte) Errno {
ap := &int(addr - 4)
size := u64(*ap) * u64(Linux_mem.page_size)
return sys_munmap(ap, size)
}
pub fn mem_copy(dest0 voidptr, src0 voidptr, n int) voidptr {
2021-04-05 21:21:46 +03:00
mut dest := &byte(dest0)
src := &byte(src0)
for i in 0 .. n {
dest[i] = src[i]
}
return dest0
}
2020-08-09 12:22:11 +03:00
[unsafe]
2021-04-05 21:21:46 +03:00
pub fn malloc(n int) &byte {
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]
pub fn free(ptr voidptr) {
assert mm_free(ptr) == .enoerror
}