contexts.cc 19.6 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/objects/contexts.h"
6

7
#include "src/ast/modules.h"
8
#include "src/debug/debug.h"
9
#include "src/execution/isolate-inl.h"
10
#include "src/init/bootstrapper.h"
11
#include "src/objects/module-inl.h"
12

13 14
namespace v8 {
namespace internal {
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 + kFirstContextSlotIndex == length) {
23
    CHECK(length < Smi::kMaxValue / 2);
24
    Isolate* isolate = script_context->GetIsolate();
25
    Handle<FixedArray> copy =
26
        isolate->factory()->CopyFixedArrayAndGrow(table, length);
27
    copy->set_map(ReadOnlyRoots(isolate).script_context_table_map());
28
    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 + kFirstContextSlotIndex, *script_context);
36 37 38
  return result;
}

39 40 41
bool ScriptContextTable::Lookup(Isolate* isolate, ScriptContextTable table,
                                String name, LookupResult* result) {
  DisallowHeapAllocation no_gc;
42 43
  // Static variables cannot be in script contexts.
  IsStaticFlag is_static_flag;
44 45 46
  for (int i = 0; i < table.used(); i++) {
    Context context = table.get_context(i);
    DCHECK(context.IsScriptContext());
47
    int slot_index = ScopeInfo::ContextSlotIndex(
48
        context.scope_info(), name, &result->mode, &result->init_flag,
49
        &result->maybe_assigned_flag, &is_static_flag);
50

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

60
bool Context::is_declaration_context() {
61 62
  if (IsFunctionContext() || IsNativeContext() || IsScriptContext() ||
      IsModuleContext()) {
63 64
    return true;
  }
65
  if (IsEvalContext()) {
66
    return scope_info().language_mode() == LanguageMode::kStrict;
67
  }
68
  if (!IsBlockContext()) return false;
69
  return scope_info().is_declaration_scope();
70 71
}

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

80 81
Context Context::closure_context() {
  Context current = *this;
82 83 84 85
  while (!current.IsFunctionContext() && !current.IsScriptContext() &&
         !current.IsModuleContext() && !current.IsNativeContext() &&
         !current.IsEvalContext()) {
    current = current.previous();
86 87 88
  }
  return current;
}
89

90
JSObject Context::extension_object() {
91
  DCHECK(IsNativeContext() || IsFunctionContext() || IsBlockContext() ||
92
         IsEvalContext() || IsCatchContext());
93
  HeapObject object = extension();
94
  if (object.IsUndefined()) return JSObject();
95 96
  DCHECK(object.IsJSContextExtensionObject() ||
         (IsNativeContext() && object.IsJSGlobalObject()));
97 98 99
  return JSObject::cast(object);
}

100
JSReceiver Context::extension_receiver() {
101
  DCHECK(IsNativeContext() || IsWithContext() || IsEvalContext() ||
102
         IsFunctionContext() || IsBlockContext());
103
  return IsWithContext() ? JSReceiver::cast(extension()) : extension_object();
104 105
}

106
ScopeInfo Context::scope_info() {
107
  return ScopeInfo::cast(get(SCOPE_INFO_INDEX));
108 109
}

110
SourceTextModule Context::module() {
111
  Context current = *this;
112 113
  while (!current.IsModuleContext()) {
    current = current.previous();
114
  }
115
  return SourceTextModule::cast(current.extension());
116
}
117

118
JSGlobalObject Context::global_object() {
119
  return JSGlobalObject::cast(native_context().extension());
120 121
}

122 123
Context Context::script_context() {
  Context current = *this;
124 125
  while (!current.IsScriptContext()) {
    current = current.previous();
126 127 128 129
  }
  return current;
}

130
JSGlobalProxy Context::global_proxy() {
131
  return native_context().global_proxy_object();
132 133
}

134 135 136 137
/**
 * Lookups a property in an object environment, taking the unscopables into
 * account. This is used For HasBinding spec algorithms for ObjectEnvironment.
 */
138
static Maybe<bool> UnscopableLookup(LookupIterator* it, bool is_with_context) {
139 140
  Isolate* isolate = it->isolate();

141
  Maybe<bool> found = JSReceiver::HasProperty(it);
142
  if (!is_with_context || found.IsNothing() || !found.FromJust()) return found;
143 144

  Handle<Object> unscopables;
145 146
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, unscopables,
147 148
      JSReceiver::GetProperty(isolate,
                              Handle<JSReceiver>::cast(it->GetReceiver()),
149
                              isolate->factory()->unscopables_symbol()),
150 151
      Nothing<bool>());
  if (!unscopables->IsJSReceiver()) return Just(true);
152
  Handle<Object> blacklist;
153 154
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, blacklist,
155
      JSReceiver::GetProperty(isolate, Handle<JSReceiver>::cast(unscopables),
156 157
                              it->name()),
      Nothing<bool>());
158
  return Just(!blacklist->BooleanValue(isolate));
159 160
}

