Skip to content

SGX: Fix fuzzy provenance casts with AtomicUsize #139775

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions library/std/src/sys/args/sgx.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
#![allow(fuzzy_provenance_casts)] // FIXME: this module systematically confuses pointers and integers

use crate::ffi::OsString;
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sync::OnceLock;
use crate::sys::os_str::Buf;
use crate::sys::pal::abi::usercalls::alloc;
use crate::sys::pal::abi::usercalls::raw::ByteBuffer;
Expand All @@ -11,23 +9,23 @@ use crate::{fmt, slice};
// Specifying linkage/symbol name is solely to ensure a single instance between this crate and its unit tests
#[cfg_attr(test, linkage = "available_externally")]
#[unsafe(export_name = "_ZN16__rust_internals3std3sys3sgx4args4ARGSE")]
static ARGS: AtomicUsize = AtomicUsize::new(0);
static ARGS: OnceLock<ArgsStore> = OnceLock::new();
type ArgsStore = Vec<OsString>;

#[cfg_attr(test, allow(dead_code))]
pub unsafe fn init(argc: isize, argv: *const *const u8) {
if argc != 0 {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
let args = args
.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
.collect::<ArgsStore>();
ARGS.store(Box::into_raw(Box::new(args)) as _, Ordering::Relaxed);
ARGS.get_or_init(|| {
let args = unsafe { alloc::User::<[ByteBuffer]>::from_raw_parts(argv as _, argc as _) };
args.iter()
.map(|a| OsString::from_inner(Buf { inner: a.copy_user_buffer() }))
.collect::<ArgsStore>()
});
}
}

pub fn args() -> Args {
let args = unsafe { (ARGS.load(Ordering::Relaxed) as *const ArgsStore).as_ref() };
let args = ARGS.get();
if let Some(args) = args { Args(args.iter()) } else { Args([].iter()) }
}

Expand Down
41 changes: 9 additions & 32 deletions library/std/src/sys/pal/sgx/os.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#![forbid(fuzzy_provenance_casts)]

use fortanix_sgx_abi::{Error, RESULT_SUCCESS};

use crate::collections::HashMap;
use crate::error::Error as StdError;
use crate::ffi::{OsStr, OsString};
use crate::marker::PhantomData;
use crate::path::{self, PathBuf};
use crate::sync::atomic::{AtomicUsize, Ordering};
use crate::sync::{Mutex, Once};
use crate::sync::{LazyLock, Mutex};
use crate::sys::{decode_error_kind, sgx_ineffective, unsupported};
use crate::{fmt, io, str, vec};

Expand Down Expand Up @@ -76,24 +77,9 @@ pub fn current_exe() -> io::Result<PathBuf> {
// Specifying linkage/symbol name is solely to ensure a single instance between this crate and its unit tests
#[cfg_attr(test, linkage = "available_externally")]
#[unsafe(export_name = "_ZN16__rust_internals3std3sys3pal3sgx2os3ENVE")]
static ENV: AtomicUsize = AtomicUsize::new(0);
// Specifying linkage/symbol name is solely to ensure a single instance between this crate and its unit tests
#[cfg_attr(test, linkage = "available_externally")]
#[unsafe(export_name = "_ZN16__rust_internals3std3sys3pal3sgx2os8ENV_INITE")]
static ENV_INIT: Once = Once::new();
static ENV: LazyLock<EnvStore> = LazyLock::new(|| EnvStore::default());
type EnvStore = Mutex<HashMap<OsString, OsString>>;

fn get_env_store() -> Option<&'static EnvStore> {
unsafe { (ENV.load(Ordering::Relaxed) as *const EnvStore).as_ref() }
}

fn create_env_store() -> &'static EnvStore {
ENV_INIT.call_once(|| {
ENV.store(Box::into_raw(Box::new(EnvStore::default())) as _, Ordering::Relaxed)
});
unsafe { &*(ENV.load(Ordering::Relaxed) as *const EnvStore) }
}

pub struct Env {
iter: vec::IntoIter<(OsString, OsString)>,
}
Expand Down Expand Up @@ -140,31 +126,22 @@ impl Iterator for Env {
}

pub fn env() -> Env {
let clone_to_vec = |map: &HashMap<OsString, OsString>| -> Vec<_> {
map.iter().map(|(k, v)| (k.clone(), v.clone())).collect()
};

let iter = get_env_store()
.map(|env| clone_to_vec(&env.lock().unwrap()))
.unwrap_or_default()
.into_iter();
Env { iter }
let env = ENV.lock().unwrap().iter().map(|(k, v)| (k.clone(), v.clone())).collect::<Vec<_>>();
Env { iter: env.into_iter() }
}

pub fn getenv(k: &OsStr) -> Option<OsString> {
get_env_store().and_then(|s| s.lock().unwrap().get(k).cloned())
ENV.lock().unwrap().get(k).cloned()
}

pub unsafe fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> {
let (k, v) = (k.to_owned(), v.to_owned());
create_env_store().lock().unwrap().insert(k, v);
ENV.lock().unwrap().insert(k, v);
Ok(())
}

pub unsafe fn unsetenv(k: &OsStr) -> io::Result<()> {
if let Some(env) = get_env_store() {
env.lock().unwrap().remove(k);
}
ENV.lock().unwrap().remove(k);
Ok(())
}

Expand Down
Loading