debug-scopes.cc 27.6 KB
Newer Older
1 2 3 4 5 6
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/debug/debug-scopes.h"

7
#include "src/ast/scopes.h"
8
#include "src/debug/debug.h"
9
#include "src/frames-inl.h"
10
#include "src/globals.h"
11
#include "src/isolate-inl.h"
12
#include "src/parsing/parser.h"
13 14 15 16 17

namespace v8 {
namespace internal {

ScopeIterator::ScopeIterator(Isolate* isolate, FrameInspector* frame_inspector,
18
                             ScopeIterator::Option option)
19 20 21
    : isolate_(isolate),
      frame_inspector_(frame_inspector),
      nested_scope_chain_(4),
22
      non_locals_(nullptr),
23 24 25 26 27 28 29 30
      seen_script_scope_(false),
      failed_(false) {
  if (!frame_inspector->GetContext()->IsContext() ||
      !frame_inspector->GetFunction()->IsJSFunction()) {
    // Optimized frame, context or function cannot be materialized. Give up.
    return;
  }

31
  context_ = Handle<Context>::cast(frame_inspector->GetContext());
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49

  // Catch the case when the debugger stops in an internal function.
  Handle<JSFunction> function = GetFunction();
  Handle<SharedFunctionInfo> shared_info(function->shared());
  Handle<ScopeInfo> scope_info(shared_info->scope_info());
  if (shared_info->script() == isolate->heap()->undefined_value()) {
    while (context_->closure() == *function) {
      context_ = Handle<Context>(context_->previous(), isolate_);
    }
    return;
  }

  // Currently it takes too much time to find nested scopes due to script
  // parsing. Sometimes we want to run the ScopeIterator as fast as possible
  // (for example, while collecting async call stacks on every
  // addEventListener call), even if we drop some nested scopes.
  // Later we may optimize getting the nested scopes (cache the result?)
  // and include nested scopes into the "fast" iteration case as well.
50 51
  bool ignore_nested_scopes = (option == IGNORE_NESTED_SCOPES);
  bool collect_non_locals = (option == COLLECT_NON_LOCALS);
52 53 54 55 56 57 58 59 60 61
  if (!ignore_nested_scopes && shared_info->HasDebugInfo()) {
    // The source position at return is always the end of the function,
    // which is not consistent with the current scope chain. Therefore all
    // nested with, catch and block contexts are skipped, and we can only
    // inspect the function scope.
    // This can only happen if we set a break point inside right before the
    // return, which requires a debug info to be available.
    Handle<DebugInfo> debug_info(shared_info->GetDebugInfo());

    // Find the break point where execution has stopped.
62
    BreakLocation location = BreakLocation::FromFrame(debug_info, GetFrame());
63 64 65 66 67 68 69 70 71 72 73 74

    ignore_nested_scopes = location.IsReturn();
  }

  if (ignore_nested_scopes) {
    if (scope_info->HasContext()) {
      context_ = Handle<Context>(context_->declaration_context(), isolate_);
    } else {
      while (context_->closure() == *function) {
        context_ = Handle<Context>(context_->previous(), isolate_);
      }
    }
75
    if (scope_info->scope_type() == FUNCTION_SCOPE) {
76 77
      nested_scope_chain_.Add(scope_info);
    }
78 79 80 81 82 83 84 85 86
    if (!collect_non_locals) return;
  }

  // Reparse the code and analyze the scopes.
  Scope* scope = NULL;
  // Check whether we are in global, eval or function code.
  Zone zone;
  if (scope_info->scope_type() != FUNCTION_SCOPE) {
    // Global or eval code.
87
    Handle<Script> script(Script::cast(shared_info->script()));
88 89 90
    ParseInfo info(&zone, script);
    if (scope_info->scope_type() == SCRIPT_SCOPE) {
      info.set_global();
91
    } else {
92 93 94 95 96 97 98 99 100 101 102 103 104 105
      DCHECK(scope_info->scope_type() == EVAL_SCOPE);
      info.set_eval();
      info.set_context(Handle<Context>(function->context()));
    }
    if (Parser::ParseStatic(&info) && Scope::Analyze(&info)) {
      scope = info.literal()->scope();
    }
    if (!ignore_nested_scopes) RetrieveScopeChain(scope);
    if (collect_non_locals) CollectNonLocals(scope);
  } else {
    // Function code
    ParseInfo info(&zone, function);
    if (Parser::ParseStatic(&info) && Scope::Analyze(&info)) {
      scope = info.literal()->scope();
106
    }
107 108
    if (!ignore_nested_scopes) RetrieveScopeChain(scope);
    if (collect_non_locals) CollectNonLocals(scope);
109 110 111 112 113 114 115 116
  }
}


ScopeIterator::ScopeIterator(Isolate* isolate, Handle<JSFunction> function)
    : isolate_(isolate),
      frame_inspector_(NULL),
      context_(function->context()),
117
      non_locals_(nullptr),
118 119
      seen_script_scope_(false),
      failed_(false) {
120
  if (!function->shared()->IsSubjectToDebugging()) context_ = Handle<Context>();
121 122 123 124 125 126 127 128 129 130 131 132
}


MUST_USE_RESULT MaybeHandle<JSObject> ScopeIterator::MaterializeScopeDetails() {
  // Calculate the size of the result.
  Handle<FixedArray> details =
      isolate_->factory()->NewFixedArray(kScopeDetailsSize);
  // Fill in scope details.
  details->set(kScopeDetailsTypeIndex, Smi::FromInt(Type()));
  Handle<JSObject> scope_object;
  ASSIGN_RETURN_ON_EXCEPTION(isolate_, scope_object, ScopeObject(), JSObject);
  details->set(kScopeDetailsObjectIndex, *scope_object);
133 134 135 136 137 138
  if (HasContext() && CurrentContext()->closure() != NULL) {
    Handle<String> closure_name = JSFunction::GetDebugName(
        Handle<JSFunction>(CurrentContext()->closure()));
    if (!closure_name.is_null() && (closure_name->length() != 0))
      details->set(kScopeDetailsNameIndex, *closure_name);
  }
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
  return isolate_->factory()->NewJSArrayWithElements(details);
}


void ScopeIterator::Next() {
  DCHECK(!failed_);
  ScopeType scope_type = Type();
  if (scope_type == ScopeTypeGlobal) {
    // The global scope is always the last in the chain.
    DCHECK(context_->IsNativeContext());
    context_ = Handle<Context>();
    return;
  }
  if (scope_type == ScopeTypeScript) {
    seen_script_scope_ = true;
    if (context_->IsScriptContext()) {
      context_ = Handle<Context>(context_->previous(), isolate_);
    }
    if (!nested_scope_chain_.is_empty()) {
      DCHECK_EQ(nested_scope_chain_.last()->scope_type(), SCRIPT_SCOPE);
      nested_scope_chain_.RemoveLast();
      DCHECK(nested_scope_chain_.is_empty());
    }
    CHECK(context_->IsNativeContext());
    return;
  }
  if (nested_scope_chain_.is_empty()) {
    context_ = Handle<Context>(context_->previous(), isolate_);
  } else {
    if (nested_scope_chain_.last()->HasContext()) {
      DCHECK(context_->previous() != NULL);
      context_ = Handle<Context>(context_->previous(), isolate_);
    }
    nested_scope_chain_.RemoveLast();
  }
}


// Return the type of the current scope.
ScopeIterator::ScopeType ScopeIterator::Type() {
  DCHECK(!failed_);
  if (!nested_scope_chain_.is_empty()) {
    Handle<ScopeInfo> scope_info = nested_scope_chain_.last();
    switch (scope_info->scope_type()) {
      case FUNCTION_SCOPE:
        DCHECK(context_->IsFunctionContext() || !scope_info->HasContext());
        return ScopeTypeLocal;
      case MODULE_SCOPE:
        DCHECK(context_->IsModuleContext());
        return ScopeTypeModule;
      case SCRIPT_SCOPE:
        DCHECK(context_->IsScriptContext() || context_->IsNativeContext());
        return ScopeTypeScript;
      case WITH_SCOPE:
        DCHECK(context_->IsWithContext());
        return ScopeTypeWith;
      case CATCH_SCOPE:
        DCHECK(context_->IsCatchContext());
        return ScopeTypeCatch;
      case BLOCK_SCOPE:
        DCHECK(!scope_info->HasContext() || context_->IsBlockContext());
        return ScopeTypeBlock;
      case EVAL_SCOPE:
        UNREACHABLE();
    }
  }
  if (context_->IsNativeContext()) {
206
    DCHECK(context_->global_object()->IsJSGlobalObject());
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    // If we are at the native context and have not yet seen script scope,
    // fake it.
    return seen_script_scope_ ? ScopeTypeGlobal : ScopeTypeScript;
  }
  if (context_->IsFunctionContext()) {
    return ScopeTypeClosure;
  }
  if (context_->IsCatchContext()) {
    return ScopeTypeCatch;
  }
  if (context_->IsBlockContext()) {
    return ScopeTypeBlock;
  }
  if (context_->IsModuleContext()) {
    return ScopeTypeModule;
  }
  if (context_->IsScriptContext()) {
    return ScopeTypeScript;
  }
  DCHECK(context_->IsWithContext());
  return ScopeTypeWith;
}


MaybeHandle<JSObject> ScopeIterator::ScopeObject() {
  DCHECK(!failed_);
  switch (Type()) {
    case ScopeIterator::ScopeTypeGlobal:
235
      return Handle<JSObject>(CurrentContext()->global_proxy());
236 237 238 239 240 241 242 243
    case ScopeIterator::ScopeTypeScript:
      return MaterializeScriptScope();
    case ScopeIterator::ScopeTypeLocal:
      // Materialize the content of the local scope into a JSObject.
      DCHECK(nested_scope_chain_.length() == 1);
      return MaterializeLocalScope();
    case ScopeIterator::ScopeTypeWith:
      // Return the with object.
244 245
      // TODO(neis): This breaks for proxies.
      return handle(JSObject::cast(CurrentContext()->extension_receiver()));
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    case ScopeIterator::ScopeTypeCatch:
      return MaterializeCatchScope();
    case ScopeIterator::ScopeTypeClosure:
      // Materialize the content of the closure scope into a JSObject.
      return MaterializeClosure();
    case ScopeIterator::ScopeTypeBlock:
      return MaterializeBlockScope();
    case ScopeIterator::ScopeTypeModule:
      return MaterializeModuleScope();
  }
  UNREACHABLE();
  return Handle<JSObject>();
}


bool ScopeIterator::HasContext() {
  ScopeType type = Type();
  if (type == ScopeTypeBlock || type == ScopeTypeLocal) {
    if (!nested_scope_chain_.is_empty()) {
      return nested_scope_chain_.last()->HasContext();
    }
  }
  return true;
}


bool ScopeIterator::SetVariableValue(Handle<String> variable_name,
                                     Handle<Object> new_value) {
  DCHECK(!failed_);
  switch (Type()) {
    case ScopeIterator::ScopeTypeGlobal:
      break;
    case ScopeIterator::ScopeTypeLocal:
      return SetLocalVariableValue(variable_name, new_value);
    case ScopeIterator::ScopeTypeWith:
      break;
    case ScopeIterator::ScopeTypeCatch:
      return SetCatchVariableValue(variable_name, new_value);
    case ScopeIterator::ScopeTypeClosure:
      return SetClosureVariableValue(variable_name, new_value);
    case ScopeIterator::ScopeTypeScript:
      return SetScriptVariableValue(variable_name, new_value);
    case ScopeIterator::ScopeTypeBlock:
      return SetBlockVariableValue(variable_name, new_value);
    case ScopeIterator::ScopeTypeModule:
      // TODO(2399): should we implement it?
      break;
  }
  return false;
}


Handle<ScopeInfo> ScopeIterator::CurrentScopeInfo() {
  DCHECK(!failed_);
  if (!nested_scope_chain_.is_empty()) {
    return nested_scope_chain_.last();
  } else if (context_->IsBlockContext()) {
303
    return Handle<ScopeInfo>(context_->scope_info());
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  } else if (context_->IsFunctionContext()) {
    return Handle<ScopeInfo>(context_->closure()->shared()->scope_info());
  }
  return Handle<ScopeInfo>::null();
}


Handle<Context> ScopeIterator::CurrentContext() {
  DCHECK(!failed_);
  if (Type() == ScopeTypeGlobal || Type() == ScopeTypeScript ||
      nested_scope_chain_.is_empty()) {
    return context_;
  } else if (nested_scope_chain_.last()->HasContext()) {
    return context_;
  } else {
    return Handle<Context>();
  }
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

void ScopeIterator::GetNonLocals(List<Handle<String> >* list_out) {
  Handle<String> this_string = isolate_->factory()->this_string();
  for (HashMap::Entry* entry = non_locals_->Start(); entry != nullptr;
       entry = non_locals_->Next(entry)) {
    Handle<String> name(reinterpret_cast<String**>(entry->key));
    // We need to treat "this" differently.
    if (name.is_identical_to(this_string)) continue;
    list_out->Add(Handle<String>(reinterpret_cast<String**>(entry->key)));
  }
}


bool ScopeIterator::ThisIsNonLocal() {
  Handle<String> this_string = isolate_->factory()->this_string();
  void* key = reinterpret_cast<void*>(this_string.location());
  HashMap::Entry* entry = non_locals_->Lookup(key, this_string->Hash());
  return entry != nullptr;
}


344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
#ifdef DEBUG
// Debug print of the content of the current scope.
void ScopeIterator::DebugPrint() {
  OFStream os(stdout);
  DCHECK(!failed_);
  switch (Type()) {
    case ScopeIterator::ScopeTypeGlobal:
      os << "Global:\n";
      CurrentContext()->Print(os);
      break;

    case ScopeIterator::ScopeTypeLocal: {
      os << "Local:\n";
      GetFunction()->shared()->scope_info()->Print();
      if (!CurrentContext().is_null()) {
        CurrentContext()->Print(os);
        if (CurrentContext()->has_extension()) {
361
          Handle<HeapObject> extension(CurrentContext()->extension(), isolate_);
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
          if (extension->IsJSContextExtensionObject()) {
            extension->Print(os);
          }
        }
      }
      break;
    }

    case ScopeIterator::ScopeTypeWith:
      os << "With:\n";
      CurrentContext()->extension()->Print(os);
      break;

    case ScopeIterator::ScopeTypeCatch:
      os << "Catch:\n";
      CurrentContext()->extension()->Print(os);
      CurrentContext()->get(Context::THROWN_OBJECT_INDEX)->Print(os);
      break;

    case ScopeIterator::ScopeTypeClosure:
      os << "Closure:\n";
      CurrentContext()->Print(os);
      if (CurrentContext()->has_extension()) {
385
        Handle<HeapObject> extension(CurrentContext()->extension(), isolate_);
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
        if (extension->IsJSContextExtensionObject()) {
          extension->Print(os);
        }
      }
      break;

    case ScopeIterator::ScopeTypeScript:
      os << "Script:\n";
      CurrentContext()
          ->global_object()
          ->native_context()
          ->script_context_table()
          ->Print(os);
      break;

    default:
      UNREACHABLE();
  }
  PrintF("\n");
}
#endif


409
void ScopeIterator::RetrieveScopeChain(Scope* scope) {
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
  if (scope != NULL) {
    int source_position = frame_inspector_->GetSourcePosition();
    scope->GetNestedScopeChain(isolate_, &nested_scope_chain_, source_position);
  } else {
    // A failed reparse indicates that the preparser has diverged from the
    // parser or that the preparse data given to the initial parse has been
    // faulty. We fail in debug mode but in release mode we only provide the
    // information we get from the context chain but nothing about
    // completely stack allocated scopes or stack allocated locals.
    // Or it could be due to stack overflow.
    DCHECK(isolate_->has_pending_exception());
    failed_ = true;
  }
}


426 427 428 429 430 431 432 433 434
void ScopeIterator::CollectNonLocals(Scope* scope) {
  if (scope != NULL) {
    DCHECK_NULL(non_locals_);
    non_locals_ = new HashMap(InternalizedStringMatch);
    scope->CollectNonLocals(non_locals_);
  }
}


435
MaybeHandle<JSObject> ScopeIterator::MaterializeScriptScope() {
436
  Handle<JSGlobalObject> global(CurrentContext()->global_object());
437 438 439 440 441 442 443 444 445 446
  Handle<ScriptContextTable> script_contexts(
      global->native_context()->script_context_table());

  Handle<JSObject> script_scope =
      isolate_->factory()->NewJSObject(isolate_->object_function());

  for (int context_index = 0; context_index < script_contexts->used();
       context_index++) {
    Handle<Context> context =
        ScriptContextTable::GetContext(script_contexts, context_index);
447
    Handle<ScopeInfo> scope_info(context->scope_info());
448 449 450 451 452 453 454 455 456 457 458 459 460
    CopyContextLocalsToScopeObject(scope_info, context, script_scope);
  }
  return script_scope;
}


MaybeHandle<JSObject> ScopeIterator::MaterializeLocalScope() {
  Handle<JSFunction> function = GetFunction();

  Handle<JSObject> local_scope =
      isolate_->factory()->NewJSObject(isolate_->object_function());
  frame_inspector_->MaterializeStackLocals(local_scope, function);

461 462
  Handle<Context> frame_context =
      Handle<Context>::cast(frame_inspector_->GetContext());
463 464 465 466 467 468 469 470

  HandleScope scope(isolate_);
  Handle<SharedFunctionInfo> shared(function->shared());
  Handle<ScopeInfo> scope_info(shared->scope_info());

  if (!scope_info->HasContext()) return local_scope;

  // Third fill all context locals.
471
  Handle<Context> function_context(frame_context->closure_context());
472 473 474 475
  CopyContextLocalsToScopeObject(scope_info, function_context, local_scope);

  // Finally copy any properties from the function context extension.
  // These will be variables introduced by eval.
476 477 478 479
  if (function_context->closure() == *function &&
      function_context->has_extension() &&
      !function_context->IsNativeContext()) {
    bool success = CopyContextExtensionToScopeObject(
480 481
        handle(function_context->extension_object(), isolate_), local_scope,
        INCLUDE_PROTOS);
482
    if (!success) return MaybeHandle<JSObject>();
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
  }

  return local_scope;
}


// Create a plain JSObject which materializes the closure content for the
// context.
Handle<JSObject> ScopeIterator::MaterializeClosure() {
  Handle<Context> context = CurrentContext();
  DCHECK(context->IsFunctionContext());

  Handle<SharedFunctionInfo> shared(context->closure()->shared());
  Handle<ScopeInfo> scope_info(shared->scope_info());

  // Allocate and initialize a JSObject with all the content of this function
  // closure.
  Handle<JSObject> closure_scope =
      isolate_->factory()->NewJSObject(isolate_->object_function());

  // Fill all context locals to the context extension.
  CopyContextLocalsToScopeObject(scope_info, context, closure_scope);

  // Finally copy any properties from the function context extension. This will
  // be variables introduced by eval.
  if (context->has_extension()) {
509
    bool success = CopyContextExtensionToScopeObject(
510
        handle(context->extension_object(), isolate_), closure_scope, OWN_ONLY);
511 512
    DCHECK(success);
    USE(success);
513 514 515 516 517 518 519 520 521 522 523
  }

  return closure_scope;
}


// Create a plain JSObject which materializes the scope for the specified
// catch context.
Handle<JSObject> ScopeIterator::MaterializeCatchScope() {
  Handle<Context> context = CurrentContext();
  DCHECK(context->IsCatchContext());
524
  Handle<String> name(context->catch_name());
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
  Handle<Object> thrown_object(context->get(Context::THROWN_OBJECT_INDEX),
                               isolate_);
  Handle<JSObject> catch_scope =
      isolate_->factory()->NewJSObject(isolate_->object_function());
  JSObject::SetOwnPropertyIgnoreAttributes(catch_scope, name, thrown_object,
                                           NONE)
      .Check();
  return catch_scope;
}


// Create a plain JSObject which materializes the block scope for the specified
// block context.
Handle<JSObject> ScopeIterator::MaterializeBlockScope() {
  Handle<JSObject> block_scope =
      isolate_->factory()->NewJSObject(isolate_->object_function());

  Handle<Context> context = Handle<Context>::null();
  if (!nested_scope_chain_.is_empty()) {
    Handle<ScopeInfo> scope_info = nested_scope_chain_.last();
    frame_inspector_->MaterializeStackLocals(block_scope, scope_info);
    if (scope_info->HasContext()) context = CurrentContext();
  } else {
    context = CurrentContext();
  }

  if (!context.is_null()) {
    // Fill all context locals.
553 554 555 556 557
    CopyContextLocalsToScopeObject(handle(context->scope_info()),
                                   context, block_scope);
    // Fill all extension variables.
    if (context->extension_object() != nullptr) {
      bool success = CopyContextExtensionToScopeObject(
558
          handle(context->extension_object()), block_scope, OWN_ONLY);
559 560 561
      DCHECK(success);
      USE(success);
    }
562 563 564 565 566 567 568 569 570 571
  }
  return block_scope;
}


// Create a plain JSObject which materializes the module scope for the specified
// module context.
MaybeHandle<JSObject> ScopeIterator::MaterializeModuleScope() {
  Handle<Context> context = CurrentContext();
  DCHECK(context->IsModuleContext());
572
  Handle<ScopeInfo> scope_info(context->scope_info());
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596

  // Allocate and initialize a JSObject with all the members of the debugged
  // module.
  Handle<JSObject> module_scope =
      isolate_->factory()->NewJSObject(isolate_->object_function());

  // Fill all context locals.
  CopyContextLocalsToScopeObject(scope_info, context, module_scope);

  return module_scope;
}


// Set the context local variable value.
bool ScopeIterator::SetContextLocalValue(Handle<ScopeInfo> scope_info,
                                         Handle<Context> context,
                                         Handle<String> variable_name,
                                         Handle<Object> new_value) {
  for (int i = 0; i < scope_info->ContextLocalCount(); i++) {
    Handle<String> next_name(scope_info->ContextLocalName(i));
    if (String::Equals(variable_name, next_name)) {
      VariableMode mode;
      InitializationFlag init_flag;
      MaybeAssignedFlag maybe_assigned_flag;
597 598
      int context_index = ScopeInfo::ContextSlotIndex(
          scope_info, next_name, &mode, &init_flag, &maybe_assigned_flag);
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
      context->set(context_index, *new_value);
      return true;
    }
  }

  return false;
}


bool ScopeIterator::SetLocalVariableValue(Handle<String> variable_name,
                                          Handle<Object> new_value) {
  JavaScriptFrame* frame = GetFrame();
  // Optimized frames are not supported.
  if (frame->is_optimized()) return false;

  Handle<JSFunction> function(frame->function());
  Handle<SharedFunctionInfo> shared(function->shared());
  Handle<ScopeInfo> scope_info(shared->scope_info());

  bool default_result = false;

  // Parameters.
  for (int i = 0; i < scope_info->ParameterCount(); ++i) {
    HandleScope scope(isolate_);
    if (String::Equals(handle(scope_info->ParameterName(i)), variable_name)) {
      frame->SetParameterValue(i, *new_value);
      // Argument might be shadowed in heap context, don't stop here.
      default_result = true;
    }
  }

  // Stack locals.
  for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
    HandleScope scope(isolate_);
    if (String::Equals(handle(scope_info->StackLocalName(i)), variable_name)) {
      frame->SetExpression(scope_info->StackLocalIndex(i), *new_value);
      return true;
    }
  }

  if (scope_info->HasContext()) {
    // Context locals.
    Handle<Context> frame_context(Context::cast(frame->context()));
    Handle<Context> function_context(frame_context->declaration_context());
    if (SetContextLocalValue(scope_info, function_context, variable_name,
                             new_value)) {
      return true;
    }

    // Function context extension. These are variables introduced by eval.
    if (function_context->closure() == *function) {
      if (function_context->has_extension() &&
          !function_context->IsNativeContext()) {
652
        Handle<JSObject> ext(function_context->extension_object());
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685

        Maybe<bool> maybe = JSReceiver::HasProperty(ext, variable_name);
        DCHECK(maybe.IsJust());
        if (maybe.FromJust()) {
          // We don't expect this to do anything except replacing
          // property value.
          Runtime::SetObjectProperty(isolate_, ext, variable_name, new_value,
                                     SLOPPY)
              .Assert();
          return true;
        }
      }
    }
  }

  return default_result;
}


bool ScopeIterator::SetBlockVariableValue(Handle<String> variable_name,
                                          Handle<Object> new_value) {
  Handle<ScopeInfo> scope_info = CurrentScopeInfo();
  JavaScriptFrame* frame = GetFrame();

  for (int i = 0; i < scope_info->StackLocalCount(); ++i) {
    HandleScope scope(isolate_);
    if (String::Equals(handle(scope_info->StackLocalName(i)), variable_name)) {
      frame->SetExpression(scope_info->StackLocalIndex(i), *new_value);
      return true;
    }
  }

  if (HasContext()) {
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    Handle<Context> context = CurrentContext();
    if (SetContextLocalValue(scope_info, context, variable_name, new_value)) {
      return true;
    }

    Handle<JSObject> ext(context->extension_object(), isolate_);
    if (!ext.is_null()) {
      Maybe<bool> maybe = JSReceiver::HasOwnProperty(ext, variable_name);
      DCHECK(maybe.IsJust());
      if (maybe.FromJust()) {
        // We don't expect this to do anything except replacing property value.
        JSObject::SetOwnPropertyIgnoreAttributes(ext, variable_name, new_value,
                                                 NONE)
            .Check();
        return true;
      }
    }
703
  }
704

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724
  return false;
}


// This method copies structure of MaterializeClosure method above.
bool ScopeIterator::SetClosureVariableValue(Handle<String> variable_name,
                                            Handle<Object> new_value) {
  Handle<Context> context = CurrentContext();
  DCHECK(context->IsFunctionContext());

  // Context locals to the context extension.
  Handle<SharedFunctionInfo> shared(context->closure()->shared());
  Handle<ScopeInfo> scope_info(shared->scope_info());
  if (SetContextLocalValue(scope_info, context, variable_name, new_value)) {
    return true;
  }

  // Properties from the function context extension. This will
  // be variables introduced by eval.
  if (context->has_extension()) {
725
    Handle<JSObject> ext(JSObject::cast(context->extension_object()));
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
    Maybe<bool> maybe = JSReceiver::HasOwnProperty(ext, variable_name);
    DCHECK(maybe.IsJust());
    if (maybe.FromJust()) {
      // We don't expect this to do anything except replacing property value.
      JSObject::SetOwnPropertyIgnoreAttributes(ext, variable_name, new_value,
                                               NONE)
          .Check();
      return true;
    }
  }

  return false;
}


bool ScopeIterator::SetScriptVariableValue(Handle<String> variable_name,
                                           Handle<Object> new_value) {
  Handle<Context> context = CurrentContext();
  Handle<ScriptContextTable> script_contexts(
      context->global_object()->native_context()->script_context_table());
  ScriptContextTable::LookupResult lookup_result;
  if (ScriptContextTable::Lookup(script_contexts, variable_name,
                                 &lookup_result)) {
    Handle<Context> script_context = ScriptContextTable::GetContext(
        script_contexts, lookup_result.context_index);
    script_context->set(lookup_result.slot_index, *new_value);
    return true;
  }

  return false;
}


bool ScopeIterator::SetCatchVariableValue(Handle<String> variable_name,
                                          Handle<Object> new_value) {
  Handle<Context> context = CurrentContext();
  DCHECK(context->IsCatchContext());
763
  Handle<String> name(context->catch_name());
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
  if (!String::Equals(name, variable_name)) {
    return false;
  }
  context->set(Context::THROWN_OBJECT_INDEX, *new_value);
  return true;
}


void ScopeIterator::CopyContextLocalsToScopeObject(
    Handle<ScopeInfo> scope_info, Handle<Context> context,
    Handle<JSObject> scope_object) {
  Isolate* isolate = scope_info->GetIsolate();
  int local_count = scope_info->ContextLocalCount();
  if (local_count == 0) return;
  // Fill all context locals to the context extension.
  int first_context_var = scope_info->StackLocalCount();
  int start = scope_info->ContextLocalNameEntriesIndex();
  for (int i = 0; i < local_count; ++i) {
    if (scope_info->LocalIsSynthetic(first_context_var + i)) continue;
    int context_index = Context::MIN_CONTEXT_SLOTS + i;
    Handle<Object> value = Handle<Object>(context->get(context_index), isolate);
    // Reflect variables under TDZ as undefined in scope object.
    if (value->IsTheHole()) continue;
    // This should always succeed.
    // TODO(verwaest): Use AddDataProperty instead.
    JSObject::SetOwnPropertyIgnoreAttributes(
        scope_object, handle(String::cast(scope_info->get(i + start))), value,
791
        NONE)
792 793 794 795
        .Check();
  }
}

796 797
bool ScopeIterator::CopyContextExtensionToScopeObject(
    Handle<JSObject> extension, Handle<JSObject> scope_object,
798
    KeyCollectionType type) {
799 800
  Handle<FixedArray> keys;
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
801 802
      isolate_, keys, JSReceiver::GetKeys(extension, type, ENUMERABLE_STRINGS),
      false);
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817

  for (int i = 0; i < keys->length(); i++) {
    // Names of variables introduced by eval are strings.
    DCHECK(keys->get(i)->IsString());
    Handle<String> key(String::cast(keys->get(i)));
    Handle<Object> value;
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(
        isolate_, value, Object::GetPropertyOrElement(extension, key), false);
    RETURN_ON_EXCEPTION_VALUE(
        isolate_, JSObject::SetOwnPropertyIgnoreAttributes(
            scope_object, key, value, NONE), false);
  }
  return true;
}

818 819
}  // namespace internal
}  // namespace v8