161
static PropertyAttributes GetAttributesForMode(VariableMode mode) {
162 163
  DCHECK(IsSerializableVariableMode(mode));
  return IsConstVariableMode(mode) ? READ_ONLY : NONE;
164 165
}

166 167 168 169
// static
Handle<Object> Context::Lookup(Handle<Context> context, Handle<String> name,
                               ContextLookupFlags flags, int* index,
                               PropertyAttributes* attributes,
170
                               InitializationFlag* init_flag,
171 172
                               VariableMode* variable_mode,
                               bool* is_sloppy_function_name) {
173
  Isolate* isolate = context->GetIsolate();
174 175

  bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0;
176
  *index = kNotFound;
177
  *attributes = ABSENT;
178
  *init_flag = kCreatedInitialized;
179
  *variable_mode = VariableMode::kVar;
180 181 182
  if (is_sloppy_function_name != nullptr) {
    *is_sloppy_function_name = false;
  }
183 184 185 186 187 188 189 190 191

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

  do {
    if (FLAG_trace_contexts) {
192 193
      PrintF(" - looking in context %p",
             reinterpret_cast<void*>(context->ptr()));
194
      if (context->IsScriptContext()) PrintF(" (script context)");
195
      if (context->IsNativeContext()) PrintF(" (native context)");
196 197 198
      PrintF("\n");
    }

199
    // 1. Check global objects, subjects of with, and extension objects.
200
    DCHECK_IMPLIES(context->IsEvalContext() && context->has_extension(),
201
                   context->extension().IsTheHole(isolate));
202
    if ((context->IsNativeContext() || context->IsWithContext() ||
203
         context->IsFunctionContext() || context->IsBlockContext()) &&
204
        context->has_extension() && !context->extension_receiver().is_null()) {
205
      Handle<JSReceiver> object(context->extension_receiver(), isolate);
206 207

      if (context->IsNativeContext()) {
208
        DisallowHeapAllocation no_gc;
209
        if (FLAG_trace_contexts) {
210
          PrintF(" - trying other script contexts\n");
211
        }
212
        // Try other script contexts.
213
        ScriptContextTable script_contexts =
214
            context->global_object().native_context().script_context_table();
215
        ScriptContextTable::LookupResult r;
216
        if (ScriptContextTable::Lookup(isolate, script_contexts, *name, &r)) {
217
          Context context = script_contexts.get_context(r.context_index);
218
          if (FLAG_trace_contexts) {
219
            PrintF("=> found property in script context %d: %p\n",
220
                   r.context_index, reinterpret_cast<void*>(context.ptr()));
221 222
          }
          *index = r.slot_index;
223
          *variable_mode = r.mode;
224
          *init_flag = r.init_flag;
225
          *attributes = GetAttributesForMode(r.mode);
226
          return handle(context, isolate);
227 228 229
        }
      }

230 231 232
      // 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.
233
      Maybe<PropertyAttributes> maybe = Nothing<PropertyAttributes>();
234 235
      if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0 ||
          object->IsJSContextExtensionObject()) {
236
        maybe = JSReceiver::GetOwnPropertyAttributes(object, name);
237
      } else {
238 239
        // A with context will never bind "this", but debug-eval may look into
        // a with context when resolving "this". Other synthetic variables such
240 241 242
        // as new.target may be resolved as VariableMode::kDynamicLocal due to
        // bug v8:5405 , skipping them here serves as a workaround until a more
        // thorough fix can be applied.
243 244 245
        // TODO(v8:5405): Replace this check with a DCHECK when resolution of
        // of synthetic variables does not go through this code path.
        if (ScopeInfo::VariableIsSynthetic(*name)) {
246
          DCHECK(context->IsWithContext());
247 248
          maybe = Just(ABSENT);
        } else {
249
          LookupIterator it(object, name, object);
250
          Maybe<bool> found = UnscopableLookup(&it, context->IsWithContext());
251 252 253 254 255 256 257 258
          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);
          }
259
        }
260
      }
