contexts.cc 18.8 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/bootstrapper.h"
8
#include "src/debug/debug.h"
9
#include "src/isolate-inl.h"
10

11 12
namespace v8 {
namespace internal {
13

14

15 16 17
Handle<ScriptContextTable> ScriptContextTable::Extend(
    Handle<ScriptContextTable> table, Handle<Context> script_context) {
  Handle<ScriptContextTable> result;
18 19 20
  int used = table->used();
  int length = table->length();
  CHECK(used >= 0 && length > 0 && used < length);
21
  if (used + kFirstContextSlot == length) {
22
    CHECK(length < Smi::kMaxValue / 2);
23 24 25 26 27
    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);
28 29 30 31 32
  } else {
    result = table;
  }
  result->set_used(used + 1);

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


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

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


59 60 61 62 63 64 65 66
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.
67 68
  return ext->IsContextExtension() ||
         ScopeInfo::cast(ext)->is_declaration_scope();
69 70 71
}


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

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

91 92
JSObject* Context::extension_object() {
  DCHECK(IsNativeContext() || IsFunctionContext() || IsBlockContext());
93
  HeapObject* object = extension();
94
  if (object->IsTheHole(GetIsolate())) return nullptr;
95
  if (IsBlockContext()) {
96 97
    if (!object->IsContextExtension()) return nullptr;
    object = JSObject::cast(ContextExtension::cast(object)->extension());
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  }
  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());
114
  HeapObject* object = extension();
115
  if (object->IsContextExtension()) {
116
    DCHECK(IsBlockContext());
117
    object = ContextExtension::cast(object)->scope_info();
118 119 120 121 122 123 124 125 126 127 128
  }
  return ScopeInfo::cast(object);
}


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


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


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


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

147

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


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

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

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

179 180
static PropertyAttributes GetAttributesForMode(VariableMode mode) {
  DCHECK(IsDeclaredVariableMode(mode));
181
  return mode == CONST ? READ_ONLY : NONE;
182 183
}

184 185
Handle<Object> Context::Lookup(Handle<String> name, ContextLookupFlags flags,
                               int* index, PropertyAttributes* attributes,
186
                               InitializationFlag* init_flag,
187
                               VariableMode* variable_mode) {
188 189
  Isolate* isolate = GetIsolate();
  Handle<Context> context(this, isolate);
190 191

  bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0;
192
  bool failed_whitelist = false;
193
  *index = kNotFound;
194
  *attributes = ABSENT;
195
  *init_flag = kCreatedInitialized;
196
  *variable_mode = VAR;
197 198 199 200 201 202 203 204 205

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

  do {
    if (FLAG_trace_contexts) {
206
      PrintF(" - looking in context %p", reinterpret_cast<void*>(*context));
207
      if (context->IsScriptContext()) PrintF(" (script context)");
208
      if (context->IsNativeContext()) PrintF(" (native context)");
209 210 211
      PrintF("\n");
    }

212
    // 1. Check global objects, subjects of with, and extension objects.
213 214
    if ((context->IsNativeContext() ||
         (context->IsWithContext() && ((flags & SKIP_WITH_CONTEXT) == 0)) ||
215 216 217
         context->IsFunctionContext() || context->IsBlockContext()) &&
        context->extension_receiver() != nullptr) {
      Handle<JSReceiver> object(context->extension_receiver());
218 219 220

      if (context->IsNativeContext()) {
        if (FLAG_trace_contexts) {
221
          PrintF(" - trying other script contexts\n");
222
        }
223 224 225 226 227
        // 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)) {
228
          if (FLAG_trace_contexts) {
229
            Handle<Context> c = ScriptContextTable::GetContext(script_contexts,
230
                                                               r.context_index);
231
            PrintF("=> found property in script context %d: %p\n",
232 233 234
                   r.context_index, reinterpret_cast<void*>(*c));
          }
          *index = r.slot_index;
235
          *variable_mode = r.mode;
236
          *init_flag = r.init_flag;
237
          *attributes = GetAttributesForMode(r.mode);
238
          return ScriptContextTable::GetContext(script_contexts,
239 240 241 242
                                                r.context_index);
        }
      }

243 244 245
      // 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.
246
      Maybe<PropertyAttributes> maybe = Nothing<PropertyAttributes>();
247 248
      if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0 ||
          object->IsJSContextExtensionObject()) {
249
        maybe = JSReceiver::GetOwnPropertyAttributes(object, name);
250
      } else if (context->IsWithContext()) {
251 252 253 254
        // A with context will never bind "this".
        if (name->Equals(*isolate->factory()->this_string())) {
          maybe = Just(ABSENT);
        } else {
255
          LookupIterator it(object, name, object);
256 257 258 259 260 261 262 263 264
          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);
          }
265
        }
