Having a free function in
std::env that allows a user to obtain Rust's internal lock on the execution environment would allow for significantly safer usage of FFI. Currently, the documentation for
Note that while concurrent access to environment variables is safe in Rust, some platforms only expose inherently unsafe non-threadsafe APIs for inspecting the environment. As a result, extra care needs to be taken when auditing calls to unsafe external FFI functions to ensure that any external environment accesses are properly synchronized with accesses in Rust.
To my understanding, Rust's
std::env::var and similar currently use an internal lock to ensure synchronization. This works great, so long as you stay within Rust. The second FFI is introduced, "extra care needs to be taken". Realistically, this isn't feasible currently, and this has led to soundness issues like time-rs/time#293; there are certainly other issues like this that exist in the ecosystem.
As a solution, it would make sense to have either a function that returns a lock (which releases on drop) or a function that accepts a closure, which is executed while the lock is held. This was briefly discussed in rust-lang/rust#27970. @RalfJung pointed out that the current use of the environment lock is incorrect, though I honestly don't understand how.
Speaking personally, I have seen a few crates pin time to 0.2.22, explicitly including unsoundness despite the fact that they could not possibly know whether the crate's consumers are upholding safety invariants (which are global in this case).