Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execve() and environment variables

Tags:

c

linux

I've got a question with how Linux process the environment varibales passed to execve():

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

Before calling execve(), we allocate the memory for holding envs/args from current process's memory mapping. But after execve(), all the text/data/bss/stack of the calling process are overwriten by the new program, and all the memory mappings of the old process are not preserved (including the memory for passed envs/args).

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

like image 336
PromisE Avatar asked Jan 16 '23 19:01

PromisE


1 Answers

Yes.

When a process calls exec, the kernel copies the entire argv and envp arrays. Then, these are copied into the new process image -- notably, when the program starts running, its stack looks like:

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

The Glibc startup code in _start massages this into the proper form to invoke main.

(For more details, the copy from the old process is done in linux/fs/exec.c, the copy to the new process is done in linux/fs/binfmt_elf.c, and program startup is done in architecture-specific code such as glibc/sysdeps/i386/start.S, glibc/sysdeps/x86_64/start.S, or glibc/ports/sysdeps/arm/start.S, which exist just to kick off into __libc_start_main in glibc/csu/libc-start.c which launches main.)

like image 113
ephemient Avatar answered Jan 25 '23 19:01

ephemient