Skip to content

Commit 823f726

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 9ddb44b commit 823f726

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
@@ -207,7 +207,17 @@ class ContextifyContext {
207207

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

212222
env->AssignToContext(ctx);
213223

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)