DEV Community

Serguey Asael Shinder
Serguey Asael Shinder

Posted on

Your Rust Code Sets an Environment Variable and the 2024 Edition Calls That Unsafe

The service had one line
at the top of main:

std::env::set_var("TZ", "UTC");

Harmless for years.

Then the team
moved the crate
to the 2024 edition.

It stopped compiling.

The compiler said
set_var is an unsafe function
and needs an unsafe block.

One environment variable.

Unsafe.

Here is the mechanism.

On Linux and most Unix systems,
the environment is a plain C array
owned by the C library.

setenv can move it,
or free old entries,
while it changes it.

getenv reads it
with no lock that Rust controls.

Rust's own std::env functions
take a lock.

C code does not.

And C code
reads the environment
all the time.

Time zone lookups.

DNS resolution.

Locale setup.

Any C library
your crate links.

So one thread sets a variable
while another resolves a hostname,
and the reader can follow a pointer
into memory that was just freed.

A crash.

Or wrong data.

Or nothing,
for months,
and then a crash
nobody can reproduce.

Rust's promise
is that safe code
cannot cause that.

set_var could.

So Rust 1.85,
in February 2025,
shipped the 2024 edition
with set_var and remove_var
marked unsafe.

Older editions still compile them
as safe.

The bug was always there.

The edition only
makes you sign for it.

cargo fix --edition
will wrap the calls
in unsafe blocks for you.

Do not stop there.

An unsafe block
is a promise
that no other thread
can touch the environment.

Check whether you can keep it.

Better moves:

Set the variable
before your program starts,
in the unit file,
the container,
the shell.

Pass configuration
as arguments or structs,
not through the environment.

For child processes,
use Command::env,
which sets it
for the child only.

If it must happen in-process,
do it first thing in main,
before the async runtime,
before any thread,
and write down why.

The 2024 edition
is not adding a danger.

It is pointing at one
your code already had.

– Serguey Asael Shinder

Top comments (0)