by oefrha · 3y ago · 0 comments
Edit: I just realized macOS/FreeBSD has execvP() that allows passing a custom search path, so PATH is now safe, but without a -e variant, everything else is again unsafe.
So, shells use a single thread that can safely modify the environment - then start new child processes by the same thread. The child processes get a =copy= of the said environment. That's a textbook example how to use env.
Starting multiple threads on your own, then modifying env should be considered a textbook example how not to do things - env is not intended for interprocess communication.
Sort of. https://pubs.opengroup.org/onlinepubs/9699919799/functions/g...:
“The returned string pointer might be invalidated or the string content might be overwritten by a subsequent call to getenv()”
There’s little you can do with a broken API, so Linux has that ‘feature’, too. https://man7.org/linux/man-pages/man3/getenv.3.html:
“The string pointed to by the return value of getenv() may be statically allocated, and can be modified by a subsequent call to getenv(), putenv(3), setenv(3), or unsetenv(3).”
FreeBSD chooses to leak memory, instead. https://man.freebsd.org/cgi/man.cgi?getenv(3):
“Successive calls to setenv() that assign a larger-sized value than any previous value to the same name will result in a memory leak. The FreeBSD semantics for this function (namely, that the contents of value are copied and that old values remain accessible indefinitely) make this bug unavoidable”
(Edit: removed unneeded pointing out execve)
Also shells generally have their own program search anyway since they need to support built-in commands. It's not particularly hard to implement PATH search.
As for I’m not aware of execve etc… You need to re-read my comment which clearly mentions execve, execvep, posix_spawn, as well as implementing PATH search on your own.
I am the OP and your assumption is incorrect. You may consider why the post ends with:
(NB: starting a new process is not "at runtime")In a program you could have either.