How do functions like getenv(3) access the environment when my program doesn’t have any references to the environment?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Your program doesn’t have a reference to the environment, but a whole copy of it.
The command line arguments and environment strings (as they were passed to the execve(2) system call) are all packed together and copied in the address space of the process [1].
In a typical implementation [2], two NULL-terminated lists of pointers to them (representing the argument lists and the environment) are made available on the stack to the entry point of the program (_start), where the startup code (run before main()) will point the char **environ global variable to the beginning of the latter.
The getenv(3) function is simply looking through that environ list and comparing each entry in turn.
When some new entry has to be added to the environment (as with setenv(3)), the environ list will be relocated elsewhere.
[1] On Linux, the addresses of the argument list and environment variables are accessible as the 48th and 50th fields of /proc/PID/stat, see procfs(5).
[2] In glibc, _start will pop argc, point argv to the top of the stack, and __libc_start_main will set __environ (an alias for environ) to argv + argc + 1.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0