aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/vlib/builtin/linux_bare/old/mm_bare.v
blob: cee5f99857a01c94a402f0a8ec1d11c26c5e0abe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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)
}

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 {
		mut ap := &int(a)
		*ap = pages
		return &byte(a + 4), e
	}
	return &byte(0), e
}

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 {
	mut dest := &byte(dest0)
	src := &byte(src0)
	for i in 0 .. n {
		dest[i] = src[i]
	}
	return dest0
}

[unsafe]
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
}

[unsafe]
pub fn free(ptr voidptr) {
	assert mm_free(ptr) == .enoerror
}