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

5
#include "src/contexts.h"
6

7
#include "src/ast/scopeinfo.h"
8
#include "src/bootstrapper.h"
9
#include "src/debug/debug.h"
10
#include "src/isolate-inl.h"
11

12 13
namespace v8 {
namespace internal {
14

15

16 17 18
Handle<ScriptContextTable> ScriptContextTable::Extend(
    Handle<ScriptContextTable> table, Handle<Context> script_context) {
  Handle<ScriptContextTable> result;
19 20 21
  int used = table->used();
  int length = table->length();
  CHECK(used >= 0 && length > 0 && used < length);
22
  if (used + kFirstContextSlot == length) {
23
    CHECK(length < Smi::kMaxValue / 2);
24 25 26 27 28
    Isolate* isolate = table->GetIsolate();
    Handle<FixedArray> copy =
        isolate->factory()->CopyFixedArrayAndGrow(table, length);
    copy->set_map(isolate->heap()->script_context_table_map());
    result = Handle<ScriptContextTable>::cast(copy);
29 30 31 32 33
  } else {
    result = table;
  }
  result->set_used(used + 1);

34
  DCHECK(script_context->IsScriptContext());
35
  result->set(used + kFirstContextSlot, *script_context);
36 37 38 39
  return result;
}


40
bool ScriptContextTable::Lookup(Handle<ScriptContextTable> table,
41 42 43
                                Handle<String> name, LookupResult* result) {
  for (int i = 0; i < table->used(); i++) {
    Handle<Context> context = GetContext(table, i);
44
    DCHECK(context->IsScriptContext());
45
    Handle<ScopeInfo> scope_info(context->scope_info());
46
    int slot_index = ScopeInfo::ContextSlotIndex(
47
        scope_info, name, &result->mode, &result->init_flag,
48 49
        &result->maybe_assigned_flag);

50
    if (slot_index >= 0) {
51 52 53 54 55 56 57 58 59
      result->context_index = i;
      result->slot_index = slot_index;
      return true;
    }
  }
  return false;
}


60 61 62 63 64 65 66 67 68 69 70 71 72
bool Context::is_declaration_context() {
  if (IsFunctionContext() || IsNativeContext() || IsScriptContext()) {
    return true;
  }
  if (!IsBlockContext()) return false;
  Object* ext = extension();
  // If we have the special extension, we immediately know it must be a
  // declaration scope. That's just a small performance shortcut.
  return ext->IsSloppyBlockWithEvalContextExtension()
      || ScopeInfo::cast(ext)->is_declaration_scope();
}


73 74
Context* Context::declaration_context() {
  Context* current = this;
75
  while (!current->is_declaration_context()) {
76
    current = current->previous();
77
    DCHECK(current->closure() == closure());
78 79 80 81
  }
  return current;
}

82 83 84 85 86 87 88 89 90
Context* Context::closure_context() {
  Context* current = this;
  while (!current->IsFunctionContext() && !current->IsScriptContext() &&
         !current->IsNativeContext()) {
    current = current->previous();
    DCHECK(current->closure() == closure());
  }
  return current;
}
91

92 93
JSObject* Context::extension_object() {
  DCHECK(IsNativeContext() || IsFunctionContext() || IsBlockContext());
94
  HeapObject* object = extension();
95
  if (object->IsTheHole(GetIsolate())) return nullptr;
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  if (IsBlockContext()) {
    if (!object->IsSloppyBlockWithEvalContextExtension()) return nullptr;
    object = SloppyBlockWithEvalContextExtension::cast(object)->extension();
  }
  DCHECK(object->IsJSContextExtensionObject() ||
         (IsNativeContext() && object->IsJSGlobalObject()));
  return JSObject::cast(object);
}


JSReceiver* Context::extension_receiver() {
  DCHECK(IsNativeContext() || IsWithContext() ||
         IsFunctionContext() || IsBlockContext());
  return IsWithContext() ? JSReceiver::cast(extension()) : extension_object();
}


ScopeInfo* Context::scope_info() {
  DCHECK(IsModuleContext() || IsScriptContext() || IsBlockContext());
115
  HeapObject* object = extension();
116 117 118 119 120 121 122 123 124 125 126 127 128 129
  if (object->IsSloppyBlockWithEvalContextExtension()) {
    DCHECK(IsBlockContext());
    object = SloppyBlockWithEvalContextExtension::cast(object)->scope_info();
  }
  return ScopeInfo::cast(object);
}


String* Context::catch_name() {
  DCHECK(IsCatchContext());
  return String::cast(extension());
}


130 131 132 133 134
JSGlobalObject* Context::global_object() {
  return JSGlobalObject::cast(native_context()->extension());
}


135
Context* Context::script_context() {
136
  Context* current = this;
137
  while (!current->IsScriptContext()) {
138 139 140 141 142 143
    current = current->previous();
  }
  return current;
}


144
JSObject* Context::global_proxy() {
145
  return native_context()->global_proxy_object();
146 147
}

148

149
void Context::set_global_proxy(JSObject* object) {
150
  native_context()->set_global_proxy_object(object);
151 152 153
}


154 155 156 157
/**
 * Lookups a property in an object environment, taking the unscopables into
 * account. This is used For HasBinding spec algorithms for ObjectEnvironment.
 */
158
static Maybe<bool> UnscopableLookup(LookupIterator* it) {
159 160
  Isolate* isolate = it->isolate();

161 162
  Maybe<bool> found = JSReceiver::HasProperty(it);
  if (!found.IsJust() || !found.FromJust()) return found;
163 164

  Handle<Object> unscopables;
165 166
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, unscopables,
167 168
      JSReceiver::GetProperty(Handle<JSReceiver>::cast(it->GetReceiver()),
                              isolate->factory()->unscopables_symbol()),
169 170
      Nothing<bool>());
  if (!unscopables->IsJSReceiver()) return Just(true);
171
  Handle<Object> blacklist;
172 173 174 175 176
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, blacklist,
      JSReceiver::GetProperty(Handle<JSReceiver>::cast(unscopables),
                              it->name()),
      Nothing<bool>());
177
  return Just(!blacklist->BooleanValue());
178 179
}

