contexts.cc 18.9 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 42 43 44 45 46 47 48
void Context::Initialize(Isolate* isolate) {
  ScopeInfo scope_info = this->scope_info();
  int header = scope_info.ContextHeaderLength();
  for (int var = 0; var < scope_info.ContextLocalCount(); var++) {
    if (scope_info.ContextLocalInitFlag(var) == kNeedsInitialization) {
      set(header + var, ReadOnlyRoots(isolate).the_hole_value());
    }
  }
}

49 50 51
bool ScriptContextTable::Lookup(Isolate* isolate, ScriptContextTable table,
                                String name, LookupResult* result) {
  DisallowHeapAllocation no_gc;
52 53
  // Static variables cannot be in script contexts.
  IsStaticFlag is_static_flag;
54 55 56
  for (int i = 0; i < table.used(); i++) {
    Context context = table.get_context(i);
    DCHECK(context.IsScriptContext());
57
    int slot_index = ScopeInfo::ContextSlotIndex(
58
        context.scope_info(), name, &result->mode, &result->init_flag,
59
        &result->maybe_assigned_flag, &is_static_flag);
60

61
    if (slot_index >= 0) {
62 63 64 65 66 67 68 69
      result->context_index = i;
      result->slot_index = slot_index;
      return true;
    }
  }
  return false;
}

70
bool Context::is_declaration_context() {
71 72
  if (IsFunctionContext() || IsNativeContext() || IsScriptContext() ||
      IsModuleContext()) {
73 74
    return true;
  }
75
  if (IsEvalContext()) {
76
    return scope_info().language_mode() == LanguageMode::kStrict;
77
  }
78
  if (!IsBlockContext()) return false;
79
  return scope_info().is_declaration_scope();
80 81
}

82 83
Context Context::declaration_context() {
  Context current = *this;
84 85
  while (!current.is_declaration_context()) {
    current = current.previous();
86 87 88 89
  }
  return current;
}

90 91
Context Context::closure_context() {
  Context current = *this;
92 93 94 95
  while (!current.IsFunctionContext() && !current.IsScriptContext() &&
         !current.IsModuleContext() && !current.IsNativeContext() &&
         !current.IsEvalContext()) {
    current = current.previous();
96 97 98
  }
  return current;
}
99

100
JSObject Context::extension_object() {
101
  DCHECK(IsNativeContext() || IsFunctionContext() || IsBlockContext() ||
102
         IsEvalContext() || IsCatchContext());
103
  HeapObject object = extension();
104
  if (object.IsUndefined()) return JSObject();
105 106
  DCHECK(object.IsJSContextExtensionObject() ||
         (IsNativeContext() && object.IsJSGlobalObject()));
107 108 109
  return JSObject::cast(object);
}

110
JSReceiver Context::extension_receiver() {
111
  DCHECK(IsNativeContext() || IsWithContext() || IsEvalContext() ||
112
         IsFunctionContext() || IsBlockContext());
113
  return IsWithContext() ? JSReceiver::cast(extension()) : extension_object();
114 115
}

116
ScopeInfo Context::scope_info() {
117
  return ScopeInfo::cast(get(SCOPE_INFO_INDEX));
118 119
}

120
SourceTextModule Context::module() {
121
  Context current = *this;
122 123
  while (!current.IsModuleContext()) {
    current = current.previous();
124
  }
125
  return SourceTextModule::cast(current.extension());
126
}
127

128
JSGlobalObject Context::global_object() {
129
  return JSGlobalObject::cast(native_context().extension());
130 131
}

132 133
Context Context::script_context() {
  Context current = *this;
134 135
  while (!current.IsScriptContext()) {
    current = current.previous();
136 137 138 139
  }
  return current;
}

140
JSGlobalProxy Context::global_proxy() {
141
  return native_context().global_proxy_object();
142 143
}

144 145 146 147
/**
 * Lookups a property in an object environment, taking the unscopables into
 * account. This is used For HasBinding spec algorithms for ObjectEnvironment.
 */
148
static Maybe<bool> UnscopableLookup(LookupIterator* it, bool is_with_context) {
149 150
  Isolate* isolate = it->isolate();

151
  Maybe<bool> found = JSReceiver::HasProperty(it);
152
  if (!is_with_context || found.IsNothing() || !found.FromJust()) return found;
153 154

  Handle<Object> unscopables;
155 156
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, unscopables,
157 158
      JSReceiver::GetProperty(isolate,
                              Handle<JSReceiver>::cast(it->GetReceiver()),
159
                              isolate->factory()->unscopables_symbol()),
160 161
      Nothing<bool>());
  if (!unscopables->IsJSReceiver()) return Just(true);
162
  Handle<Object> blacklist;
163 164
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
      isolate, blacklist,
165
      JSReceiver::GetProperty(isolate, Handle<JSReceiver>::cast(unscopables),
166 167
                              it->name()),
      Nothing<bool>());
168
  return Just(!blacklist->BooleanValue(isolate));
169 170
}

171
static PropertyAttributes GetAttributesForMode(VariableMode mode) {
172 173
  DCHECK(IsSerializableVariableMode(mode));
  return IsConstVariableMode(mode) ? READ_ONLY : NONE;
174 175
}

176 177 178 179
// static
Handle<Object> Context::Lookup(Handle<Context> context, Handle<String> name,
                               ContextLookupFlags flags, int* index,
                               PropertyAttributes* attributes,
180
                               InitializationFlag* init_flag,
181 182
                               VariableMode* variable_mode,
                               bool* is_sloppy_function_name) {
183
  Isolate* isolate = context->GetIsolate();
184 185

  bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0;
186
  *index = kNotFound;
187
  *attributes = ABSENT;
188
  *init_flag = kCreatedInitialized;
189
  *variable_mode = VariableMode::kVar;
190 191 192
  if (is_sloppy_function_name != nullptr) {
    *is_sloppy_function_name = false;
  }
193 194 195 196 197 198 199 200 201

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

  do {
    if (FLAG_trace_contexts) {
202 203
      PrintF(" - looking in context %p",
             reinterpret_cast<void*>(context->ptr()));
204
      if (context->IsScriptContext()) PrintF(" (script context)");
205
      if (context->IsNativeContext()) PrintF(" (native context)");
206 207 208
      PrintF("\n");
    }

209
    // 1. Check global objects, subjects of with, and extension objects.
210
    DCHECK_IMPLIES(context->IsEvalContext() && context->has_extension(),
211
                   context->extension().IsTheHole(isolate));
212
    if ((context->IsNativeContext() || context->IsWithContext() ||
213
         context->IsFunctionContext() || context->IsBlockContext()) &&
214
        context->has_extension() && !context->extension_receiver().is_null()) {
215
      Handle<JSReceiver> object(context->extension_receiver(), isolate);
216 217

      if (context->IsNativeContext()) {
218
        DisallowHeapAllocation no_gc;
219
        if (FLAG_trace_contexts) {
220
          PrintF(" - trying other script contexts\n");
221
        }
222
        // Try other script contexts.
223
        ScriptContextTable script_contexts =
224
            context->global_object().native_context().script_context_table();
225
        ScriptContextTable::LookupResult r;
226
        if (ScriptContextTable::Lookup(isolate, script_contexts, *name, &r)) {
227
          Context context = script_contexts.get_context(r.context_index);
228
          if (FLAG_trace_contexts) {
229
            PrintF("=> found property in script context %d: %p\n",
230
                   r.context_index, reinterpret_cast<void*>(context.ptr()));
231 232
          }
          *index = r.slot_index;
233
          *variable_mode = r.mode;
234
          *init_flag = r.init_flag;
235
          *attributes = GetAttributesForMode(r.mode);
236
          return handle(context, isolate);
237 238 239
        }
      }

240 241 242
      // 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.
243
      Maybe<PropertyAttributes> maybe = Nothing<PropertyAttributes>();
244 245
      if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0 ||
          object->IsJSContextExtensionObject()) {
246
        maybe = JSReceiver::GetOwnPropertyAttributes(object, name);
247
      } else {
248 249
        // A with context will never bind "this", but debug-eval may look into
        // a with context when resolving "this". Other synthetic variables such
250 251 252
        // 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.
253 254 255
        // 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)) {
256
          DCHECK(context->IsWithContext());
257 258
          maybe = Just(ABSENT);
        } else {
259
          LookupIterator it(isolate, object, name, object);
260
          Maybe<bool> found = UnscopableLookup(&it, context->IsWithContext());
261 262 263 264 265 266 267 268
          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);
          }
269
        }
270
      }
271

272
      if (maybe.IsNothing()) return Handle<Object>();
273
      DCHECK(!isolate->has_pending_exception());
274
      *attributes = maybe.FromJust();
275

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

285
    // 2. Check the context proper if it has slots.
286
    if (context->IsFunctionContext() || context->IsBlockContext() ||
287
        context->IsScriptContext() || context->IsEvalContext() ||
288
        context->IsModuleContext() || context->IsCatchContext()) {
289
      DisallowHeapAllocation no_gc;
290 291
      // Use serialized scope information of functions and blocks to search
      // for the context index.
292
      ScopeInfo scope_info = context->scope_info();
293
      VariableMode mode;
294
      InitializationFlag flag;
295
      MaybeAssignedFlag maybe_assigned_flag;
296 297 298 299
      IsStaticFlag is_static_flag;
      int slot_index =
          ScopeInfo::ContextSlotIndex(scope_info, *name, &mode, &flag,
                                      &maybe_assigned_flag, &is_static_flag);
300
      DCHECK(slot_index < 0 || slot_index >= MIN_CONTEXT_SLOTS);
301
      if (slot_index >= 0) {
Simon Zünd's avatar
Simon Zünd committed
302 303 304 305 306 307 308 309 310 311 312
        // 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;
        }

313
        if (FLAG_trace_contexts) {
314
          PrintF("=> found local in context slot %d (mode = %hhu)\n",
315
                 slot_index, static_cast<uint8_t>(mode));
316
        }
317
        *index = slot_index;
318
        *variable_mode = mode;
319 320
        *init_flag = flag;
        *attributes = GetAttributesForMode(mode);
321 322 323
        return context;
      }

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

