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