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/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.
39 : namespace U_ICU_NAMESPACE {
40 : class UObject;
41 : } // namespace U_ICU_NAMESPACE
42 : #endif // V8_INTL_SUPPORT
43 :
44 : namespace v8 {
45 :
46 : namespace base {
47 : class RandomNumberGenerator;
48 : }
49 :
50 : namespace debug {
51 : class ConsoleDelegate;
52 : class AsyncEventDelegate;
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 ReadOnlyDeserializer;
88 : class RegExpStack;
89 : class RootVisitor;
90 : class RuntimeProfiler;
91 : class SetupIsolateDelegate;
92 : class Simulator;
93 : class StartupDeserializer;
94 : class StandardFrame;
95 : class StubCache;
96 : class ThreadManager;
97 : class ThreadState;
98 : class ThreadVisitor; // Defined in v8threads.h
99 : class TracingCpuProfilerImpl;
100 : class UnicodeCache;
101 : struct ManagedPtrDestructor;
102 :
103 : template <StateTag Tag> class VMState;
104 :
105 : namespace interpreter {
106 : class Interpreter;
107 : }
108 :
109 : namespace compiler {
110 : class PerIsolateCompilerCache;
111 : }
112 :
113 : namespace wasm {
114 : class WasmEngine;
115 : }
116 :
117 : #define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate) \
118 : do { \
119 : Isolate* __isolate__ = (isolate); \
120 : DCHECK(!__isolate__->has_pending_exception()); \
121 : if (__isolate__->has_scheduled_exception()) { \
122 : return __isolate__->PromoteScheduledException(); \
123 : } \
124 : } while (false)
125 :
126 : // Macros for MaybeHandle.
127 :
128 : #define RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, value) \
129 : do { \
130 : Isolate* __isolate__ = (isolate); \
131 : DCHECK(!__isolate__->has_pending_exception()); \
132 : if (__isolate__->has_scheduled_exception()) { \
133 : __isolate__->PromoteScheduledException(); \
134 : return value; \
135 : } \
136 : } while (false)
137 :
138 : #define RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, T) \
139 : RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, MaybeHandle<T>())
140 :
141 : #define ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, dst, call, value) \
142 : do { \
143 : Isolate* __isolate__ = (isolate); \
144 : if (!(call).ToLocal(&dst)) { \
145 : DCHECK(__isolate__->has_scheduled_exception()); \
146 : __isolate__->PromoteScheduledException(); \
147 : return value; \
148 : } \
149 : } while (false)
150 :
151 : #define RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, call, value) \
152 : do { \
153 : Isolate* __isolate__ = (isolate); \
154 : if ((call).IsNothing()) { \
155 : DCHECK(__isolate__->has_scheduled_exception()); \
156 : __isolate__->PromoteScheduledException(); \
157 : return value; \
158 : } \
159 : } while (false)
160 :
161 : /**
162 : * RETURN_RESULT_OR_FAILURE is used in functions with return type Object (such
163 : * as "RUNTIME_FUNCTION(...) {...}" or "BUILTIN(...) {...}" ) to return either
164 : * the contents of a MaybeHandle<X>, or the "exception" sentinel value.
165 : * Example usage:
166 : *
167 : * RUNTIME_FUNCTION(Runtime_Func) {
168 : * ...
169 : * RETURN_RESULT_OR_FAILURE(
170 : * isolate,
171 : * FunctionWithReturnTypeMaybeHandleX(...));
172 : * }
173 : *
174 : * If inside a function with return type MaybeHandle<X> use RETURN_ON_EXCEPTION
175 : * instead.
176 : * If inside a function with return type Handle<X>, or Maybe<X> use
177 : * RETURN_ON_EXCEPTION_VALUE instead.
178 : */
179 : #define RETURN_RESULT_OR_FAILURE(isolate, call) \
180 : do { \
181 : Handle<Object> __result__; \
182 : Isolate* __isolate__ = (isolate); \
183 : if (!(call).ToHandle(&__result__)) { \
184 : DCHECK(__isolate__->has_pending_exception()); \
185 : return ReadOnlyRoots(__isolate__).exception(); \
186 : } \
187 : DCHECK(!__isolate__->has_pending_exception()); \
188 : return *__result__; \
189 : } while (false)
190 :
191 : #define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value) \
192 : do { \
193 : if (!(call).ToHandle(&dst)) { \
194 : DCHECK((isolate)->has_pending_exception()); \
195 : return value; \
196 : } \
197 : } while (false)
198 :
199 : #define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call) \
200 : do { \
201 : Isolate* __isolate__ = (isolate); \
202 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(__isolate__, dst, call, \
203 : ReadOnlyRoots(__isolate__).exception()); \
204 : } while (false)
205 :
206 : #define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T) \
207 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, MaybeHandle<T>())
208 :
209 : #define THROW_NEW_ERROR(isolate, call, T) \
210 : do { \
211 : Isolate* __isolate__ = (isolate); \
212 : return __isolate__->Throw<T>(__isolate__->factory()->call); \
213 : } while (false)
214 :
215 : #define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call) \
216 : do { \
217 : Isolate* __isolate__ = (isolate); \
218 : return __isolate__->Throw(*__isolate__->factory()->call); \
219 : } while (false)
220 :
221 : #define THROW_NEW_ERROR_RETURN_VALUE(isolate, call, value) \
222 : do { \
223 : Isolate* __isolate__ = (isolate); \
224 : __isolate__->Throw(*__isolate__->factory()->call); \
225 : return value; \
226 : } while (false)
227 :
228 : /**
229 : * RETURN_ON_EXCEPTION_VALUE conditionally returns the given value when the
230 : * given MaybeHandle is empty. It is typically used in functions with return
231 : * type Maybe<X> or Handle<X>. Example usage:
232 : *
233 : * Handle<X> Func() {
234 : * ...
235 : * RETURN_ON_EXCEPTION_VALUE(
236 : * isolate,
237 : * FunctionWithReturnTypeMaybeHandleX(...),
238 : * Handle<X>());
239 : * // code to handle non exception
240 : * ...
241 : * }
242 : *
243 : * Maybe<bool> Func() {
244 : * ..
245 : * RETURN_ON_EXCEPTION_VALUE(
246 : * isolate,
247 : * FunctionWithReturnTypeMaybeHandleX(...),
248 : * Nothing<bool>);
249 : * // code to handle non exception
250 : * return Just(true);
251 : * }
252 : *
253 : * If inside a function with return type MaybeHandle<X>, use RETURN_ON_EXCEPTION
254 : * instead.
255 : * If inside a function with return type Object, use
256 : * RETURN_FAILURE_ON_EXCEPTION instead.
257 : */
258 : #define RETURN_ON_EXCEPTION_VALUE(isolate, call, value) \
259 : do { \
260 : if ((call).is_null()) { \
261 : DCHECK((isolate)->has_pending_exception()); \
262 : return value; \
263 : } \
264 : } while (false)
265 :
266 : /**
267 : * RETURN_FAILURE_ON_EXCEPTION conditionally returns the "exception" sentinel if
268 : * the given MaybeHandle is empty; so it can only be used in functions with
269 : * return type Object, such as RUNTIME_FUNCTION(...) {...} or BUILTIN(...)
270 : * {...}. Example usage:
271 : *
272 : * RUNTIME_FUNCTION(Runtime_Func) {
273 : * ...
274 : * RETURN_FAILURE_ON_EXCEPTION(
275 : * isolate,
276 : * FunctionWithReturnTypeMaybeHandleX(...));
277 : * // code to handle non exception
278 : * ...
279 : * }
280 : *
281 : * If inside a function with return type MaybeHandle<X>, use RETURN_ON_EXCEPTION
282 : * instead.
283 : * If inside a function with return type Maybe<X> or Handle<X>, use
284 : * RETURN_ON_EXCEPTION_VALUE instead.
285 : */
286 : #define RETURN_FAILURE_ON_EXCEPTION(isolate, call) \
287 : do { \
288 : Isolate* __isolate__ = (isolate); \
289 : RETURN_ON_EXCEPTION_VALUE(__isolate__, call, \
290 : ReadOnlyRoots(__isolate__).exception()); \
291 : } while (false);
292 :
293 : /**
294 : * RETURN_ON_EXCEPTION conditionally returns an empty MaybeHandle<T> if the
295 : * given MaybeHandle is empty. Use it to return immediately from a function with
296 : * return type MaybeHandle when an exception was thrown. Example usage:
297 : *
298 : * MaybeHandle<X> Func() {
299 : * ...
300 : * RETURN_ON_EXCEPTION(
301 : * isolate,
302 : * FunctionWithReturnTypeMaybeHandleY(...),
303 : * X);
304 : * // code to handle non exception
305 : * ...
306 : * }
307 : *
308 : * If inside a function with return type Object, use
309 : * RETURN_FAILURE_ON_EXCEPTION instead.
310 : * If inside a function with return type
311 : * Maybe<X> or Handle<X>, use RETURN_ON_EXCEPTION_VALUE instead.
312 : */
313 : #define RETURN_ON_EXCEPTION(isolate, call, T) \
314 : RETURN_ON_EXCEPTION_VALUE(isolate, call, MaybeHandle<T>())
315 :
316 :
317 : #define FOR_WITH_HANDLE_SCOPE(isolate, loop_var_type, init, loop_var, \
318 : limit_check, increment, body) \
319 : do { \
320 : loop_var_type init; \
321 : loop_var_type for_with_handle_limit = loop_var; \
322 : Isolate* for_with_handle_isolate = isolate; \
323 : while (limit_check) { \
324 : for_with_handle_limit += 1024; \
325 : HandleScope loop_scope(for_with_handle_isolate); \
326 : for (; limit_check && loop_var < for_with_handle_limit; increment) { \
327 : body \
328 : } \
329 : } \
330 : } while (false)
331 :
332 : #define FIELD_ACCESSOR(type, name) \
333 : inline void set_##name(type v) { name##_ = v; } \
334 : inline type name() const { return name##_; }
335 :
336 : // Controls for manual embedded blob lifecycle management, used by tests and
337 : // mksnapshot.
338 : V8_EXPORT_PRIVATE void DisableEmbeddedBlobRefcounting();
339 : V8_EXPORT_PRIVATE void FreeCurrentEmbeddedBlob();
340 :
341 : #ifdef DEBUG
342 :
343 : #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V) \
344 : V(CommentStatistic, paged_space_comments_statistics, \
345 : CommentStatistic::kMaxComments + 1) \
346 : V(int, code_kind_statistics, AbstractCode::NUMBER_OF_KINDS)
347 : #else
348 :
349 : #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
350 :
351 : #endif
352 :
353 : #define ISOLATE_INIT_ARRAY_LIST(V) \
354 : /* SerializerDeserializer state. */ \
355 : V(int32_t, jsregexp_static_offsets_vector, kJSRegexpStaticOffsetsVectorSize) \
356 : V(int, bad_char_shift_table, kUC16AlphabetSize) \
357 : V(int, good_suffix_shift_table, (kBMMaxShift + 1)) \
358 : V(int, suffix_table, (kBMMaxShift + 1)) \
359 : ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
360 :
361 : using DebugObjectCache = std::vector<Handle<HeapObject>>;
362 :
363 : #define ISOLATE_INIT_LIST(V) \
364 : /* Assembler state. */ \
365 : V(FatalErrorCallback, exception_behavior, nullptr) \
366 : V(OOMErrorCallback, oom_behavior, nullptr) \
367 : V(LogEventCallback, event_logger, nullptr) \
368 : V(AllowCodeGenerationFromStringsCallback, allow_code_gen_callback, nullptr) \
369 : V(AllowWasmCodeGenerationCallback, allow_wasm_code_gen_callback, nullptr) \
370 : V(ExtensionCallback, wasm_module_callback, &NoExtension) \
371 : V(ExtensionCallback, wasm_instance_callback, &NoExtension) \
372 : V(WasmStreamingCallback, wasm_streaming_callback, nullptr) \
373 : V(WasmThreadsEnabledCallback, wasm_threads_enabled_callback, nullptr) \
374 : /* State for Relocatable. */ \
375 : V(Relocatable*, relocatable_top, nullptr) \
376 : V(DebugObjectCache*, string_stream_debug_object_cache, nullptr) \
377 : V(Object, string_stream_current_security_token, Object()) \
378 : V(const intptr_t*, api_external_references, nullptr) \
379 : V(AddressToIndexHashMap*, external_reference_map, nullptr) \
380 : V(HeapObjectToIndexHashMap*, root_index_map, nullptr) \
381 : V(MicrotaskQueue*, default_microtask_queue, nullptr) \
382 : V(CompilationStatistics*, turbo_statistics, nullptr) \
383 : V(CodeTracer*, code_tracer, nullptr) \
384 : V(uint32_t, per_isolate_assert_data, 0xFFFFFFFFu) \
385 : V(PromiseRejectCallback, promise_reject_callback, nullptr) \
386 : V(const v8::StartupData*, snapshot_blob, nullptr) \
387 : V(int, code_and_metadata_size, 0) \
388 : V(int, bytecode_and_metadata_size, 0) \
389 : V(int, external_script_source_size, 0) \
390 : /* true if being profiled. Causes collection of extra compile info. */ \
391 : V(bool, is_profiling, false) \
392 : /* true if a trace is being formatted through Error.prepareStackTrace. */ \
393 : V(bool, formatting_stack_trace, false) \
394 : /* Perform side effect checks on function call and API callbacks. */ \
395 : V(DebugInfo::ExecutionMode, debug_execution_mode, DebugInfo::kBreakpoints) \
396 : /* Current code coverage mode */ \
397 : V(debug::CoverageMode, code_coverage_mode, debug::CoverageMode::kBestEffort) \
398 : V(debug::TypeProfileMode, type_profile_mode, debug::TypeProfileMode::kNone) \
399 : V(int, last_stack_frame_info_id, 0) \
400 : V(int, last_console_context_id, 0) \
401 : V(v8_inspector::V8Inspector*, inspector, nullptr) \
402 : V(bool, next_v8_call_is_safe_for_termination, false) \
403 : V(bool, only_terminate_in_safe_scope, false) \
404 : V(bool, detailed_source_positions_for_profiling, FLAG_detailed_line_info)
405 :
406 : #define THREAD_LOCAL_TOP_ACCESSOR(type, name) \
407 : inline void set_##name(type v) { thread_local_top()->name##_ = v; } \
408 : inline type name() const { return thread_local_top()->name##_; }
409 :
410 : #define THREAD_LOCAL_TOP_ADDRESS(type, name) \
411 : type* name##_address() { return &thread_local_top()->name##_; }
412 :
413 : // HiddenFactory exists so Isolate can privately inherit from it without making
414 : // Factory's members available to Isolate directly.
415 : class V8_EXPORT_PRIVATE HiddenFactory : private Factory {};
416 :
417 : class Isolate final : private HiddenFactory {
418 : // These forward declarations are required to make the friend declarations in
419 : // PerIsolateThreadData work on some older versions of gcc.
420 : class ThreadDataTable;
421 : class EntryStackItem;
422 : public:
423 : // A thread has a PerIsolateThreadData instance for each isolate that it has
424 : // entered. That instance is allocated when the isolate is initially entered
425 : // and reused on subsequent entries.
426 : class PerIsolateThreadData {
427 : public:
428 : PerIsolateThreadData(Isolate* isolate, ThreadId thread_id)
429 : : isolate_(isolate),
430 : thread_id_(thread_id),
431 : stack_limit_(0),
432 : thread_state_(nullptr),
433 : #if USE_SIMULATOR
434 : simulator_(nullptr),
435 : #endif
436 : next_(nullptr),
437 67069 : prev_(nullptr) {
438 : }
439 : ~PerIsolateThreadData();
440 : Isolate* isolate() const { return isolate_; }
441 : ThreadId thread_id() const { return thread_id_; }
442 :
443 5918 : FIELD_ACCESSOR(uintptr_t, stack_limit)
444 68770 : FIELD_ACCESSOR(ThreadState*, thread_state)
445 :
446 : #if USE_SIMULATOR
447 : FIELD_ACCESSOR(Simulator*, simulator)
448 : #endif
449 :
450 : bool Matches(Isolate* isolate, ThreadId thread_id) const {
451 : return isolate_ == isolate && thread_id_ == thread_id;
452 : }
453 :
454 : private:
455 : Isolate* isolate_;
456 : ThreadId thread_id_;
457 : uintptr_t stack_limit_;
458 : ThreadState* thread_state_;
459 :
460 : #if USE_SIMULATOR
461 : Simulator* simulator_;
462 : #endif
463 :
464 : PerIsolateThreadData* next_;
465 : PerIsolateThreadData* prev_;
466 :
467 : friend class Isolate;
468 : friend class ThreadDataTable;
469 : friend class EntryStackItem;
470 :
471 : DISALLOW_COPY_AND_ASSIGN(PerIsolateThreadData);
472 : };
473 :
474 : static void InitializeOncePerProcess();
475 :
476 : // Creates Isolate object. Must be used instead of constructing Isolate with
477 : // new operator.
478 : static V8_EXPORT_PRIVATE Isolate* New(
479 : IsolateAllocationMode mode = IsolateAllocationMode::kDefault);
480 :
481 : // Deletes Isolate object. Must be used instead of delete operator.
482 : // Destroys the non-default isolates.
483 : // Sets default isolate into "has_been_disposed" state rather then destroying,
484 : // for legacy API reasons.
485 : static void Delete(Isolate* isolate);
486 :
487 : // Returns allocation mode of this isolate.
488 : V8_INLINE IsolateAllocationMode isolate_allocation_mode();
489 :
490 : // Page allocator that must be used for allocating V8 heap pages.
491 : v8::PageAllocator* page_allocator();
492 :
493 : // Returns the PerIsolateThreadData for the current thread (or nullptr if one
494 : // is not currently set).
495 : static PerIsolateThreadData* CurrentPerIsolateThreadData() {
496 : return reinterpret_cast<PerIsolateThreadData*>(
497 283642 : base::Thread::GetThreadLocal(per_isolate_thread_data_key_));
498 : }
499 :
500 : // Returns the isolate inside which the current thread is running or nullptr.
501 : V8_INLINE static Isolate* TryGetCurrent() {
502 : DCHECK_EQ(true, isolate_key_created_.load(std::memory_order_relaxed));
503 : return reinterpret_cast<Isolate*>(
504 978206 : base::Thread::GetExistingThreadLocal(isolate_key_));
505 : }
506 :
507 : // Returns the isolate inside which the current thread is running.
508 : V8_INLINE static Isolate* Current() {
509 : Isolate* isolate = TryGetCurrent();
510 : DCHECK_NOT_NULL(isolate);
511 : return isolate;
512 : }
513 :
514 : // Usually called by Init(), but can be called early e.g. to allow
515 : // testing components that require logging but not the whole
516 : // isolate.
517 : //
518 : // Safe to call more than once.
519 : void InitializeLoggingAndCounters();
520 : bool InitializeCounters(); // Returns false if already initialized.
521 :
522 : bool InitWithoutSnapshot();
523 : bool InitWithSnapshot(ReadOnlyDeserializer* read_only_deserializer,
524 : StartupDeserializer* startup_deserializer);
525 :
526 : // True if at least one thread Enter'ed this isolate.
527 66148 : bool IsInUse() { return entry_stack_ != nullptr; }
528 :
529 : void ReleaseSharedPtrs();
530 :
531 : void ClearSerializerData();
532 :
533 : bool LogObjectRelocation();
534 :
535 : // Initializes the current thread to run this Isolate.
536 : // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
537 : // at the same time, this should be prevented using external locking.
538 : void Enter();
539 :
540 : // Exits the current thread. The previosuly entered Isolate is restored
541 : // for the thread.
542 : // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
543 : // at the same time, this should be prevented using external locking.
544 : void Exit();
545 :
546 : // Find the PerThread for this particular (isolate, thread) combination.
547 : // If one does not yet exist, allocate a new one.
548 : PerIsolateThreadData* FindOrAllocatePerThreadDataForThisThread();
549 :
550 : // Find the PerThread for this particular (isolate, thread) combination
551 : // If one does not yet exist, return null.
552 : PerIsolateThreadData* FindPerThreadDataForThisThread();
553 :
554 : // Find the PerThread for given (isolate, thread) combination
555 : // If one does not yet exist, return null.
556 : PerIsolateThreadData* FindPerThreadDataForThread(ThreadId thread_id);
557 :
558 : // Discard the PerThread for this particular (isolate, thread) combination
559 : // If one does not yet exist, no-op.
560 : void DiscardPerThreadDataForThisThread();
561 :
562 : // Mutex for serializing access to break control structures.
563 20747617 : base::RecursiveMutex* break_access() { return &break_access_; }
564 :
565 : Address get_address_from_id(IsolateAddressId id);
566 :
567 : // Access to top context (where the current function object was created).
568 159066524 : Context context() { return thread_local_top()->context_; }
569 : inline void set_context(Context context);
570 61532 : Context* context_address() { return &thread_local_top()->context_; }
571 :
572 : // Access to current thread id.
573 211932 : THREAD_LOCAL_TOP_ACCESSOR(ThreadId, thread_id)
574 :
575 : // Interface to pending exception.
576 : inline Object pending_exception();
577 : inline void set_pending_exception(Object exception_obj);
578 : inline void clear_pending_exception();
579 :
580 : bool AreWasmThreadsEnabled(Handle<Context> context);
581 :
582 61532 : THREAD_LOCAL_TOP_ADDRESS(Object, pending_exception)
583 :
584 : inline bool has_pending_exception();
585 :
586 61532 : THREAD_LOCAL_TOP_ADDRESS(Context, pending_handler_context)
587 61532 : THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_entrypoint)
588 61532 : THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_constant_pool)
589 61532 : THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_fp)
590 61532 : THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_sp)
591 :
592 8047 : THREAD_LOCAL_TOP_ACCESSOR(bool, external_caught_exception)
593 :
594 : v8::TryCatch* try_catch_handler() {
595 22421184 : return thread_local_top()->try_catch_handler_;
596 : }
597 : bool* external_caught_exception_address() {
598 61532 : return &thread_local_top()->external_caught_exception_;
599 : }
600 :
601 61646 : THREAD_LOCAL_TOP_ADDRESS(Object, scheduled_exception)
602 :
603 : inline void clear_pending_message();
604 : Address pending_message_obj_address() {
605 118814 : return reinterpret_cast<Address>(&thread_local_top()->pending_message_obj_);
606 : }
607 :
608 : inline Object scheduled_exception();
609 : inline bool has_scheduled_exception();
610 : inline void clear_scheduled_exception();
611 :
612 : bool IsJavaScriptHandlerOnTop(Object exception);
613 : bool IsExternalHandlerOnTop(Object exception);
614 :
615 : inline bool is_catchable_by_javascript(Object exception);
616 :
617 : // JS execution stack (see frames.h).
618 : static Address c_entry_fp(ThreadLocalTop* thread) {
619 : return thread->c_entry_fp_;
620 : }
621 : static Address handler(ThreadLocalTop* thread) { return thread->handler_; }
622 18929 : Address c_function() { return thread_local_top()->c_function_; }
623 :
624 : inline Address* c_entry_fp_address() {
625 61532 : return &thread_local_top()->c_entry_fp_;
626 : }
627 61532 : inline Address* handler_address() { return &thread_local_top()->handler_; }
628 : inline Address* c_function_address() {
629 61532 : return &thread_local_top()->c_function_;
630 : }
631 :
632 : // Bottom JS entry.
633 65291 : Address js_entry_sp() { return thread_local_top()->js_entry_sp_; }
634 : inline Address* js_entry_sp_address() {
635 61532 : return &thread_local_top()->js_entry_sp_;
636 : }
637 :
638 : // Returns the global object of the current context. It could be
639 : // a builtin object, or a JS global object.
640 : inline Handle<JSGlobalObject> global_object();
641 :
642 : // Returns the global proxy object of the current context.
643 : inline Handle<JSGlobalProxy> global_proxy();
644 :
645 : static int ArchiveSpacePerThread() { return sizeof(ThreadLocalTop); }
646 67436 : void FreeThreadResources() { thread_local_top()->Free(); }
647 :
648 : // This method is called by the api after operations that may throw
649 : // exceptions. If an exception was thrown and not handled by an external
650 : // handler the exception is scheduled to be rethrown when we return to running
651 : // JavaScript code. If an exception is scheduled true is returned.
652 : V8_EXPORT_PRIVATE bool OptionalRescheduleException(bool clear_exception);
653 :
654 : // Push and pop a promise and the current try-catch handler.
655 : void PushPromise(Handle<JSObject> promise);
656 : void PopPromise();
657 :
658 : // Return the relevant Promise that a throw/rejection pertains to, based
659 : // on the contents of the Promise stack
660 : Handle<Object> GetPromiseOnStackOnThrow();
661 :
662 : // Heuristically guess whether a Promise is handled by user catch handler
663 : bool PromiseHasUserDefinedRejectHandler(Handle<Object> promise);
664 :
665 : class ExceptionScope {
666 : public:
667 : // Scope currently can only be used for regular exceptions,
668 : // not termination exception.
669 : inline explicit ExceptionScope(Isolate* isolate);
670 : inline ~ExceptionScope();
671 :
672 : private:
673 : Isolate* isolate_;
674 : Handle<Object> pending_exception_;
675 : };
676 :
677 : void SetCaptureStackTraceForUncaughtExceptions(
678 : bool capture,
679 : int frame_limit,
680 : StackTrace::StackTraceOptions options);
681 :
682 : void SetAbortOnUncaughtExceptionCallback(
683 : v8::Isolate::AbortOnUncaughtExceptionCallback callback);
684 :
685 : enum PrintStackMode { kPrintStackConcise, kPrintStackVerbose };
686 : void PrintCurrentStackTrace(FILE* out);
687 : void PrintStack(StringStream* accumulator,
688 : PrintStackMode mode = kPrintStackVerbose);
689 : V8_EXPORT_PRIVATE void PrintStack(FILE* out,
690 : PrintStackMode mode = kPrintStackVerbose);
691 : Handle<String> StackTraceString();
692 : // Stores a stack trace in a stack-allocated temporary buffer which will
693 : // end up in the minidump for debugging purposes.
694 : V8_NOINLINE void PushStackTraceAndDie(void* ptr1 = nullptr,
695 : void* ptr2 = nullptr,
696 : void* ptr3 = nullptr,
697 : void* ptr4 = nullptr);
698 : Handle<FixedArray> CaptureCurrentStackTrace(
699 : int frame_limit, StackTrace::StackTraceOptions options);
700 : Handle<Object> CaptureSimpleStackTrace(Handle<JSReceiver> error_object,
701 : FrameSkipMode mode,
702 : Handle<Object> caller);
703 : MaybeHandle<JSReceiver> CaptureAndSetDetailedStackTrace(
704 : Handle<JSReceiver> error_object);
705 : MaybeHandle<JSReceiver> CaptureAndSetSimpleStackTrace(
706 : Handle<JSReceiver> error_object, FrameSkipMode mode,
707 : Handle<Object> caller);
708 : Handle<FixedArray> GetDetailedStackTrace(Handle<JSObject> error_object);
709 :
710 : Address GetAbstractPC(int* line, int* column);
711 :
712 : // Returns if the given context may access the given global object. If
713 : // the result is false, the pending exception is guaranteed to be
714 : // set.
715 : bool MayAccess(Handle<Context> accessing_context, Handle<JSObject> receiver);
716 :
717 : void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback);
718 : void ReportFailedAccessCheck(Handle<JSObject> receiver);
719 :
720 : // Exception throwing support. The caller should use the result
721 : // of Throw() as its return value.
722 : Object Throw(Object exception, MessageLocation* location = nullptr);
723 : Object ThrowIllegalOperation();
724 :
725 : template <typename T>
726 : V8_WARN_UNUSED_RESULT MaybeHandle<T> Throw(
727 : Handle<Object> exception, MessageLocation* location = nullptr) {
728 320114 : Throw(*exception, location);
729 : return MaybeHandle<T>();
730 : }
731 :
732 : void set_console_delegate(debug::ConsoleDelegate* delegate) {
733 37837 : console_delegate_ = delegate;
734 : }
735 : debug::ConsoleDelegate* console_delegate() { return console_delegate_; }
736 :
737 : void set_async_event_delegate(debug::AsyncEventDelegate* delegate) {
738 460 : async_event_delegate_ = delegate;
739 460 : PromiseHookStateUpdated();
740 : }
741 : void OnAsyncFunctionStateChanged(Handle<JSPromise> promise,
742 : debug::DebugAsyncActionType);
743 :
744 : // Re-throw an exception. This involves no error reporting since error
745 : // reporting was handled when the exception was thrown originally.
746 : Object ReThrow(Object exception);
747 :
748 : // Find the correct handler for the current pending exception. This also
749 : // clears and returns the current pending exception.
750 : Object UnwindAndFindHandler();
751 :
752 : // Tries to predict whether an exception will be caught. Note that this can
753 : // only produce an estimate, because it is undecidable whether a finally
754 : // clause will consume or re-throw an exception.
755 : enum CatchType {
756 : NOT_CAUGHT,
757 : CAUGHT_BY_JAVASCRIPT,
758 : CAUGHT_BY_EXTERNAL,
759 : CAUGHT_BY_DESUGARING,
760 : CAUGHT_BY_PROMISE,
761 : CAUGHT_BY_ASYNC_AWAIT
762 : };
763 : CatchType PredictExceptionCatcher();
764 :
765 : V8_EXPORT_PRIVATE void ScheduleThrow(Object exception);
766 : // Re-set pending message, script and positions reported to the TryCatch
767 : // back to the TLS for re-use when rethrowing.
768 : void RestorePendingMessageFromTryCatch(v8::TryCatch* handler);
769 : // Un-schedule an exception that was caught by a TryCatch handler.
770 : void CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler);
771 : void ReportPendingMessages();
772 : void ReportPendingMessagesFromJavaScript();
773 :
774 : // Implements code shared between the two above methods
775 : void ReportPendingMessagesImpl(bool report_externally);
776 :
777 : // Return pending location if any or unfilled structure.
778 : MessageLocation GetMessageLocation();
779 :
780 : // Promote a scheduled exception to pending. Asserts has_scheduled_exception.
781 : Object PromoteScheduledException();
782 :
783 : // Attempts to compute the current source location, storing the
784 : // result in the target out parameter. The source location is attached to a
785 : // Message object as the location which should be shown to the user. It's
786 : // typically the top-most meaningful location on the stack.
787 : bool ComputeLocation(MessageLocation* target);
788 : bool ComputeLocationFromException(MessageLocation* target,
789 : Handle<Object> exception);
790 : bool ComputeLocationFromStackTrace(MessageLocation* target,
791 : Handle<Object> exception);
792 :
793 : Handle<JSMessageObject> CreateMessage(Handle<Object> exception,
794 : MessageLocation* location);
795 :
796 : // Out of resource exception helpers.
797 : Object StackOverflow();
798 : Object TerminateExecution();
799 : void CancelTerminateExecution();
800 :
801 : void RequestInterrupt(InterruptCallback callback, void* data);
802 : void InvokeApiInterruptCallbacks();
803 :
804 : // Administration
805 : void Iterate(RootVisitor* v);
806 : void Iterate(RootVisitor* v, ThreadLocalTop* t);
807 : char* Iterate(RootVisitor* v, char* t);
808 : void IterateThread(ThreadVisitor* v, char* t);
809 :
810 : // Returns the current native context.
811 : inline Handle<NativeContext> native_context();
812 : inline NativeContext raw_native_context();
813 :
814 : Handle<Context> GetIncumbentContext();
815 :
816 : void RegisterTryCatchHandler(v8::TryCatch* that);
817 : void UnregisterTryCatchHandler(v8::TryCatch* that);
818 :
819 : char* ArchiveThread(char* to);
820 : char* RestoreThread(char* from);
821 :
822 : static const int kUC16AlphabetSize = 256; // See StringSearchBase.
823 : static const int kBMMaxShift = 250; // See StringSearchBase.
824 :
825 : // Accessors.
826 : #define GLOBAL_ACCESSOR(type, name, initialvalue) \
827 : inline type name() const { \
828 : DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
829 : return name##_; \
830 : } \
831 : inline void set_##name(type value) { \
832 : DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
833 : name##_ = value; \
834 : }
835 67063665 : ISOLATE_INIT_LIST(GLOBAL_ACCESSOR)
836 : #undef GLOBAL_ACCESSOR
837 :
838 : #define GLOBAL_ARRAY_ACCESSOR(type, name, length) \
839 : inline type* name() { \
840 : DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
841 : return &(name##_)[0]; \
842 : }
843 4528231 : ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_ACCESSOR)
844 : #undef GLOBAL_ARRAY_ACCESSOR
845 :
846 : #define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name) \
847 : inline Handle<type> name(); \
848 : inline bool is_##name(type value);
849 : NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
850 : #undef NATIVE_CONTEXT_FIELD_ACCESSOR
851 :
852 : Bootstrapper* bootstrapper() { return bootstrapper_; }
853 : // Use for updating counters on a foreground thread.
854 3476 : Counters* counters() { return async_counters().get(); }
855 : // Use for updating counters on a background thread.
856 3476 : const std::shared_ptr<Counters>& async_counters() {
857 : // Make sure InitializeCounters() has been called.
858 : DCHECK_NOT_NULL(async_counters_.get());
859 3476 : return async_counters_;
860 : }
861 : RuntimeProfiler* runtime_profiler() { return runtime_profiler_; }
862 56 : CompilationCache* compilation_cache() { return compilation_cache_; }
863 : Logger* logger() {
864 : // Call InitializeLoggingAndCounters() if logging is needed before
865 : // the isolate is fully initialized.
866 : DCHECK_NOT_NULL(logger_);
867 : return logger_;
868 : }
869 18200706 : StackGuard* stack_guard() { return &stack_guard_; }
870 3872959497 : Heap* heap() { return &heap_; }
871 9408 : static Isolate* FromHeap(Heap* heap) {
872 4084934100 : return reinterpret_cast<Isolate*>(reinterpret_cast<Address>(heap) -
873 4084933950 : OFFSET_OF(Isolate, heap_));
874 : }
875 :
876 13214433 : const IsolateData* isolate_data() const { return &isolate_data_; }
877 18050944 : IsolateData* isolate_data() { return &isolate_data_; }
878 :
879 : // Generated code can embed this address to get access to the isolate-specific
880 : // data (for example, roots, external references, builtins, etc.).
881 : // The kRootRegister is set to this value.
882 : Address isolate_root() const { return isolate_data()->isolate_root(); }
883 : static size_t isolate_root_bias() {
884 : return OFFSET_OF(Isolate, isolate_data_) + IsolateData::kIsolateRootBias;
885 : }
886 :
887 69608 : RootsTable& roots_table() { return isolate_data()->roots(); }
888 :
889 : // A sub-region of the Isolate object that has "predictable" layout which
890 : // depends only on the pointer size and therefore it's guaranteed that there
891 : // will be no compatibility issues because of different compilers used for
892 : // snapshot generator and actual V8 code.
893 : // Thus, kRootRegister may be used to address any location that falls into
894 : // this region.
895 : // See IsolateData::AssertPredictableLayout() for details.
896 : base::AddressRegion root_register_addressable_region() const {
897 : return base::AddressRegion(reinterpret_cast<Address>(&isolate_data_),
898 909384 : sizeof(IsolateData));
899 : }
900 :
901 957681413 : Object root(RootIndex index) { return Object(roots_table()[index]); }
902 :
903 : Handle<Object> root_handle(RootIndex index) {
904 : return Handle<Object>(&roots_table()[index]);
905 : }
906 :
907 : ExternalReferenceTable* external_reference_table() {
908 : DCHECK(isolate_data()->external_reference_table()->is_initialized());
909 : return isolate_data()->external_reference_table();
910 : }
911 :
912 : Address* builtin_entry_table() { return isolate_data_.builtin_entry_table(); }
913 : V8_INLINE Address* builtins_table() { return isolate_data_.builtins(); }
914 :
915 224 : StubCache* load_stub_cache() { return load_stub_cache_; }
916 56 : StubCache* store_stub_cache() { return store_stub_cache_; }
917 : DeoptimizerData* deoptimizer_data() { return deoptimizer_data_; }
918 : bool deoptimizer_lazy_throw() const { return deoptimizer_lazy_throw_; }
919 : void set_deoptimizer_lazy_throw(bool value) {
920 10736 : deoptimizer_lazy_throw_ = value;
921 : }
922 : ThreadLocalTop* thread_local_top() {
923 9112292 : return &isolate_data_.thread_local_top_;
924 : }
925 : ThreadLocalTop const* thread_local_top() const {
926 : return &isolate_data_.thread_local_top_;
927 : }
928 :
929 : static uint32_t thread_in_wasm_flag_address_offset() {
930 : // For WebAssembly trap handlers there is a flag in thread-local storage
931 : // which indicates that the executing thread executes WebAssembly code. To
932 : // access this flag directly from generated code, we store a pointer to the
933 : // flag in ThreadLocalTop in thread_in_wasm_flag_address_. This function
934 : // here returns the offset of that member from {isolate_root()}.
935 : return static_cast<uint32_t>(
936 : OFFSET_OF(Isolate, thread_local_top()->thread_in_wasm_flag_address_) -
937 291760 : isolate_root_bias());
938 : }
939 :
940 : MaterializedObjectStore* materialized_object_store() {
941 : return materialized_object_store_;
942 : }
943 :
944 56 : DescriptorLookupCache* descriptor_lookup_cache() {
945 56 : return descriptor_lookup_cache_;
946 : }
947 :
948 151377 : HandleScopeData* handle_scope_data() { return &handle_scope_data_; }
949 :
950 : HandleScopeImplementer* handle_scope_implementer() {
951 : DCHECK(handle_scope_implementer_);
952 : return handle_scope_implementer_;
953 : }
954 :
955 : UnicodeCache* unicode_cache() {
956 : return unicode_cache_;
957 : }
958 :
959 : InnerPointerToCodeCache* inner_pointer_to_code_cache() {
960 : return inner_pointer_to_code_cache_;
961 : }
962 :
963 : GlobalHandles* global_handles() { return global_handles_; }
964 :
965 : EternalHandles* eternal_handles() { return eternal_handles_; }
966 :
967 : ThreadManager* thread_manager() { return thread_manager_; }
968 :
969 : unibrow::Mapping<unibrow::Ecma262UnCanonicalize>* jsregexp_uncanonicalize() {
970 7757887 : return &jsregexp_uncanonicalize_;
971 : }
972 :
973 : unibrow::Mapping<unibrow::CanonicalizationRange>* jsregexp_canonrange() {
974 7731409 : return &jsregexp_canonrange_;
975 : }
976 :
977 : RuntimeState* runtime_state() { return &runtime_state_; }
978 :
979 55169214 : Builtins* builtins() { return &builtins_; }
980 :
981 : unibrow::Mapping<unibrow::Ecma262Canonicalize>*
982 : regexp_macro_assembler_canonicalize() {
983 421120 : return ®exp_macro_assembler_canonicalize_;
984 : }
985 :
986 : RegExpStack* regexp_stack() { return regexp_stack_; }
987 :
988 : size_t total_regexp_code_generated() { return total_regexp_code_generated_; }
989 : void IncreaseTotalRegexpCodeGenerated(int size) {
990 85312 : total_regexp_code_generated_ += size;
991 : }
992 :
993 32234 : std::vector<int>* regexp_indices() { return ®exp_indices_; }
994 :
995 : unibrow::Mapping<unibrow::Ecma262Canonicalize>*
996 : interp_canonicalize_mapping() {
997 : return ®exp_macro_assembler_canonicalize_;
998 : }
999 :
1000 : Debug* debug() { return debug_; }
1001 :
1002 61646 : bool* is_profiling_address() { return &is_profiling_; }
1003 111384 : CodeEventDispatcher* code_event_dispatcher() const {
1004 111384 : 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 126112 : 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 126112 : return (v8::internal::Factory*)this; // NOLINT(readability/casting)
1017 : }
1018 :
1019 : static const int kJSRegexpStaticOffsetsVectorSize = 128;
1020 :
1021 16222897 : THREAD_LOCAL_TOP_ACCESSOR(ExternalCallbackScope*, external_callback_scope)
1022 :
1023 210866254 : 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 60 : return isolate_data_.embedder_data_[slot];
1032 : }
1033 :
1034 38920 : bool serializer_enabled() const { return serializer_enabled_; }
1035 :
1036 251 : void enable_serializer() { serializer_enabled_ = true; }
1037 :
1038 : bool snapshot_available() const {
1039 336451 : return snapshot_blob_ != nullptr && snapshot_blob_->raw_size != 0;
1040 : }
1041 :
1042 : bool IsDead() { return has_fatal_error_; }
1043 10 : void SignalFatalError() { has_fatal_error_ = true; }
1044 :
1045 : bool use_optimizer();
1046 :
1047 : bool initialized_from_snapshot() { return initialized_from_snapshot_; }
1048 :
1049 : bool NeedsSourcePositionsForProfiling() const;
1050 :
1051 : 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 2451299 : 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 95002 : return heap_.MonotonicallyIncreasingTimeInMs() - time_millis_at_init_;
1092 : }
1093 :
1094 : DateCache* date_cache() {
1095 : return date_cache_;
1096 : }
1097 :
1098 : 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 474 : 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 : 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 722217 : UpdateNoElementsProtectorOnSetElement(object);
1207 : }
1208 : void UpdateNoElementsProtectorOnSetPrototype(Handle<JSObject> object) {
1209 184598 : UpdateNoElementsProtectorOnSetElement(object);
1210 : }
1211 : void UpdateNoElementsProtectorOnNormalizeElements(Handle<JSObject> object) {
1212 293059 : 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 : CodeTracer* GetCodeTracer();
1259 :
1260 : void DumpAndResetStats();
1261 :
1262 61822 : void* stress_deopt_count_address() { return &stress_deopt_count_; }
1263 :
1264 20 : void set_force_slow_path(bool v) { force_slow_path_ = v; }
1265 : bool force_slow_path() const { return force_slow_path_; }
1266 61534 : bool* force_slow_path_address() { return &force_slow_path_; }
1267 :
1268 : DebugInfo::ExecutionMode* debug_execution_mode_address() {
1269 61538 : 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 : Code FindCodeObject(Address a);
1282 :
1283 : int NextOptimizationId() {
1284 482575 : int id = next_optimization_id_++;
1285 482575 : if (!Smi::IsValid(next_optimization_id_)) {
1286 0 : 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 : void SetUseCounterCallback(v8::Isolate::UseCounterCallback callback);
1312 : void CountUsage(v8::Isolate::UseCounterFeature feature);
1313 :
1314 : static std::string GetTurboCfgFileName(Isolate* isolate);
1315 :
1316 : #if V8_SFI_HAS_UNIQUE_ID
1317 : int GetNextUniqueSharedFunctionInfoId() { return next_unique_sfi_id_++; }
1318 : #endif
1319 :
1320 : Address promise_hook_address() {
1321 61590 : return reinterpret_cast<Address>(&promise_hook_);
1322 : }
1323 :
1324 : Address async_event_delegate_address() {
1325 61758 : return reinterpret_cast<Address>(&async_event_delegate_);
1326 : }
1327 :
1328 : Address promise_hook_or_async_event_delegate_address() {
1329 62290 : return reinterpret_cast<Address>(&promise_hook_or_async_event_delegate_);
1330 : }
1331 :
1332 : Address promise_hook_or_debug_is_active_or_async_event_delegate_address() {
1333 : return reinterpret_cast<Address>(
1334 62710 : &promise_hook_or_debug_is_active_or_async_event_delegate_);
1335 : }
1336 :
1337 : Address handle_scope_implementer_address() {
1338 62206 : return reinterpret_cast<Address>(&handle_scope_implementer_);
1339 : }
1340 :
1341 : void SetAtomicsWaitCallback(v8::Isolate::AtomicsWaitCallback callback,
1342 : void* data);
1343 : void RunAtomicsWaitCallback(v8::Isolate::AtomicsWaitEvent event,
1344 : Handle<JSArrayBuffer> array_buffer,
1345 : size_t offset_in_bytes, int64_t value,
1346 : double timeout_in_ms,
1347 : AtomicsWaitWakeHandle* stop_handle);
1348 :
1349 : void SetPromiseHook(PromiseHook hook);
1350 : void RunPromiseHook(PromiseHookType type, Handle<JSPromise> promise,
1351 : Handle<Object> parent);
1352 : void PromiseHookStateUpdated();
1353 :
1354 : void AddDetachedContext(Handle<Context> context);
1355 : void CheckDetachedContextsAfterGC();
1356 :
1357 : std::vector<Object>* partial_snapshot_cache() {
1358 276627 : return &partial_snapshot_cache_;
1359 : }
1360 :
1361 : // Off-heap builtins cannot embed constants within the code object itself,
1362 : // and thus need to load them from the root list.
1363 84840 : bool IsGeneratingEmbeddedBuiltins() const {
1364 : return FLAG_embedded_builtins &&
1365 84840 : builtins_constants_table_builder() != nullptr;
1366 : }
1367 :
1368 84840 : BuiltinsConstantsTableBuilder* builtins_constants_table_builder() const {
1369 84840 : 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 61689 : array_buffer_allocator_ = allocator;
1388 : }
1389 : v8::ArrayBuffer::Allocator* array_buffer_allocator() const {
1390 : return array_buffer_allocator_;
1391 : }
1392 :
1393 995245 : 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 : 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 14677 : compiler_cache_ = cache;
1411 14677 : compiler_zone_ = zone;
1412 : }
1413 :
1414 65464 : 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_.load(); }
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 61251 : 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 15 : elements_deletion_counter_ = value;
1483 : }
1484 :
1485 : 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 : bool Init(ReadOnlyDeserializer* read_only_deserializer,
1503 : StartupDeserializer* startup_deserializer);
1504 :
1505 : void CheckIsolateLayout();
1506 :
1507 61518 : class ThreadDataTable {
1508 : public:
1509 : ThreadDataTable() = default;
1510 :
1511 : PerIsolateThreadData* Lookup(ThreadId thread_id);
1512 : void Insert(PerIsolateThreadData* data);
1513 : void Remove(PerIsolateThreadData* data);
1514 : void RemoveAllThreads();
1515 :
1516 : private:
1517 : struct Hasher {
1518 : std::size_t operator()(const ThreadId& t) const {
1519 : return std::hash<int>()(t.ToInteger());
1520 : }
1521 : };
1522 :
1523 : std::unordered_map<ThreadId, PerIsolateThreadData*, Hasher> table_;
1524 : };
1525 :
1526 : // These items form a stack synchronously with threads Enter'ing and Exit'ing
1527 : // the Isolate. The top of the stack points to a thread which is currently
1528 : // running the Isolate. When the stack is empty, the Isolate is considered
1529 : // not entered by any thread and can be Disposed.
1530 : // If the same thread enters the Isolate more than once, the entry_count_
1531 : // is incremented rather then a new item pushed to the stack.
1532 : class EntryStackItem {
1533 : public:
1534 : EntryStackItem(PerIsolateThreadData* previous_thread_data,
1535 : Isolate* previous_isolate,
1536 : EntryStackItem* previous_item)
1537 : : entry_count(1),
1538 : previous_thread_data(previous_thread_data),
1539 : previous_isolate(previous_isolate),
1540 211893 : previous_item(previous_item) { }
1541 :
1542 : int entry_count;
1543 : PerIsolateThreadData* previous_thread_data;
1544 : Isolate* previous_isolate;
1545 : EntryStackItem* previous_item;
1546 :
1547 : private:
1548 : DISALLOW_COPY_AND_ASSIGN(EntryStackItem);
1549 : };
1550 :
1551 : static base::Thread::LocalStorageKey per_isolate_thread_data_key_;
1552 : static base::Thread::LocalStorageKey isolate_key_;
1553 :
1554 : #ifdef DEBUG
1555 : static std::atomic<bool> 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 : const int 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 : std::atomic<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 64792 : 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> partial_snapshot_cache_;
1759 :
1760 : // Used during builtins compilation to build the builtins constants table,
1761 : // which is stored on the root list prior to serialization.
1762 : BuiltinsConstantsTableBuilder* builtins_constants_table_builder_ = nullptr;
1763 :
1764 : void InitializeDefaultEmbeddedBlob();
1765 : void CreateAndSetEmbeddedBlob();
1766 : void TearDownEmbeddedBlob();
1767 :
1768 : void SetEmbeddedBlob(const uint8_t* blob, uint32_t blob_size);
1769 : void ClearEmbeddedBlob();
1770 :
1771 : const uint8_t* embedded_blob_ = nullptr;
1772 : uint32_t embedded_blob_size_ = 0;
1773 :
1774 : v8::ArrayBuffer::Allocator* array_buffer_allocator_ = nullptr;
1775 :
1776 : FutexWaitListNode futex_wait_list_node_;
1777 :
1778 : CancelableTaskManager* cancelable_task_manager_ = nullptr;
1779 :
1780 : debug::ConsoleDelegate* console_delegate_ = nullptr;
1781 :
1782 : debug::AsyncEventDelegate* async_event_delegate_ = nullptr;
1783 : bool promise_hook_or_async_event_delegate_ = false;
1784 : bool promise_hook_or_debug_is_active_or_async_event_delegate_ = false;
1785 : int async_task_count_ = 0;
1786 :
1787 : v8::Isolate::AbortOnUncaughtExceptionCallback
1788 : abort_on_uncaught_exception_callback_ = nullptr;
1789 :
1790 : bool allow_atomics_wait_ = true;
1791 :
1792 : base::Mutex managed_ptr_destructors_mutex_;
1793 : ManagedPtrDestructor* managed_ptr_destructors_head_ = nullptr;
1794 :
1795 : size_t total_regexp_code_generated_ = 0;
1796 :
1797 : size_t elements_deletion_counter_ = 0;
1798 :
1799 : std::shared_ptr<wasm::WasmEngine> wasm_engine_;
1800 :
1801 : std::unique_ptr<TracingCpuProfilerImpl> tracing_cpu_profiler_;
1802 :
1803 : EmbeddedFileWriterInterface* embedded_file_writer_ = nullptr;
1804 :
1805 : // The top entry of the v8::Context::BackupIncumbentScope stack.
1806 : const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope_ =
1807 : nullptr;
1808 :
1809 : PrepareStackTraceCallback prepare_stack_trace_callback_ = nullptr;
1810 :
1811 : // TODO(kenton@cloudflare.com): This mutex can be removed if
1812 : // thread_data_table_ is always accessed under the isolate lock. I do not
1813 : // know if this is the case, so I'm preserving it for now.
1814 : base::Mutex thread_data_table_mutex_;
1815 : ThreadDataTable thread_data_table_;
1816 :
1817 : // Delete new/delete operators to ensure that Isolate::New() and
1818 : // Isolate::Delete() are used for Isolate creation and deletion.
1819 : void* operator new(size_t, void* ptr) { return ptr; }
1820 : void* operator new(size_t) = delete;
1821 : void operator delete(void*) = delete;
1822 :
1823 : friend class heap::HeapTester;
1824 : friend class TestSerializer;
1825 :
1826 : DISALLOW_COPY_AND_ASSIGN(Isolate);
1827 : };
1828 :
1829 : #undef FIELD_ACCESSOR
1830 : #undef THREAD_LOCAL_TOP_ACCESSOR
1831 :
1832 : class PromiseOnStack {
1833 : public:
1834 : PromiseOnStack(Handle<JSObject> promise, PromiseOnStack* prev)
1835 17420 : : promise_(promise), prev_(prev) {}
1836 : Handle<JSObject> promise() { return promise_; }
1837 : PromiseOnStack* prev() { return prev_; }
1838 :
1839 : private:
1840 : Handle<JSObject> promise_;
1841 : PromiseOnStack* prev_;
1842 : };
1843 :
1844 : // SaveContext scopes save the current context on the Isolate on creation, and
1845 : // restore it on destruction.
1846 : class V8_EXPORT_PRIVATE SaveContext {
1847 : public:
1848 : explicit SaveContext(Isolate* isolate);
1849 :
1850 : ~SaveContext();
1851 :
1852 : Handle<Context> context() { return context_; }
1853 :
1854 : // Returns true if this save context is below a given JavaScript frame.
1855 : bool IsBelowFrame(StandardFrame* frame);
1856 :
1857 : private:
1858 : Isolate* const isolate_;
1859 : Handle<Context> context_;
1860 : Address c_entry_fp_;
1861 : };
1862 :
1863 : // Like SaveContext, but also switches the Context to a new one in the
1864 : // constructor.
1865 211378 : class V8_EXPORT_PRIVATE SaveAndSwitchContext : public SaveContext {
1866 : public:
1867 : SaveAndSwitchContext(Isolate* isolate, Context new_context);
1868 : };
1869 :
1870 : class AssertNoContextChange {
1871 : #ifdef DEBUG
1872 : public:
1873 : explicit AssertNoContextChange(Isolate* isolate);
1874 : ~AssertNoContextChange() {
1875 : DCHECK(isolate_->context() == *context_);
1876 : }
1877 :
1878 : private:
1879 : Isolate* isolate_;
1880 : Handle<Context> context_;
1881 : #else
1882 : public:
1883 : explicit AssertNoContextChange(Isolate* isolate) { }
1884 : #endif
1885 : };
1886 :
1887 : class ExecutionAccess {
1888 : public:
1889 105806 : explicit ExecutionAccess(Isolate* isolate) : isolate_(isolate) {
1890 : Lock(isolate);
1891 : }
1892 211610 : ~ExecutionAccess() { Unlock(isolate_); }
1893 :
1894 20641812 : static void Lock(Isolate* isolate) { isolate->break_access()->Lock(); }
1895 20568957 : static void Unlock(Isolate* isolate) { isolate->break_access()->Unlock(); }
1896 :
1897 : static bool TryLock(Isolate* isolate) {
1898 : return isolate->break_access()->TryLock();
1899 : }
1900 :
1901 : private:
1902 : Isolate* isolate_;
1903 : };
1904 :
1905 :
1906 : // Support for checking for stack-overflows.
1907 : class StackLimitCheck {
1908 : public:
1909 54861588 : explicit StackLimitCheck(Isolate* isolate) : isolate_(isolate) { }
1910 :
1911 : // Use this to check for stack-overflows in C++ code.
1912 : bool HasOverflowed() const {
1913 : StackGuard* stack_guard = isolate_->stack_guard();
1914 437804961 : return GetCurrentStackPosition() < stack_guard->real_climit();
1915 : }
1916 :
1917 : // Use this to check for interrupt request in C++ code.
1918 52174303 : bool InterruptRequested() {
1919 52174303 : StackGuard* stack_guard = isolate_->stack_guard();
1920 104348606 : return GetCurrentStackPosition() < stack_guard->climit();
1921 : }
1922 :
1923 : // Use this to check for stack-overflow when entering runtime from JS code.
1924 : bool JsHasOverflowed(uintptr_t gap = 0) const;
1925 :
1926 : private:
1927 : Isolate* isolate_;
1928 : };
1929 :
1930 : #define STACK_CHECK(isolate, result_value) \
1931 : do { \
1932 : StackLimitCheck stack_check(isolate); \
1933 : if (stack_check.HasOverflowed()) { \
1934 : isolate->StackOverflow(); \
1935 : return result_value; \
1936 : } \
1937 : } while (false)
1938 :
1939 : // Scope intercepts only interrupt which is part of its interrupt_mask and does
1940 : // not affect other interrupts.
1941 : class InterruptsScope {
1942 : public:
1943 : enum Mode { kPostponeInterrupts, kRunInterrupts, kNoop };
1944 :
1945 30573082 : virtual ~InterruptsScope() {
1946 15286537 : if (mode_ != kNoop) stack_guard_->PopInterruptsScope();
1947 0 : }
1948 :
1949 : // Find the scope that intercepts this interrupt.
1950 : // It may be outermost PostponeInterruptsScope or innermost
1951 : // SafeForInterruptsScope if any.
1952 : // Return whether the interrupt has been intercepted.
1953 : bool Intercept(StackGuard::InterruptFlag flag);
1954 :
1955 : InterruptsScope(Isolate* isolate, int intercept_mask, Mode mode)
1956 : : stack_guard_(isolate->stack_guard()),
1957 : intercept_mask_(intercept_mask),
1958 : intercepted_flags_(0),
1959 30573061 : mode_(mode) {
1960 15286533 : if (mode_ != kNoop) stack_guard_->PushInterruptsScope(this);
1961 : }
1962 :
1963 : private:
1964 : StackGuard* stack_guard_;
1965 : int intercept_mask_;
1966 : int intercepted_flags_;
1967 : Mode mode_;
1968 : InterruptsScope* prev_;
1969 :
1970 : friend class StackGuard;
1971 : };
1972 :
1973 : // Support for temporarily postponing interrupts. When the outermost
1974 : // postpone scope is left the interrupts will be re-enabled and any
1975 : // interrupts that occurred while in the scope will be taken into
1976 : // account.
1977 : class PostponeInterruptsScope : public InterruptsScope {
1978 : public:
1979 : PostponeInterruptsScope(Isolate* isolate,
1980 : int intercept_mask = StackGuard::ALL_INTERRUPTS)
1981 : : InterruptsScope(isolate, intercept_mask,
1982 3118569 : InterruptsScope::kPostponeInterrupts) {}
1983 5724689 : ~PostponeInterruptsScope() override = default;
1984 : };
1985 :
1986 : // Support for overriding PostponeInterruptsScope. Interrupt is not ignored if
1987 : // innermost scope is SafeForInterruptsScope ignoring any outer
1988 : // PostponeInterruptsScopes.
1989 : class SafeForInterruptsScope : public InterruptsScope {
1990 : public:
1991 : SafeForInterruptsScope(Isolate* isolate,
1992 : int intercept_mask = StackGuard::ALL_INTERRUPTS)
1993 : : InterruptsScope(isolate, intercept_mask,
1994 11364 : InterruptsScope::kRunInterrupts) {}
1995 22728 : ~SafeForInterruptsScope() override = default;
1996 : };
1997 :
1998 : class StackTraceFailureMessage {
1999 : public:
2000 : explicit StackTraceFailureMessage(Isolate* isolate, void* ptr1 = nullptr,
2001 : void* ptr2 = nullptr, void* ptr3 = nullptr,
2002 : void* ptr4 = nullptr);
2003 :
2004 : V8_NOINLINE void Print() volatile;
2005 :
2006 : static const uintptr_t kStartMarker = 0xdecade30;
2007 : static const uintptr_t kEndMarker = 0xdecade31;
2008 : static const int kStacktraceBufferSize = 32 * KB;
2009 :
2010 : uintptr_t start_marker_ = kStartMarker;
2011 : void* isolate_;
2012 : void* ptr1_;
2013 : void* ptr2_;
2014 : void* ptr3_;
2015 : void* ptr4_;
2016 : void* code_objects_[4];
2017 : char js_stack_trace_[kStacktraceBufferSize];
2018 : uintptr_t end_marker_ = kEndMarker;
2019 : };
2020 :
2021 : } // namespace internal
2022 : } // namespace v8
2023 :
2024 : #endif // V8_ISOLATE_H_
|