proc.readEnv() improvements

- Minimize the risk of race conditions when we're prompting the user to
   allow/deny a connection, while we're still reading proc's environ file.
   (this was actually a leak).
 - Preallocate the Env map with the expected environ vars.
This commit is contained in:
Gustavo Iñiguez Goia 2025-02-17 14:15:28 +01:00
parent 6ba7265364
commit c6b42890c0
Failed to generate hash of commit

View file

@ -174,6 +174,7 @@ func (p *Process) ReadEnv() {
} }
raw = bytes.Trim(raw, "\r\n\t") raw = bytes.Trim(raw, "\r\n\t")
vars := strings.Split(string(raw), "\x00") vars := strings.Split(string(raw), "\x00")
env := make(map[string]string, len(vars))
for _, s := range vars { for _, s := range vars {
idx := strings.Index(s, "=") idx := strings.Index(s, "=")
if idx == -1 { if idx == -1 {
@ -182,10 +183,14 @@ func (p *Process) ReadEnv() {
key := s[:idx] key := s[:idx]
val := s[idx+1 : len(s)] val := s[idx+1 : len(s)]
p.mu.Lock() env[key] = val
p.Env[key] = val
p.mu.Unlock()
} }
// Minimize the risk of race conditions by not locking the map inside the loop.
// It may cause leaks when prompting the user to allow/deny.
p.mu.Lock()
p.Env = env
p.mu.Unlock()
} }
// ReadMaps reads the /proc/<pid>/maps file. // ReadMaps reads the /proc/<pid>/maps file.