phobos icon indicating copy to clipboard operation
phobos copied to clipboard

std.process.environment is NOT SAFE

Open schveiguy opened this issue 1 year ago • 2 comments

Yet, all the members of the environment class are marked @safe or @trusted.

As an example, setting an environment variable on one thread, and reading it on another thread, could call setenv and getenv respectively. These functions are not thread safe, and getenv can easily return memory that is deallocated. I've even had getenv itself segfault, because it is iterating the environment pointer as it is being realloc'd in another thread.

We should lock around any reading or manipulation of environment. We can't mark these functions as not safe at this point.

schveiguy avatar Dec 10 '24 03:12 schveiguy

We are not alone. PHP suffers from this as well. A popular environment file loader library in their ecosystem specifically warns about this problem:

Using getenv() and putenv() is strongly discouraged due to the fact that these functions are not thread safe

0xEAB avatar Dec 10 '24 23:12 0xEAB

This is an abuse of @trusted. Since getenv and putenv are not thread-safe, @trusted is unwarranted here unless we implement locking.

quickfur avatar Jul 31 '25 00:07 quickfur