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