V8 API Reference, 7.2.502.16 (for Deno 0.2.4)
contexts.cc
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/contexts.h"
6 
7 #include "src/ast/modules.h"
8 #include "src/bootstrapper.h"
9 #include "src/debug/debug.h"
10 #include "src/isolate-inl.h"
11 #include "src/objects/module-inl.h"
12 
13 namespace v8 {
14 namespace internal {
15 
16 
17 Handle<ScriptContextTable> ScriptContextTable::Extend(
18  Handle<ScriptContextTable> table, Handle<Context> script_context) {
19  Handle<ScriptContextTable> result;
20  int used = table->used();
21  int length = table->length();
22  CHECK(used >= 0 && length > 0 && used < length);
23  if (used + kFirstContextSlotIndex == length) {
24  CHECK(length < Smi::kMaxValue / 2);
25  Isolate* isolate = script_context->GetIsolate();
26  Handle<FixedArray> copy =
27  isolate->factory()->CopyFixedArrayAndGrow(table, length);
28  copy->set_map(ReadOnlyRoots(isolate).script_context_table_map());
29  result = Handle<ScriptContextTable>::cast(copy);
30  } else {
31  result = table;
32  }
33  result->set_used(used + 1);
34 
35  DCHECK(script_context->IsScriptContext());
36  result->set(used + kFirstContextSlotIndex, *script_context);
37  return result;
38 }
39 
40 bool ScriptContextTable::Lookup(Isolate* isolate,
41  Handle<ScriptContextTable> table,
42  Handle<String> name, LookupResult* result) {
43  for (int i = 0; i < table->used(); i++) {
44  Handle<Context> context = GetContext(isolate, table, i);
45  DCHECK(context->IsScriptContext());
46  Handle<ScopeInfo> scope_info(context->scope_info(), context->GetIsolate());
47  int slot_index = ScopeInfo::ContextSlotIndex(
48  scope_info, name, &result->mode, &result->init_flag,
49  &result->maybe_assigned_flag);
50 
51  if (slot_index >= 0) {
52  result->context_index = i;
53  result->slot_index = slot_index;
54  return true;
55  }
56  }
57  return false;
58 }
59 
60 
61 bool Context::is_declaration_context() {
62  if (IsFunctionContext() || IsNativeContext() || IsScriptContext() ||
63  IsModuleContext()) {
64  return true;
65  }
66  if (IsEvalContext()) {
67  return scope_info()->language_mode() == LanguageMode::kStrict;
68  }
69  if (!IsBlockContext()) return false;
70  return scope_info()->is_declaration_scope();
71 }
72 
73 Context Context::declaration_context() {
74  Context current = *this;
75  while (!current->is_declaration_context()) {
76  current = current->previous();
77  }
78  return current;
79 }
80 
81 Context Context::closure_context() {
82  Context current = *this;
83  while (!current->IsFunctionContext() && !current->IsScriptContext() &&
84  !current->IsModuleContext() && !current->IsNativeContext() &&
85  !current->IsEvalContext()) {
86  current = current->previous();
87  }
88  return current;
89 }
90 
91 JSObject* Context::extension_object() {
92  DCHECK(IsNativeContext() || IsFunctionContext() || IsBlockContext() ||
93  IsEvalContext() || IsCatchContext());
94  HeapObject* object = extension();
95  if (object->IsTheHole()) return nullptr;
96  DCHECK(object->IsJSContextExtensionObject() ||
97  (IsNativeContext() && object->IsJSGlobalObject()));
98  return JSObject::cast(object);
99 }
100 
101 JSReceiver* Context::extension_receiver() {
102  DCHECK(IsNativeContext() || IsWithContext() || IsEvalContext() ||
103  IsFunctionContext() || IsBlockContext());
104  return IsWithContext() ? JSReceiver::cast(extension()) : extension_object();
105 }
106 
107 ScopeInfo Context::scope_info() {
108  return ScopeInfo::cast(get(SCOPE_INFO_INDEX));
109 }
110 
111 Module* Context::module() {
112  Context current = *this;
113  while (!current->IsModuleContext()) {
114  current = current->previous();
115  }
116  return Module::cast(current->extension());
117 }
118 
119 JSGlobalObject* Context::global_object() {
120  return JSGlobalObject::cast(native_context()->extension());
121 }
122 
123 Context Context::script_context() {
124  Context current = *this;
125  while (!current->IsScriptContext()) {
126  current = current->previous();
127  }
128  return current;
129 }
130 
131 JSGlobalProxy* Context::global_proxy() {
132  return native_context()->global_proxy_object();
133 }
134 
135 void Context::set_global_proxy(JSGlobalProxy* object) {
136  native_context()->set_global_proxy_object(object);
137 }
138 
139 
144 static Maybe<bool> UnscopableLookup(LookupIterator* it) {
145  Isolate* isolate = it->isolate();
146 
147  Maybe<bool> found = JSReceiver::HasProperty(it);
148  if (found.IsNothing() || !found.FromJust()) return found;
149 
150  Handle<Object> unscopables;
151  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
152  isolate, unscopables,
153  JSReceiver::GetProperty(isolate,
154  Handle<JSReceiver>::cast(it->GetReceiver()),
155  isolate->factory()->unscopables_symbol()),
156  Nothing<bool>());
157  if (!unscopables->IsJSReceiver()) return Just(true);
158  Handle<Object> blacklist;
159  ASSIGN_RETURN_ON_EXCEPTION_VALUE(
160  isolate, blacklist,
161  JSReceiver::GetProperty(isolate, Handle<JSReceiver>::cast(unscopables),
162  it->name()),
163  Nothing<bool>());
164  return Just(!blacklist->BooleanValue(isolate));
165 }
166 
167 static PropertyAttributes GetAttributesForMode(VariableMode mode) {
168  DCHECK(IsDeclaredVariableMode(mode));
169  return mode == VariableMode::kConst ? READ_ONLY : NONE;
170 }
171 
172 Handle<Object> Context::Lookup(Handle<String> name, ContextLookupFlags flags,
173  int* index, PropertyAttributes* attributes,
174  InitializationFlag* init_flag,
175  VariableMode* variable_mode,
176  bool* is_sloppy_function_name) {
177  Isolate* isolate = GetIsolate();
178  Handle<Context> context(*this, isolate);
179 
180  bool follow_context_chain = (flags & FOLLOW_CONTEXT_CHAIN) != 0;
181  bool failed_whitelist = false;
182  *index = kNotFound;
183  *attributes = ABSENT;
184  *init_flag = kCreatedInitialized;
185  *variable_mode = VariableMode::kVar;
186  if (is_sloppy_function_name != nullptr) {
187  *is_sloppy_function_name = false;
188  }
189 
190  if (FLAG_trace_contexts) {
191  PrintF("Context::Lookup(");
192  name->ShortPrint();
193  PrintF(")\n");
194  }
195 
196  do {
197  if (FLAG_trace_contexts) {
198  PrintF(" - looking in context %p",
199  reinterpret_cast<void*>(context->ptr()));
200  if (context->IsScriptContext()) PrintF(" (script context)");
201  if (context->IsNativeContext()) PrintF(" (native context)");
202  PrintF("\n");
203  }
204 
205  // 1. Check global objects, subjects of with, and extension objects.
206  DCHECK_IMPLIES(context->IsEvalContext(),
207  context->extension()->IsTheHole(isolate));
208  if ((context->IsNativeContext() ||
209  (context->IsWithContext() && ((flags & SKIP_WITH_CONTEXT) == 0)) ||
210  context->IsFunctionContext() || context->IsBlockContext()) &&
211  context->extension_receiver() != nullptr) {
212  Handle<JSReceiver> object(context->extension_receiver(), isolate);
213 
214  if (context->IsNativeContext()) {
215  if (FLAG_trace_contexts) {
216  PrintF(" - trying other script contexts\n");
217  }
218  // Try other script contexts.
219  Handle<ScriptContextTable> script_contexts(
220  context->global_object()->native_context()->script_context_table(),
221  isolate);
222  ScriptContextTable::LookupResult r;
223  if (ScriptContextTable::Lookup(isolate, script_contexts, name, &r)) {
224  if (FLAG_trace_contexts) {
225  Handle<Context> c = ScriptContextTable::GetContext(
226  isolate, script_contexts, r.context_index);
227  PrintF("=> found property in script context %d: %p\n",
228  r.context_index, reinterpret_cast<void*>(c->ptr()));
229  }
230  *index = r.slot_index;
231  *variable_mode = r.mode;
232  *init_flag = r.init_flag;
233  *attributes = GetAttributesForMode(r.mode);
234  return ScriptContextTable::GetContext(isolate, script_contexts,
235  r.context_index);
236  }
237  }
238 
239  // Context extension objects needs to behave as if they have no
240  // prototype. So even if we want to follow prototype chains, we need
241  // to only do a local lookup for context extension objects.
242  Maybe<PropertyAttributes> maybe = Nothing<PropertyAttributes>();
243  if ((flags & FOLLOW_PROTOTYPE_CHAIN) == 0 ||
244  object->IsJSContextExtensionObject()) {
245  maybe = JSReceiver::GetOwnPropertyAttributes(object, name);
246  } else if (context->IsWithContext()) {
247  // A with context will never bind "this", but debug-eval may look into
248  // a with context when resolving "this". Other synthetic variables such
249  // as new.target may be resolved as VariableMode::kDynamicLocal due to
250  // bug v8:5405 , skipping them here serves as a workaround until a more
251  // thorough fix can be applied.
252  // TODO(v8:5405): Replace this check with a DCHECK when resolution of
253  // of synthetic variables does not go through this code path.
254  if (ScopeInfo::VariableIsSynthetic(*name)) {
255  maybe = Just(ABSENT);
256  } else {
257  LookupIterator it(object, name, object);
258  Maybe<bool> found = UnscopableLookup(&it);
259  if (found.IsNothing()) {
260  maybe = Nothing<PropertyAttributes>();
261  } else {
262  // Luckily, consumers of |maybe| only care whether the property
263  // was absent or not, so we can return a dummy |NONE| value
264  // for its attributes when it was present.
265  maybe = Just(found.FromJust() ? NONE : ABSENT);
266  }
267  }
268  } else {
269  maybe = JSReceiver::GetPropertyAttributes(object, name);
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  if (FLAG_trace_contexts) {
278  PrintF("=> found property in context object %p\n",
279  reinterpret_cast<void*>(*object));
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  // Use serialized scope information of functions and blocks to search
290  // for the context index.
291  Handle<ScopeInfo> scope_info(context->scope_info(), isolate);
292  VariableMode mode;
293  InitializationFlag flag;
294  MaybeAssignedFlag maybe_assigned_flag;
295  int slot_index = ScopeInfo::ContextSlotIndex(scope_info, name, &mode,
296  &flag, &maybe_assigned_flag);
297  DCHECK(slot_index < 0 || slot_index >= MIN_CONTEXT_SLOTS);
298  if (slot_index >= 0) {
299  if (FLAG_trace_contexts) {
300  PrintF("=> found local in context slot %d (mode = %hhu)\n",
301  slot_index, static_cast<uint8_t>(mode));
302  }
303  *index = slot_index;
304  *variable_mode = mode;
305  *init_flag = flag;
306  *attributes = GetAttributesForMode(mode);
307  return context;
308  }
309 
310  // Check the slot corresponding to the intermediate context holding
311  // only the function name variable. It's conceptually (and spec-wise)
312  // in an outer scope of the function's declaration scope.
313  if (follow_context_chain && (flags & STOP_AT_DECLARATION_SCOPE) == 0 &&
314  context->IsFunctionContext()) {
315  int function_index = scope_info->FunctionContextSlotIndex(*name);
316  if (function_index >= 0) {
317  if (FLAG_trace_contexts) {
318  PrintF("=> found intermediate function in context slot %d\n",
319  function_index);
320  }
321  *index = function_index;
322  *attributes = READ_ONLY;
323  *init_flag = kCreatedInitialized;
324  *variable_mode = VariableMode::kConst;
325  if (is_sloppy_function_name != nullptr &&
326  is_sloppy(scope_info->language_mode())) {
327  *is_sloppy_function_name = true;
328  }
329  return context;
330  }
331  }
332 
333  // Lookup variable in module imports and exports.
334  if (context->IsModuleContext()) {
335  VariableMode mode;
336  InitializationFlag flag;
337  MaybeAssignedFlag maybe_assigned_flag;
338  int cell_index =
339  scope_info->ModuleIndex(name, &mode, &flag, &maybe_assigned_flag);
340  if (cell_index != 0) {
341  if (FLAG_trace_contexts) {
342  PrintF("=> found in module imports or exports\n");
343  }
344  *index = cell_index;
345  *variable_mode = mode;
346  *init_flag = flag;
347  *attributes = ModuleDescriptor::GetCellIndexKind(cell_index) ==
348  ModuleDescriptor::kExport
349  ? GetAttributesForMode(mode)
350  : READ_ONLY;
351  return handle(context->module(), isolate);
352  }
353  }
354  } else if (context->IsDebugEvaluateContext()) {
355  // Check materialized locals.
356  Object* ext = context->get(EXTENSION_INDEX);
357  if (ext->IsJSReceiver()) {
358  Handle<JSReceiver> extension(JSReceiver::cast(ext), isolate);
359  LookupIterator it(extension, name, extension);
360  Maybe<bool> found = JSReceiver::HasProperty(&it);
361  if (found.FromMaybe(false)) {
362  *attributes = NONE;
363  return extension;
364  }
365  }
366  // Check the original context, but do not follow its context chain.
367  Object* obj = context->get(WRAPPED_CONTEXT_INDEX);
368  if (obj->IsContext()) {
369  Handle<Object> result =
370  Context::cast(obj)->Lookup(name, DONT_FOLLOW_CHAINS, index,
371  attributes, init_flag, variable_mode);
372  if (!result.is_null()) return result;
373  }
374  // Check whitelist. Names that do not pass whitelist shall only resolve
375  // to with, script or native contexts up the context chain.
376  obj = context->get(WHITE_LIST_INDEX);
377  if (obj->IsStringSet()) {
378  failed_whitelist =
379  failed_whitelist || !StringSet::cast(obj)->Has(isolate, name);
380  }
381  }
382 
383  // 3. Prepare to continue with the previous (next outermost) context.
384  if (context->IsNativeContext() ||
385  ((flags & STOP_AT_DECLARATION_SCOPE) != 0 &&
386  context->is_declaration_context())) {
387  follow_context_chain = false;
388  } else {
389  do {
390  context = Handle<Context>(context->previous(), isolate);
391  // If we come across a whitelist context, and the name is not
392  // whitelisted, then only consider with, script, module or native
393  // contexts.
394  } while (failed_whitelist && !context->IsScriptContext() &&
395  !context->IsNativeContext() && !context->IsWithContext() &&
396  !context->IsModuleContext());
397  }
398  } while (follow_context_chain);
399 
400  if (FLAG_trace_contexts) {
401  PrintF("=> no property/slot found\n");
402  }
403  return Handle<Object>::null();
404 }
405 
406 void Context::AddOptimizedCode(Code code) {
407  DCHECK(IsNativeContext());
408  DCHECK(code->kind() == Code::OPTIMIZED_FUNCTION);
409  DCHECK(code->next_code_link()->IsUndefined());
410  code->set_next_code_link(get(OPTIMIZED_CODE_LIST));
411  set(OPTIMIZED_CODE_LIST, code, UPDATE_WEAK_WRITE_BARRIER);
412 }
413 
414 
415 void Context::SetOptimizedCodeListHead(Object* head) {
416  DCHECK(IsNativeContext());
417  set(OPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
418 }
419 
420 
421 Object* Context::OptimizedCodeListHead() {
422  DCHECK(IsNativeContext());
423  return get(OPTIMIZED_CODE_LIST);
424 }
425 
426 
427 void Context::SetDeoptimizedCodeListHead(Object* head) {
428  DCHECK(IsNativeContext());
429  set(DEOPTIMIZED_CODE_LIST, head, UPDATE_WEAK_WRITE_BARRIER);
430 }
431 
432 
433 Object* Context::DeoptimizedCodeListHead() {
434  DCHECK(IsNativeContext());
435  return get(DEOPTIMIZED_CODE_LIST);
436 }
437 
438 
439 Handle<Object> Context::ErrorMessageForCodeGenerationFromStrings() {
440  Isolate* isolate = GetIsolate();
441  Handle<Object> result(error_message_for_code_gen_from_strings(), isolate);
442  if (!result->IsUndefined(isolate)) return result;
443  return isolate->factory()->NewStringFromStaticChars(
444  "Code generation from strings disallowed for this context");
445 }
446 
447 
448 #define COMPARE_NAME(index, type, name) \
449  if (string->IsOneByteEqualTo(STATIC_CHAR_VECTOR(#name))) return index;
450 
451 int Context::ImportedFieldIndexForName(Handle<String> string) {
452  NATIVE_CONTEXT_IMPORTED_FIELDS(COMPARE_NAME)
453  return kNotFound;
454 }
455 
456 
457 int Context::IntrinsicIndexForName(Handle<String> string) {
458  NATIVE_CONTEXT_INTRINSIC_FUNCTIONS(COMPARE_NAME);
459  return kNotFound;
460 }
461 
462 #undef COMPARE_NAME
463 
464 #define COMPARE_NAME(index, type, name) \
465  if (strncmp(string, #name, length) == 0) return index;
466 
467 int Context::IntrinsicIndexForName(const unsigned char* unsigned_string,
468  int length) {
469  const char* string = reinterpret_cast<const char*>(unsigned_string);
470  NATIVE_CONTEXT_INTRINSIC_FUNCTIONS(COMPARE_NAME);
471  return kNotFound;
472 }
473 
474 #undef COMPARE_NAME
475 
476 #ifdef DEBUG
477 
478 bool Context::IsBootstrappingOrNativeContext(Isolate* isolate, Object* object) {
479  // During bootstrapping we allow all objects to pass as global
480  // objects. This is necessary to fix circular dependencies.
481  return isolate->heap()->gc_state() != Heap::NOT_IN_GC ||
482  isolate->bootstrapper()->IsActive() || object->IsNativeContext();
483 }
484 
485 bool Context::IsBootstrappingOrValidParentContext(Object* object,
486  Context child) {
487  // During bootstrapping we allow all objects to pass as
488  // contexts. This is necessary to fix circular dependencies.
489  if (child->GetIsolate()->bootstrapper()->IsActive()) return true;
490  if (!object->IsContext()) return false;
491  Context context = Context::cast(object);
492  return context->IsNativeContext() || context->IsScriptContext() ||
493  context->IsModuleContext() || !child->IsModuleContext();
494 }
495 
496 #endif
497 
498 void Context::ResetErrorsThrown() {
499  DCHECK(IsNativeContext());
500  set_errors_thrown(Smi::FromInt(0));
501 }
502 
503 void Context::IncrementErrorsThrown() {
504  DCHECK(IsNativeContext());
505 
506  int previous_value = errors_thrown()->value();
507  set_errors_thrown(Smi::FromInt(previous_value + 1));
508 }
509 
510 int Context::GetErrorsThrown() { return errors_thrown()->value(); }
511 
512 STATIC_ASSERT(Context::MIN_CONTEXT_SLOTS == 4);
513 STATIC_ASSERT(NativeContext::kScopeInfoOffset ==
514  Context::OffsetOfElementAt(NativeContext::SCOPE_INFO_INDEX));
515 STATIC_ASSERT(NativeContext::kPreviousOffset ==
516  Context::OffsetOfElementAt(NativeContext::PREVIOUS_INDEX));
517 STATIC_ASSERT(NativeContext::kExtensionOffset ==
518  Context::OffsetOfElementAt(NativeContext::EXTENSION_INDEX));
519 STATIC_ASSERT(NativeContext::kNativeContextOffset ==
520  Context::OffsetOfElementAt(NativeContext::NATIVE_CONTEXT_INDEX));
521 
522 STATIC_ASSERT(NativeContext::kStartOfStrongFieldsOffset ==
523  Context::OffsetOfElementAt(0));
524 STATIC_ASSERT(NativeContext::kStartOfWeakFieldsOffset ==
525  Context::OffsetOfElementAt(NativeContext::FIRST_WEAK_SLOT));
526 STATIC_ASSERT(NativeContext::kMicrotaskQueueOffset ==
527  Context::SizeFor(NativeContext::NATIVE_CONTEXT_SLOTS));
528 STATIC_ASSERT(NativeContext::kSize ==
529  (Context::SizeFor(NativeContext::NATIVE_CONTEXT_SLOTS) +
530  kSystemPointerSize));
531 
532 } // namespace internal
533 } // namespace v8
Definition: libplatform.h:13