safa_api/syscalls/
process_misc.rs

1use crate::syscalls::types::{OptionalPtrMut, StrPtr, StrPtrMut};
2
3use super::{define_syscall, err_from_u16, SyscallNum};
4
5#[cfg(not(feature = "rustc-dep-of-std"))]
6extern crate alloc;
7
8define_syscall! {
9    SyscallNum::SysSbrk => {
10        /// Increases the range of the process's data break by `size` bytes and puts the new break pointer in `target_ptr`
11        syssbrk(size: isize, target_ptr: OptionalPtrMut<*mut u8>)
12    },
13    SyscallNum::SysCHDir => {
14        /// Changes the current working directory to the path `buf` with length `buf_len`
15        /// (expects given buffer to be utf-8)
16        syschdir(buf_ptr: StrPtr, buf_len: usize)
17    },
18    SyscallNum::SysGetCWD => {
19        /// Gets the current working directory and puts it in `cwd_buf` with length `cwd_buf_len`
20        /// if `dest_len` is not null, it will be set to the length of the cwd
21        /// if the cwd is too long to fit in `cwd_buf`, the syscall will return [`ErrorStatus::Generic`] (1)
22        /// the cwd is currently maximumally 1024 bytes
23        sysgetcwd(cwd_buf: StrPtrMut, cwd_buf_len: usize, dest_len: OptionalPtrMut<usize>)
24    }
25}
26
27#[inline]
28/// Increases the range of the process's data break by `size` bytes
29/// returns the new break pointer
30///
31/// you should probably use [`crate::alloc::GLOBAL_SYSTEM_ALLOCATOR`] instead for allocating memory
32pub fn sbrk(size: isize) -> Result<*mut u8, ErrorStatus> {
33    let mut target_ptr: *mut u8 = core::ptr::null_mut();
34    err_from_u16!(syssbrk(size, &mut target_ptr), target_ptr)
35}
36
37#[inline]
38/// Changes the current work dir to `path`
39pub fn chdir(path: &str) -> Result<(), ErrorStatus> {
40    let path = path.as_bytes();
41    err_from_u16!(syschdir(path.as_ptr(), path.len()))
42}
43
44use alloc::string::String;
45use alloc::vec::Vec;
46use safa_abi::errors::ErrorStatus;
47
48#[inline]
49/// Retrieves the current work dir
50pub fn getcwd() -> Result<String, ErrorStatus> {
51    let mut buffer = Vec::with_capacity(safa_abi::consts::MAX_PATH_LENGTH);
52    unsafe {
53        buffer.set_len(buffer.capacity());
54    }
55
56    let mut dest_len: usize = 0xAAAAAAAAAAAAAAAAusize;
57    let len = err_from_u16!(
58        sysgetcwd(buffer.as_mut_ptr(), buffer.len(), &raw mut dest_len),
59        dest_len
60    )?;
61
62    buffer.truncate(len);
63    unsafe { Ok(String::from_utf8_unchecked(buffer)) }
64}