261

262
      if (maybe.IsNothing()) return Handle<Object>();
263
      DCHECK(!isolate->has_pending_exception());
264
      *attributes = maybe.FromJust();
265

266
      if (maybe.FromJust() != ABSENT) {
267 268
        if (FLAG_trace_contexts) {
          PrintF("=> found property in context object %p\n",
269
                 reinterpret_cast<void*>(object->ptr()));
270
        }
271
        return object;
272 273 274
      }
    }

275
    // 2. Check the context proper if it has slots.
276
    if (context->IsFunctionContext() || context->IsBlockContext() ||
277
        context->IsScriptContext() || context->IsEvalContext() ||
278
        context->IsModuleContext() || context->IsCatchContext()) {
279
      DisallowHeapAllocation no_gc;
280 281
      // Use serialized scope information of functions and blocks to search
      // for the context index.
282
      ScopeInfo scope_info = context->scope_info();
283
      VariableMode mode;
284
      InitializationFlag flag;
285
      MaybeAssignedFlag maybe_assigned_flag;
286 287 288 289
      IsStaticFlag is_static_flag;
      int slot_index =
          ScopeInfo::ContextSlotIndex(scope_info, *name, &mode, &flag,
                                      &maybe_assigned_flag, &is_static_flag);
290
      DCHECK(slot_index < 0 || slot_index >= MIN_CONTEXT_SLOTS);
291
      if (slot_index >= 0) {
Simon Zünd's avatar
Simon Zünd committed
292 293 294 295 296 297 298 299 300 301 302
        // Re-direct lookup to the ScriptContextTable in case we find a hole in
        // a REPL script context. REPL scripts allow re-declaration of
        // script-level let bindings. The value itself is stored in the script
        // context of the first script that declared a variable, all other
        // script contexts will contain 'the hole' for that particular name.
        if (scope_info.IsReplModeScope() &&
            context->get(slot_index).IsTheHole(isolate)) {
          context = Handle<Context>(context->previous(), isolate);
          continue;
        }

303
        if (FLAG_trace_contexts) {
304
          PrintF("=> found local in context slot %d (mode = %hhu)\n",
305
                 slot_index, static_cast<uint8_t>(mode));
306
        }
307
        *index = slot_index;
308
        *variable_mode = mode;
309 310
        *init_flag = flag;
        *attributes = GetAttributesForMode(mode);
311 312 313
        return context;
      }

314
      // Check the slot corresponding to the intermediate context holding
315 316
      // only the function name variable. It's conceptually (and spec-wise)
      // in an outer scope of the function's declaration scope.
317
      if (follow_context_chain && context->IsFunctionContext()) {
318
        int function_index = scope_info.FunctionContextSlotIndex(*name);
319
        if (function_index >= 0) {
320 321
          if (FLAG_trace_contexts) {
            PrintF("=> found intermediate function in context slot %d\n",
322
                   function_index);
323
          }
324
          *index = function_index;
325
          *attributes = READ_ONLY;
326
          *init_flag = kCreatedInitialized;
327
          *variable_mode = VariableMode::kConst;
328
          if (is_sloppy_function_name != nullptr &&
329
              is_sloppy(scope_info.language_mode())) {
330 331
            *is_sloppy_function_name = true;
          }
332 333 334
          return context;
        }
      }
335

336 337 338 339 340 341
      // Lookup variable in module imports and exports.
      if (context->IsModuleContext()) {
        VariableMode mode;
        InitializationFlag flag;
        MaybeAssignedFlag maybe_assigned_flag;
        int cell_index =
342
            scope_info.ModuleIndex(*name, &mode, &flag, &maybe_assigned_flag);
343 344 345 346 347 348 349
        if (cell_index != 0) {
          if (FLAG_trace_contexts) {
            PrintF("=> found in module imports or exports\n");
          }
          *index = cell_index;
          *variable_mode = mode;
          *init_flag = flag;
350 351
          *attributes = SourceTextModuleDescriptor::GetCellIndexKind(
                            cell_index) == SourceTextModuleDescriptor::kExport
352 353 354 355 356
                            ? GetAttributesForMode(mode)
                            : READ_ONLY;
          return handle(context->module(), isolate);
        }
      }
357 358
    } else if (context->IsDebugEvaluateContext()) {
      // Check materialized locals.
359
      Object ext = context->get(EXTENSION_INDEX);
360
      if (ext.IsJSReceiver()) {
361
        Handle<JSReceiver> extension(JSReceiver::cast(ext), isolate);
362 363 364 365 366
        LookupIterator it(extension, name, extension);
        Maybe<bool> found = JSReceiver::HasProperty(&it);
        if (found.FromMaybe(false)) {
          *attributes = NONE;
          return extension;
367 368
        }
      }
369 370 371 372 373 374 375 376 377 378 379

      // Check blacklist. Names that are listed, cannot be resolved further.
      Object blacklist = context->get(BLACK_LIST_INDEX);
      if (blacklist.IsStringSet() &&
          StringSet::cast(blacklist).Has(isolate, name)) {
        if (FLAG_trace_contexts) {
          PrintF(" - name is blacklisted. Aborting.\n");
        }
        break;
      }

380
      // Check the original context, but do not follow its context chain.
381
      Object obj = context->get(WRAPPED_CONTEXT_INDEX);
382
      if (obj.IsContext()) {
383
        Handle<Context> context(Context::cast(obj), isolate);
384
        Handle<Object> result =
385 386
            Context::Lookup(context, name, DONT_FOLLOW_CHAINS, index,
                            attributes, init_flag, variable_mode);
387 388
        if (!result.is_null()) return result;
      }
389 390
    }

