minimal_rt/
rt.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Architecture-independent runtime support.
5
6#[cfg(minimal_rt)]
7#[expect(clippy::missing_safety_doc)]
8mod instead_of_builtins {
9    /// Implementation cribbed from compiler_builtins.
10    #[inline(always)]
11    unsafe fn copy_backward_bytes(mut dest: *mut u8, mut src: *const u8, n: usize) {
12        // SAFETY: The caller guarantees that the pointers and length are correct.
13        unsafe {
14            let dest_start = dest.sub(n);
15            while dest_start < dest {
16                dest = dest.sub(1);
17                src = src.sub(1);
18                *dest = *src;
19            }
20        }
21    }
22
23    unsafe extern "C" {
24        fn memcpy(dest: *mut u8, src: *const u8, n: usize) -> *mut u8;
25    }
26
27    /// Implementation cribbed from compiler_builtins.
28    // SAFETY: The minimal_rt_build crate ensures that when this code is compiled
29    // there is no libc for this to conflict with.
30    #[unsafe(no_mangle)]
31    unsafe extern "C" fn memmove(dest: *mut u8, src: *const u8, n: usize) -> *mut u8 {
32        let delta = (dest as usize).wrapping_sub(src as usize);
33        if delta >= n {
34            // SAFETY: We can copy forwards because either dest is far enough ahead of src,
35            // or src is ahead of dest (and delta overflowed).
36            unsafe {
37                memcpy(dest, src, n);
38            }
39        } else {
40            // SAFETY: dest and src must be copied backward due to src and dest.
41            unsafe {
42                let dest = dest.add(n);
43                let src = src.add(n);
44                copy_backward_bytes(dest, src, n);
45            }
46        }
47        dest
48    }
49
50    /// This implementation is cribbed from compiler_builtins. It would be nice to
51    /// use those implementation for all the above functions, but those require
52    /// nightly as these are not yet stabilized.
53    // SAFETY: The minimal_rt_build crate ensures that when this code is compiled
54    // there is no libc for this to conflict with.
55    #[unsafe(no_mangle)]
56    unsafe extern "C" fn bcmp(s1: *const u8, s2: *const u8, n: usize) -> i32 {
57        // SAFETY: The caller guarantees that the pointers and length are correct.
58        unsafe {
59            let mut i = 0;
60            while i < n {
61                let a = *s1.add(i);
62                let b = *s2.add(i);
63                if a != b {
64                    return a as i32 - b as i32;
65                }
66                i += 1;
67            }
68            0
69        }
70    }
71}