1// Copyright 2012 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#ifndef V8_ISOLATE_H_
6#define V8_ISOLATE_H_
7
8#include <cstddef>
9#include <functional>
10#include <memory>
11#include <queue>
12#include <unordered_map>
13#include <vector>
14
15#include "include/v8-inspector.h"
16#include "include/v8-internal.h"
17#include "include/v8.h"
18#include "src/allocation.h"
19#include "src/base/macros.h"
20#include "src/builtins/builtins.h"
21#include "src/contexts.h"
22#include "src/debug/interface-types.h"
23#include "src/execution.h"
24#include "src/futex-emulation.h"
25#include "src/globals.h"
26#include "src/handles.h"
27#include "src/heap/factory.h"
28#include "src/heap/heap.h"
29#include "src/isolate-allocator.h"
30#include "src/isolate-data.h"
31#include "src/messages.h"
32#include "src/objects/code.h"
33#include "src/objects/debug-objects.h"
34#include "src/runtime/runtime.h"
35#include "src/unicode.h"
36
37#ifdef V8_INTL_SUPPORT
38#include "unicode/uversion.h" // Define U_ICU_NAMESPACE.
39namespace U_ICU_NAMESPACE {
40class UObject;
41} // namespace U_ICU_NAMESPACE
42#endif // V8_INTL_SUPPORT
43
44namespace v8 {
45
46namespace base {
47class RandomNumberGenerator;
48}
49
50namespace debug {
51class ConsoleDelegate;
52class AsyncEventDelegate;
53}
54
55namespace internal {
56
57namespace heap {
58class HeapTester;
59} // namespace heap
60
61class AddressToIndexHashMap;
62class AstStringConstants;
63class Bootstrapper;
64class BuiltinsConstantsTableBuilder;
65class CancelableTaskManager;
66class CodeEventDispatcher;
67class CodeTracer;
68class CompilationCache;
69class CompilationStatistics;
70class CompilerDispatcher;
71class ContextSlotCache;
72class Counters;
73class Debug;
74class DeoptimizerData;
75class DescriptorLookupCache;
76class EmbeddedFileWriterInterface;
77class EternalHandles;
78class HandleScopeImplementer;
79class HeapObjectToIndexHashMap;
80class HeapProfiler;
81class InnerPointerToCodeCache;
82class Logger;
83class MaterializedObjectStore;
84class Microtask;
85class MicrotaskQueue;
86class OptimizingCompileDispatcher;
87class ReadOnlyDeserializer;
88class RegExpStack;
89class RootVisitor;
90class RuntimeProfiler;
91class SetupIsolateDelegate;
92class Simulator;
93class StartupDeserializer;
94class StandardFrame;
95class StubCache;
96class ThreadManager;
97class ThreadState;
98class ThreadVisitor; // Defined in v8threads.h
99class TracingCpuProfilerImpl;
100class UnicodeCache;
101struct ManagedPtrDestructor;
102
103template <StateTag Tag> class VMState;
104
105namespace interpreter {
106class Interpreter;
107}
108
109namespace compiler {
110class PerIsolateCompilerCache;
111}
112
113namespace wasm {
114class WasmEngine;
115}
116
117namespace win64_unwindinfo {
118class BuiltinUnwindInfo;
119}
120
121#define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate) \
122 do { \
123 Isolate* __isolate__ = (isolate); \
124 DCHECK(!__isolate__->has_pending_exception()); \
125 if (__isolate__->has_scheduled_exception()) { \
126 return __isolate__->PromoteScheduledException(); \
127 } \
128 } while (false)
129
130// Macros for MaybeHandle.
131
132#define RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, value) \
133 do { \
134 Isolate* __isolate__ = (isolate); \
135 DCHECK(!__isolate__->has_pending_exception()); \
136 if (__isolate__->has_scheduled_exception()) { \
137 __isolate__->PromoteScheduledException(); \
138 return value; \
139 } \
140 } while (false)
141
142#define RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, T) \
143 RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, MaybeHandle<T>())
144
145#define ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, dst, call, value) \
146 do { \
147 Isolate* __isolate__ = (isolate); \
148 if (!(call).ToLocal(&dst)) { \
149 DCHECK(__isolate__->has_scheduled_exception()); \
150 __isolate__->PromoteScheduledException(); \
151 return value; \
152 } \
153 } while (false)
154
155#define RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, call, value) \
156 do { \
157 Isolate* __isolate__ = (isolate); \
158 if ((call).IsNothing()) { \
159 DCHECK(__isolate__->has_scheduled_exception()); \
160 __isolate__->PromoteScheduledException(); \
161 return value; \
162 } \
163 } while (false)
164
165/**
166 * RETURN_RESULT_OR_FAILURE is used in functions with return type Object (such
167 * as "RUNTIME_FUNCTION(...) {...}" or "BUILTIN(...) {...}" ) to return either
168 * the contents of a MaybeHandle<X>, or the "exception" sentinel value.
169 * Example usage:
170 *
171 * RUNTIME_FUNCTION(Runtime_Func) {
172 * ...
173 * RETURN_RESULT_OR_FAILURE(
174 * isolate,
175 * FunctionWithReturnTypeMaybeHandleX(...));
176 * }
177 *
178 * If inside a function with return type MaybeHandle<X> use RETURN_ON_EXCEPTION
179 * instead.
180 * If inside a function with return type Handle<X>, or Maybe<X> use
181 * RETURN_ON_EXCEPTION_VALUE instead.
182 */
183#define RETURN_RESULT_OR_FAILURE(isolate, call) \
184 do { \
185 Handle<Object> __result__; \
186 Isolate* __isolate__ = (isolate); \
187 if (!(call).ToHandle(&__result__)) { \
188 DCHECK(__isolate__->has_pending_exception()); \
189 return ReadOnlyRoots(__isolate__).exception(); \
190 } \
191 DCHECK(!__isolate__->has_pending_exception()); \
192 return *__result__; \
193 } while (false)
194
195#define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value) \
196 do { \
197 if (!(call).ToHandle(&dst)) { \
198 DCHECK((isolate)->has_pending_exception()); \
199 return value; \
200 } \
201 } while (false)
202
203#define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call) \
204 do { \
205 Isolate* __isolate__ = (isolate); \
206 ASSIGN_RETURN_ON_EXCEPTION_VALUE(__isolate__, dst, call, \
207 ReadOnlyRoots(__isolate__).exception()); \
208 } while (false)
209
210#define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T) \
211 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, MaybeHandle<T>())
212
213#define THROW_NEW_ERROR(isolate, call, T) \
214 do { \
215 Isolate* __isolate__ = (isolate); \
216 return __isolate__->Throw<T>(__isolate__->factory()->call); \
217 } while (false)
218
219#define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call) \
220 do { \
221 Isolate* __isolate__ = (isolate); \
222 return __isolate__->Throw(*__isolate__->factory()->call); \
223 } while (false)
224
225#define THROW_NEW_ERROR_RETURN_VALUE(isolate, call, value) \
226 do { \
227 Isolate* __isolate__ = (isolate); \
228 __isolate__->Throw(*__isolate__->factory()->call); \
229 return value; \
230 } while (false)
231
232/**
233 * RETURN_ON_EXCEPTION_VALUE conditionally returns the given value when the
234 * given MaybeHandle is empty. It is typically used in functions with return
235 * type Maybe<X> or Handle<X>. Example usage:
236 *
237 * Handle<X> Func() {
238 * ...
239 * RETURN_ON_EXCEPTION_VALUE(
240 * isolate,
241 * FunctionWithReturnTypeMaybeHandleX(...),
242 * Handle<X>());
243 * // code to handle non exception
244 * ...
245 * }
246 *
247 * Maybe<bool> Func() {
248 * ..
249 * RETURN_ON_EXCEPTION_VALUE(
250 * isolate,
251 * FunctionWithReturnTypeMaybeHandleX(...),
252 * Nothing<bool>);
253 * // code to handle non exception
254 * return Just(true);
255 * }
256 *
257 * If inside a function with return type MaybeHandle<X>, use RETURN_ON_EXCEPTION
258 * instead.
259 * If inside a function with return type Object, use
260 * RETURN_FAILURE_ON_EXCEPTION instead.
261 */
262#define RETURN_ON_EXCEPTION_VALUE(isolate, call, value) \
263 do { \
264 if ((call).is_null()) { \
265 DCHECK((isolate)->has_pending_exception()); \
266 return value; \
267 } \
268 } while (false)
269
270/**
271 * RETURN_FAILURE_ON_EXCEPTION conditionally returns the "exception" sentinel if
272 * the given MaybeHandle is empty; so it can only be used in functions with
273 * return type Object, such as RUNTIME_FUNCTION(...) {...} or BUILTIN(...)
274 * {...}. Example usage:
275 *
276 * RUNTIME_FUNCTION(Runtime_Func) {
277 * ...
278 * RETURN_FAILURE_ON_EXCEPTION(
279 * isolate,
280 * FunctionWithReturnTypeMaybeHandleX(...));
281 * // code to handle non exception
282 * ...
283 * }
284 *
285 * If inside a function with return type MaybeHandle<X>, use RETURN_ON_EXCEPTION
286 * instead.
287 * If inside a function with return type Maybe<X> or Handle<X>, use
288 * RETURN_ON_EXCEPTION_VALUE instead.
289 */
290#define RETURN_FAILURE_ON_EXCEPTION(isolate, call) \
291 do { \
292 Isolate* __isolate__ = (isolate); \
293 RETURN_ON_EXCEPTION_VALUE(__isolate__, call, \
294 ReadOnlyRoots(__isolate__).exception()); \
295 } while (false);
296
297/**
298 * RETURN_ON_EXCEPTION conditionally returns an empty MaybeHandle<T> if the
299 * given MaybeHandle is empty. Use it to return immediately from a function with
300 * return type MaybeHandle when an exception was thrown. Example usage:
301 *
302 * MaybeHandle<X> Func() {
303 * ...
304 * RETURN_ON_EXCEPTION(
305 * isolate,
306 * FunctionWithReturnTypeMaybeHandleY(...),
307 * X);
308 * // code to handle non exception
309 * ...
310 * }
311 *
312 * If inside a function with return type Object, use
313 * RETURN_FAILURE_ON_EXCEPTION instead.
314 * If inside a function with return type
315 * Maybe<X> or Handle<X>, use RETURN_ON_EXCEPTION_VALUE instead.
316 */
317#define RETURN_ON_EXCEPTION(isolate, call, T) \
318 RETURN_ON_EXCEPTION_VALUE(isolate, call, MaybeHandle<T>())
319
320
321#define FOR_WITH_HANDLE_SCOPE(isolate, loop_var_type, init, loop_var, \
322 limit_check, increment, body) \
323 do { \
324 loop_var_type init; \
325 loop_var_type for_with_handle_limit = loop_var; \
326 Isolate* for_with_handle_isolate = isolate; \
327 while (limit_check) { \
328 for_with_handle_limit += 1024; \
329 HandleScope loop_scope(for_with_handle_isolate); \
330 for (; limit_check && loop_var < for_with_handle_limit; increment) { \
331 body \
332 } \
333 } \
334 } while (false)
335
336#define FIELD_ACCESSOR(type, name) \
337 inline void set_##name(type v) { name##_ = v; } \
338 inline type name() const { return name##_; }
339
340// Controls for manual embedded blob lifecycle management, used by tests and
341// mksnapshot.
342V8_EXPORT_PRIVATE void DisableEmbeddedBlobRefcounting();
343V8_EXPORT_PRIVATE void FreeCurrentEmbeddedBlob();
344
345#ifdef DEBUG
346
347#define ISOLATE_INIT_DEBUG_ARRAY_LIST(V) \
348 V(CommentStatistic, paged_space_comments_statistics, \
349 CommentStatistic::kMaxComments + 1) \
350 V(int, code_kind_statistics, AbstractCode::NUMBER_OF_KINDS)
351#else
352
353#define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
354
355#endif
356
357#define ISOLATE_INIT_ARRAY_LIST(V) \
358 /* SerializerDeserializer state. */ \
359 V(int32_t, jsregexp_static_offsets_vector, kJSRegexpStaticOffsetsVectorSize) \
360 V(int, bad_char_shift_table, kUC16AlphabetSize) \
361 V(int, good_suffix_shift_table, (kBMMaxShift + 1)) \
362 V(int, suffix_table, (kBMMaxShift + 1)) \
363 ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
364
365using DebugObjectCache = std::vector<Handle<HeapObject>>;
366
367#define ISOLATE_INIT_LIST(V) \
368 /* Assembler state. */ \
369 V(FatalErrorCallback, exception_behavior, nullptr) \
370 V(OOMErrorCallback, oom_behavior, nullptr) \
371 V(LogEventCallback, event_logger, nullptr) \
372 V(AllowCodeGenerationFromStringsCallback, allow_code_gen_callback, nullptr) \
373 V(AllowWasmCodeGenerationCallback, allow_wasm_code_gen_callback, nullptr) \
374 V(ExtensionCallback, wasm_module_callback, &NoExtension) \
375 V(ExtensionCallback, wasm_instance_callback, &NoExtension) \
376 V(WasmStreamingCallback, wasm_streaming_callback, nullptr) \
377 V(WasmThreadsEnabledCallback, wasm_threads_enabled_callback, nullptr) \
378 /* State for Relocatable. */ \
379 V(Relocatable*, relocatable_top, nullptr) \
380 V(DebugObjectCache*, string_stream_debug_object_cache, nullptr) \
381 V(Object, string_stream_current_security_token, Object()) \
382 V(const intptr_t*, api_external_references, nullptr) \
383 V(AddressToIndexHashMap*, external_reference_map, nullptr) \
384 V(HeapObjectToIndexHashMap*, root_index_map, nullptr) \
385 V(MicrotaskQueue*, default_microtask_queue, nullptr) \
386 V(CompilationStatistics*, turbo_statistics, nullptr) \
387 V(CodeTracer*, code_tracer, nullptr) \
388 V(uint32_t, per_isolate_assert_data, 0xFFFFFFFFu) \
389 V(PromiseRejectCallback, promise_reject_callback, nullptr) \
390 V(const v8::StartupData*, snapshot_blob, nullptr) \
391 V(int, code_and_metadata_size, 0) \
392 V(int, bytecode_and_metadata_size, 0) \
393 V(int, external_script_source_size, 0) \
394 /* true if being profiled. Causes collection of extra compile info. */ \
395 V(bool, is_profiling, false) \
396 /* true if a trace is being formatted through Error.prepareStackTrace. */ \
397 V(bool, formatting_stack_trace, false) \
398 /* Perform side effect checks on function call and API callbacks. */ \
399 V(DebugInfo::ExecutionMode, debug_execution_mode, DebugInfo::kBreakpoints) \
400 /* Current code coverage mode */ \
401 V(debug::CoverageMode, code_coverage_mode, debug::CoverageMode::kBestEffort) \
402 V(debug::TypeProfileMode, type_profile_mode, debug::TypeProfileMode::kNone) \
403 V(int, last_stack_frame_info_id, 0) \
404 V(int, last_console_context_id, 0) \
405 V(v8_inspector::V8Inspector*, inspector, nullptr) \
406 V(bool, next_v8_call_is_safe_for_termination, false) \
407 V(bool, only_terminate_in_safe_scope, false) \
408 V(bool, detailed_source_positions_for_profiling, FLAG_detailed_line_info)
409
410#define THREAD_LOCAL_TOP_ACCESSOR(type, name) \
411 inline void set_##name(type v) { thread_local_top()->name##_ = v; } \
412 inline type name() const { return thread_local_top()->name##_; }
413
414#define THREAD_LOCAL_TOP_ADDRESS(type, name) \
415 type* name##_address() { return &thread_local_top()->name##_; }
416
417// HiddenFactory exists so Isolate can privately inherit from it without making
418// Factory's members available to Isolate directly.
419class V8_EXPORT_PRIVATE HiddenFactory : private Factory {};
420
421class Isolate final : private HiddenFactory {
422 // These forward declarations are required to make the friend declarations in
423 // PerIsolateThreadData work on some older versions of gcc.
424 class ThreadDataTable;
425 class EntryStackItem;
426 public:
427 // A thread has a PerIsolateThreadData instance for each isolate that it has
428 // entered. That instance is allocated when the isolate is initially entered
429 // and reused on subsequent entries.
430 class PerIsolateThreadData {
431 public:
432 PerIsolateThreadData(Isolate* isolate, ThreadId thread_id)
433 : isolate_(isolate),
434 thread_id_(thread_id),
435 stack_limit_(0),
436 thread_state_(nullptr),
437#if USE_SIMULATOR
438 simulator_(nullptr),
439#endif
440 next_(nullptr),
441 prev_(nullptr) {
442 }
443 ~PerIsolateThreadData();
444 Isolate* isolate() const { return isolate_; }
445 ThreadId thread_id() const { return thread_id_; }
446
447 FIELD_ACCESSOR(uintptr_t, stack_limit)
448 FIELD_ACCESSOR(ThreadState*, thread_state)
449
450#if USE_SIMULATOR
451 FIELD_ACCESSOR(Simulator*, simulator)
452#endif
453
454 bool Matches(Isolate* isolate, ThreadId thread_id) const {
455 return isolate_ == isolate && thread_id_ == thread_id;
456 }
457
458 private:
459 Isolate* isolate_;
460 ThreadId thread_id_;
461 uintptr_t stack_limit_;
462 ThreadState* thread_state_;
463
464#if USE_SIMULATOR
465 Simulator* simulator_;
466#endif
467
468 PerIsolateThreadData* next_;
469 PerIsolateThreadData* prev_;
470
471 friend class Isolate;
472 friend class ThreadDataTable;
473 friend class EntryStackItem;
474
475 DISALLOW_COPY_AND_ASSIGN(PerIsolateThreadData);
476 };
477
478 static void InitializeOncePerProcess();
479
480 // Creates Isolate object. Must be used instead of constructing Isolate with
481 // new operator.
482 static V8_EXPORT_PRIVATE Isolate* New(
483 IsolateAllocationMode mode = IsolateAllocationMode::kDefault);
484
485 // Deletes Isolate object. Must be used instead of delete operator.
486 // Destroys the non-default isolates.
487 // Sets default isolate into "has_been_disposed" state rather then destroying,
488 // for legacy API reasons.
489 static void Delete(Isolate* isolate);
490
491 // Returns allocation mode of this isolate.
492 V8_INLINE IsolateAllocationMode isolate_allocation_mode();
493
494 // Page allocator that must be used for allocating V8 heap pages.
495 v8::PageAllocator* page_allocator();
496
497 // Returns the PerIsolateThreadData for the current thread (or nullptr if one
498 // is not currently set).
499 static PerIsolateThreadData* CurrentPerIsolateThreadData() {
500 return reinterpret_cast<PerIsolateThreadData*>(
501 base::Thread::GetThreadLocal(per_isolate_thread_data_key_));
502 }
503
504 // Returns the isolate inside which the current thread is running or nullptr.
505 V8_INLINE static Isolate* TryGetCurrent() {
506 DCHECK_EQ(true, isolate_key_created_.load(std::memory_order_relaxed));
507 return reinterpret_cast<Isolate*>(
508 base::Thread::GetExistingThreadLocal(isolate_key_));
509 }
510
511 // Returns the isolate inside which the current thread is running.
512 V8_INLINE static Isolate* Current() {
513 Isolate* isolate = TryGetCurrent();
514 DCHECK_NOT_NULL(isolate);
515 return isolate;
516 }
517
518 // Usually called by Init(), but can be called early e.g. to allow
519 // testing components that require logging but not the whole
520 // isolate.
521 //
522 // Safe to call more than once.
523 void InitializeLoggingAndCounters();
524 bool InitializeCounters(); // Returns false if already initialized.
525
526 bool InitWithoutSnapshot();
527 bool InitWithSnapshot(ReadOnlyDeserializer* read_only_deserializer,
528 StartupDeserializer* startup_deserializer);
529
530 // True if at least one thread Enter'ed this isolate.
531 bool IsInUse() { return entry_stack_ != nullptr; }
532
533 void ReleaseSharedPtrs();
534
535 void ClearSerializerData();
536
537 bool LogObjectRelocation();
538
539 // Initializes the current thread to run this Isolate.
540 // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
541 // at the same time, this should be prevented using external locking.
542 void Enter();
543
544 // Exits the current thread. The previosuly entered Isolate is restored
545 // for the thread.
546 // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
547 // at the same time, this should be prevented using external locking.
548 void Exit();
549
550 // Find the PerThread for this particular (isolate, thread) combination.
551 // If one does not yet exist, allocate a new one.
552 PerIsolateThreadData* FindOrAllocatePerThreadDataForThisThread();
553
554 // Find the PerThread for this particular (isolate, thread) combination
555 // If one does not yet exist, return null.
556 PerIsolateThreadData* FindPerThreadDataForThisThread();
557
558 // Find the PerThread for given (isolate, thread) combination
559 // If one does not yet exist, return null.
560 PerIsolateThreadData* FindPerThreadDataForThread(ThreadId thread_id);
561
562 // Discard the PerThread for this particular (isolate, thread) combination
563 // If one does not yet exist, no-op.
564 void DiscardPerThreadDataForThisThread();
565
566 // Mutex for serializing access to break control structures.
567 base::RecursiveMutex* break_access() { return &break_access_; }
568
569 Address get_address_from_id(IsolateAddressId id);
570
571 // Access to top context (where the current function object was created).
572 Context context() { return thread_local_top()->context_; }
573 inline void set_context(Context context);
574 Context* context_address() { return &thread_local_top()->context_; }
575
576 // Access to current thread id.
577 THREAD_LOCAL_TOP_ACCESSOR(ThreadId, thread_id)
578
579 // Interface to pending exception.
580 inline Object pending_exception();
581 inline void set_pending_exception(Object exception_obj);
582 inline void clear_pending_exception();
583
584 V8_EXPORT_PRIVATE bool AreWasmThreadsEnabled(Handle<Context> context);
585
586 THREAD_LOCAL_TOP_ADDRESS(Object, pending_exception)
587
588 inline bool has_pending_exception();
589
590 THREAD_LOCAL_TOP_ADDRESS(Context, pending_handler_context)
591 THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_entrypoint)
592 THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_constant_pool)
593 THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_fp)
594 THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_sp)
595
596 THREAD_LOCAL_TOP_ACCESSOR(bool, external_caught_exception)
597
598 v8::TryCatch* try_catch_handler() {
599 return thread_local_top()->try_catch_handler_;
600 }
601 bool* external_caught_exception_address() {
602 return &thread_local_top()->external_caught_exception_;
603 }
604
605 THREAD_LOCAL_TOP_ADDRESS(Object, scheduled_exception)
606
607 inline void clear_pending_message();
608 Address pending_message_obj_address() {
609 return reinterpret_cast<Address>(&thread_local_top()->pending_message_obj_);
610 }
611
612 inline Object scheduled_exception();
613 inline bool has_scheduled_exception();
614 inline void clear_scheduled_exception();
615
616 bool IsJavaScriptHandlerOnTop(Object exception);
617 bool IsExternalHandlerOnTop(Object exception);
618
619 inline bool is_catchable_by_javascript(Object exception);
620
621 // JS execution stack (see frames.h).
622 static Address c_entry_fp(ThreadLocalTop* thread) {
623 return thread->c_entry_fp_;
624 }
625 static Address handler(ThreadLocalTop* thread) { return thread->handler_; }
626 Address c_function() { return thread_local_top()->c_function_; }
627
628 inline Address* c_entry_fp_address() {
629 return &thread_local_top()->c_entry_fp_;
630 }
631 inline Address* handler_address() { return &thread_local_top()->handler_; }
632 inline Address* c_function_address() {
633 return &thread_local_top()->c_function_;
634 }
635
636 // Bottom JS entry.
637 Address js_entry_sp() { return thread_local_top()->js_entry_sp_; }
638 inline Address* js_entry_sp_address() {
639 return &thread_local_top()->js_entry_sp_;
640 }
641
642 // Returns the global object of the current context. It could be
643 // a builtin object, or a JS global object.
644 inline Handle<JSGlobalObject> global_object();
645
646 // Returns the global proxy object of the current context.
647 inline Handle<JSGlobalProxy> global_proxy();
648
649 static int ArchiveSpacePerThread() { return sizeof(ThreadLocalTop); }
650 void FreeThreadResources() { thread_local_top()->Free(); }
651
652 // This method is called by the api after operations that may throw
653 // exceptions. If an exception was thrown and not handled by an external
654 // handler the exception is scheduled to be rethrown when we return to running
655 // JavaScript code. If an exception is scheduled true is returned.
656 V8_EXPORT_PRIVATE bool OptionalRescheduleException(bool clear_exception);
657
658 // Push and pop a promise and the current try-catch handler.
659 void PushPromise(Handle<JSObject> promise);
660 void PopPromise();
661
662 // Return the relevant Promise that a throw/rejection pertains to, based
663 // on the contents of the Promise stack
664 Handle<Object> GetPromiseOnStackOnThrow();
665
666 // Heuristically guess whether a Promise is handled by user catch handler
667 bool PromiseHasUserDefinedRejectHandler(Handle<Object> promise);
668
669 class ExceptionScope {
670 public:
671 // Scope currently can only be used for regular exceptions,
672 // not termination exception.
673 inline explicit ExceptionScope(Isolate* isolate);
674 inline ~ExceptionScope();
675
676 private:
677 Isolate* isolate_;
678 Handle<Object> pending_exception_;
679 };
680
681 V8_EXPORT_PRIVATE void SetCaptureStackTraceForUncaughtExceptions(
682 bool capture, int frame_limit, StackTrace::StackTraceOptions options);
683
684 void SetAbortOnUncaughtExceptionCallback(
685 v8::Isolate::AbortOnUncaughtExceptionCallback callback);
686
687 enum PrintStackMode { kPrintStackConcise, kPrintStackVerbose };
688 void PrintCurrentStackTrace(FILE* out);
689 void PrintStack(StringStream* accumulator,
690 PrintStackMode mode = kPrintStackVerbose);
691 V8_EXPORT_PRIVATE void PrintStack(FILE* out,
692 PrintStackMode mode = kPrintStackVerbose);
693 Handle<String> StackTraceString();
694 // Stores a stack trace in a stack-allocated temporary buffer which will
695 // end up in the minidump for debugging purposes.
696 V8_NOINLINE void PushStackTraceAndDie(void* ptr1 = nullptr,
697 void* ptr2 = nullptr,
698 void* ptr3 = nullptr,
699 void* ptr4 = nullptr);
700 Handle<FixedArray> CaptureCurrentStackTrace(
701 int frame_limit, StackTrace::StackTraceOptions options);
702 Handle<Object> CaptureSimpleStackTrace(Handle<JSReceiver> error_object,
703 FrameSkipMode mode,
704 Handle<Object> caller);
705 MaybeHandle<JSReceiver> CaptureAndSetDetailedStackTrace(
706 Handle<JSReceiver> error_object);
707 MaybeHandle<JSReceiver> CaptureAndSetSimpleStackTrace(
708 Handle<JSReceiver> error_object, FrameSkipMode mode,
709 Handle<Object> caller);
710 Handle<FixedArray> GetDetailedStackTrace(Handle<JSObject> error_object);
711
712 Address GetAbstractPC(int* line, int* column);
713
714 // Returns if the given context may access the given global object. If
715 // the result is false, the pending exception is guaranteed to be
716 // set.
717 bool MayAccess(Handle<Context> accessing_context, Handle<JSObject> receiver);
718
719 void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback);
720 void ReportFailedAccessCheck(Handle<JSObject> receiver);
721
722 // Exception throwing support. The caller should use the result
723 // of Throw() as its return value.
724 Object Throw(Object exception, MessageLocation* location = nullptr);
725 Object ThrowIllegalOperation();
726
727 template <typename T>
728 V8_WARN_UNUSED_RESULT MaybeHandle<T> Throw(
729 Handle<Object> exception, MessageLocation* location = nullptr) {
730 Throw(*exception, location);
731 return MaybeHandle<T>();
732 }
733
734 void set_console_delegate(debug::ConsoleDelegate* delegate) {
735 console_delegate_ = delegate;
736 }
737 debug::ConsoleDelegate* console_delegate() { return console_delegate_; }
738
739 void set_async_event_delegate(debug::AsyncEventDelegate* delegate) {
740 async_event_delegate_ = delegate;
741 PromiseHookStateUpdated();
742 }
743 void OnAsyncFunctionStateChanged(Handle<JSPromise> promise,
744 debug::DebugAsyncActionType);
745
746 // Re-throw an exception. This involves no error reporting since error
747 // reporting was handled when the exception was thrown originally.
748 Object ReThrow(Object exception);
749
750 // Find the correct handler for the current pending exception. This also
751 // clears and returns the current pending exception.
752 Object UnwindAndFindHandler();
753
754 // Tries to predict whether an exception will be caught. Note that this can
755 // only produce an estimate, because it is undecidable whether a finally
756 // clause will consume or re-throw an exception.
757 enum CatchType {
758 NOT_CAUGHT,
759 CAUGHT_BY_JAVASCRIPT,
760 CAUGHT_BY_EXTERNAL,
761 CAUGHT_BY_DESUGARING,
762 CAUGHT_BY_PROMISE,
763 CAUGHT_BY_ASYNC_AWAIT
764 };
765 CatchType PredictExceptionCatcher();
766
767 V8_EXPORT_PRIVATE void ScheduleThrow(Object exception);
768 // Re-set pending message, script and positions reported to the TryCatch
769 // back to the TLS for re-use when rethrowing.
770 void RestorePendingMessageFromTryCatch(v8::TryCatch* handler);
771 // Un-schedule an exception that was caught by a TryCatch handler.
772 void CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler);
773 void ReportPendingMessages();
774 void ReportPendingMessagesFromJavaScript();
775
776 // Implements code shared between the two above methods
777 void ReportPendingMessagesImpl(bool report_externally);
778
779 // Return pending location if any or unfilled structure.
780 MessageLocation GetMessageLocation();
781
782 // Promote a scheduled exception to pending. Asserts has_scheduled_exception.
783 Object PromoteScheduledException();
784
785 // Attempts to compute the current source location, storing the
786 // result in the target out parameter. The source location is attached to a
787 // Message object as the location which should be shown to the user. It's
788 // typically the top-most meaningful location on the stack.
789 bool ComputeLocation(MessageLocation* target);
790 bool ComputeLocationFromException(MessageLocation* target,
791 Handle<Object> exception);
792 V8_EXPORT_PRIVATE bool ComputeLocationFromStackTrace(
793 MessageLocation* target, Handle<Object> exception);
794
795 V8_EXPORT_PRIVATE Handle<JSMessageObject> CreateMessage(
796 Handle<Object> exception, MessageLocation* location);
797
798 // Out of resource exception helpers.
799 Object StackOverflow();
800 Object TerminateExecution();
801 void CancelTerminateExecution();
802
803 V8_EXPORT_PRIVATE void RequestInterrupt(InterruptCallback callback,
804 void* data);
805 void InvokeApiInterruptCallbacks();
806
807 // Administration
808 void Iterate(RootVisitor* v);
809 void Iterate(RootVisitor* v, ThreadLocalTop* t);
810 char* Iterate(RootVisitor* v, char* t);
811 void IterateThread(ThreadVisitor* v, char* t);
812
813 // Returns the current native context.
814 inline Handle<NativeContext> native_context();
815 inline NativeContext raw_native_context();
816
817 Handle<Context> GetIncumbentContext();
818
819 void RegisterTryCatchHandler(v8::TryCatch* that);
820 void UnregisterTryCatchHandler(v8::TryCatch* that);
821
822 char* ArchiveThread(char* to);
823 char* RestoreThread(char* from);
824
825 static const int kUC16AlphabetSize = 256; // See StringSearchBase.
826 static const int kBMMaxShift = 250; // See StringSearchBase.
827
828 // Accessors.
829#define GLOBAL_ACCESSOR(type, name, initialvalue) \
830 inline type name() const { \
831 DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
832 return name##_; \
833 } \
834 inline void set_##name(type value) { \
835 DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
836 name##_ = value; \
837 }
838 ISOLATE_INIT_LIST(GLOBAL_ACCESSOR)
839#undef GLOBAL_ACCESSOR
840
841#define GLOBAL_ARRAY_ACCESSOR(type, name, length) \
842 inline type* name() { \
843 DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
844 return &(name##_)[0]; \
845 }
846 ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_ACCESSOR)
847#undef GLOBAL_ARRAY_ACCESSOR
848
849#define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name) \
850 inline Handle<type> name(); \
851 inline bool is_##name(type value);
852 NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
853#undef NATIVE_CONTEXT_FIELD_ACCESSOR
854
855 Bootstrapper* bootstrapper() { return bootstrapper_; }
856 // Use for updating counters on a foreground thread.
857 Counters* counters() { return async_counters().get(); }
858 // Use for updating counters on a background thread.
859 const std::shared_ptr<Counters>& async_counters() {
860 // Make sure InitializeCounters() has been called.
861 DCHECK_NOT_NULL(async_counters_.get());
862 return async_counters_;
863 }
864 RuntimeProfiler* runtime_profiler() { return runtime_profiler_; }
865 CompilationCache* compilation_cache() { return compilation_cache_; }
866 Logger* logger() {
867 // Call InitializeLoggingAndCounters() if logging is needed before
868 // the isolate is fully initialized.
869 DCHECK_NOT_NULL(logger_);
870 return logger_;
871 }
872 StackGuard* stack_guard() { return &stack_guard_; }
873 Heap* heap() { return &heap_; }
874 static Isolate* FromHeap(Heap* heap) {
875 return reinterpret_cast<Isolate*>(reinterpret_cast<Address>(heap) -
876 OFFSET_OF(Isolate, heap_));
877 }
878
879 const IsolateData* isolate_data() const { return &isolate_data_; }
880 IsolateData* isolate_data() { return &isolate_data_; }
881
882 // Generated code can embed this address to get access to the isolate-specific
883 // data (for example, roots, external references, builtins, etc.).
884 // The kRootRegister is set to this value.
885 Address isolate_root() const { return isolate_data()->isolate_root(); }
886 static size_t isolate_root_bias() {
887 return OFFSET_OF(Isolate, isolate_data_) + IsolateData::kIsolateRootBias;
888 }
889
890 RootsTable& roots_table() { return isolate_data()->roots(); }
891
892 // A sub-region of the Isolate object that has "predictable" layout which
893 // depends only on the pointer size and therefore it's guaranteed that there
894 // will be no compatibility issues because of different compilers used for
895 // snapshot generator and actual V8 code.
896 // Thus, kRootRegister may be used to address any location that falls into
897 // this region.
898 // See IsolateData::AssertPredictableLayout() for details.
899 base::AddressRegion root_register_addressable_region() const {
900 return base::AddressRegion(reinterpret_cast<Address>(&isolate_data_),
901 sizeof(IsolateData));
902 }
903
904 Object root(RootIndex index) { return Object(roots_table()[index]); }
905
906 Handle<Object> root_handle(RootIndex index) {
907 return Handle<Object>(&roots_table()[index]);
908 }
909
910 ExternalReferenceTable* external_reference_table() {
911 DCHECK(isolate_data()->external_reference_table()->is_initialized());
912 return isolate_data()->external_reference_table();
913 }
914
915 Address* builtin_entry_table() { return isolate_data_.builtin_entry_table(); }
916 V8_INLINE Address* builtins_table() { return isolate_data_.builtins(); }
917
918 StubCache* load_stub_cache() { return load_stub_cache_; }
919 StubCache* store_stub_cache() { return store_stub_cache_; }
920 DeoptimizerData* deoptimizer_data() { return deoptimizer_data_; }
921 bool deoptimizer_lazy_throw() const { return deoptimizer_lazy_throw_; }
922 void set_deoptimizer_lazy_throw(bool value) {
923 deoptimizer_lazy_throw_ = value;
924 }
925 ThreadLocalTop* thread_local_top() {
926 return &isolate_data_.thread_local_top_;
927 }
928 ThreadLocalTop const* thread_local_top() const {
929 return &isolate_data_.thread_local_top_;
930 }
931
932 static uint32_t thread_in_wasm_flag_address_offset() {
933 // For WebAssembly trap handlers there is a flag in thread-local storage
934 // which indicates that the executing thread executes WebAssembly code. To
935 // access this flag directly from generated code, we store a pointer to the
936 // flag in ThreadLocalTop in thread_in_wasm_flag_address_. This function
937 // here returns the offset of that member from {isolate_root()}.
938 return static_cast<uint32_t>(
939 OFFSET_OF(Isolate, thread_local_top()->thread_in_wasm_flag_address_) -
940 isolate_root_bias());
941 }
942
943 MaterializedObjectStore* materialized_object_store() {
944 return materialized_object_store_;
945 }
946
947 DescriptorLookupCache* descriptor_lookup_cache() {
948 return descriptor_lookup_cache_;
949 }
950
951 HandleScopeData* handle_scope_data() { return &handle_scope_data_; }
952
953 HandleScopeImplementer* handle_scope_implementer() {
954 DCHECK(handle_scope_implementer_);
955 return handle_scope_implementer_;
956 }
957
958 UnicodeCache* unicode_cache() {
959 return unicode_cache_;
960 }
961
962 InnerPointerToCodeCache* inner_pointer_to_code_cache() {
963 return inner_pointer_to_code_cache_;
964 }
965
966 GlobalHandles* global_handles() { return global_handles_; }
967
968 EternalHandles* eternal_handles() { return eternal_handles_; }
969
970 ThreadManager* thread_manager() { return thread_manager_; }
971
972#ifndef V8_INTL_SUPPORT
973 unibrow::Mapping<unibrow::Ecma262UnCanonicalize>* jsregexp_uncanonicalize() {
974 return &jsregexp_uncanonicalize_;
975 }
976
977 unibrow::Mapping<unibrow::CanonicalizationRange>* jsregexp_canonrange() {
978 return &jsregexp_canonrange_;
979 }
980
981 unibrow::Mapping<unibrow::Ecma262Canonicalize>*
982 regexp_macro_assembler_canonicalize() {
983 return &regexp_macro_assembler_canonicalize_;
984 }
985#endif // !V8_INTL_SUPPORT
986
987 RuntimeState* runtime_state() { return &runtime_state_; }
988
989 Builtins* builtins() { return &builtins_; }
990
991 RegExpStack* regexp_stack() { return regexp_stack_; }
992
993 size_t total_regexp_code_generated() { return total_regexp_code_generated_; }
994 void IncreaseTotalRegexpCodeGenerated(int size) {
995 total_regexp_code_generated_ += size;
996 }
997
998 std::vector<int>* regexp_indices() { return &regexp_indices_; }
999
1000 Debug* debug() { return debug_; }
1001
1002 bool* is_profiling_address() { return &is_profiling_; }
1003 CodeEventDispatcher* code_event_dispatcher() const {
1004 return code_event_dispatcher_.get();
1005 }
1006 HeapProfiler* heap_profiler() const { return heap_profiler_; }
1007
1008#ifdef DEBUG
1009 static size_t non_disposed_isolates() { return non_disposed_isolates_; }
1010#endif
1011
1012 v8::internal::Factory* factory() {
1013 // Upcast to the privately inherited base-class using c-style casts to avoid
1014 // undefined behavior (as static_cast cannot cast across private bases).
1015 // NOLINTNEXTLINE (google-readability-casting)
1016 return (v8::internal::Factory*)this; // NOLINT(readability/casting)
1017 }
1018
1019 static const int kJSRegexpStaticOffsetsVectorSize = 128;
1020
1021 THREAD_LOCAL_TOP_ACCESSOR(ExternalCallbackScope*, external_callback_scope)
1022
1023 THREAD_LOCAL_TOP_ACCESSOR(StateTag, current_vm_state)
1024
1025 void SetData(uint32_t slot, void* data) {
1026 DCHECK_LT(slot, Internals::kNumIsolateDataSlots);
1027 isolate_data_.embedder_data_[slot] = data;
1028 }
1029 void* GetData(uint32_t slot) {
1030 DCHECK_LT(slot, Internals::kNumIsolateDataSlots);
1031 return isolate_data_.embedder_data_[slot];
1032 }
1033
1034 bool serializer_enabled() const { return serializer_enabled_; }
1035
1036 void enable_serializer() { serializer_enabled_ = true; }
1037
1038 bool snapshot_available() const {
1039 return snapshot_blob_ != nullptr && snapshot_blob_->raw_size != 0;
1040 }
1041
1042 bool IsDead() { return has_fatal_error_; }
1043 void SignalFatalError() { has_fatal_error_ = true; }
1044
1045 V8_EXPORT_PRIVATE bool use_optimizer();
1046
1047 bool initialized_from_snapshot() { return initialized_from_snapshot_; }
1048
1049 bool NeedsSourcePositionsForProfiling() const;
1050
1051 V8_EXPORT_PRIVATE bool NeedsDetailedOptimizedCodeLineInfo() const;
1052
1053 bool is_best_effort_code_coverage() const {
1054 return code_coverage_mode() == debug::CoverageMode::kBestEffort;
1055 }
1056
1057 bool is_precise_count_code_coverage() const {
1058 return code_coverage_mode() == debug::CoverageMode::kPreciseCount;
1059 }
1060
1061 bool is_precise_binary_code_coverage() const {
1062 return code_coverage_mode() == debug::CoverageMode::kPreciseBinary;
1063 }
1064
1065 bool is_block_count_code_coverage() const {
1066 return code_coverage_mode() == debug::CoverageMode::kBlockCount;
1067 }
1068
1069 bool is_block_binary_code_coverage() const {
1070 return code_coverage_mode() == debug::CoverageMode::kBlockBinary;
1071 }
1072
1073 bool is_block_code_coverage() const {
1074 return is_block_count_code_coverage() || is_block_binary_code_coverage();
1075 }
1076
1077 bool is_collecting_type_profile() const {
1078 return type_profile_mode() == debug::TypeProfileMode::kCollect;
1079 }
1080
1081 // Collect feedback vectors with data for code coverage or type profile.
1082 // Reset the list, when both code coverage and type profile are not
1083 // needed anymore. This keeps many feedback vectors alive, but code
1084 // coverage or type profile are used for debugging only and increase in
1085 // memory usage is expected.
1086 void SetFeedbackVectorsForProfilingTools(Object value);
1087
1088 void MaybeInitializeVectorListFromHeap();
1089
1090 double time_millis_since_init() {
1091 return heap_.MonotonicallyIncreasingTimeInMs() - time_millis_at_init_;
1092 }
1093
1094 DateCache* date_cache() {
1095 return date_cache_;
1096 }
1097
1098 V8_EXPORT_PRIVATE void set_date_cache(DateCache* date_cache);
1099
1100#ifdef V8_INTL_SUPPORT
1101
1102 const std::string& default_locale() { return default_locale_; }
1103
1104 void ResetDefaultLocale() { default_locale_.clear(); }
1105
1106 void set_default_locale(const std::string& locale) {
1107 DCHECK_EQ(default_locale_.length(), 0);
1108 default_locale_ = locale;
1109 }
1110
1111 // enum to access the icu object cache.
1112 enum class ICUObjectCacheType{
1113 kDefaultCollator, kDefaultNumberFormat, kDefaultSimpleDateFormat,
1114 kDefaultSimpleDateFormatForTime, kDefaultSimpleDateFormatForDate};
1115
1116 icu::UObject* get_cached_icu_object(ICUObjectCacheType cache_type);
1117 void set_icu_object_in_cache(ICUObjectCacheType cache_type,
1118 std::shared_ptr<icu::UObject> obj);
1119 void clear_cached_icu_object(ICUObjectCacheType cache_type);
1120
1121#endif // V8_INTL_SUPPORT
1122
1123 static const int kProtectorValid = 1;
1124 static const int kProtectorInvalid = 0;
1125
1126 inline bool IsArrayConstructorIntact();
1127
1128 // The version with an explicit context parameter can be used when
1129 // Isolate::context is not set up, e.g. when calling directly into C++ from
1130 // CSA.
1131 bool IsNoElementsProtectorIntact(Context context);
1132 V8_EXPORT_PRIVATE bool IsNoElementsProtectorIntact();
1133
1134 bool IsArrayOrObjectOrStringPrototype(Object object);
1135
1136 inline bool IsArraySpeciesLookupChainIntact();
1137 inline bool IsTypedArraySpeciesLookupChainIntact();
1138 inline bool IsRegExpSpeciesLookupChainIntact();
1139 inline bool IsPromiseSpeciesLookupChainIntact();
1140 bool IsIsConcatSpreadableLookupChainIntact();
1141 bool IsIsConcatSpreadableLookupChainIntact(JSReceiver receiver);
1142 inline bool IsStringLengthOverflowIntact();
1143 inline bool IsArrayIteratorLookupChainIntact();
1144
1145 // The MapIterator protector protects the original iteration behaviors of
1146 // Map.prototype.keys(), Map.prototype.values(), and Set.prototype.entries().
1147 // It does not protect the original iteration behavior of
1148 // Map.prototype[Symbol.iterator](). The protector is invalidated when:
1149 // * The 'next' property is set on an object where the property holder is the
1150 // %MapIteratorPrototype% (e.g. because the object is that very prototype).
1151 // * The 'Symbol.iterator' property is set on an object where the property
1152 // holder is the %IteratorPrototype%. Note that this also invalidates the
1153 // SetIterator protector (see below).
1154 inline bool IsMapIteratorLookupChainIntact();
1155
1156 // The SetIterator protector protects the original iteration behavior of
1157 // Set.prototype.keys(), Set.prototype.values(), Set.prototype.entries(),
1158 // and Set.prototype[Symbol.iterator](). The protector is invalidated when:
1159 // * The 'next' property is set on an object where the property holder is the
1160 // %SetIteratorPrototype% (e.g. because the object is that very prototype).
1161 // * The 'Symbol.iterator' property is set on an object where the property
1162 // holder is the %SetPrototype% OR %IteratorPrototype%. This means that
1163 // setting Symbol.iterator on a MapIterator object can also invalidate the
1164 // SetIterator protector, and vice versa, setting Symbol.iterator on a
1165 // SetIterator object can also invalidate the MapIterator. This is an over-
1166 // approximation for the sake of simplicity.
1167 inline bool IsSetIteratorLookupChainIntact();
1168
1169 // The StringIteratorProtector protects the original string iteration behavior
1170 // for primitive strings. As long as the StringIteratorProtector is valid,
1171 // iterating over a primitive string is guaranteed to be unobservable from
1172 // user code and can thus be cut short. More specifically, the protector gets
1173 // invalidated as soon as either String.prototype[Symbol.iterator] or
1174 // String.prototype[Symbol.iterator]().next is modified. This guarantee does
1175 // not apply to string objects (as opposed to primitives), since they could
1176 // define their own Symbol.iterator.
1177 // String.prototype itself does not need to be protected, since it is
1178 // non-configurable and non-writable.
1179 inline bool IsStringIteratorLookupChainIntact();
1180
1181 // Make sure we do check for detached array buffers.
1182 inline bool IsArrayBufferDetachingIntact();
1183
1184 // Disable promise optimizations if promise (debug) hooks have ever been
1185 // active.
1186 bool IsPromiseHookProtectorIntact();
1187
1188 // Make sure a lookup of "resolve" on the %Promise% intrinsic object
1189 // yeidls the initial Promise.resolve method.
1190 bool IsPromiseResolveLookupChainIntact();
1191
1192 // Make sure a lookup of "then" on any JSPromise whose [[Prototype]] is the
1193 // initial %PromisePrototype% yields the initial method. In addition this
1194 // protector also guards the negative lookup of "then" on the intrinsic
1195 // %ObjectPrototype%, meaning that such lookups are guaranteed to yield
1196 // undefined without triggering any side-effects.
1197 bool IsPromiseThenLookupChainIntact();
1198 bool IsPromiseThenLookupChainIntact(Handle<JSReceiver> receiver);
1199
1200 // On intent to set an element in object, make sure that appropriate
1201 // notifications occur if the set is on the elements of the array or
1202 // object prototype. Also ensure that changes to prototype chain between
1203 // Array and Object fire notifications.
1204 void UpdateNoElementsProtectorOnSetElement(Handle<JSObject> object);
1205 void UpdateNoElementsProtectorOnSetLength(Handle<JSObject> object) {
1206 UpdateNoElementsProtectorOnSetElement(object);
1207 }
1208 void UpdateNoElementsProtectorOnSetPrototype(Handle<JSObject> object) {
1209 UpdateNoElementsProtectorOnSetElement(object);
1210 }
1211 void UpdateNoElementsProtectorOnNormalizeElements(Handle<JSObject> object) {
1212 UpdateNoElementsProtectorOnSetElement(object);
1213 }
1214 void InvalidateArrayConstructorProtector();
1215 void InvalidateArraySpeciesProtector();
1216 void InvalidateTypedArraySpeciesProtector();
1217 void InvalidateRegExpSpeciesProtector();
1218 void InvalidatePromiseSpeciesProtector();
1219 void InvalidateIsConcatSpreadableProtector();
1220 void InvalidateStringLengthOverflowProtector();
1221 void InvalidateArrayIteratorProtector();
1222 void InvalidateMapIteratorProtector();
1223 void InvalidateSetIteratorProtector();
1224 void InvalidateStringIteratorProtector();
1225 void InvalidateArrayBufferDetachingProtector();
1226 V8_EXPORT_PRIVATE void InvalidatePromiseHookProtector();
1227 void InvalidatePromiseResolveProtector();
1228 void InvalidatePromiseThenProtector();
1229
1230 // Returns true if array is the initial array prototype in any native context.
1231 bool IsAnyInitialArrayPrototype(Handle<JSArray> array);
1232
1233 void IterateDeferredHandles(RootVisitor* visitor);
1234 void LinkDeferredHandles(DeferredHandles* deferred_handles);
1235 void UnlinkDeferredHandles(DeferredHandles* deferred_handles);
1236
1237#ifdef DEBUG
1238 bool IsDeferredHandle(Address* location);
1239#endif // DEBUG
1240
1241 bool concurrent_recompilation_enabled() {
1242 // Thread is only available with flag enabled.
1243 DCHECK(optimizing_compile_dispatcher_ == nullptr ||
1244 FLAG_concurrent_recompilation);
1245 return optimizing_compile_dispatcher_ != nullptr;
1246 }
1247
1248 OptimizingCompileDispatcher* optimizing_compile_dispatcher() {
1249 return optimizing_compile_dispatcher_;
1250 }
1251 // Flushes all pending concurrent optimzation jobs from the optimizing
1252 // compile dispatcher's queue.
1253 void AbortConcurrentOptimization(BlockingBehavior blocking_behavior);
1254
1255 int id() const { return id_; }
1256
1257 CompilationStatistics* GetTurboStatistics();
1258 V8_EXPORT_PRIVATE CodeTracer* GetCodeTracer();
1259
1260 void DumpAndResetStats();
1261
1262 void* stress_deopt_count_address() { return &stress_deopt_count_; }
1263
1264 void set_force_slow_path(bool v) { force_slow_path_ = v; }
1265 bool force_slow_path() const { return force_slow_path_; }
1266 bool* force_slow_path_address() { return &force_slow_path_; }
1267
1268 DebugInfo::ExecutionMode* debug_execution_mode_address() {
1269 return &debug_execution_mode_;
1270 }
1271
1272 V8_EXPORT_PRIVATE base::RandomNumberGenerator* random_number_generator();
1273
1274 V8_EXPORT_PRIVATE base::RandomNumberGenerator* fuzzer_rng();
1275
1276 // Generates a random number that is non-zero when masked
1277 // with the provided mask.
1278 int GenerateIdentityHash(uint32_t mask);
1279
1280 // Given an address occupied by a live code object, return that object.
1281 V8_EXPORT_PRIVATE Code FindCodeObject(Address a);
1282
1283 int NextOptimizationId() {
1284 int id = next_optimization_id_++;
1285 if (!Smi::IsValid(next_optimization_id_)) {
1286 next_optimization_id_ = 0;
1287 }
1288 return id;
1289 }
1290
1291 void AddNearHeapLimitCallback(v8::NearHeapLimitCallback, void* data);
1292 void RemoveNearHeapLimitCallback(v8::NearHeapLimitCallback callback,
1293 size_t heap_limit);
1294 void AddCallCompletedCallback(CallCompletedCallback callback);
1295 void RemoveCallCompletedCallback(CallCompletedCallback callback);
1296 void FireCallCompletedCallback(MicrotaskQueue* microtask_queue);
1297
1298 void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1299 void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1300 inline void FireBeforeCallEnteredCallback();
1301
1302 void SetPromiseRejectCallback(PromiseRejectCallback callback);
1303 void ReportPromiseReject(Handle<JSPromise> promise, Handle<Object> value,
1304 v8::PromiseRejectEvent event);
1305
1306 void SetTerminationOnExternalTryCatch();
1307
1308 Handle<Symbol> SymbolFor(RootIndex dictionary_index, Handle<String> name,
1309 bool private_symbol);
1310
1311 V8_EXPORT_PRIVATE void SetUseCounterCallback(
1312 v8::Isolate::UseCounterCallback callback);
1313 void CountUsage(v8::Isolate::UseCounterFeature feature);
1314
1315 static std::string GetTurboCfgFileName(Isolate* isolate);
1316
1317#if V8_SFI_HAS_UNIQUE_ID
1318 int GetNextUniqueSharedFunctionInfoId() { return next_unique_sfi_id_++; }
1319#endif
1320
1321 Address promise_hook_address() {
1322 return reinterpret_cast<Address>(&promise_hook_);
1323 }
1324
1325 Address async_event_delegate_address() {
1326 return reinterpret_cast<Address>(&async_event_delegate_);
1327 }
1328
1329 Address promise_hook_or_async_event_delegate_address() {
1330 return reinterpret_cast<Address>(&promise_hook_or_async_event_delegate_);
1331 }
1332
1333 Address promise_hook_or_debug_is_active_or_async_event_delegate_address() {
1334 return reinterpret_cast<Address>(
1335 &promise_hook_or_debug_is_active_or_async_event_delegate_);
1336 }
1337
1338 Address handle_scope_implementer_address() {
1339 return reinterpret_cast<Address>(&handle_scope_implementer_);
1340 }
1341
1342 void SetAtomicsWaitCallback(v8::Isolate::AtomicsWaitCallback callback,
1343 void* data);
1344 void RunAtomicsWaitCallback(v8::Isolate::AtomicsWaitEvent event,
1345 Handle<JSArrayBuffer> array_buffer,
1346 size_t offset_in_bytes, int64_t value,
1347 double timeout_in_ms,
1348 AtomicsWaitWakeHandle* stop_handle);
1349
1350 V8_EXPORT_PRIVATE void SetPromiseHook(PromiseHook hook);
1351 V8_EXPORT_PRIVATE void RunPromiseHook(PromiseHookType type,
1352 Handle<JSPromise> promise,
1353 Handle<Object> parent);
1354 void PromiseHookStateUpdated();
1355
1356 void AddDetachedContext(Handle<Context> context);
1357 void CheckDetachedContextsAfterGC();
1358
1359 std::vector<Object>* partial_snapshot_cache() {
1360 return &partial_snapshot_cache_;
1361 }
1362
1363 // Off-heap builtins cannot embed constants within the code object itself,
1364 // and thus need to load them from the root list.
1365 bool IsGeneratingEmbeddedBuiltins() const {
1366 return FLAG_embedded_builtins &&
1367 builtins_constants_table_builder() != nullptr;
1368 }
1369
1370 BuiltinsConstantsTableBuilder* builtins_constants_table_builder() const {
1371 return builtins_constants_table_builder_;
1372 }
1373
1374 // Hashes bits of the Isolate that are relevant for embedded builtins. In
1375 // particular, the embedded blob requires builtin Code object layout and the
1376 // builtins constants table to remain unchanged from build-time.
1377 size_t HashIsolateForEmbeddedBlob();
1378
1379 V8_EXPORT_PRIVATE static const uint8_t* CurrentEmbeddedBlob();
1380 V8_EXPORT_PRIVATE static uint32_t CurrentEmbeddedBlobSize();
1381 static bool CurrentEmbeddedBlobIsBinaryEmbedded();
1382
1383 // These always return the same result as static methods above, but don't
1384 // access the global atomic variable (and thus *might be* slightly faster).
1385 const uint8_t* embedded_blob() const;
1386 uint32_t embedded_blob_size() const;
1387
1388 void set_array_buffer_allocator(v8::ArrayBuffer::Allocator* allocator) {
1389 array_buffer_allocator_ = allocator;
1390 }
1391 v8::ArrayBuffer::Allocator* array_buffer_allocator() const {
1392 return array_buffer_allocator_;
1393 }
1394
1395 FutexWaitListNode* futex_wait_list_node() { return &futex_wait_list_node_; }
1396
1397 CancelableTaskManager* cancelable_task_manager() {
1398 return cancelable_task_manager_;
1399 }
1400
1401 const AstStringConstants* ast_string_constants() const {
1402 return ast_string_constants_;
1403 }
1404
1405 interpreter::Interpreter* interpreter() const { return interpreter_; }
1406
1407 compiler::PerIsolateCompilerCache* compiler_cache() const {
1408 return compiler_cache_;
1409 }
1410 void set_compiler_utils(compiler::PerIsolateCompilerCache* cache,
1411 Zone* zone) {
1412 compiler_cache_ = cache;
1413 compiler_zone_ = zone;
1414 }
1415
1416 AccountingAllocator* allocator() { return allocator_; }
1417
1418 CompilerDispatcher* compiler_dispatcher() const {
1419 return compiler_dispatcher_;
1420 }
1421
1422 bool IsInAnyContext(Object object, uint32_t index);
1423
1424 void SetHostImportModuleDynamicallyCallback(
1425 HostImportModuleDynamicallyCallback callback);
1426 V8_EXPORT_PRIVATE MaybeHandle<JSPromise>
1427 RunHostImportModuleDynamicallyCallback(Handle<Script> referrer,
1428 Handle<Object> specifier);
1429
1430 void SetHostInitializeImportMetaObjectCallback(
1431 HostInitializeImportMetaObjectCallback callback);
1432 V8_EXPORT_PRIVATE Handle<JSObject> RunHostInitializeImportMetaObjectCallback(
1433 Handle<Module> module);
1434
1435 void RegisterEmbeddedFileWriter(EmbeddedFileWriterInterface* writer) {
1436 embedded_file_writer_ = writer;
1437 }
1438
1439 int LookupOrAddExternallyCompiledFilename(const char* filename);
1440 const char* GetExternallyCompiledFilename(int index) const;
1441 int GetExternallyCompiledFilenameCount() const;
1442 // PrepareBuiltinSourcePositionMap is necessary in order to preserve the
1443 // builtin source positions before the corresponding code objects are
1444 // replaced with trampolines. Those source positions are used to
1445 // annotate the builtin blob with debugging information.
1446 void PrepareBuiltinSourcePositionMap();
1447
1448#if defined(V8_OS_WIN_X64)
1449 void SetBuiltinUnwindData(
1450 int builtin_index,
1451 const win64_unwindinfo::BuiltinUnwindInfo& unwinding_info);
1452#endif
1453
1454 void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
1455 MaybeHandle<Object> RunPrepareStackTraceCallback(Handle<Context>,
1456 Handle<JSObject> Error,
1457 Handle<JSArray> sites);
1458 bool HasPrepareStackTraceCallback() const;
1459
1460 void SetRAILMode(RAILMode rail_mode);
1461
1462 RAILMode rail_mode() { return rail_mode_.load(); }
1463
1464 double LoadStartTimeMs();
1465
1466 void IsolateInForegroundNotification();
1467
1468 void IsolateInBackgroundNotification();
1469
1470 bool IsIsolateInBackground() { return is_isolate_in_background_; }
1471
1472 void EnableMemorySavingsMode() { memory_savings_mode_active_ = true; }
1473
1474 void DisableMemorySavingsMode() { memory_savings_mode_active_ = false; }
1475
1476 bool IsMemorySavingsModeActive() { return memory_savings_mode_active_; }
1477
1478 PRINTF_FORMAT(2, 3) void PrintWithTimestamp(const char* format, ...);
1479
1480 void set_allow_atomics_wait(bool set) { allow_atomics_wait_ = set; }
1481 bool allow_atomics_wait() { return allow_atomics_wait_; }
1482
1483 // Register a finalizer to be called at isolate teardown.
1484 V8_EXPORT_PRIVATE void RegisterManagedPtrDestructor(
1485 ManagedPtrDestructor* finalizer);
1486
1487 // Removes a previously-registered shared object finalizer.
1488 void UnregisterManagedPtrDestructor(ManagedPtrDestructor* finalizer);
1489
1490 size_t elements_deletion_counter() { return elements_deletion_counter_; }
1491 void set_elements_deletion_counter(size_t value) {
1492 elements_deletion_counter_ = value;
1493 }
1494
1495 wasm::WasmEngine* wasm_engine() const { return wasm_engine_.get(); }
1496 V8_EXPORT_PRIVATE void SetWasmEngine(
1497 std::shared_ptr<wasm::WasmEngine> engine);
1498
1499 const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope() const {
1500 return top_backup_incumbent_scope_;
1501 }
1502 void set_top_backup_incumbent_scope(
1503 const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope) {
1504 top_backup_incumbent_scope_ = top_backup_incumbent_scope;
1505 }
1506
1507 V8_EXPORT_PRIVATE void SetIdle(bool is_idle);
1508
1509 private:
1510 explicit Isolate(std::unique_ptr<IsolateAllocator> isolate_allocator);
1511 ~Isolate();
1512
1513 V8_EXPORT_PRIVATE bool Init(ReadOnlyDeserializer* read_only_deserializer,
1514 StartupDeserializer* startup_deserializer);
1515
1516 void CheckIsolateLayout();
1517
1518 class ThreadDataTable {
1519 public:
1520 ThreadDataTable() = default;
1521
1522 PerIsolateThreadData* Lookup(ThreadId thread_id);
1523 void Insert(PerIsolateThreadData* data);
1524 void Remove(PerIsolateThreadData* data);
1525 void RemoveAllThreads();
1526
1527 private:
1528 struct Hasher {
1529 std::size_t operator()(const ThreadId& t) const {
1530 return std::hash<int>()(t.ToInteger());
1531 }
1532 };
1533
1534 std::unordered_map<ThreadId, PerIsolateThreadData*, Hasher> table_;
1535 };
1536
1537 // These items form a stack synchronously with threads Enter'ing and Exit'ing
1538 // the Isolate. The top of the stack points to a thread which is currently
1539 // running the Isolate. When the stack is empty, the Isolate is considered
1540 // not entered by any thread and can be Disposed.
1541 // If the same thread enters the Isolate more than once, the entry_count_
1542 // is incremented rather then a new item pushed to the stack.
1543 class EntryStackItem {
1544 public:
1545 EntryStackItem(PerIsolateThreadData* previous_thread_data,
1546 Isolate* previous_isolate,
1547 EntryStackItem* previous_item)
1548 : entry_count(1),
1549 previous_thread_data(previous_thread_data),
1550 previous_isolate(previous_isolate),
1551 previous_item(previous_item) { }
1552
1553 int entry_count;
1554 PerIsolateThreadData* previous_thread_data;
1555 Isolate* previous_isolate;
1556 EntryStackItem* previous_item;
1557
1558 private:
1559 DISALLOW_COPY_AND_ASSIGN(EntryStackItem);
1560 };
1561
1562 static base::Thread::LocalStorageKey per_isolate_thread_data_key_;
1563 static base::Thread::LocalStorageKey isolate_key_;
1564
1565#ifdef DEBUG
1566 static std::atomic<bool> isolate_key_created_;
1567#endif
1568
1569 void Deinit();
1570
1571 static void SetIsolateThreadLocals(Isolate* isolate,
1572 PerIsolateThreadData* data);
1573
1574 void InitializeThreadLocal();
1575
1576 void MarkCompactPrologue(bool is_compacting,
1577 ThreadLocalTop* archived_thread_data);
1578 void MarkCompactEpilogue(bool is_compacting,
1579 ThreadLocalTop* archived_thread_data);
1580
1581 void FillCache();
1582
1583 // Propagate pending exception message to the v8::TryCatch.
1584 // If there is no external try-catch or message was successfully propagated,
1585 // then return true.
1586 bool PropagatePendingExceptionToExternalTryCatch();
1587
1588 void RunPromiseHookForAsyncEventDelegate(PromiseHookType type,
1589 Handle<JSPromise> promise);
1590
1591 const char* RAILModeName(RAILMode rail_mode) const {
1592 switch (rail_mode) {
1593 case PERFORMANCE_RESPONSE:
1594 return "RESPONSE";
1595 case PERFORMANCE_ANIMATION:
1596 return "ANIMATION";
1597 case PERFORMANCE_IDLE:
1598 return "IDLE";
1599 case PERFORMANCE_LOAD:
1600 return "LOAD";
1601 }
1602 return "";
1603 }
1604
1605 // This class contains a collection of data accessible from both C++ runtime
1606 // and compiled code (including assembly stubs, builtins, interpreter bytecode
1607 // handlers and optimized code).
1608 IsolateData isolate_data_;
1609
1610 std::unique_ptr<IsolateAllocator> isolate_allocator_;
1611 Heap heap_;
1612
1613 const int id_;
1614 EntryStackItem* entry_stack_ = nullptr;
1615 int stack_trace_nesting_level_ = 0;
1616 StringStream* incomplete_message_ = nullptr;
1617 Address isolate_addresses_[kIsolateAddressCount + 1] = {};
1618 Bootstrapper* bootstrapper_ = nullptr;
1619 RuntimeProfiler* runtime_profiler_ = nullptr;
1620 CompilationCache* compilation_cache_ = nullptr;
1621 std::shared_ptr<Counters> async_counters_;
1622 base::RecursiveMutex break_access_;
1623 Logger* logger_ = nullptr;
1624 StackGuard stack_guard_;
1625 StubCache* load_stub_cache_ = nullptr;
1626 StubCache* store_stub_cache_ = nullptr;
1627 DeoptimizerData* deoptimizer_data_ = nullptr;
1628 bool deoptimizer_lazy_throw_ = false;
1629 MaterializedObjectStore* materialized_object_store_ = nullptr;
1630 bool capture_stack_trace_for_uncaught_exceptions_ = false;
1631 int stack_trace_for_uncaught_exceptions_frame_limit_ = 0;
1632 StackTrace::StackTraceOptions stack_trace_for_uncaught_exceptions_options_ =
1633 StackTrace::kOverview;
1634 DescriptorLookupCache* descriptor_lookup_cache_ = nullptr;
1635 HandleScopeData handle_scope_data_;
1636 HandleScopeImplementer* handle_scope_implementer_ = nullptr;
1637 UnicodeCache* unicode_cache_ = nullptr;
1638 AccountingAllocator* allocator_ = nullptr;
1639 InnerPointerToCodeCache* inner_pointer_to_code_cache_ = nullptr;
1640 GlobalHandles* global_handles_ = nullptr;
1641 EternalHandles* eternal_handles_ = nullptr;
1642 ThreadManager* thread_manager_ = nullptr;
1643 RuntimeState runtime_state_;
1644 Builtins builtins_;
1645 SetupIsolateDelegate* setup_delegate_ = nullptr;
1646#ifndef V8_INTL_SUPPORT
1647 unibrow::Mapping<unibrow::Ecma262UnCanonicalize> jsregexp_uncanonicalize_;
1648 unibrow::Mapping<unibrow::CanonicalizationRange> jsregexp_canonrange_;
1649 unibrow::Mapping<unibrow::Ecma262Canonicalize>
1650 regexp_macro_assembler_canonicalize_;
1651#endif // !V8_INTL_SUPPORT
1652 RegExpStack* regexp_stack_ = nullptr;
1653 std::vector<int> regexp_indices_;
1654 DateCache* date_cache_ = nullptr;
1655 base::RandomNumberGenerator* random_number_generator_ = nullptr;
1656 base::RandomNumberGenerator* fuzzer_rng_ = nullptr;
1657 std::atomic<RAILMode> rail_mode_;
1658 v8::Isolate::AtomicsWaitCallback atomics_wait_callback_ = nullptr;
1659 void* atomics_wait_callback_data_ = nullptr;
1660 PromiseHook promise_hook_ = nullptr;
1661 HostImportModuleDynamicallyCallback host_import_module_dynamically_callback_ =
1662 nullptr;
1663 HostInitializeImportMetaObjectCallback
1664 host_initialize_import_meta_object_callback_ = nullptr;
1665 base::Mutex rail_mutex_;
1666 double load_start_time_ms_ = 0;
1667
1668#ifdef V8_INTL_SUPPORT
1669 std::string default_locale_;
1670
1671 struct ICUObjectCacheTypeHash {
1672 std::size_t operator()(ICUObjectCacheType a) const {
1673 return static_cast<std::size_t>(a);
1674 }
1675 };
1676 std::unordered_map<ICUObjectCacheType, std::shared_ptr<icu::UObject>,
1677 ICUObjectCacheTypeHash>
1678 icu_object_cache_;
1679
1680#endif // V8_INTL_SUPPORT
1681
1682 // Whether the isolate has been created for snapshotting.
1683 bool serializer_enabled_ = false;
1684
1685 // True if fatal error has been signaled for this isolate.
1686 bool has_fatal_error_ = false;
1687
1688 // True if this isolate was initialized from a snapshot.
1689 bool initialized_from_snapshot_ = false;
1690
1691 // TODO(ishell): remove
1692 // True if ES2015 tail call elimination feature is enabled.
1693 bool is_tail_call_elimination_enabled_ = true;
1694
1695 // True if the isolate is in background. This flag is used
1696 // to prioritize between memory usage and latency.
1697 bool is_isolate_in_background_ = false;
1698
1699 // True if the isolate is in memory savings mode. This flag is used to
1700 // favor memory over runtime performance.
1701 bool memory_savings_mode_active_ = false;
1702
1703 // Time stamp at initialization.
1704 double time_millis_at_init_ = 0;
1705
1706#ifdef DEBUG
1707 V8_EXPORT_PRIVATE static std::atomic<size_t> non_disposed_isolates_;
1708
1709 JSObject::SpillInformation js_spill_information_;
1710#endif
1711
1712 Debug* debug_ = nullptr;
1713 HeapProfiler* heap_profiler_ = nullptr;
1714 std::unique_ptr<CodeEventDispatcher> code_event_dispatcher_;
1715
1716 const AstStringConstants* ast_string_constants_ = nullptr;
1717
1718 interpreter::Interpreter* interpreter_ = nullptr;
1719
1720 compiler::PerIsolateCompilerCache* compiler_cache_ = nullptr;
1721 Zone* compiler_zone_ = nullptr;
1722
1723 CompilerDispatcher* compiler_dispatcher_ = nullptr;
1724
1725 typedef std::pair<InterruptCallback, void*> InterruptEntry;
1726 std::queue<InterruptEntry> api_interrupts_queue_;
1727
1728#define GLOBAL_BACKING_STORE(type, name, initialvalue) \
1729 type name##_;
1730 ISOLATE_INIT_LIST(GLOBAL_BACKING_STORE)
1731#undef GLOBAL_BACKING_STORE
1732
1733#define GLOBAL_ARRAY_BACKING_STORE(type, name, length) \
1734 type name##_[length];
1735 ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_BACKING_STORE)
1736#undef GLOBAL_ARRAY_BACKING_STORE
1737
1738#ifdef DEBUG
1739 // This class is huge and has a number of fields controlled by
1740 // preprocessor defines. Make sure the offsets of these fields agree
1741 // between compilation units.
1742#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1743 V8_EXPORT_PRIVATE static const intptr_t name##_debug_offset_;
1744 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
1745 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
1746#undef ISOLATE_FIELD_OFFSET
1747#endif
1748
1749 DeferredHandles* deferred_handles_head_ = nullptr;
1750 OptimizingCompileDispatcher* optimizing_compile_dispatcher_ = nullptr;
1751
1752 // Counts deopt points if deopt_every_n_times is enabled.
1753 unsigned int stress_deopt_count_ = 0;
1754
1755 bool force_slow_path_ = false;
1756
1757 int next_optimization_id_ = 0;
1758
1759#if V8_SFI_HAS_UNIQUE_ID
1760 int next_unique_sfi_id_ = 0;
1761#endif
1762
1763 // Vector of callbacks before a Call starts execution.
1764 std::vector<BeforeCallEnteredCallback> before_call_entered_callbacks_;
1765
1766 // Vector of callbacks when a Call completes.
1767 std::vector<CallCompletedCallback> call_completed_callbacks_;
1768
1769 v8::Isolate::UseCounterCallback use_counter_callback_ = nullptr;
1770
1771 std::vector<Object> partial_snapshot_cache_;
1772
1773 // Used during builtins compilation to build the builtins constants table,
1774 // which is stored on the root list prior to serialization.
1775 BuiltinsConstantsTableBuilder* builtins_constants_table_builder_ = nullptr;
1776
1777 void InitializeDefaultEmbeddedBlob();
1778 void CreateAndSetEmbeddedBlob();
1779 void TearDownEmbeddedBlob();
1780
1781 void SetEmbeddedBlob(const uint8_t* blob, uint32_t blob_size);
1782 void ClearEmbeddedBlob();
1783
1784 const uint8_t* embedded_blob_ = nullptr;
1785 uint32_t embedded_blob_size_ = 0;
1786
1787 v8::ArrayBuffer::Allocator* array_buffer_allocator_ = nullptr;
1788
1789 FutexWaitListNode futex_wait_list_node_;
1790
1791 CancelableTaskManager* cancelable_task_manager_ = nullptr;
1792
1793 debug::ConsoleDelegate* console_delegate_ = nullptr;
1794
1795 debug::AsyncEventDelegate* async_event_delegate_ = nullptr;
1796 bool promise_hook_or_async_event_delegate_ = false;
1797 bool promise_hook_or_debug_is_active_or_async_event_delegate_ = false;
1798 int async_task_count_ = 0;
1799
1800 v8::Isolate::AbortOnUncaughtExceptionCallback
1801 abort_on_uncaught_exception_callback_ = nullptr;
1802
1803 bool allow_atomics_wait_ = true;
1804
1805 base::Mutex managed_ptr_destructors_mutex_;
1806 ManagedPtrDestructor* managed_ptr_destructors_head_ = nullptr;
1807
1808 size_t total_regexp_code_generated_ = 0;
1809
1810 size_t elements_deletion_counter_ = 0;
1811
1812 std::shared_ptr<wasm::WasmEngine> wasm_engine_;
1813
1814 std::unique_ptr<TracingCpuProfilerImpl> tracing_cpu_profiler_;
1815
1816 EmbeddedFileWriterInterface* embedded_file_writer_ = nullptr;
1817
1818 // The top entry of the v8::Context::BackupIncumbentScope stack.
1819 const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope_ =
1820 nullptr;
1821
1822 PrepareStackTraceCallback prepare_stack_trace_callback_ = nullptr;
1823
1824 // TODO(kenton@cloudflare.com): This mutex can be removed if
1825 // thread_data_table_ is always accessed under the isolate lock. I do not
1826 // know if this is the case, so I'm preserving it for now.
1827 base::Mutex thread_data_table_mutex_;
1828 ThreadDataTable thread_data_table_;
1829
1830 // Delete new/delete operators to ensure that Isolate::New() and
1831 // Isolate::Delete() are used for Isolate creation and deletion.
1832 void* operator new(size_t, void* ptr) { return ptr; }
1833 void* operator new(size_t) = delete;
1834 void operator delete(void*) = delete;
1835
1836 friend class heap::HeapTester;
1837 friend class TestSerializer;
1838
1839 DISALLOW_COPY_AND_ASSIGN(Isolate);
1840};
1841
1842#undef FIELD_ACCESSOR
1843#undef THREAD_LOCAL_TOP_ACCESSOR
1844
1845class PromiseOnStack {
1846 public:
1847 PromiseOnStack(Handle<JSObject> promise, PromiseOnStack* prev)
1848 : promise_(promise), prev_(prev) {}
1849 Handle<JSObject> promise() { return promise_; }
1850 PromiseOnStack* prev() { return prev_; }
1851
1852 private:
1853 Handle<JSObject> promise_;
1854 PromiseOnStack* prev_;
1855};
1856
1857// SaveContext scopes save the current context on the Isolate on creation, and
1858// restore it on destruction.
1859class V8_EXPORT_PRIVATE SaveContext {
1860 public:
1861 explicit SaveContext(Isolate* isolate);
1862
1863 ~SaveContext();
1864
1865 Handle<Context> context() { return context_; }
1866
1867 // Returns true if this save context is below a given JavaScript frame.
1868 bool IsBelowFrame(StandardFrame* frame);
1869
1870 private:
1871 Isolate* const isolate_;
1872 Handle<Context> context_;
1873 Address c_entry_fp_;
1874};
1875
1876// Like SaveContext, but also switches the Context to a new one in the
1877// constructor.
1878class V8_EXPORT_PRIVATE SaveAndSwitchContext : public SaveContext {
1879 public:
1880 SaveAndSwitchContext(Isolate* isolate, Context new_context);
1881};
1882
1883class AssertNoContextChange {
1884#ifdef DEBUG
1885 public:
1886 explicit AssertNoContextChange(Isolate* isolate);
1887 ~AssertNoContextChange() {
1888 DCHECK(isolate_->context() == *context_);
1889 }
1890
1891 private:
1892 Isolate* isolate_;
1893 Handle<Context> context_;
1894#else
1895 public:
1896 explicit AssertNoContextChange(Isolate* isolate) { }
1897#endif
1898};
1899
1900class ExecutionAccess {
1901 public:
1902 explicit ExecutionAccess(Isolate* isolate) : isolate_(isolate) {
1903 Lock(isolate);
1904 }
1905 ~ExecutionAccess() { Unlock(isolate_); }
1906
1907 static void Lock(Isolate* isolate) { isolate->break_access()->Lock(); }
1908 static void Unlock(Isolate* isolate) { isolate->break_access()->Unlock(); }
1909
1910 static bool TryLock(Isolate* isolate) {
1911 return isolate->break_access()->TryLock();
1912 }
1913
1914 private:
1915 Isolate* isolate_;
1916};
1917
1918
1919// Support for checking for stack-overflows.
1920class StackLimitCheck {
1921 public:
1922 explicit StackLimitCheck(Isolate* isolate) : isolate_(isolate) { }
1923
1924 // Use this to check for stack-overflows in C++ code.
1925 bool HasOverflowed() const {
1926 StackGuard* stack_guard = isolate_->stack_guard();
1927 return GetCurrentStackPosition() < stack_guard->real_climit();
1928 }
1929
1930 // Use this to check for interrupt request in C++ code.
1931 bool InterruptRequested() {
1932 StackGuard* stack_guard = isolate_->stack_guard();
1933 return GetCurrentStackPosition() < stack_guard->climit();
1934 }
1935
1936 // Use this to check for stack-overflow when entering runtime from JS code.
1937 bool JsHasOverflowed(uintptr_t gap = 0) const;
1938
1939 private:
1940 Isolate* isolate_;
1941};
1942
1943#define STACK_CHECK(isolate, result_value) \
1944 do { \
1945 StackLimitCheck stack_check(isolate); \
1946 if (stack_check.HasOverflowed()) { \
1947 isolate->StackOverflow(); \
1948 return result_value; \
1949 } \
1950 } while (false)
1951
1952// Scope intercepts only interrupt which is part of its interrupt_mask and does
1953// not affect other interrupts.
1954class InterruptsScope {
1955 public:
1956 enum Mode { kPostponeInterrupts, kRunInterrupts, kNoop };
1957
1958 virtual ~InterruptsScope() {
1959 if (mode_ != kNoop) stack_guard_->PopInterruptsScope();
1960 }
1961
1962 // Find the scope that intercepts this interrupt.
1963 // It may be outermost PostponeInterruptsScope or innermost
1964 // SafeForInterruptsScope if any.
1965 // Return whether the interrupt has been intercepted.
1966 bool Intercept(StackGuard::InterruptFlag flag);
1967
1968 InterruptsScope(Isolate* isolate, int intercept_mask, Mode mode)
1969 : stack_guard_(isolate->stack_guard()),
1970 intercept_mask_(intercept_mask),
1971 intercepted_flags_(0),
1972 mode_(mode) {
1973 if (mode_ != kNoop) stack_guard_->PushInterruptsScope(this);
1974 }
1975
1976 private:
1977 StackGuard* stack_guard_;
1978 int intercept_mask_;
1979 int intercepted_flags_;
1980 Mode mode_;
1981 InterruptsScope* prev_;
1982
1983 friend class StackGuard;
1984};
1985
1986// Support for temporarily postponing interrupts. When the outermost
1987// postpone scope is left the interrupts will be re-enabled and any
1988// interrupts that occurred while in the scope will be taken into
1989// account.
1990class PostponeInterruptsScope : public InterruptsScope {
1991 public:
1992 PostponeInterruptsScope(Isolate* isolate,
1993 int intercept_mask = StackGuard::ALL_INTERRUPTS)
1994 : InterruptsScope(isolate, intercept_mask,
1995 InterruptsScope::kPostponeInterrupts) {}
1996 ~PostponeInterruptsScope() override = default;
1997};
1998
1999// Support for overriding PostponeInterruptsScope. Interrupt is not ignored if
2000// innermost scope is SafeForInterruptsScope ignoring any outer
2001// PostponeInterruptsScopes.
2002class SafeForInterruptsScope : public InterruptsScope {
2003 public:
2004 SafeForInterruptsScope(Isolate* isolate,
2005 int intercept_mask = StackGuard::ALL_INTERRUPTS)
2006 : InterruptsScope(isolate, intercept_mask,
2007 InterruptsScope::kRunInterrupts) {}
2008 ~SafeForInterruptsScope() override = default;
2009};
2010
2011class StackTraceFailureMessage {
2012 public:
2013 explicit StackTraceFailureMessage(Isolate* isolate, void* ptr1 = nullptr,
2014 void* ptr2 = nullptr, void* ptr3 = nullptr,
2015 void* ptr4 = nullptr);
2016
2017 V8_NOINLINE void Print() volatile;
2018
2019 static const uintptr_t kStartMarker = 0xdecade30;
2020 static const uintptr_t kEndMarker = 0xdecade31;
2021 static const int kStacktraceBufferSize = 32 * KB;
2022
2023 uintptr_t start_marker_ = kStartMarker;
2024 void* isolate_;
2025 void* ptr1_;
2026 void* ptr2_;
2027 void* ptr3_;
2028 void* ptr4_;
2029 void* code_objects_[4];
2030 char js_stack_trace_[kStacktraceBufferSize];
2031 uintptr_t end_marker_ = kEndMarker;
2032};
2033
2034} // namespace internal
2035} // namespace v8
2036
2037#endif // V8_ISOLATE_H_
2038