266
      } else {
267
        maybe = JSReceiver::GetPropertyAttributes(object, name);
268
      }
269

270
      if (!maybe.IsJust()) return Handle<Object>();
271
      DCHECK(!isolate->has_pending_exception());
272
      *attributes = maybe.FromJust();
273

274
      if (maybe.FromJust() != ABSENT) {
275 276 277
        if (FLAG_trace_contexts) {
          PrintF("=> found property in context object %p\n",
                 reinterpret_cast<void*>(*object));
278
        }
279
        return object;
280 281 282
      }
    }

283
    // 2. Check the context proper if it has slots.
284
    if (context->IsFunctionContext() || context->IsBlockContext() ||
285
        context->IsScriptContext()) {
286 287
      // Use serialized scope information of functions and blocks to search
      // for the context index.
288 289 290
      Handle<ScopeInfo> scope_info(context->IsFunctionContext()
          ? context->closure()->shared()->scope_info()
          : context->scope_info());
291
      VariableMode mode;
292
      InitializationFlag flag;
293
      MaybeAssignedFlag maybe_assigned_flag;
294 295
      int slot_index = ScopeInfo::ContextSlotIndex(scope_info, name, &mode,
                                                   &flag, &maybe_assigned_flag);
296
      DCHECK(slot_index < 0 || slot_index >= MIN_CONTEXT_SLOTS);
297
      if (slot_index >= 0) {
298 299
        if (FLAG_trace_contexts) {
          PrintF("=> found local in context slot %d (mode = %d)\n",
300
                 slot_index, mode);
301
        }
302
        *index = slot_index;
303
        *variable_mode = mode;
304 305
        *init_flag = flag;
        *attributes = GetAttributesForMode(mode);
306 307 308
        return context;
      }

309
      // Check the slot corresponding to the intermediate context holding
310 311 312 313 314
      // only the function name variable. It's conceptually (and spec-wise)
      // in an outer scope of the function's declaration scope.
      if (follow_context_chain && (flags & STOP_AT_DECLARATION_SCOPE) == 0 &&
          context->IsFunctionContext()) {
        int function_index = scope_info->FunctionContextSlotIndex(*name);
315
        if (function_index >= 0) {
316 317
          if (FLAG_trace_contexts) {
            PrintF("=> found intermediate function in context slot %d\n",
318
                   function_index);
319
          }
320
          *index = function_index;
321
          *attributes = READ_ONLY;
322
          *init_flag = kCreatedInitialized;
323
          *variable_mode = CONST;
324 325 326
          return context;
        }
      }
327 328 329

    } else if (context->IsCatchContext()) {
      // Catch contexts have the variable name in the extension slot.
330
      if (String::Equals(name, handle(context->catch_name()))) {
331 332 333 334 335
        if (FLAG_trace_contexts) {
          PrintF("=> found in catch context\n");
        }
        *index = Context::THROWN_OBJECT_INDEX;
        *attributes = NONE;
336
        *init_flag = kCreatedInitialized;
337
        *variable_mode = VAR;
338 339
        return context;
      }
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
    } 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()) {
355 356 357
        Handle<Object> result =
            Context::cast(obj)->Lookup(name, DONT_FOLLOW_CHAINS, index,
                                       attributes, init_flag, variable_mode);
358 359 360 361 362 363 364 365
        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);
      }
366 367
    }

368
    // 3. Prepare to continue with the previous (next outermost) context.
369 370 371
    if (context->IsNativeContext() ||
        ((flags & STOP_AT_DECLARATION_SCOPE) != 0 &&
         context->is_declaration_context())) {
372
      follow_context_chain = false;
373
    } else {
374 375 376 377 378 379
      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());
380 381 382 383 384 385
    }
  } while (follow_context_chain);

  if (FLAG_trace_contexts) {
    PrintF("=> no property/slot found\n");
  }
386
  return Handle<Object>::null();
387 388 389
}


