Execve () and environment variables

I have a question about how Linux handles varibales variables for execve ():

Synopsis for execve (): int execve (const char * filename, char * const argv [], char * const envp []);

Before calling execve (), we allocate memory to store envs / args from the current process memory mapping. But after execve (), the entire text / data / bss / stack of the calling process is overwritten by the new program, and all the memory mappings of the old process are not saved (including memory for passed envs / args).

For a new program, where to read envs / args? Does the kernel create a copy of the passed envs / args and put it in a new memory mapping or some other tricks?

+4
source share
1 answer

Yes.

When the process calls exec , the kernel copies all the argv and envp . Then they are copied into a new process image - especially when the program starts, its stack looks like this:

 NULL ... envp[1] envp[0] NULL argv[argc-1] ... argv[1] argv[0] argc 

Glibc's startup code in _start massages it into the correct form to invoke main .

(For more information, the copy from the old process is executed in linux/fs/exec.c , the copy of the new process is executed in linux/fs/binfmt_elf.c , and the program is launched in architecture-specific code, for example glibc/sysdeps/i386/start.S , glibc/sysdeps/x86_64/start.S , or glibc/ports/sysdeps/arm/start.S , which only exist to start at __libc_start_main in glibc/csu/libc-start.c , which starts main .)

+8
source

All Articles