rs_libc/
lib.rs

1/* Copyright (c) Fortanix, Inc.
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7pub mod alloc;
8
9extern crate zeroize;
10use zeroize::Zeroize;
11
12/// Rust version of [`explicit_bzero`], implemented by using [`zeroize::Zeroize`](https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html)
13#[no_mangle]
14pub unsafe extern "C" fn explicit_bzero(buf: *mut std::ffi::c_void, len: alloc::size_t) {
15    let buffer = core::slice::from_raw_parts_mut(buf as *mut std::ffi::c_char, len);
16    buffer.zeroize();
17}
18
19#[cfg(test)]
20mod tests {
21    use std::ffi::c_void;
22
23    use super::*;
24
25    #[test]
26    fn test_explicit_bzero() {
27        let mut buf = [1u8, 2, 3, 4, 5];
28        let len = buf.len();
29
30        // Call the unsafe C function
31        unsafe {
32            explicit_bzero(buf.as_mut_ptr() as *mut c_void, len as alloc::size_t);
33        }
34
35        // Check that the buffer has been zeroed out
36        assert_eq!(&buf, &[0u8; 5]);
37    }
38
39    #[test]
40    fn test_explicit_bzero_zero_buffer() {
41        let mut buf = [0u8; 5];
42        let len = buf.len();
43
44        // Call the unsafe C function
45        unsafe {
46            explicit_bzero(buf.as_mut_ptr() as *mut c_void, len as alloc::size_t);
47        }
48
49        // Check that the buffer is still all zero
50        assert_eq!(&buf, &[0u8; 5]);
51    }
52}