391
    // 3. Prepare to continue with the previous (next outermost) context.
392 393
    if (context->IsNativeContext()) break;

394
    context = Handle<Context>(context->previous(), isolate);
395 396 397 398 399
  } while (follow_context_chain);

  if (FLAG_trace_contexts) {
    PrintF("=> no property/slot found\n");
  }
400
  return Handle<Object>::null();
401 402
}

403
void NativeContext::AddOptimizedCode(Code code) {
404 405 406
  DCHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
  DCHECK(code.next_code_link().IsUndefined());
  code.set_next_code_link(get(OPTIMIZED_CODE_LIST));
407
  set(OPTIMIZED_CODE_LIST, code, UPDATE_WEAK_WRITE_BARRIER);
408 409
}

410
void NativeContext::SetOptimizedCodeListHead(Object head) {
411
  set(OPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
412 413
}

414
Object NativeContext::OptimizedCodeListHead() {
415 416 417
  return get(OPTIMIZED_CODE_LIST);
}

418
void NativeContext::SetDeoptimizedCodeListHead(Object head) {
419
  set(DEOPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
420 421
}

422
Object NativeContext::DeoptimizedCodeListHead() {
423
  return get(DEOPTIMIZED_CODE_LIST);
424 425
}

426
Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
427 428
  Isolate* isolate = GetIsolate();
  Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
429
  if (!result->IsUndefined(isolate)) return result;
430
  return isolate->factory()->NewStringFromStaticChars(
431
      "Code generation from strings disallowed for this context");
432 433
}

434
#define COMPARE_NAME(index, type, name) \
435
  if (string->IsOneByteEqualTo(StaticCharVector(#name))) return index;
436 437 438 439 440 441 442 443

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

#undef COMPARE_NAME

444 445 446 447 448 449
#define COMPARE_NAME(index, type, name)                                      \
  {                                                                          \
    const int name_length = static_cast<int>(arraysize(#name)) - 1;          \
    if ((length == name_length) && strncmp(string, #name, name_length) == 0) \
      return index;                                                          \
  }
450 451 452 453 454 455 456 457 458

int Context::IntrinsicIndexForName(const unsigned char* unsigned_string,
                                   int length) {
  const char* string = reinterpret_cast<const char*>(unsigned_string);
  NATIVE_CONTEXT_INTRINSIC_FUNCTIONS(COMPARE_NAME);
  return kNotFound;
}

#undef COMPARE_NAME
459

460
#ifdef DEBUG
461

462
bool Context::IsBootstrappingOrValidParentContext(Object object,
463
                                                  Context child) {
464 465
  // During bootstrapping we allow all objects to pass as
  // contexts. This is necessary to fix circular dependencies.
466 467
  if (child.GetIsolate()->bootstrapper()->IsActive()) return true;
  if (!object.IsContext()) return false;
468
  Context context = Context::cast(object);
469 470
  return context.IsNativeContext() || context.IsScriptContext() ||
         context.IsModuleContext() || !child.IsModuleContext();
471 472 473 474
}

#endif

475
void NativeContext::ResetErrorsThrown() { set_errors_thrown(Smi::FromInt(0)); }
476

477
void NativeContext::IncrementErrorsThrown() {
478
  int previous_value = errors_thrown().value();
479 480 481
  set_errors_thrown(Smi::FromInt(previous_value + 1));
}

482
int NativeContext::GetErrorsThrown() { return errors_thrown().value(); }
483

484 485
STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 2);
STATIC_ASSERT(Context::MIN_CONTEXT_EXTENDED_SLOTS == 3);
486 487 488 489 490 491 492
STATIC_ASSERT(NativeContext::kScopeInfoOffset ==
              Context::OffsetOfElementAt(NativeContext::SCOPE_INFO_INDEX));
STATIC_ASSERT(NativeContext::kPreviousOffset ==
              Context::OffsetOfElementAt(NativeContext::PREVIOUS_INDEX));
STATIC_ASSERT(NativeContext::kExtensionOffset ==
              Context::OffsetOfElementAt(NativeContext::EXTENSION_INDEX));

493
STATIC_ASSERT(NativeContext::kStartOfStrongFieldsOffset ==
494
              Context::OffsetOfElementAt(-1));
495 496 497 498 499 500 501 502
STATIC_ASSERT(NativeContext::kStartOfWeakFieldsOffset ==
              Context::OffsetOfElementAt(NativeContext::FIRST_WEAK_SLOT));
STATIC_ASSERT(NativeContext::kMicrotaskQueueOffset ==
              Context::SizeFor(NativeContext::NATIVE_CONTEXT_SLOTS));
STATIC_ASSERT(NativeContext::kSize ==
              (Context::SizeFor(NativeContext::NATIVE_CONTEXT_SLOTS) +
               kSystemPointerSize));

503 504 505
void NativeContext::SetDetachedWindowReason(
    v8::Context::DetachedWindowReason reason) {
  set_detached_window_reason(Smi::FromEnum(reason));
506 507 508 509 510 511 512 513 514 515

  Isolate* isolate = GetIsolate();
  // kWindowNotDetached is used when initializing. Don't initialize to time
  // based value due to build artifact inconsistency (see crbug/1029863).
  // It's safe to use 0, because the value isn't used in the kWindowNotDetached
  // case.
  set_detached_window_time_in_seconds(Smi::FromInt(
      reason == v8::Context::kWindowNotDetached
          ? 0
          : static_cast<int>(isolate->time_millis_since_init() / 1000)));
516 517 518 519 520 521 522 523
}

v8::Context::DetachedWindowReason NativeContext::GetDetachedWindowReason()
    const {
  return static_cast<v8::Context::DetachedWindowReason>(
      detached_window_reason().value());
}

524 525 526 527 528 529 530
int NativeContext::SecondsSinceDetachedWindow() const {
  DCHECK(detached_window_reason().value() != v8::Context::kWindowNotDetached);
  Isolate* isolate = GetIsolate();
  return static_cast<int>(isolate->time_millis_since_init() / 1000 -
                          detached_window_time_in_seconds().value());
}

531 532
}  // namespace internal
}  // namespace v8