180 181 182 183 184 185 186
static void GetAttributesAndBindingFlags(VariableMode mode,
                                         InitializationFlag init_flag,
                                         PropertyAttributes* attributes,
                                         BindingFlags* binding_flags) {
  switch (mode) {
    case VAR:
      *attributes = NONE;
187
      *binding_flags = BINDING_IS_INITIALIZED;
188 189 190 191
      break;
    case LET:
      *attributes = NONE;
      *binding_flags = (init_flag == kNeedsInitialization)
192 193
                           ? BINDING_CHECK_INITIALIZED
                           : BINDING_IS_INITIALIZED;
194 195
      break;
    case CONST_LEGACY:
196
      DCHECK_EQ(kCreatedInitialized, init_flag);
197
      *attributes = READ_ONLY;
198
      *binding_flags = BINDING_IS_INITIALIZED;
199 200 201 202
      break;
    case CONST:
      *attributes = READ_ONLY;
      *binding_flags = (init_flag == kNeedsInitialization)
203 204
                           ? BINDING_CHECK_INITIALIZED
                           : BINDING_IS_INITIALIZED;
205
      break;
206
    case IMPORT:  // TODO(neis): Make sure this is what we want for IMPORT.
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    case DYNAMIC:
    case DYNAMIC_GLOBAL:
    case DYNAMIC_LOCAL:
    case TEMPORARY:
      // Note: Fixed context slots are statically allocated by the compiler.
      // Statically allocated variables always have a statically known mode,
      // which is the mode with which they were declared when added to the
      // scope. Thus, the DYNAMIC mode (which corresponds to dynamically
      // declared variables that were introduced through declaration nodes)
      // must not appear here.
      UNREACHABLE();
      break;
  }
}

222

