0

When a process execs, looking at kernel code for environ_read(), it seems that if the mm_struct doesn't yet exist / is null or the env_end member of that mm_struct is null, environ_read() will return 0 ~immediately.

My question is, are there protections WRT fork/exec races such that (pseudo-code ahead)

if ((pid = fork) != 0) execv*("/bin/exe", {"exe", "-l"}, &envp) read("/proc/${pid}/environ") 

Cannot:

A: erroneously read a zero-length env due to races with execve and the subsequent read (e.g: assuming the user space program that issues the read is multi-threaded or performing asynchronous IO)

B: erroneously read a partial env (assuming user-space code is not causing a short read due to a bug in user space code)

C: erroneously read the parent's env

Are reads from /p/p/environ atomic?

1 Answer 1

0

I ended up patching the kernel code just to be certain and the answer is definitely NO, it's not safe to assume if the pid exists / fork returned > 0 that you can assume the env is safe and sanely accessible at /p/p/environ.

You can get an erroneous Zero-length read if you fork(), exec() and then try to read /proc/pid/environ for the new process.

Why not block on the read until it's ready Linux upstream? Oh well, question answered!

envrion_read does this:

/* Ensure the process spawned far enough to have an environment. */ if (!mm || !mm->env_end) return 0 

That means if you read it too early, read will get zero bytes, so they've put the onus on user-space to check the read.

2
  • If the process is a zombie, the mm has been cleaned up as well. If your process is the parent, you have a guarantee that the PID still exists and has not been reused. Commented Nov 19, 2024 at 14:34
  • Also, the environment accessible via proc is the initial environment, not the current one, so if you started the process, there is no point in reading it. Commented Nov 19, 2024 at 14:35

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.