GeezerVison is showing github.com — child_process: build the default env block in one native pass · nodejs/node@db5d16a
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: lib/child_process.js +95-50Lines changed: 95 additions & 50 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -41,6 +41,7 @@ const { | 41 | 41 | RegExpPrototypeExec, | 42 | 42 | SafeSet, | 43 | 43 | StringPrototypeIncludes, | | 44 | + StringPrototypeIndexOf, | 44 | 45 | StringPrototypeSlice, | 45 | 46 | StringPrototypeToUpperCase, | 46 | 47 | SymbolDispose, | @@ -93,6 +94,8 @@ const { | 93 | 94 | stdioStringToArray, | 94 | 95 | } = child_process; | 95 | 96 |
| | 97 | +const { getEnvPairs } = internalBinding('process_wrap'); | | 98 | + | 96 | 99 | const MAX_BUFFER = 1024 * 1024; | 97 | 100 |
| 98 | 101 | const permission = require('internal/process/permission'); | @@ -697,60 +700,74 @@ function normalizeSpawnArguments(file, args, options) { | 697 | 700 | ArrayPrototypeUnshift(args, file); | 698 | 701 | } | 699 | 702 |
| 700 | | - // Shallow copy to guarantee changes won't impact process.env | 701 | | - const env = options.env || { ...process.env }; | 702 | | - const envPairs = []; | 703 | | - | 704 | | - // process.env.NODE_V8_COVERAGE always propagates, making it possible to | 705 | | - // collect coverage for programs that spawn with white-listed environment. | 706 | | - copyProcessEnvToEnv(env, 'NODE_V8_COVERAGE', options.env); | 707 | | - | 708 | | - if (isZOS) { | 709 | | - // The following environment variables must always propagate if set. | 710 | | - copyProcessEnvToEnv(env, '_BPXK_AUTOCVT', options.env); | 711 | | - copyProcessEnvToEnv(env, '_CEE_RUNOPTS', options.env); | 712 | | - copyProcessEnvToEnv(env, '_TAG_REDIR_ERR', options.env); | 713 | | - copyProcessEnvToEnv(env, '_TAG_REDIR_IN', options.env); | 714 | | - copyProcessEnvToEnv(env, '_TAG_REDIR_OUT', options.env); | 715 | | - copyProcessEnvToEnv(env, 'STEPLIB', options.env); | 716 | | - copyProcessEnvToEnv(env, 'LIBPATH', options.env); | 717 | | - copyProcessEnvToEnv(env, '_EDC_SIG_DFLT', options.env); | 718 | | - copyProcessEnvToEnv(env, '_EDC_SUSV3', options.env); | 719 | | - } | | 703 | + let envPairs; | | 704 | + if (!options.env && !permission.isEnabled()) { | | 705 | + // Default: the child inherits this process's environment. Take it as | | 706 | + // 'KEY=value' strings in one native pass over the environment block | | 707 | + // instead of copying process.env (one interceptor round trip and one | | 708 | + // getenv() scan per variable). Everything copyProcessEnvToEnv() would | | 709 | + // propagate below is part of it by definition, and entries of the real | | 710 | + // environment block cannot contain null bytes. | | 711 | + envPairs = getEnvPairs(); | | 712 | + if (process.platform === 'win32') { | | 713 | + envPairs = dedupeWindowsEnvPairs(envPairs); | | 714 | + } | | 715 | + } else { | | 716 | + // Shallow copy to guarantee changes won't impact process.env | | 717 | + const env = options.env || { ...process.env }; | | 718 | + envPairs = []; | | 719 | + | | 720 | + // process.env.NODE_V8_COVERAGE always propagates, making it possible to | | 721 | + // collect coverage for programs that spawn with white-listed environment. | | 722 | + copyProcessEnvToEnv(env, 'NODE_V8_COVERAGE', options.env); | | 723 | + | | 724 | + if (isZOS) { | | 725 | + // The following environment variables must always propagate if set. | | 726 | + copyProcessEnvToEnv(env, '_BPXK_AUTOCVT', options.env); | | 727 | + copyProcessEnvToEnv(env, '_CEE_RUNOPTS', options.env); | | 728 | + copyProcessEnvToEnv(env, '_TAG_REDIR_ERR', options.env); | | 729 | + copyProcessEnvToEnv(env, '_TAG_REDIR_IN', options.env); | | 730 | + copyProcessEnvToEnv(env, '_TAG_REDIR_OUT', options.env); | | 731 | + copyProcessEnvToEnv(env, 'STEPLIB', options.env); | | 732 | + copyProcessEnvToEnv(env, 'LIBPATH', options.env); | | 733 | + copyProcessEnvToEnv(env, '_EDC_SIG_DFLT', options.env); | | 734 | + copyProcessEnvToEnv(env, '_EDC_SUSV3', options.env); | | 735 | + } | 720 | 736 |
| 721 | | - if (permission.isEnabled()) { | 722 | | - copyPermissionModelFlagsToEnv(env, 'NODE_OPTIONS', args); | 723 | | - } | | 737 | + if (permission.isEnabled()) { | | 738 | + copyPermissionModelFlagsToEnv(env, 'NODE_OPTIONS', args); | | 739 | + } | 724 | 740 |
| 725 | | - let envKeys = []; | 726 | | - // Prototype values are intentionally included. | 727 | | - for (const key in env) { | 728 | | - ArrayPrototypePush(envKeys, key); | 729 | | - } | | 741 | + let envKeys = []; | | 742 | + // Prototype values are intentionally included. | | 743 | + for (const key in env) { | | 744 | + ArrayPrototypePush(envKeys, key); | | 745 | + } | 730 | 746 |
| 731 | | - if (process.platform === 'win32') { | 732 | | - // On Windows env keys are case insensitive. Filter out duplicates, | 733 | | - // keeping only the first one (in lexicographic order) | 734 | | - const sawKey = new SafeSet(); | 735 | | - envKeys = ArrayPrototypeFilter( | 736 | | - ArrayPrototypeSort(envKeys), | 737 | | - (key) => { | 738 | | - const uppercaseKey = StringPrototypeToUpperCase(key); | 739 | | - if (sawKey.has(uppercaseKey)) { | 740 | | - return false; | 741 | | - } | 742 | | - sawKey.add(uppercaseKey); | 743 | | - return true; | 744 | | - }, | 745 | | - ); | 746 | | - } | | 747 | + if (process.platform === 'win32') { | | 748 | + // On Windows env keys are case insensitive. Filter out duplicates, | | 749 | + // keeping only the first one (in lexicographic order) | | 750 | + const sawKey = new SafeSet(); | | 751 | + envKeys = ArrayPrototypeFilter( | | 752 | + ArrayPrototypeSort(envKeys), | | 753 | + (key) => { | | 754 | + const uppercaseKey = StringPrototypeToUpperCase(key); | | 755 | + if (sawKey.has(uppercaseKey)) { | | 756 | + return false; | | 757 | + } | | 758 | + sawKey.add(uppercaseKey); | | 759 | + return true; | | 760 | + }, | | 761 | + ); | | 762 | + } | 747 | 763 |
| 748 | | - for (const key of envKeys) { | 749 | | - const value = env[key]; | 750 | | - if (value !== undefined) { | 751 | | - validateArgumentNullCheck(key, `options.env['${key}']`); | 752 | | - validateArgumentNullCheck(value, `options.env['${key}']`); | 753 | | - ArrayPrototypePush(envPairs, `${key}=${value}`); | | 764 | + for (const key of envKeys) { | | 765 | + const value = env[key]; | | 766 | + if (value !== undefined) { | | 767 | + validateArgumentNullCheck(key, `options.env['${key}']`); | | 768 | + validateArgumentNullCheck(value, `options.env['${key}']`); | | 769 | + ArrayPrototypePush(envPairs, `${key}=${value}`); | | 770 | + } | 754 | 771 | } | 755 | 772 | } | 756 | 773 |
| @@ -768,6 +785,34 @@ function normalizeSpawnArguments(file, args, options) { | 768 | 785 | }; | 769 | 786 | } | 770 | 787 |
| | 788 | +/** | | 789 | + * Windows environment variable names are case-insensitive: keep only the | | 790 | + * first entry for each name in lexicographic order of the names, exactly like | | 791 | + * the key filtering applied to a user-supplied `options.env`. | | 792 | + * @param {string[]} envPairs 'KEY=value' strings | | 793 | + * @returns {string[]} | | 794 | + */ | | 795 | +function dedupeWindowsEnvPairs(envPairs) { | | 796 | + const keyed = []; | | 797 | + for (let i = 0; i < envPairs.length; i++) { | | 798 | + const pair = envPairs[i]; | | 799 | + // Names never start with '=' here (hidden variables are not enumerated), | | 800 | + // so the first '=' ends the name. | | 801 | + const eq = StringPrototypeIndexOf(pair, '='); | | 802 | + ArrayPrototypePush(keyed, { key: eq === -1 ? pair : StringPrototypeSlice(pair, 0, eq), pair }); | | 803 | + } | | 804 | + ArrayPrototypeSort(keyed, (a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)); | | 805 | + const sawKey = new SafeSet(); | | 806 | + const result = []; | | 807 | + for (let i = 0; i < keyed.length; i++) { | | 808 | + const uppercaseKey = StringPrototypeToUpperCase(keyed[i].key); | | 809 | + if (sawKey.has(uppercaseKey)) continue; | | 810 | + sawKey.add(uppercaseKey); | | 811 | + ArrayPrototypePush(result, keyed[i].pair); | | 812 | + } | | 813 | + return result; | | 814 | +} | | 815 | + | 771 | 816 | function abortChildProcess(child, killSignal, reason) { | 772 | 817 | if (!child) | 773 | 818 | return; | |
Collapse file Copy file name to clipboardExpand all lines: src/node_env_var.cc +60Lines changed: 60 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -14,6 +14,7 @@ using v8::Boolean; | 14 | 14 | using v8::Context; | 15 | 15 | using v8::DontDelete; | 16 | 16 | using v8::DontEnum; | | 17 | +using v8::EscapableHandleScope; | 17 | 18 | using v8::FunctionTemplate; | 18 | 19 | using v8::HandleScope; | 19 | 20 | using v8::Integer; | @@ -45,6 +46,7 @@ class RealEnvStore final : public KVStore { | 45 | 46 | int32_t Query(const char* key) const override; | 46 | 47 | void Delete(Isolate* isolate, Local<String> key) override; | 47 | 48 | MaybeLocal<Array> Enumerate(Isolate* isolate) const override; | | 49 | + MaybeLocal<Array> Pairs(Isolate* isolate) const override; | 48 | 50 | }; | 49 | 51 |
| 50 | 52 | class MapKVStore final : public KVStore { | @@ -217,6 +219,64 @@ MaybeLocal<Array> RealEnvStore::Enumerate(Isolate* isolate) const { | 217 | 219 | return Array::New(isolate, env_v.out(), env_v_index); | 218 | 220 | } | 219 | 221 |
| | 222 | +MaybeLocal<Array> RealEnvStore::Pairs(Isolate* isolate) const { | | 223 | + Mutex::ScopedLock lock(per_process::env_var_mutex); | | 224 | + uv_env_item_t* items; | | 225 | + int count; | | 226 | + | | 227 | + auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); }); | | 228 | + CHECK_EQ(uv_os_environ(&items, &count), 0); | | 229 | + | | 230 | + MaybeStackBuffer<Local<Value>, 256> pairs_v(count); | | 231 | + int pairs_v_index = 0; | | 232 | + std::string pair; | | 233 | + for (int i = 0; i < count; i++) { | | 234 | +#ifdef _WIN32 | | 235 | + // If the key starts with '=' it is a hidden environment variable. | | 236 | + // Enumerate() skips these, so a copy of process.env never had them. | | 237 | + if (items[i].name[0] == '=') continue; | | 238 | +#endif | | 239 | + pair.assign(items[i].name); | | 240 | + pair += '='; | | 241 | + pair += items[i].value; | | 242 | + Local<Value> str; | | 243 | + if (!ToV8Value(isolate->GetCurrentContext(), pair, isolate).ToLocal(&str)) { | | 244 | + return {}; | | 245 | + } | | 246 | + pairs_v[pairs_v_index++] = str; | | 247 | + } | | 248 | + | | 249 | + return Array::New(isolate, pairs_v.out(), pairs_v_index); | | 250 | +} | | 251 | + | | 252 | +MaybeLocal<Array> KVStore::Pairs(Isolate* isolate) const { | | 253 | + EscapableHandleScope scope(isolate); | | 254 | + Local<Context> context = isolate->GetCurrentContext(); | | 255 | + Local<Array> keys; | | 256 | + if (!Enumerate(isolate).ToLocal(&keys)) return {}; | | 257 | + uint32_t keys_length = keys->Length(); | | 258 | + MaybeStackBuffer<Local<Value>, 256> pairs(keys_length); | | 259 | + uint32_t pairs_index = 0; | | 260 | + std::string pair; | | 261 | + for (uint32_t i = 0; i < keys_length; i++) { | | 262 | + Local<Value> key; | | 263 | + if (!keys->Get(context, i).ToLocal(&key)) return {}; | | 264 | + if (!key->IsString()) continue; | | 265 | + Utf8Value key_utf8(isolate, key); | | 266 | + // A key that disappeared between Enumerate() and Get() is skipped, like an | | 267 | + // undefined value is when copying process.env in JS. | | 268 | + std::optional<std::string> value = Get(*key_utf8); | | 269 | + if (!value.has_value()) continue; | | 270 | + pair.assign(*key_utf8, key_utf8.length()); | | 271 | + pair += '='; | | 272 | + pair += *value; | | 273 | + Local<Value> str; | | 274 | + if (!ToV8Value(context, pair, isolate).ToLocal(&str)) return {}; | | 275 | + pairs[pairs_index++] = str; | | 276 | + } | | 277 | + return scope.Escape(Array::New(isolate, pairs.out(), pairs_index)); | | 278 | +} | | 279 | + | 220 | 280 | std::shared_ptr<KVStore> KVStore::Clone(Isolate* isolate) const { | 221 | 281 | HandleScope handle_scope(isolate); | 222 | 282 | Local<Context> context = isolate->GetCurrentContext(); | |
Collapse file Copy file name to clipboardExpand all lines: src/process_wrap.cc +13Lines changed: 13 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -79,6 +79,7 @@ class ProcessWrap : public HandleWrap { | 79 | 79 | SetProtoMethod(isolate, constructor, "kill", Kill); | 80 | 80 |
| 81 | 81 | SetConstructorFunction(context, target, "Process", constructor); | | 82 | + SetMethodNoSideEffect(context, target, "getEnvPairs", GetEnvPairs); | 82 | 83 |
| 83 | 84 | Local<Object> constants = Object::New(isolate); | 84 | 85 | NODE_DEFINE_CONSTANT(constants, kProcessFlagDetached); | @@ -91,6 +92,7 @@ class ProcessWrap : public HandleWrap { | 91 | 92 | registry->Register(New); | 92 | 93 | registry->Register(Spawn); | 93 | 94 | registry->Register(Kill); | | 95 | + registry->Register(GetEnvPairs); | 94 | 96 | } | 95 | 97 |
| 96 | 98 | SET_NO_MEMORY_INFO() | @@ -342,6 +344,17 @@ class ProcessWrap : public HandleWrap { | 342 | 344 | args.GetReturnValue().Set(err); | 343 | 345 | } | 344 | 346 |
| | 347 | + // The current environment as ["KEY=value", ...], i.e. what a spawned | | 348 | + // child inherits by default, produced in one pass over the environment | | 349 | + // block instead of one interceptor round trip per variable. | | 350 | + static void GetEnvPairs(const FunctionCallbackInfo<Value>& args) { | | 351 | + Environment* env = Environment::GetCurrent(args); | | 352 | + Local<Array> pairs; | | 353 | + if (env->env_vars()->Pairs(env->isolate()).ToLocal(&pairs)) { | | 354 | + args.GetReturnValue().Set(pairs); | | 355 | + } | | 356 | + } | | 357 | + | 345 | 358 | static void Kill(const FunctionCallbackInfo<Value>& args) { | 346 | 359 | Environment* env = Environment::GetCurrent(args); | 347 | 360 | ProcessWrap* wrap; | |
Collapse file Copy file name to clipboardExpand all lines: src/util.h +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -321,6 +321,10 @@ class KVStore { | 321 | 321 | virtual int32_t Query(const char* key) const = 0; | 322 | 322 | virtual void Delete(v8::Isolate* isolate, v8::Local<v8::String> key) = 0; | 323 | 323 | virtual v8::MaybeLocal<v8::Array> Enumerate(v8::Isolate* isolate) const = 0; | | 324 | + // All entries as an array of "KEY=value" strings, in enumeration order — | | 325 | + // the form uv_spawn() consumes. The default implementation is | | 326 | + // Enumerate() + Get(); stores that can produce it in one pass override it. | | 327 | + virtual v8::MaybeLocal<v8::Array> Pairs(v8::Isolate* isolate) const; | 324 | 328 |
| 325 | 329 | virtual std::shared_ptr<KVStore> Clone(v8::Isolate* isolate) const; | 326 | 330 | virtual v8::Maybe<void> AssignFromObject(v8::Local<v8::Context> context, | |
Collapse file Copy file name to clipboard +76Lines changed: 76 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | +// When no `env` option is given, a child process must inherit exactly the | | 3 | +// parent's current environment: same variables and values, reflecting runtime | | 4 | +// additions/deletions made through process.env. | | 5 | +const common = require('../common'); | | 6 | +const assert = require('assert'); | | 7 | +const { spawn, spawnSync, execFileSync } = require('child_process'); | | 8 | + | | 9 | +// Mutate the environment at runtime in a few ways first. | | 10 | +process.env.TEST_DEFAULT_ENV_ADDED = 'added ünïcödé ✓'; | | 11 | +process.env.TEST_DEFAULT_ENV_EMPTY = ''; | | 12 | +process.env.TEST_DEFAULT_ENV_EQUALS = 'a=b=c'; | | 13 | +process.env.TEST_DEFAULT_ENV_DELETED = 'x'; | | 14 | +delete process.env.TEST_DEFAULT_ENV_DELETED; | | 15 | + | | 16 | +function expectedEnv() { | | 17 | + // What `{ ...process.env }` yields, minus keys whose value is undefined | | 18 | + // (there are none for the real environment, but keep the definition exact). | | 19 | + const copy = { ...process.env }; | | 20 | + for (const key of Object.keys(copy)) { | | 21 | + if (copy[key] === undefined) delete copy[key]; | | 22 | + } | | 23 | + return copy; | | 24 | +} | | 25 | + | | 26 | +const printEnv = ['-e', 'process.stdout.write(JSON.stringify(process.env))']; | | 27 | + | | 28 | +function run(options) { | | 29 | + const child = spawnSync(process.execPath, printEnv, { encoding: 'utf8', ...options }); | | 30 | + assert.strictEqual(child.status, 0, child.stderr || String(child.error)); | | 31 | + return child.stdout; | | 32 | +} | | 33 | + | | 34 | +function check(output, label, expected = expectedEnv()) { | | 35 | + const childEnv = JSON.parse(output); | | 36 | + assert.deepStrictEqual(childEnv, expected, `${label}: contents`); | | 37 | + assert.strictEqual(childEnv.TEST_DEFAULT_ENV_ADDED, 'added ünïcödé ✓'); | | 38 | + assert.strictEqual(childEnv.TEST_DEFAULT_ENV_EMPTY, ''); | | 39 | + assert.strictEqual(childEnv.TEST_DEFAULT_ENV_EQUALS, 'a=b=c'); | | 40 | + assert.ok(!('TEST_DEFAULT_ENV_DELETED' in childEnv)); | | 41 | +} | | 42 | + | | 43 | +// spawnSync, options omitted entirely. | | 44 | +check(run(), 'spawnSync no options'); | | 45 | +// Explicitly undefined / null env behave like the default. | | 46 | +check(run({ env: undefined }), 'spawnSync env undefined'); | | 47 | +check(run({ env: null }), 'spawnSync env null'); | | 48 | +// execFileSync goes through the same normalization. | | 49 | +check(execFileSync(process.execPath, printEnv, { encoding: 'utf8' }), 'execFileSync'); | | 50 | +// A user-supplied env is still passed through as given (not merged). | | 51 | +{ | | 52 | + const env = { ...process.env, ONLY: 'this' }; | | 53 | + delete env.TEST_DEFAULT_ENV_ADDED; | | 54 | + const childEnv = JSON.parse(run({ env })); | | 55 | + assert.strictEqual(childEnv.ONLY, 'this'); | | 56 | + assert.ok(!('TEST_DEFAULT_ENV_ADDED' in childEnv)); | | 57 | +} | | 58 | +// Async spawn (the environment is captured at spawn() time). | | 59 | +{ | | 60 | + const expectedAtSpawn = expectedEnv(); | | 61 | + const child = spawn(process.execPath, printEnv); | | 62 | + let out = ''; | | 63 | + child.stdout.setEncoding('utf8').on('data', (d) => { out += d; }); | | 64 | + let err = ''; | | 65 | + child.stderr.setEncoding('utf8').on('data', (d) => { err += d; }); | | 66 | + child.on('close', common.mustCall((code) => { | | 67 | + assert.strictEqual(code, 0, err); | | 68 | + check(out, 'spawn', expectedAtSpawn); | | 69 | + })); | | 70 | +} | | 71 | +// A variable added after an earlier spawn is seen by a later one (no caching). | | 72 | +process.env.TEST_DEFAULT_ENV_LATE = 'late'; | | 73 | +{ | | 74 | + const childEnv = JSON.parse(run()); | | 75 | + assert.strictEqual(childEnv.TEST_DEFAULT_ENV_LATE, 'late'); | | 76 | +} |
|