223 224
Handle<Object> Context::Lookup(Handle<String> name,
                               ContextLookupFlags flags,
225
                               int* index,
226 227
                               PropertyAttributes* attributes,
                               BindingFlags* binding_flags) {
228 229
  Isolate* isolate = GetIsolate();
  Handle<Context> context(this, isolate);
230 231

  bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0;
232
  bool failed_whitelist = false;
233
  *index = kNotFound;
234
  *attributes = ABSENT;
235
  *binding_flags = MISSING_BINDING;
236 237 238 239 240 241 242 243 244

  if (FLAG_trace_contexts) {
    PrintF("Context::Lookup(");
    name->ShortPrint();
    PrintF(")\n");
  }

  do {
    if (FLAG_trace_contexts) {
245
      PrintF(" - looking in context %p", reinterpret_cast<void*>(*context));
246
      if (context->IsScriptContext()) PrintF(" (script context)");
247
      if (context->IsNativeContext()) PrintF(" (native context)");
248 249 250
      PrintF("\n");
    }

251
    // 1. Check global objects, subjects of with, and extension objects.
252 253
    if ((context->IsNativeContext() ||
         (context->IsWithContext() && ((flags & SKIP_WITH_CONTEXT) == 0)) ||
254 255 256
         context->IsFunctionContext() || context->IsBlockContext()) &&
        context->extension_receiver() != nullptr) {
      Handle<JSReceiver> object(context->extension_receiver());
257 258 259

      if (context->IsNativeContext()) {
        if (FLAG_trace_contexts) {
260
          PrintF(" - trying other script contexts\n");
261
        }
262 263 264 265 266
        // Try other script contexts.
        Handle<ScriptContextTable> script_contexts(
            context->global_object()->native_context()->script_context_table());
        ScriptContextTable::LookupResult r;
        if (ScriptContextTable::Lookup(script_contexts, name, &r)) {
267
          if (FLAG_trace_contexts) {
268
            Handle<Context> c = ScriptContextTable::GetContext(script_contexts,
269
                                                               r.context_index);
270
            PrintF("=> found property in script context %d: %p\n",
271 272 273 274 275
                   r.context_index, reinterpret_cast<void*>(*c));
          }
          *index = r.slot_index;
          GetAttributesAndBindingFlags(r.mode, r.init_flag, attributes,
                                       binding_flags);
276
          return ScriptContextTable::GetContext(script_contexts,
277 278 279 280
                                                r.context_index);
        }
      }

281 282 283
      // Context extension objects needs to behave as if they have no
      // prototype.  So even if we want to follow prototype chains, we need
      // to only do a local lookup for context extension objects.
284
      Maybe<PropertyAttributes> maybe = Nothing<PropertyAttributes>();
285 286
      if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0 ||
          object->IsJSContextExtensionObject()) {
287
        maybe = JSReceiver::GetOwnPropertyAttributes(object, name);
288
      } else if (context->IsWithContext()) {
289 290 291 292
        // A with context will never bind "this".
        if (name->Equals(*isolate->factory()->this_string())) {
          maybe = Just(ABSENT);
        } else {
293
          LookupIterator it(object, name, object);
294 295 296 297 298 299 300 301 302
          Maybe<bool> found = UnscopableLookup(&it);
          if (found.IsNothing()) {
            maybe = Nothing<PropertyAttributes>();
          } else {
            // Luckily, consumers of |maybe| only care whether the property
            // was absent or not, so we can return a dummy |NONE| value
            // for its attributes when it was present.
            maybe = Just(found.FromJust() ? NONE : ABSENT);
          }
303
        }
304
      } else {
305
        maybe = JSReceiver::GetPropertyAttributes(object, name);
306
      }
307

308
      if (!maybe.IsJust()) return Handle<Object>();
309
      DCHECK(!isolate->has_pending_exception());
310
      *attributes = maybe.FromJust();
311

312
      if (maybe.FromJust() != ABSENT) {
313 314 315
        if (FLAG_trace_contexts) {
          PrintF("=> found property in context object %p\n",
                 reinterpret_cast<void*>(*object));
316
        }
317
        return object;
318 319 320
      }
    }

321
    // 2. Check the context proper if it has slots.
322
    if (context->IsFunctionContext() || context->IsBlockContext() ||
323
        context->IsScriptContext()) {
324 325
      // Use serialized scope information of functions and blocks to search
      // for the context index.
326 327 328
      Handle<ScopeInfo> scope_info(context->IsFunctionContext()
          ? context->closure()->shared()->scope_info()
          : context->scope_info());
329
      VariableMode mode;
330
      InitializationFlag init_flag;
331 332 333 334
      // TODO(sigurds) Figure out whether maybe_assigned_flag should
      // be used to compute binding_flags.
      MaybeAssignedFlag maybe_assigned_flag;
      int slot_index = ScopeInfo::ContextSlotIndex(
335
          scope_info, name, &mode, &init_flag, &maybe_assigned_flag);
336
      DCHECK(slot_index < 0 || slot_index >= MIN_CONTEXT_SLOTS);
337
      if (slot_index >= 0) {
338 339
        if (FLAG_trace_contexts) {
          PrintF("=> found local in context slot %d (mode = %d)\n",
340
                 slot_index, mode);
341
        }
342
        *index = slot_index;
343 344
        GetAttributesAndBindingFlags(mode, init_flag, attributes,
                                     binding_flags);
345 346 347
        return context;
      }

348 349
      // Check the slot corresponding to the intermediate context holding
      // only the function name variable.
350
      if (follow_context_chain && context->IsFunctionContext()) {
351 352
        VariableMode mode;
        int function_index = scope_info->FunctionContextSlotIndex(*name, &mode);
353
        if (function_index >= 0) {
354 355
          if (FLAG_trace_contexts) {
            PrintF("=> found intermediate function in context slot %d\n",
356
                   function_index);
357
          }
358
          *index = function_index;
359
          *attributes = READ_ONLY;
360
          DCHECK(mode == CONST_LEGACY || mode == CONST);
361
          *binding_flags = BINDING_IS_INITIALIZED;
362 363 364
          return context;
        }
      }
365 366 367

    } else if (context->IsCatchContext()) {
      // Catch contexts have the variable name in the extension slot.
368
      if (String::Equals(name, handle(context->catch_name()))) {
369 370 371 372 373
        if (FLAG_trace_contexts) {
          PrintF("=> found in catch context\n");
        }
        *index = Context::THROWN_OBJECT_INDEX;
        *attributes = NONE;
374
        *binding_flags = BINDING_IS_INITIALIZED;
375 376
        return context;
      }
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    } else if (context->IsDebugEvaluateContext()) {
      // Check materialized locals.
      Object* obj = context->get(EXTENSION_INDEX);
      if (obj->IsJSReceiver()) {
        Handle<JSReceiver> extension(JSReceiver::cast(obj));
        LookupIterator it(extension, name, extension);
        Maybe<bool> found = JSReceiver::HasProperty(&it);
        if (found.FromMaybe(false)) {
          *attributes = NONE;
          return extension;
        }
      }
      // Check the original context, but do not follow its context chain.
      obj = context->get(WRAPPED_CONTEXT_INDEX);
      if (obj->IsContext()) {
        Handle<Object> result = Context::cast(obj)->Lookup(
            name, DONT_FOLLOW_CHAINS, index, attributes, binding_flags);
        if (!result.is_null()) return result;
      }
      // Check whitelist. Names that do not pass whitelist shall only resolve
      // to with, script or native contexts up the context chain.
      obj = context->get(WHITE_LIST_INDEX);
      if (obj->IsStringSet()) {
        failed_whitelist = failed_whitelist || !StringSet::cast(obj)->Has(name);
      }
402 403
    }

404
    // 3. Prepare to continue with the previous (next outermost) context.
405 406 407
    if (context->IsNativeContext() ||
        ((flags & STOP_AT_DECLARATION_SCOPE) != 0 &&
         context->is_declaration_context())) {
408
      follow_context_chain = false;
409
    } else {
410 411 412 413 414 415
      do {
        context = Handle<Context>(context->previous(), isolate);
        // If we come across a whitelist context, and the name is not
        // whitelisted, then only consider with, script or native contexts.
      } while (failed_whitelist && !context->IsScriptContext() &&
               !context->IsNativeContext() && !context->IsWithContext());
416 417 418 419 420 421
    }
  } while (follow_context_chain);

  if (FLAG_trace_contexts) {
    PrintF("=> no property/slot found\n");
  }
