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