Skip to main content

relibc/header/unistd/
brk.rs

1use core::ptr;
2
3use crate::{
4    error::ResultExtPtrMut,
5    header::errno::ENOMEM,
6    platform::{
7        self, Pal, Sys,
8        types::{c_int, c_void, intptr_t},
9    },
10};
11
12static mut BRK: *mut c_void = ptr::null_mut();
13
14/// See <https://pubs.opengroup.org/onlinepubs/7908799/xsh/brk.html>.
15///
16/// # Deprecation
17/// The `brk()` function was marked legacy in the System Interface & Headers
18/// Issue 5, and removed in Issue 6.
19#[deprecated]
20#[unsafe(no_mangle)]
21pub unsafe extern "C" fn brk(addr: *mut c_void) -> c_int {
22    unsafe { BRK = Sys::brk(addr).or_errno_null_mut() };
23
24    if unsafe { BRK } < addr {
25        platform::ERRNO.set(ENOMEM);
26        return -1;
27    }
28
29    0
30}
31
32/// See <https://pubs.opengroup.org/onlinepubs/7908799/xsh/brk.html>.
33///
34/// # Deprecation
35/// The `sbrk()` function was marked legacy in the System Interface & Headers
36/// Issue 5, and removed in Issue 6.
37#[deprecated]
38#[unsafe(no_mangle)]
39pub unsafe extern "C" fn sbrk(incr: intptr_t) -> *mut c_void {
40    if unsafe { BRK }.is_null() {
41        unsafe { BRK = Sys::brk(ptr::null_mut()).or_errno_null_mut() };
42    }
43
44    let old_brk = unsafe { BRK };
45
46    if incr != 0 {
47        let addr = unsafe { old_brk.offset(incr) };
48
49        unsafe { BRK = Sys::brk(addr).or_errno_null_mut() };
50
51        if unsafe { BRK } < addr {
52            platform::ERRNO.set(ENOMEM);
53            return -1isize as *mut c_void;
54        }
55    }
56
57    old_brk.cast::<c_void>()
58}