Skip to content

Commit c5d8369

Browse files
ofrobotsMyles Borins
authored and
Myles Borins
committed
contextify: tie lifetimes of context & sandbox
When the previous set of changes (bfff07b) it was possible to have the context get garbage collected while sandbox was still live. We need to tie the lifetime of the context to the lifetime of the sandbox. This is a backport of #5786 to v5.x. Ref: #5786 PR-URL: #5800 Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 0cac777 commit c5d8369

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

src/node_contextify.cc

+10
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,17 @@ class ContextifyContext {
209209

210210
CHECK(!ctx.IsEmpty());
211211
ctx->SetSecurityToken(env->context()->GetSecurityToken());
212+
213+
// We need to tie the lifetime of the sandbox object with the lifetime of
214+
// newly created context. We do this by making them hold references to each
215+
// other. The context can directly hold a reference to the sandbox as an
216+
// embedder data field. However, we cannot hold a reference to a v8::Context
217+
// directly in an Object, we instead hold onto the new context's global
218+
// object instead (which then has a reference to the context).
212219
ctx->SetEmbedderData(kSandboxObjectIndex, sandbox_obj);
220+
sandbox_obj->SetHiddenValue(
221+
FIXED_ONE_BYTE_STRING(env->isolate(), "_contextifyHiddenGlobal"),
222+
ctx->Global());
213223

214224
env->AssignToContext(ctx);
215225

test/parallel/test-vm-create-and-run-in-context.js

+9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
'use strict';
2+
// Flags: --expose-gc
23
require('../common');
34
var assert = require('assert');
45

@@ -18,3 +19,11 @@ console.error('test updating context');
1819
result = vm.runInContext('var foo = 3;', context);
1920
assert.equal(3, context.foo);
2021
assert.equal('lala', context.thing);
22+
23+
// https://github.com/nodejs/node/issues/5768
24+
console.error('run in contextified sandbox without referencing the context');
25+
var sandbox = {x: 1};
26+
vm.createContext(sandbox);
27+
gc();
28+
vm.runInContext('x = 2', sandbox);
29+
// Should not crash.

0 commit comments

Comments
 (0)