Skip to content

Copy ENV before building a spawned process's environment - #10108

Open
sampokuokkanen wants to merge 1 commit into
jruby:jruby-10.0from
sampokuokkanen:env-spawn-snapshot
Open

sampokuokkanen wants to merge 1 commit into
jruby:jruby-10.0from
sampokuokkanen:env-spawn-snapshot

Conversation

@sampokuokkanen

Copy link
Copy Markdown
Contributor

Fixes #10031.

Without an env hash, spawn, system, backticks and popen walked the live ENV into an array sized from ENV.size. If another thread added a key meanwhile, it raised ArrayIndexOutOfBoundsException:

Thread.new { i = 0; loop { ENV["REPRO_#{i += 1}"] = "x" } }
100.times { `echo` }

Now ENV is copied first, as the env-hash path already does and as CRuby does in rb_execarg_parent_start1 with rb_env_to_hash.

Tested with a stress variant (running /usr/bin/true by full path to avoid the PATH race below): 9000 backticks with no errors, against about 250 exceptions per 3000 before. Process, popen and ENV specs pass.

Noticed but not fixed:

  • JRuby's ENV has no lock, so ENV["PATH"] can return nil under concurrent writes (about once in 2 million reads) and a spawn can fail with Errno::ENOENT. CRuby locks every ENV operation (ENV_LOCKING).
  • JRubyPOSIXHandler.getEnv walks the live ENV the same way.

Without an env hash, execargParentStart1 walked the live ENV hash, and
buildEnvp had sized its array from ENV.size first. If another thread
added a key during the walk, it raised ArrayIndexOutOfBoundsException
(jruby#10031):

    Thread.new { i = 0; loop { ENV["REPRO_#{i += 1}"] = "x" } }
    100.times { `echo` }

Copy ENV first, as the path with an env hash already does and as MRI
does with rb_env_to_hash.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant