contexts.cc 18.1 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 95 96
  if (object.IsTheHole()) return JSObject();
  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
void Context::set_global_proxy(JSGlobalProxy object) {
135
  native_context().set_global_proxy_object(object);
136 137
}

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

145
  Maybe<bool> found = JSReceiver::HasProperty(it);
146
  if (found.IsNothing() || !found.FromJust()) return found;
147 148

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

165
static PropertyAttributes GetAttributesForMode(VariableMode mode) {
166 167
  DCHECK(IsSerializableVariableMode(mode));
  return IsConstVariableMode(mode) ? READ_ONLY : NONE;
168 169
}

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

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

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

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

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

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

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

267
      if (maybe.IsNothing()) return Handle<Object>();
268
      DCHECK(!isolate->has_pending_exception());
269
      *attributes = maybe.FromJust();
270

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

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

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

330 331 332 333 334 335
      // Lookup variable in module imports and exports.
      if (context->IsModuleContext()) {
        VariableMode mode;
        InitializationFlag flag;
        MaybeAssignedFlag maybe_assigned_flag;
        int cell_index =
336
            scope_info.ModuleIndex(*name, &mode, &flag, &maybe_assigned_flag);
337 338 339 340 341 342 343
        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;
344 345
          *attributes = SourceTextModuleDescriptor::GetCellIndexKind(
                            cell_index) == SourceTextModuleDescriptor::kExport
346 347 348 349 350
                            ? GetAttributesForMode(mode)
                            : READ_ONLY;
          return handle(context->module(), isolate);
        }
      }
351 352
    } else if (context->IsDebugEvaluateContext()) {
      // Check materialized locals.
353
      Object ext = context->get(EXTENSION_INDEX);
354
      if (ext.IsJSReceiver()) {
355
        Handle<JSReceiver> extension(JSReceiver::cast(ext), isolate);
356 357 358 359 360
        LookupIterator it(extension, name, extension);
        Maybe<bool> found = JSReceiver::HasProperty(&it);
        if (found.FromMaybe(false)) {
          *attributes = NONE;
          return extension;
361 362
        }
      }
363 364 365 366 367 368 369 370 371 372 373

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

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

385
    // 3. Prepare to continue with the previous (next outermost) context.
386 387
    if (context->IsNativeContext()) break;

388
    context = Handle<Context>(context->previous(), isolate);
389 390 391 392 393
  } while (follow_context_chain);

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

397
void NativeContext::AddOptimizedCode(Code code) {
398 399 400
  DCHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
  DCHECK(code.next_code_link().IsUndefined());
  code.set_next_code_link(get(OPTIMIZED_CODE_LIST));
401
  set(OPTIMIZED_CODE_LIST, code, UPDATE_WEAK_WRITE_BARRIER);
402 403
}

404
void NativeContext::SetOptimizedCodeListHead(Object head) {
405
  set(OPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
406 407
}

408
Object NativeContext::OptimizedCodeListHead() {
409 410 411
  return get(OPTIMIZED_CODE_LIST);
}

412
void NativeContext::SetDeoptimizedCodeListHead(Object head) {
413
  set(DEOPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
414 415
}

416
Object NativeContext::DeoptimizedCodeListHead() {
417
  return get(DEOPTIMIZED_CODE_LIST);
418 419
}

420
Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
421 422
  Isolate* isolate = GetIsolate();
  Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
423
  if (!result->IsUndefined(isolate)) return result;
424
  return isolate->factory()->NewStringFromStaticChars(
425
      "Code generation from strings disallowed for this context");
426 427
}

428
#define COMPARE_NAME(index, type, name) \
429
  if (string->IsOneByteEqualTo(StaticCharVector(#name))) return index;
430 431 432 433 434 435 436 437

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

#undef COMPARE_NAME

438 439 440 441 442 443 444 445 446 447 448
#define COMPARE_NAME(index, type, name) \
  if (strncmp(string, #name, length) == 0) return index;

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
449

450
#ifdef DEBUG
451

452
bool Context::IsBootstrappingOrNativeContext(Isolate* isolate, Object object) {
453 454 455
  // 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 ||
456
         isolate->bootstrapper()->IsActive() || object.IsNativeContext();
457 458
}

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

#endif

472
void NativeContext::ResetErrorsThrown() { set_errors_thrown(Smi::FromInt(0)); }
473

474
void NativeContext::IncrementErrorsThrown() {
475
  int previous_value = errors_thrown().value();
476 477 478
  set_errors_thrown(Smi::FromInt(previous_value + 1));
}

479
int NativeContext::GetErrorsThrown() { return errors_thrown().value(); }
480

481 482 483 484 485 486 487 488 489 490
STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 4);
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));
STATIC_ASSERT(NativeContext::kNativeContextOffset ==
              Context::OffsetOfElementAt(NativeContext::NATIVE_CONTEXT_INDEX));

491
STATIC_ASSERT(NativeContext::kStartOfStrongFieldsOffset ==
492
              Context::OffsetOfElementAt(-1));
493 494 495 496 497 498 499 500
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));

501 502
}  // namespace internal
}  // namespace v8