safa_api/syscalls/
process_misc.rs

1use crate::syscalls::types::{OptionalPtrMut, RequiredPtrMut};
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: OptZero<FFINonNull<*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: Str)
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: Slice<u8>, 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    let ptr = RequiredPtrMut::new(&raw mut target_ptr).into();
35    err_from_u16!(syssbrk(size, ptr), target_ptr)
36}
37
38#[inline]
39/// Changes the current work dir to `path`
40pub fn chdir(path: &str) -> Result<(), ErrorStatus> {
41    err_from_u16!(syschdir(Str::from_str(path)))
42}
43
44use alloc::string::String;
45use alloc::vec::Vec;
46use safa_abi::errors::ErrorStatus;
47use safa_abi::ffi::option::OptZero;
48use safa_abi::ffi::ptr::FFINonNull;
49use safa_abi::ffi::slice::Slice;
50use safa_abi::ffi::str::Str;
51
52#[inline]
53/// Retrieves the current work dir
54pub fn getcwd() -> Result<String, ErrorStatus> {
55    let mut buffer = Vec::with_capacity(safa_abi::consts::MAX_PATH_LENGTH);
56    unsafe {
57        buffer.set_len(buffer.capacity());
58    }
59
60    let mut dest_len: usize = 0xAAAAAAAAAAAAAAAAusize;
61    let ptr = RequiredPtrMut::new(&raw mut dest_len).into();
62    let len = err_from_u16!(sysgetcwd(Slice::from_slice(&buffer), ptr), dest_len)?;
63
64    buffer.truncate(len);
65    unsafe { Ok(String::from_utf8_unchecked(buffer)) }
66}