@@ -348,12 +348,18 @@ 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
@@ -362,11 +368,10 @@ Handle<Value> WrappedScript::EvalMachine(const Arguments& args) {
362368 context = nContext->GetV8Context ();
363369 }
364370
371+ Context::Scope context_scope (context);
372+
365373 // New and user context share code. DRY it up.
366374 if (context_flag == userContext || context_flag == newContext) {
367- // Enter the context
368- context->Enter ();
369-
370375 // Copy everything from the passed in sandbox (either the persistent
371376 // context for runInContext(), or the sandbox arg to runInNewContext()).
372377 CloneObject (args.This (), sandbox, context->Global ()->GetPrototype ());
@@ -408,11 +413,6 @@ Handle<Value> WrappedScript::EvalMachine(const Arguments& args) {
408413 if (output_flag == returnResult) {
409414 result = script->Run ();
410415 if (result.IsEmpty ()) {
411- if (context_flag == newContext) {
412- context->DetachGlobal ();
413- context->Exit ();
414- context.Dispose ();
415- }
416416 return try_catch.ReThrow ();
417417 }
418418 } else {
@@ -430,16 +430,6 @@ Handle<Value> WrappedScript::EvalMachine(const Arguments& args) {
430430 CloneObject (args.This (), context->Global ()->GetPrototype (), sandbox);
431431 }
432432
433- if (context_flag == newContext) {
434- // Clean up, clean up, everybody everywhere!
435- context->DetachGlobal ();
436- context->Exit ();
437- context.Dispose ();
438- } else if (context_flag == userContext) {
439- // Exit the passed in context.
440- context->Exit ();
441- }
442-
443433 return result == args.This () ? result : scope.Close (result);
444434}
445435
0 commit comments