v2 / vlib / builtin / closure / closure_nix.c.v
84 lines · 75 sloc · 1.77 KB · e2e5cf8db56f3562c7baa735061690be936bdf3e
Raw
1module closure
2
3$if !freestanding && !vinix {
4 #include <sys/mman.h>
5}
6
7@[typedef]
8pub struct C.pthread_mutex_t {}
9
10struct ClosureMutex {
11 closure_mtx C.pthread_mutex_t
12}
13
14@[inline]
15fn closure_alloc_platform() &u8 {
16 mut p := &u8(unsafe { nil })
17 $if freestanding {
18 // Freestanding environments (no OS) use simple malloc
19 p = unsafe { malloc(g_closure.v_page_size * 2) }
20 if isnil(p) {
21 return unsafe { nil }
22 }
23 } $else {
24 // Main OS environments use mmap to get aligned pages
25 p = unsafe {
26 C.mmap(0, g_closure.v_page_size * 2, C.PROT_READ | C.PROT_WRITE,
27 C.MAP_ANONYMOUS | C.MAP_PRIVATE, -1, 0)
28 }
29 if p == &u8(C.MAP_FAILED) {
30 return unsafe { nil }
31 }
32 }
33 return p
34}
35
36@[inline]
37fn closure_memory_protect_platform(ptr voidptr, size isize, attr MemoryProtectAtrr) {
38 $if freestanding {
39 // No memory protection in freestanding mode
40 } $else {
41 match attr {
42 .read_exec {
43 unsafe { C.mprotect(ptr, size, C.PROT_READ | C.PROT_EXEC) }
44 }
45 .read_write {
46 unsafe { C.mprotect(ptr, size, C.PROT_READ | C.PROT_WRITE) }
47 }
48 }
49 }
50}
51
52@[inline]
53fn get_page_size_platform() int {
54 // Determine system page size
55 mut page_size := 0x4000
56 $if !freestanding {
57 // Query actual page size in OS environments
58 page_size = unsafe { int(C.sysconf(C._SC_PAGESIZE)) }
59 }
60 // Calculate required allocation size
61 page_size = page_size * (((assumed_page_size - 1) / page_size) + 1)
62 return page_size
63}
64
65@[inline]
66fn closure_mtx_lock_init_platform() {
67 $if !freestanding || vinix {
68 C.pthread_mutex_init(&g_closure.closure_mtx, 0)
69 }
70}
71
72@[inline]
73fn closure_mtx_lock_platform() {
74 $if !freestanding || vinix {
75 C.pthread_mutex_lock(&g_closure.closure_mtx)
76 }
77}
78
79@[inline]
80fn closure_mtx_unlock_platform() {
81 $if !freestanding || vinix {
82 C.pthread_mutex_unlock(&g_closure.closure_mtx)
83 }
84}
85