@@ -348,24 +348,29 @@ Handle<Value> WrappedScript::EvalMachine(const Arguments& args) {
348348 display_error = true ;
349349 }
350350
351- Persistent <Context> context;
351+ Handle <Context> context = Context::GetCurrent () ;
352352
353353 Local<Array> keys;
354354 if (context_flag == newContext) {
355355 // Create the new context
356- context = Context::New ();
356+ // Context::New returns a Persistent<Context>, but we only need it for this
357+ // function. Here we grab a temporary handle to the new context, assign it
358+ // to a local handle, and then dispose the persistent handle. This ensures
359+ // that when this function exits the context will be disposed.
360+ Persistent<Context> tmp = Context::New ();
361+ context = Local<Context>::New (tmp);
362+ tmp.Dispose ();
357363
358364 } else if (context_flag == userContext) {
359365 // Use the passed in context
360366 WrappedContext *nContext = ObjectWrap::Unwrap<WrappedContext>(sandbox);
361367 context = nContext->GetV8Context ();
362368 }
363369
370+ Context::Scope context_scope (context);
371+
364372 // New and user context share code. DRY it up.
365373 if (context_flag == userContext || context_flag == newContext) {
366- // Enter the context
367- context->Enter ();
368-
369374 // Copy everything from the passed in sandbox (either the persistent
370375 // context for runInContext(), or the sandbox arg to runInNewContext()).
371376 CloneObject (args.This (), sandbox, context->Global ()->GetPrototype ());
@@ -407,11 +412,6 @@ Handle<Value> WrappedScript::EvalMachine(const Arguments& args) {
407412 if (output_flag == returnResult) {
408413 result = script->Run ();
409414 if (result.IsEmpty ()) {
410- if (context_flag == newContext) {
411- context->DetachGlobal ();
412- context->Exit ();
413- context.Dispose ();
414- }
415415 return try_catch.ReThrow ();
416416 }
417417 } else {
@@ -429,16 +429,6 @@ Handle<Value> WrappedScript::EvalMachine(const Arguments& args) {
429429 CloneObject (args.This (), context->Global ()->GetPrototype (), sandbox);
430430 }
431431
432- if (context_flag == newContext) {
433- // Clean up, clean up, everybody everywhere!
434- context->DetachGlobal ();
435- context->Exit ();
436- context.Dispose ();
437- } else if (context_flag == userContext) {
438- // Exit the passed in context.
439- context->Exit ();
440- }
441-
442432 return result == args.This () ? result : scope.Close (result);
443433}
444434
0 commit comments