346 347 348 349 350 351
      // Lookup variable in module imports and exports.
      if (context->IsModuleContext()) {
        VariableMode mode;
        InitializationFlag flag;
        MaybeAssignedFlag maybe_assigned_flag;
        int cell_index =
352
            scope_info.ModuleIndex(*name, &mode, &flag, &maybe_assigned_flag);
353 354 355 356 357 358 359
        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;
360 361
          *attributes = SourceTextModuleDescriptor::GetCellIndexKind(
                            cell_index) == SourceTextModuleDescriptor::kExport
362 363 364 365 366
                            ? GetAttributesForMode(mode)
                            : READ_ONLY;
          return handle(context->module(), isolate);
        }
      }
367 368
    } else if (context->IsDebugEvaluateContext()) {
      // Check materialized locals.
369
      Object ext = context->get(EXTENSION_INDEX);
370
      if (ext.IsJSReceiver()) {
371
        Handle<JSReceiver> extension(JSReceiver::cast(ext), isolate);
372
        LookupIterator it(isolate, extension, name, extension);
373 374 375 376
        Maybe<bool> found = JSReceiver::HasProperty(&it);
        if (found.FromMaybe(false)) {
          *attributes = NONE;
          return extension;
377 378
        }
      }
379 380 381 382 383 384 385 386 387 388 389

      // 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;
      }

390
      // Check the original context, but do not follow its context chain.
391
      Object obj = context->get(WRAPPED_CONTEXT_INDEX);
392
      if (obj.IsContext()) {
393
        Handle<Context> context(Context::cast(obj), isolate);
394
        Handle<Object> result =
395 396
            Context::Lookup(context, name, DONT_FOLLOW_CHAINS, index,
                            attributes, init_flag, variable_mode);
397 398
        if (!result.is_null()) return result;
      }
399 400
    }

401
    // 3. Prepare to continue with the previous (next outermost) context.
402 403
    if (context->IsNativeContext()) break;

404
    context = Handle<Context>(context->previous(), isolate);
405 406 407 408 409
  } while (follow_context_chain);

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

413
void NativeContext::AddOptimizedCode(Code code) {
414 415 416
  DCHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
  DCHECK(code.next_code_link().IsUndefined());
  code.set_next_code_link(get(OPTIMIZED_CODE_LIST));
417
  set(OPTIMIZED_CODE_LIST, code, UPDATE_WEAK_WRITE_BARRIER);
418 419
}

420
void NativeContext::SetOptimizedCodeListHead(Object head) {
421
  set(OPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
422 423
}

424
Object NativeContext::OptimizedCodeListHead() {
425 426 427
  return get(OPTIMIZED_CODE_LIST);
}

428
void NativeContext::SetDeoptimizedCodeListHead(Object head) {
429
  set(DEOPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
430 431
}

432
Object NativeContext::DeoptimizedCodeListHead() {
433
  return get(DEOPTIMIZED_CODE_LIST);
434 435
}

436
Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
437 438
  Isolate* isolate = GetIsolate();
  Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
439
  if (!result->IsUndefined(isolate)) return result;
440
  return isolate->factory()->NewStringFromStaticChars(
441
      "Code generation from strings disallowed for this context");
442 443
}

444
#define COMPARE_NAME(index, type, name) \
445
  if (string->IsOneByteEqualTo(StaticCharVector(#name))) return index;
446 447 448 449 450 451 452 453

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

#undef COMPARE_NAME

454 455 456 457 458 459
#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;                                                          \
  }
460 461 462 463 464 465 466 467 468

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
469

470
#ifdef DEBUG
471

472
bool Context::IsBootstrappingOrValidParentContext(Object object,
473
                                                  Context child) {
474 475
  // During bootstrapping we allow all objects to pass as
  // contexts. This is necessary to fix circular dependencies.
476 477
  if (child.GetIsolate()->bootstrapper()->IsActive()) return true;
  if (!object.IsContext()) return false;
478
  Context context = Context::cast(object);
479 480
  return context.IsNativeContext() || context.IsScriptContext() ||
         context.IsModuleContext() || !child.IsModuleContext();
481 482 483 484
}

#endif

485
void NativeContext::ResetErrorsThrown() { set_errors_thrown(Smi::FromInt(0)); }
486

487
void NativeContext::IncrementErrorsThrown() {
488
  int previous_value = errors_thrown().value();
489 490 491
  set_errors_thrown(Smi::FromInt(previous_value + 1));
}

492
int NativeContext::GetErrorsThrown() { return errors_thrown().value(); }
493

494 495
STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 2);
STATIC_ASSERT(Context::MIN_CONTEXT_EXTENDED_SLOTS == 3);
496 497 498 499 500 501 502
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));

503
STATIC_ASSERT(NativeContext::kStartOfStrongFieldsOffset ==
504
              Context::OffsetOfElementAt(-1));
505 506 507 508 509 510 511 512
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));

513 514
}  // namespace internal
}  // namespace v8