422
  return Handle<Object>::null();
423 424 425
}


426 427 428 429
void Context::InitializeGlobalSlots() {
  DCHECK(IsScriptContext());
  DisallowHeapAllocation no_gc;

430
  ScopeInfo* scope_info = this->scope_info();
431 432 433 434 435 436 437 438 439 440 441 442 443 444

  int context_globals = scope_info->ContextGlobalCount();
  if (context_globals > 0) {
    PropertyCell* empty_cell = GetHeap()->empty_property_cell();

    int context_locals = scope_info->ContextLocalCount();
    int index = Context::MIN_CONTEXT_SLOTS + context_locals;
    for (int i = 0; i < context_globals; i++) {
      set(index++, empty_cell);
    }
  }
}


445
void Context::AddOptimizedFunction(JSFunction* function) {
446
  DCHECK(IsNativeContext());
447
  Isolate* isolate = GetIsolate();
448
#ifdef ENABLE_SLOW_DCHECKS
449 450
  if (FLAG_enable_slow_asserts) {
    Object* element = get(OPTIMIZED_FUNCTIONS_LIST);
451
    while (!element->IsUndefined(isolate)) {
452 453 454
      CHECK(element != function);
      element = JSFunction::cast(element)->next_function_link();
    }
455 456
  }

457
  // Check that the context belongs to the weak native contexts list.
458
  bool found = false;
459 460
  Object* context = isolate->heap()->native_contexts_list();
  while (!context->IsUndefined(isolate)) {
461 462 463 464
    if (context == this) {
      found = true;
      break;
    }
465
    context = Context::cast(context)->next_context_link();
466 467 468
  }
  CHECK(found);
#endif
469 470 471

  // If the function link field is already used then the function was
  // enqueued as a code flushing candidate and we remove it now.
472
  if (!function->next_function_link()->IsUndefined(isolate)) {
473 474 475 476
    CodeFlusher* flusher = GetHeap()->mark_compact_collector()->code_flusher();
    flusher->EvictCandidate(function);
  }

477
  DCHECK(function->next_function_link()->IsUndefined(isolate));
478

479 480
  function->set_next_function_link(get(OPTIMIZED_FUNCTIONS_LIST),
                                   UPDATE_WEAK_WRITE_BARRIER);
481
  set(OPTIMIZED_FUNCTIONS_LIST, function, UPDATE_WEAK_WRITE_BARRIER);
482 483 484 485
}


