std/sys/alloc/
mod.rs

1#![forbid(unsafe_op_in_unsafe_fn)]
2
3use crate::alloc::{GlobalAlloc, Layout, System};
4use crate::ptr;
5
6// The minimum alignment guaranteed by the architecture. This value is used to
7// add fast paths for low alignment values.
8#[allow(dead_code)]
9const MIN_ALIGN: usize = if cfg!(any(
10    all(target_arch = "riscv32", any(target_os = "espidf", target_os = "zkvm")),
11    all(target_arch = "xtensa", target_os = "espidf"),
12)) {
13    // The allocator on the esp-idf and zkvm platforms guarantees 4 byte alignment.
14    4
15} else if cfg!(any(
16    target_arch = "x86",
17    target_arch = "arm",
18    target_arch = "m68k",
19    target_arch = "csky",
20    target_arch = "loongarch32",
21    target_arch = "mips",
22    target_arch = "mips32r6",
23    target_arch = "powerpc",
24    target_arch = "powerpc64",
25    target_arch = "sparc",
26    target_arch = "wasm32",
27    target_arch = "hexagon",
28    target_arch = "riscv32",
29    target_arch = "xtensa",
30)) {
31    8
32} else if cfg!(any(
33    target_arch = "x86_64",
34    target_arch = "aarch64",
35    target_arch = "arm64ec",
36    target_arch = "loongarch64",
37    target_arch = "mips64",
38    target_arch = "mips64r6",
39    target_arch = "s390x",
40    target_arch = "sparc64",
41    target_arch = "riscv64",
42    target_arch = "wasm64",
43)) {
44    16
45} else {
46    panic!("add a value for MIN_ALIGN")
47};
48
49#[allow(dead_code)]
50unsafe fn realloc_fallback(
51    alloc: &System,
52    ptr: *mut u8,
53    old_layout: Layout,
54    new_size: usize,
55) -> *mut u8 {
56    // SAFETY: Docs for GlobalAlloc::realloc require this to be valid
57    unsafe {
58        let new_layout = Layout::from_size_align_unchecked(new_size, old_layout.align());
59
60        let new_ptr = GlobalAlloc::alloc(alloc, new_layout);
61        if !new_ptr.is_null() {
62            let size = usize::min(old_layout.size(), new_size);
63            ptr::copy_nonoverlapping(ptr, new_ptr, size);
64            GlobalAlloc::dealloc(alloc, ptr, old_layout);
65        }
66
67        new_ptr
68    }
69}
70
71cfg_select! {
72    any(
73        target_family = "unix",
74        target_os = "wasi",
75        target_os = "teeos",
76        target_os = "trusty",
77    ) => {
78        mod unix;
79    }
80    target_os = "windows" => {
81        mod windows;
82    }
83    target_os = "hermit" => {
84        mod hermit;
85    }
86    all(target_vendor = "fortanix", target_env = "sgx") => {
87        mod sgx;
88    }
89    target_os = "solid_asp3" => {
90        mod solid;
91    }
92    target_os = "uefi" => {
93        mod uefi;
94    }
95    target_family = "wasm" => {
96        mod wasm;
97    }
98    target_os = "xous" => {
99        mod xous;
100    }
101    target_os = "zkvm" => {
102        mod zkvm;
103    }
104}