Skip to content

Commit

Permalink
miri: implement TlsFree
Browse files Browse the repository at this point in the history
If the variable does not need a destructor, `std` uses racy initialization for creating TLS keys on Windows. With just the right timing, this can lead to `TlsFree` being called. Unfortunately, with rust-lang#132654 this is hit quite often, so miri should definitely support `TlsFree` ([documentation](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-tlsfree)).

I'm filing this here instead of in the miri repo so that rust-lang#132654 isn't blocked for so long.
  • Loading branch information
joboet committed Nov 25, 2024
1 parent 7db7489 commit 77fccf5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/tools/miri/src/shims/windows/foreign_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,14 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
// Return success (`1`).
this.write_int(1, dest)?;
}
"TlsFree" => {
let [key] = this.check_shim(abi, ExternAbi::System { unwind: false }, link_name, args)?;
let key = u128::from(this.read_scalar(key)?.to_u32()?);
this.machine.tls.delete_tls_key(key)?;

// Return success (`1`).
this.write_int(1, dest)?;
}

// Access to command-line arguments
"GetCommandLineW" => {
Expand Down
18 changes: 18 additions & 0 deletions src/tools/miri/tests/pass/tls/windows-tls.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//@only-target: windows # this directly tests windows-only functions

use std::ffi::c_void;
use std::ptr;

extern "system" {
fn TlsAlloc() -> u32;
fn TlsSetValue(key: u32, val: *mut c_void) -> bool;
fn TlsGetValue(key: u32) -> *mut c_void;
fn TlsFree(key: u32) -> bool;
}

fn main() {
let key = unsafe { TlsAlloc() };
assert!(unsafe { TlsSetValue(key, ptr::without_provenance_mut(1)) });
assert_eq!(unsafe { TlsGetValue(key).addr() }, 1);
assert!(unsafe { TlsFree(key) });
}

0 comments on commit 77fccf5

Please sign in to comment.