void Context::RemoveOptimizedFunction(JSFunction* function) {
486
  DCHECK(IsNativeContext());
487 488
  Object* element = get(OPTIMIZED_FUNCTIONS_LIST);
  JSFunction* prev = NULL;
489 490
  Isolate* isolate = function->GetIsolate();
  while (!element->IsUndefined(isolate)) {
491
    JSFunction* element_function = JSFunction::cast(element);
492
    DCHECK(element_function->next_function_link()->IsUndefined(isolate) ||
493 494 495
           element_function->next_function_link()->IsJSFunction());
    if (element_function == function) {
      if (prev == NULL) {
496 497
        set(OPTIMIZED_FUNCTIONS_LIST, element_function->next_function_link(),
            UPDATE_WEAK_WRITE_BARRIER);
498
      } else {
499 500
        prev->set_next_function_link(element_function->next_function_link(),
                                     UPDATE_WEAK_WRITE_BARRIER);
501
      }
502 503
      element_function->set_next_function_link(GetHeap()->undefined_value(),
                                               UPDATE_WEAK_WRITE_BARRIER);
504 505 506 507 508 509 510 511 512
      return;
    }
    prev = element_function;
    element = element_function->next_function_link();
  }
  UNREACHABLE();
}


513
void Context::SetOptimizedFunctionsListHead(Object* head) {
514
  DCHECK(IsNativeContext());
515
  set(OPTIMIZED_FUNCTIONS_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
516 517 518
}


519
Object* Context::OptimizedFunctionsListHead() {
520
  DCHECK(IsNativeContext());
521 522 523 524
  return get(OPTIMIZED_FUNCTIONS_LIST);
}


525
void Context::AddOptimizedCode(Code* code) {
526 527
  DCHECK(IsNativeContext());
  DCHECK(code->kind() == Code::OPTIMIZED_FUNCTION);
528
  DCHECK(code->next_code_link()->IsUndefined(GetIsolate()));
529
  code->set_next_code_link(get(OPTIMIZED_CODE_LIST));
530
  set(OPTIMIZED_CODE_LIST, code, UPDATE_WEAK_WRITE_BARRIER);
531 532 533 534
}


void Context::SetOptimizedCodeListHead(Object* head) {
535
  DCHECK(IsNativeContext());
536
  set(OPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
537 538 539 540
}


Object* Context::OptimizedCodeListHead() {
541
  DCHECK(IsNativeContext());
542 543 544 545 546
  return get(OPTIMIZED_CODE_LIST);
}


void Context::SetDeoptimizedCodeListHead(Object* head) {
547
  DCHECK(IsNativeContext());
548
  set(DEOPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
549 550 551 552
}


Object* Context::DeoptimizedCodeListHead() {
553
  DCHECK(IsNativeContext());
554
  return get(DEOPTIMIZED_CODE_LIST);
555 556 557
}


558
Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
559 560
  Isolate* isolate = GetIsolate();
  Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
561
  if (!result->IsUndefined(isolate)) return result;
562
  return isolate->factory()->NewStringFromStaticChars(
563
      "Code generation from strings disallowed for this context");
564 565 566
}


567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
#define COMPARE_NAME(index, type, name) \
  if (string->IsOneByteEqualTo(STATIC_CHAR_VECTOR(#name))) return index;

int Context::ImportedFieldIndexForName(Handle<String> string) {
  NATIVE_CONTEXT_IMPORTED_FIELDS(COMPARE_NAME)
  return kNotFound;
}


int Context::IntrinsicIndexForName(Handle<String> string) {
  NATIVE_CONTEXT_INTRINSIC_FUNCTIONS(COMPARE_NAME);
  return kNotFound;
}

#undef COMPARE_NAME


584
#ifdef DEBUG
585 586 587 588 589 590 591 592 593

bool Context::IsBootstrappingOrNativeContext(Isolate* isolate, Object* object) {
  // During bootstrapping we allow all objects to pass as global
  // objects. This is necessary to fix circular dependencies.
  return isolate->heap()->gc_state() != Heap::NOT_IN_GC ||
         isolate->bootstrapper()->IsActive() || object->IsNativeContext();
}


594 595
bool Context::IsBootstrappingOrValidParentContext(
    Object* object, Context* child) {
596 597
  // During bootstrapping we allow all objects to pass as
  // contexts. This is necessary to fix circular dependencies.
598
  if (child->GetIsolate()->bootstrapper()->IsActive()) return true;
599 600
  if (!object->IsContext()) return false;
  Context* context = Context::cast(object);
601
  return context->IsNativeContext() || context->IsScriptContext() ||
602
         context->IsModuleContext() || !child->IsModuleContext();
603 604 605 606
}

#endif

607 608 609 610 611 612 613 614 615 616 617

void Context::IncrementErrorsThrown() {
  DCHECK(IsNativeContext());

  int previous_value = errors_thrown()->value();
  set_errors_thrown(Smi::FromInt(previous_value + 1));
}


int Context::GetErrorsThrown() { return errors_thrown()->value(); }

618 619
}  // namespace internal
}  // namespace v8