Initial import of ViperOS

This commit is contained in:
Viper
2026-07-19 12:38:20 +08:00
commit 6813947181
104 changed files with 26710 additions and 0 deletions

59
vpsdk/stdlib.py Normal file
View File

@@ -0,0 +1,59 @@
import vpsdk.syscall as _sc
import string
import t, c
HEAP_BLOCK_MAGIC: t.CDefine = 0x48454150
@t.Object
class _heap_hdr:
magic: t.CUInt32T
size: t.CUInt32T
_heap_inited: t.CInt = 0
def _heap_init():
global _heap_inited
_heap_inited = 1
def malloc(size: t.CSizeT) -> t.CVoid | t.CPtr | t.CExport:
global _heap_inited
if size == 0: return None
if _heap_inited == 0:
_heap_init()
hdr_size: t.CSizeT = _heap_hdr.__sizeof__()
total: t.CSizeT = hdr_size + size
ptr: t.CUInt64T = _sc._syscall1(t.CUInt64T(_sc.SYSCALL_MMAP), t.CUInt64T(total))
if ptr == 0: return None
hdr: _heap_hdr | t.CPtr = t.CVoid(ptr, t.CPtr)
hdr.magic = HEAP_BLOCK_MAGIC
hdr.size = t.CUInt32T(size)
return t.CVoid(ptr + hdr_size, t.CPtr)
def free(ptr: t.CVoid | t.CPtr) -> t.CExport:
if ptr is None: return
hdr_size: t.CSizeT = _heap_hdr.__sizeof__()
hdr: _heap_hdr | t.CPtr = t.CVoid(t.CUInt64T(ptr) - hdr_size, t.CPtr)
if hdr.magic != HEAP_BLOCK_MAGIC: return
def calloc(nmemb: t.CSizeT, size: t.CSizeT) -> t.CVoid | t.CPtr | t.CExport:
total: t.CSizeT = nmemb * size
p: t.CVoid | t.CPtr = malloc(total)
if p:
string.memset(p, 0, total)
return p
def realloc(ptr: t.CVoid | t.CPtr, size: t.CSizeT) -> t.CVoid | t.CPtr | t.CExport:
if ptr is None: return malloc(size)
if size == 0:
free(ptr)
return None
hdr_size: t.CSizeT = _heap_hdr.__sizeof__()
hdr: _heap_hdr | t.CPtr = t.CVoid(t.CUInt64T(ptr) - hdr_size, t.CPtr)
if hdr.magic != HEAP_BLOCK_MAGIC: return None
old_size: t.CSizeT = hdr.size
new_ptr: t.CVoid | t.CPtr = malloc(size)
if new_ptr is None: return None
copy_size: t.CSizeT = old_size if old_size < size else size
string.memcpy(new_ptr, ptr, copy_size)
free(ptr)
return new_ptr