390
void Context::AddOptimizedFunction(JSFunction* function) {
391
  DCHECK(IsNativeContext());
392
  Isolate* isolate = GetIsolate();
393
#ifdef ENABLE_SLOW_DCHECKS
394 395
  if (FLAG_enable_slow_asserts) {
    Object* element = get(OPTIMIZED_FUNCTIONS_LIST);
396
    while (!element->IsUndefined(isolate)) {
397 398 399
      CHECK(element != function);
      element = JSFunction::cast(element)->next_function_link();
    }
400 401
  }

402
  // Check that the context belongs to the weak native contexts list.
403
  bool found = false;
404 405
  Object* context = isolate->heap()->native_contexts_list();
  while (!context->IsUndefined(isolate)) {
406 407 408 409
    if (context == this) {
      found = true;
      break;
    }
410
    context = Context::cast(context)->next_context_link();
411 412 413
  }
  CHECK(found);
#endif
414 415 416

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

422
  DCHECK(function->next_function_link()->IsUndefined(isolate));
423

424 425
  function->set_next_function_link(get(OPTIMIZED_FUNCTIONS_LIST),
                                   UPDATE_WEAK_WRITE_BARRIER);
426
  set(OPTIMIZED_FUNCTIONS_LIST, function, UPDATE_WEAK_WRITE_BARRIER);
427 428 429 430
}


void Context::RemoveOptimizedFunction(JSFunction* function) {
431
  DCHECK(IsNativeContext());
432 433
  Object* element = get(OPTIMIZED_FUNCTIONS_LIST);
  JSFunction* prev = NULL;
434 435
  Isolate* isolate = function->GetIsolate();
  while (!element->IsUndefined(isolate)) {
436
    JSFunction* element_function = JSFunction::cast(element);
437
    DCHECK(element_function->next_function_link()->IsUndefined(isolate) ||
438 439 440
           element_function->next_function_link()->IsJSFunction());
    if (element_function == function) {
      if (prev == NULL) {
441 442
        set(OPTIMIZED_FUNCTIONS_LIST, element_function->next_function_link(),
            UPDATE_WEAK_WRITE_BARRIER);
443
      } else {
444 445
        prev->set_next_function_link(element_function->next_function_link(),
                                     UPDATE_WEAK_WRITE_BARRIER);
446
      }
447 448
      element_function->set_next_function_link(GetHeap()->undefined_value(),
                                               UPDATE_WEAK_WRITE_BARRIER);
449 450 451 452 453 454 455 456 457
      return;
    }
    prev = element_function;
    element = element_function->next_function_link();
  }
  UNREACHABLE();
}


458
void Context::SetOptimizedFunctionsListHead(Object* head) {
459
  DCHECK(IsNativeContext());
460
  set(OPTIMIZED_FUNCTIONS_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
461 462 463
}


464
Object* Context::OptimizedFunctionsListHead() {
465
  DCHECK(IsNativeContext());
466 467 468 469
  return get(OPTIMIZED_FUNCTIONS_LIST);
}


470
void Context::AddOptimizedCode(Code* code) {
471 472
  DCHECK(IsNativeContext());
  DCHECK(code->kind() == Code::OPTIMIZED_FUNCTION);
473
  DCHECK(code->next_code_link()->IsUndefined(GetIsolate()));
474
  code->set_next_code_link(get(OPTIMIZED_CODE_LIST));
475
  set(OPTIMIZED_CODE_LIST, code, UPDATE_WEAK_WRITE_BARRIER);
476 477 478 479
}


void Context::SetOptimizedCodeListHead(Object* head) {
480
  DCHECK(IsNativeContext());
481
  set(OPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
482 483 484 485
}


Object* Context::OptimizedCodeListHead() {
486
  DCHECK(IsNativeContext());
487 488 489 490 491
  return get(OPTIMIZED_CODE_LIST);
}


void Context::SetDeoptimizedCodeListHead(Object* head) {
492
  DCHECK(IsNativeContext());
493
  set(DEOPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
494 495 496 497
}


Object* Context::DeoptimizedCodeListHead() {
498
  DCHECK(IsNativeContext());
499
  return get(DEOPTIMIZED_CODE_LIST);
500 501 502
}


503
Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
504 505
  Isolate* isolate = GetIsolate();
  Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
506
  if (!result->IsUndefined(isolate)) return result;
507
  return isolate->factory()->NewStringFromStaticChars(
508
      "Code generation from strings disallowed for this context");
509 510 511
}


512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
#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


529
#ifdef DEBUG
530 531 532 533 534 535 536 537 538

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();
}


539 540
bool Context::IsBootstrappingOrValidParentContext(
    Object* object, Context* child) {
541 542
  // During bootstrapping we allow all objects to pass as
  // contexts. This is necessary to fix circular dependencies.
543
  if (child->GetIsolate()->bootstrapper()->IsActive()) return true;
544 545
  if (!object->IsContext()) return false;
  Context* context = Context::cast(object);
546
  return context->IsNativeContext() || context->IsScriptContext() ||
547
         context->IsModuleContext() || !child->IsModuleContext();
548 549 550 551
}

#endif

552 553 554 555 556 557 558 559 560 561 562

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(); }

563 564
}  // namespace internal
}  // namespace v8