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 <memory>
10 : #include <queue>
11 : #include <vector>
12 :
13 : #include "include/v8-debug.h"
14 : #include "src/allocation.h"
15 : #include "src/base/atomicops.h"
16 : #include "src/builtins/builtins.h"
17 : #include "src/contexts.h"
18 : #include "src/date.h"
19 : #include "src/debug/debug-interface.h"
20 : #include "src/execution.h"
21 : #include "src/futex-emulation.h"
22 : #include "src/global-handles.h"
23 : #include "src/handles.h"
24 : #include "src/heap/heap.h"
25 : #include "src/messages.h"
26 : #include "src/objects/code.h"
27 : #include "src/regexp/regexp-stack.h"
28 : #include "src/runtime/runtime.h"
29 : #include "src/zone/zone.h"
30 :
31 : namespace v8 {
32 :
33 : namespace base {
34 : class RandomNumberGenerator;
35 : }
36 :
37 : namespace debug {
38 : class ConsoleDelegate;
39 : }
40 :
41 : namespace internal {
42 :
43 : namespace heap {
44 : class HeapTester;
45 : } // namespace heap
46 :
47 : class AccessCompilerData;
48 : class AddressToIndexHashMap;
49 : class AstStringConstants;
50 : class BasicBlockProfiler;
51 : class Bootstrapper;
52 : class CallInterfaceDescriptorData;
53 : class CancelableTaskManager;
54 : class CodeEventDispatcher;
55 : class CodeGenerator;
56 : class CodeRange;
57 : class CodeStubDescriptor;
58 : class CodeTracer;
59 : class CompilationCache;
60 : class CompilationStatistics;
61 : class CompilerDispatcher;
62 : class ContextSlotCache;
63 : class Counters;
64 : class CpuFeatures;
65 : class CpuProfiler;
66 : class Debug;
67 : class DeoptimizerData;
68 : class DescriptorLookupCache;
69 : class EmptyStatement;
70 : class ExternalCallbackScope;
71 : class ExternalReferenceTable;
72 : class Factory;
73 : class HandleScopeImplementer;
74 : class HeapObjectToIndexHashMap;
75 : class HeapProfiler;
76 : class InlineRuntimeFunctionsTable;
77 : class InnerPointerToCodeCache;
78 : class Logger;
79 : class MaterializedObjectStore;
80 : class OptimizingCompileDispatcher;
81 : class PromiseOnStack;
82 : class Redirection;
83 : class RegExpStack;
84 : class RootVisitor;
85 : class RuntimeProfiler;
86 : class SaveContext;
87 : class SetupIsolateDelegate;
88 : class Simulator;
89 : class StartupDeserializer;
90 : class StandardFrame;
91 : class StatsTable;
92 : class StringTracker;
93 : class StubCache;
94 : class SweeperThread;
95 : class ThreadManager;
96 : class ThreadState;
97 : class ThreadVisitor; // Defined in v8threads.h
98 : class UnicodeCache;
99 :
100 : template <StateTag Tag> class VMState;
101 :
102 : // 'void function pointer', used to roundtrip the
103 : // ExternalReference::ExternalReferenceRedirector since we can not include
104 : // assembler.h, where it is defined, here.
105 : typedef void* ExternalReferenceRedirectorPointer();
106 :
107 : namespace interpreter {
108 : class Interpreter;
109 : }
110 :
111 : namespace wasm {
112 : class CompilationManager;
113 : }
114 :
115 : #define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate) \
116 : do { \
117 : Isolate* __isolate__ = (isolate); \
118 : DCHECK(!__isolate__->has_pending_exception()); \
119 : if (__isolate__->has_scheduled_exception()) { \
120 : return __isolate__->PromoteScheduledException(); \
121 : } \
122 : } while (false)
123 :
124 : // Macros for MaybeHandle.
125 :
126 : #define RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, value) \
127 : do { \
128 : Isolate* __isolate__ = (isolate); \
129 : DCHECK(!__isolate__->has_pending_exception()); \
130 : if (__isolate__->has_scheduled_exception()) { \
131 : __isolate__->PromoteScheduledException(); \
132 : return value; \
133 : } \
134 : } while (false)
135 :
136 : #define RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, T) \
137 : RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, MaybeHandle<T>())
138 :
139 : #define ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, dst, call, value) \
140 : do { \
141 : Isolate* __isolate__ = (isolate); \
142 : if (!(call).ToLocal(&dst)) { \
143 : DCHECK(__isolate__->has_scheduled_exception()); \
144 : __isolate__->PromoteScheduledException(); \
145 : return value; \
146 : } \
147 : } while (false)
148 :
149 : #define RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, call, value) \
150 : do { \
151 : Isolate* __isolate__ = (isolate); \
152 : if ((call).IsNothing()) { \
153 : DCHECK(__isolate__->has_scheduled_exception()); \
154 : __isolate__->PromoteScheduledException(); \
155 : return value; \
156 : } \
157 : } while (false)
158 :
159 : #define RETURN_RESULT_OR_FAILURE(isolate, call) \
160 : do { \
161 : Handle<Object> __result__; \
162 : Isolate* __isolate__ = (isolate); \
163 : if (!(call).ToHandle(&__result__)) { \
164 : DCHECK(__isolate__->has_pending_exception()); \
165 : return __isolate__->heap()->exception(); \
166 : } \
167 : DCHECK(!__isolate__->has_pending_exception()); \
168 : return *__result__; \
169 : } while (false)
170 :
171 : #define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value) \
172 : do { \
173 : if (!(call).ToHandle(&dst)) { \
174 : DCHECK((isolate)->has_pending_exception()); \
175 : return value; \
176 : } \
177 : } while (false)
178 :
179 : #define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call) \
180 : do { \
181 : Isolate* __isolate__ = (isolate); \
182 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(__isolate__, dst, call, \
183 : __isolate__->heap()->exception()); \
184 : } while (false)
185 :
186 : #define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T) \
187 : ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, MaybeHandle<T>())
188 :
189 : #define THROW_NEW_ERROR(isolate, call, T) \
190 : do { \
191 : Isolate* __isolate__ = (isolate); \
192 : return __isolate__->Throw<T>(__isolate__->factory()->call); \
193 : } while (false)
194 :
195 : #define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call) \
196 : do { \
197 : Isolate* __isolate__ = (isolate); \
198 : return __isolate__->Throw(*__isolate__->factory()->call); \
199 : } while (false)
200 :
201 : #define RETURN_ON_EXCEPTION_VALUE(isolate, call, value) \
202 : do { \
203 : if ((call).is_null()) { \
204 : DCHECK((isolate)->has_pending_exception()); \
205 : return value; \
206 : } \
207 : } while (false)
208 :
209 : #define RETURN_FAILURE_ON_EXCEPTION(isolate, call) \
210 : do { \
211 : Isolate* __isolate__ = (isolate); \
212 : RETURN_ON_EXCEPTION_VALUE(__isolate__, call, \
213 : __isolate__->heap()->exception()); \
214 : } while (false);
215 :
216 : #define RETURN_ON_EXCEPTION(isolate, call, T) \
217 : RETURN_ON_EXCEPTION_VALUE(isolate, call, MaybeHandle<T>())
218 :
219 :
220 : #define FOR_WITH_HANDLE_SCOPE(isolate, loop_var_type, init, loop_var, \
221 : limit_check, increment, body) \
222 : do { \
223 : loop_var_type init; \
224 : loop_var_type for_with_handle_limit = loop_var; \
225 : Isolate* for_with_handle_isolate = isolate; \
226 : while (limit_check) { \
227 : for_with_handle_limit += 1024; \
228 : HandleScope loop_scope(for_with_handle_isolate); \
229 : for (; limit_check && loop_var < for_with_handle_limit; increment) { \
230 : body \
231 : } \
232 : } \
233 : } while (false)
234 :
235 : // Platform-independent, reliable thread identifier.
236 : class ThreadId {
237 : public:
238 : // Creates an invalid ThreadId.
239 109998 : ThreadId() { base::Relaxed_Store(&id_, kInvalidId); }
240 :
241 560272 : ThreadId& operator=(const ThreadId& other) {
242 1120544 : base::Relaxed_Store(&id_, base::Relaxed_Load(&other.id_));
243 560272 : return *this;
244 : }
245 :
246 : // Returns ThreadId for current thread.
247 7397159 : static ThreadId Current() { return ThreadId(GetCurrentThreadId()); }
248 :
249 : // Returns invalid ThreadId (guaranteed not to be equal to any thread).
250 440177 : static ThreadId Invalid() { return ThreadId(kInvalidId); }
251 :
252 : // Compares ThreadIds for equality.
253 : INLINE(bool Equals(const ThreadId& other) const) {
254 6181203 : return base::Relaxed_Load(&id_) == base::Relaxed_Load(&other.id_);
255 : }
256 :
257 : // Checks whether this ThreadId refers to any thread.
258 : INLINE(bool IsValid() const) {
259 30619 : return base::Relaxed_Load(&id_) != kInvalidId;
260 : }
261 :
262 : // Converts ThreadId to an integer representation
263 : // (required for public API: V8::V8::GetCurrentThreadId).
264 : int ToInteger() const { return static_cast<int>(base::Relaxed_Load(&id_)); }
265 :
266 : // Converts ThreadId to an integer representation
267 : // (required for public API: V8::V8::TerminateExecution).
268 : static ThreadId FromInteger(int id) { return ThreadId(id); }
269 :
270 : private:
271 : static const int kInvalidId = -1;
272 :
273 : explicit ThreadId(int id) { base::Relaxed_Store(&id_, id); }
274 :
275 : static int AllocateThreadId();
276 :
277 : V8_EXPORT_PRIVATE static int GetCurrentThreadId();
278 :
279 : base::Atomic32 id_;
280 :
281 : static base::Atomic32 highest_thread_id_;
282 :
283 : friend class Isolate;
284 : };
285 :
286 :
287 : #define FIELD_ACCESSOR(type, name) \
288 : inline void set_##name(type v) { name##_ = v; } \
289 : inline type name() const { return name##_; }
290 :
291 :
292 : class ThreadLocalTop BASE_EMBEDDED {
293 : public:
294 : // Does early low-level initialization that does not depend on the
295 : // isolate being present.
296 : ThreadLocalTop();
297 :
298 : // Initialize the thread data.
299 : void Initialize();
300 :
301 : // Get the top C++ try catch handler or nullptr if none are registered.
302 : //
303 : // This method is not guaranteed to return an address that can be
304 : // used for comparison with addresses into the JS stack. If such an
305 : // address is needed, use try_catch_handler_address.
306 33592073 : FIELD_ACCESSOR(v8::TryCatch*, try_catch_handler)
307 :
308 : // Get the address of the top C++ try catch handler or nullptr if
309 : // none are registered.
310 : //
311 : // This method always returns an address that can be compared to
312 : // pointers into the JavaScript stack. When running on actual
313 : // hardware, try_catch_handler_address and TryCatchHandler return
314 : // the same pointer. When running on a simulator with a separate JS
315 : // stack, try_catch_handler_address returns a JS stack address that
316 : // corresponds to the place on the JS stack where the C++ handler
317 : // would have been if the stack were not separate.
318 151205 : Address try_catch_handler_address() {
319 : return reinterpret_cast<Address>(
320 : v8::TryCatch::JSStackComparableAddress(try_catch_handler()));
321 : }
322 :
323 : void Free();
324 :
325 : Isolate* isolate_;
326 : // The context where the current execution method is created and for variable
327 : // lookups.
328 : Context* context_;
329 : ThreadId thread_id_;
330 : Object* pending_exception_;
331 : // TODO(kschimpf): Change this to a stack of caught exceptions (rather than
332 : // just innermost catching try block).
333 : Object* wasm_caught_exception_;
334 :
335 : // Communication channel between Isolate::FindHandler and the CEntryStub.
336 : Context* pending_handler_context_;
337 : Code* pending_handler_code_;
338 : intptr_t pending_handler_offset_;
339 : Address pending_handler_fp_;
340 : Address pending_handler_sp_;
341 :
342 : // Communication channel between Isolate::Throw and message consumers.
343 : bool rethrowing_message_;
344 : Object* pending_message_obj_;
345 :
346 : // Use a separate value for scheduled exceptions to preserve the
347 : // invariants that hold about pending_exception. We may want to
348 : // unify them later.
349 : Object* scheduled_exception_;
350 : bool external_caught_exception_;
351 : SaveContext* save_context_;
352 :
353 : // Stack.
354 : Address c_entry_fp_; // the frame pointer of the top c entry frame
355 : Address handler_; // try-blocks are chained through the stack
356 : Address c_function_; // C function that was called at c entry.
357 :
358 : // Throwing an exception may cause a Promise rejection. For this purpose
359 : // we keep track of a stack of nested promises and the corresponding
360 : // try-catch handlers.
361 : PromiseOnStack* promise_on_stack_;
362 :
363 : #ifdef USE_SIMULATOR
364 : Simulator* simulator_;
365 : #endif
366 :
367 : Address js_entry_sp_; // the stack pointer of the bottom JS entry frame
368 : // the external callback we're currently in
369 : ExternalCallbackScope* external_callback_scope_;
370 : StateTag current_vm_state_;
371 :
372 : // Call back function to report unsafe JS accesses.
373 : v8::FailedAccessCheckCallback failed_access_check_callback_;
374 :
375 : private:
376 : void InitializeInternal();
377 :
378 : v8::TryCatch* try_catch_handler_;
379 : };
380 :
381 :
382 : #if USE_SIMULATOR
383 :
384 : #define ISOLATE_INIT_SIMULATOR_LIST(V) \
385 : V(bool, simulator_initialized, false) \
386 : V(base::CustomMatcherHashMap*, simulator_i_cache, nullptr) \
387 : V(Redirection*, simulator_redirection, nullptr)
388 : #else
389 :
390 : #define ISOLATE_INIT_SIMULATOR_LIST(V)
391 :
392 : #endif
393 :
394 :
395 : #ifdef DEBUG
396 :
397 : #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V) \
398 : V(CommentStatistic, paged_space_comments_statistics, \
399 : CommentStatistic::kMaxComments + 1) \
400 : V(int, code_kind_statistics, AbstractCode::NUMBER_OF_KINDS)
401 : #else
402 :
403 : #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
404 :
405 : #endif
406 :
407 : #define ISOLATE_INIT_ARRAY_LIST(V) \
408 : /* SerializerDeserializer state. */ \
409 : V(int32_t, jsregexp_static_offsets_vector, kJSRegexpStaticOffsetsVectorSize) \
410 : V(int, bad_char_shift_table, kUC16AlphabetSize) \
411 : V(int, good_suffix_shift_table, (kBMMaxShift + 1)) \
412 : V(int, suffix_table, (kBMMaxShift + 1)) \
413 : ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
414 :
415 : typedef std::vector<HeapObject*> DebugObjectCache;
416 :
417 : #define ISOLATE_INIT_LIST(V) \
418 : /* Assembler state. */ \
419 : V(FatalErrorCallback, exception_behavior, nullptr) \
420 : V(OOMErrorCallback, oom_behavior, nullptr) \
421 : V(LogEventCallback, event_logger, nullptr) \
422 : V(AllowCodeGenerationFromStringsCallback, allow_code_gen_callback, nullptr) \
423 : V(ExtensionCallback, wasm_module_callback, &NoExtension) \
424 : V(ExtensionCallback, wasm_instance_callback, &NoExtension) \
425 : V(ApiImplementationCallback, wasm_compile_streaming_callback, nullptr) \
426 : V(ExternalReferenceRedirectorPointer*, external_reference_redirector, \
427 : nullptr) \
428 : /* State for Relocatable. */ \
429 : V(Relocatable*, relocatable_top, nullptr) \
430 : V(DebugObjectCache*, string_stream_debug_object_cache, nullptr) \
431 : V(Object*, string_stream_current_security_token, nullptr) \
432 : V(ExternalReferenceTable*, external_reference_table, nullptr) \
433 : V(const intptr_t*, api_external_references, nullptr) \
434 : V(AddressToIndexHashMap*, external_reference_map, nullptr) \
435 : V(HeapObjectToIndexHashMap*, root_index_map, nullptr) \
436 : V(int, pending_microtask_count, 0) \
437 : V(CompilationStatistics*, turbo_statistics, nullptr) \
438 : V(CodeTracer*, code_tracer, nullptr) \
439 : V(uint32_t, per_isolate_assert_data, 0xFFFFFFFFu) \
440 : V(PromiseRejectCallback, promise_reject_callback, nullptr) \
441 : V(const v8::StartupData*, snapshot_blob, nullptr) \
442 : V(int, code_and_metadata_size, 0) \
443 : V(int, bytecode_and_metadata_size, 0) \
444 : /* true if being profiled. Causes collection of extra compile info. */ \
445 : V(bool, is_profiling, false) \
446 : /* true if a trace is being formatted through Error.prepareStackTrace. */ \
447 : V(bool, formatting_stack_trace, false) \
448 : /* Perform side effect checks on function call and API callbacks. */ \
449 : V(bool, needs_side_effect_check, false) \
450 : /* Current code coverage mode */ \
451 : V(debug::Coverage::Mode, code_coverage_mode, debug::Coverage::kBestEffort) \
452 : V(debug::TypeProfile::Mode, type_profile_mode, debug::TypeProfile::kNone) \
453 : V(int, last_stack_frame_info_id, 0) \
454 : V(int, last_console_context_id, 0) \
455 : ISOLATE_INIT_SIMULATOR_LIST(V)
456 :
457 : #define THREAD_LOCAL_TOP_ACCESSOR(type, name) \
458 : inline void set_##name(type v) { thread_local_top_.name##_ = v; } \
459 : inline type name() const { return thread_local_top_.name##_; }
460 :
461 : #define THREAD_LOCAL_TOP_ADDRESS(type, name) \
462 : type* name##_address() { return &thread_local_top_.name##_; }
463 :
464 :
465 : class Isolate {
466 : // These forward declarations are required to make the friend declarations in
467 : // PerIsolateThreadData work on some older versions of gcc.
468 : class ThreadDataTable;
469 : class EntryStackItem;
470 : public:
471 : ~Isolate();
472 :
473 : // A thread has a PerIsolateThreadData instance for each isolate that it has
474 : // entered. That instance is allocated when the isolate is initially entered
475 : // and reused on subsequent entries.
476 : class PerIsolateThreadData {
477 : public:
478 : PerIsolateThreadData(Isolate* isolate, ThreadId thread_id)
479 : : isolate_(isolate),
480 : thread_id_(thread_id),
481 : stack_limit_(0),
482 : thread_state_(nullptr),
483 : #if USE_SIMULATOR
484 : simulator_(nullptr),
485 : #endif
486 : next_(nullptr),
487 60505 : prev_(nullptr) {
488 : }
489 : ~PerIsolateThreadData();
490 : Isolate* isolate() const { return isolate_; }
491 : ThreadId thread_id() const { return thread_id_; }
492 :
493 5856 : FIELD_ACCESSOR(uintptr_t, stack_limit)
494 52298 : FIELD_ACCESSOR(ThreadState*, thread_state)
495 :
496 : #if USE_SIMULATOR
497 : FIELD_ACCESSOR(Simulator*, simulator)
498 : #endif
499 :
500 3095412 : bool Matches(Isolate* isolate, ThreadId thread_id) const {
501 6020861 : return isolate_ == isolate && thread_id_.Equals(thread_id);
502 : }
503 :
504 : private:
505 : Isolate* isolate_;
506 : ThreadId thread_id_;
507 : uintptr_t stack_limit_;
508 : ThreadState* thread_state_;
509 :
510 : #if USE_SIMULATOR
511 : Simulator* simulator_;
512 : #endif
513 :
514 : PerIsolateThreadData* next_;
515 : PerIsolateThreadData* prev_;
516 :
517 : friend class Isolate;
518 : friend class ThreadDataTable;
519 : friend class EntryStackItem;
520 :
521 : DISALLOW_COPY_AND_ASSIGN(PerIsolateThreadData);
522 : };
523 :
524 : static void InitializeOncePerProcess();
525 :
526 : // Returns the PerIsolateThreadData for the current thread (or nullptr if one
527 : // is not currently set).
528 : static PerIsolateThreadData* CurrentPerIsolateThreadData() {
529 : return reinterpret_cast<PerIsolateThreadData*>(
530 238930 : base::Thread::GetThreadLocal(per_isolate_thread_data_key_));
531 : }
532 :
533 : // Returns the isolate inside which the current thread is running.
534 : INLINE(static Isolate* Current()) {
535 : DCHECK_EQ(base::Relaxed_Load(&isolate_key_created_), 1);
536 : Isolate* isolate = reinterpret_cast<Isolate*>(
537 668074 : base::Thread::GetExistingThreadLocal(isolate_key_));
538 : DCHECK_NOT_NULL(isolate);
539 : return isolate;
540 : }
541 :
542 : // Usually called by Init(), but can be called early e.g. to allow
543 : // testing components that require logging but not the whole
544 : // isolate.
545 : //
546 : // Safe to call more than once.
547 : void InitializeLoggingAndCounters();
548 : bool InitializeCounters(); // Returns false if already initialized.
549 :
550 : bool Init(StartupDeserializer* des);
551 :
552 : // True if at least one thread Enter'ed this isolate.
553 32235 : bool IsInUse() { return entry_stack_ != nullptr; }
554 :
555 : // Destroys the non-default isolates.
556 : // Sets default isolate into "has_been_disposed" state rather then destroying,
557 : // for legacy API reasons.
558 : void TearDown();
559 :
560 : void ReleaseManagedObjects();
561 :
562 : static void GlobalTearDown();
563 :
564 : void ClearSerializerData();
565 :
566 : // Find the PerThread for this particular (isolate, thread) combination
567 : // If one does not yet exist, return null.
568 : PerIsolateThreadData* FindPerThreadDataForThisThread();
569 :
570 : // Find the PerThread for given (isolate, thread) combination
571 : // If one does not yet exist, return null.
572 : PerIsolateThreadData* FindPerThreadDataForThread(ThreadId thread_id);
573 :
574 : // Discard the PerThread for this particular (isolate, thread) combination
575 : // If one does not yet exist, no-op.
576 : void DiscardPerThreadDataForThisThread();
577 :
578 : // Returns the key used to store the pointer to the current isolate.
579 : // Used internally for V8 threads that do not execute JavaScript but still
580 : // are part of the domain of an isolate (like the context switcher).
581 : static base::Thread::LocalStorageKey isolate_key() {
582 : return isolate_key_;
583 : }
584 :
585 : // Returns the key used to store process-wide thread IDs.
586 : static base::Thread::LocalStorageKey thread_id_key() {
587 : return thread_id_key_;
588 : }
589 :
590 : static base::Thread::LocalStorageKey per_isolate_thread_data_key();
591 :
592 : // Mutex for serializing access to break control structures.
593 : base::RecursiveMutex* break_access() { return &break_access_; }
594 :
595 : Address get_address_from_id(IsolateAddressId id);
596 :
597 : // Access to top context (where the current function object was created).
598 9508736 : Context* context() { return thread_local_top_.context_; }
599 : inline void set_context(Context* context);
600 : Context** context_address() { return &thread_local_top_.context_; }
601 :
602 50889839 : THREAD_LOCAL_TOP_ACCESSOR(SaveContext*, save_context)
603 :
604 : // Access to current thread id.
605 177745 : THREAD_LOCAL_TOP_ACCESSOR(ThreadId, thread_id)
606 :
607 : // Interface to pending exception.
608 : inline Object* pending_exception();
609 : inline void set_pending_exception(Object* exception_obj);
610 : inline void clear_pending_exception();
611 :
612 : // Interface to wasm caught exception.
613 : inline Object* get_wasm_caught_exception();
614 : inline void set_wasm_caught_exception(Object* exception);
615 : inline void clear_wasm_caught_exception();
616 :
617 : THREAD_LOCAL_TOP_ADDRESS(Object*, pending_exception)
618 :
619 : inline bool has_pending_exception();
620 :
621 : THREAD_LOCAL_TOP_ADDRESS(Context*, pending_handler_context)
622 : THREAD_LOCAL_TOP_ADDRESS(Code*, pending_handler_code)
623 : THREAD_LOCAL_TOP_ADDRESS(intptr_t, pending_handler_offset)
624 : THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_fp)
625 : THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_sp)
626 :
627 9674 : THREAD_LOCAL_TOP_ACCESSOR(bool, external_caught_exception)
628 :
629 : v8::TryCatch* try_catch_handler() {
630 18031404 : return thread_local_top_.try_catch_handler();
631 : }
632 : bool* external_caught_exception_address() {
633 : return &thread_local_top_.external_caught_exception_;
634 : }
635 :
636 : THREAD_LOCAL_TOP_ADDRESS(Object*, scheduled_exception)
637 :
638 : inline void clear_pending_message();
639 : Address pending_message_obj_address() {
640 : return reinterpret_cast<Address>(&thread_local_top_.pending_message_obj_);
641 : }
642 :
643 : inline Object* scheduled_exception();
644 : inline bool has_scheduled_exception();
645 : inline void clear_scheduled_exception();
646 :
647 : bool IsJavaScriptHandlerOnTop(Object* exception);
648 : bool IsExternalHandlerOnTop(Object* exception);
649 :
650 : inline bool is_catchable_by_javascript(Object* exception);
651 : bool is_catchable_by_wasm(Object* exception);
652 :
653 : // JS execution stack (see frames.h).
654 : static Address c_entry_fp(ThreadLocalTop* thread) {
655 : return thread->c_entry_fp_;
656 : }
657 : static Address handler(ThreadLocalTop* thread) { return thread->handler_; }
658 : Address c_function() { return thread_local_top_.c_function_; }
659 :
660 : inline Address* c_entry_fp_address() {
661 : return &thread_local_top_.c_entry_fp_;
662 : }
663 : inline Address* handler_address() { return &thread_local_top_.handler_; }
664 : inline Address* c_function_address() {
665 : return &thread_local_top_.c_function_;
666 : }
667 :
668 : // Bottom JS entry.
669 : Address js_entry_sp() {
670 : return thread_local_top_.js_entry_sp_;
671 : }
672 : inline Address* js_entry_sp_address() {
673 : return &thread_local_top_.js_entry_sp_;
674 : }
675 :
676 : // Returns the global object of the current context. It could be
677 : // a builtin object, or a JS global object.
678 : inline Handle<JSGlobalObject> global_object();
679 :
680 : // Returns the global proxy object of the current context.
681 : inline Handle<JSObject> global_proxy();
682 :
683 : static int ArchiveSpacePerThread() { return sizeof(ThreadLocalTop); }
684 5856 : void FreeThreadResources() { thread_local_top_.Free(); }
685 :
686 : // This method is called by the api after operations that may throw
687 : // exceptions. If an exception was thrown and not handled by an external
688 : // handler the exception is scheduled to be rethrown when we return to running
689 : // JavaScript code. If an exception is scheduled true is returned.
690 : V8_EXPORT_PRIVATE bool OptionalRescheduleException(bool is_bottom_call);
691 :
692 : // Push and pop a promise and the current try-catch handler.
693 : void PushPromise(Handle<JSObject> promise);
694 : void PopPromise();
695 :
696 : // Return the relevant Promise that a throw/rejection pertains to, based
697 : // on the contents of the Promise stack
698 : Handle<Object> GetPromiseOnStackOnThrow();
699 :
700 : // Heuristically guess whether a Promise is handled by user catch handler
701 : bool PromiseHasUserDefinedRejectHandler(Handle<Object> promise);
702 :
703 : class ExceptionScope {
704 : public:
705 : // Scope currently can only be used for regular exceptions,
706 : // not termination exception.
707 : inline explicit ExceptionScope(Isolate* isolate);
708 : inline ~ExceptionScope();
709 :
710 : private:
711 : Isolate* isolate_;
712 : Handle<Object> pending_exception_;
713 : };
714 :
715 : void SetCaptureStackTraceForUncaughtExceptions(
716 : bool capture,
717 : int frame_limit,
718 : StackTrace::StackTraceOptions options);
719 :
720 : void SetAbortOnUncaughtExceptionCallback(
721 : v8::Isolate::AbortOnUncaughtExceptionCallback callback);
722 :
723 : enum PrintStackMode { kPrintStackConcise, kPrintStackVerbose };
724 : void PrintCurrentStackTrace(FILE* out);
725 : void PrintStack(StringStream* accumulator,
726 : PrintStackMode mode = kPrintStackVerbose);
727 : V8_EXPORT_PRIVATE void PrintStack(FILE* out,
728 : PrintStackMode mode = kPrintStackVerbose);
729 : Handle<String> StackTraceString();
730 : // Stores a stack trace in a stack-allocated temporary buffer which will
731 : // end up in the minidump for debugging purposes.
732 : NO_INLINE(void PushStackTraceAndDie(unsigned int magic1, void* ptr1,
733 : void* ptr2, unsigned int magic2));
734 : NO_INLINE(void PushStackTraceAndDie(unsigned int magic1, void* ptr1,
735 : void* ptr2, void* ptr3, void* ptr4,
736 : void* ptr5, void* ptr6, void* ptr7,
737 : void* ptr8, unsigned int magic2));
738 : NO_INLINE(void PushCodeObjectsAndDie(unsigned int magic, void* ptr1,
739 : void* ptr2, void* ptr3, void* ptr4,
740 : void* ptr5, void* ptr6, void* ptr7,
741 : void* ptr8, unsigned int magic2));
742 : Handle<FixedArray> CaptureCurrentStackTrace(
743 : int frame_limit, StackTrace::StackTraceOptions options);
744 : Handle<Object> CaptureSimpleStackTrace(Handle<JSReceiver> error_object,
745 : FrameSkipMode mode,
746 : Handle<Object> caller);
747 : MaybeHandle<JSReceiver> CaptureAndSetDetailedStackTrace(
748 : Handle<JSReceiver> error_object);
749 : MaybeHandle<JSReceiver> CaptureAndSetSimpleStackTrace(
750 : Handle<JSReceiver> error_object, FrameSkipMode mode,
751 : Handle<Object> caller);
752 : Handle<FixedArray> GetDetailedStackTrace(Handle<JSObject> error_object);
753 :
754 : // Returns if the given context may access the given global object. If
755 : // the result is false, the pending exception is guaranteed to be
756 : // set.
757 : bool MayAccess(Handle<Context> accessing_context, Handle<JSObject> receiver);
758 :
759 : void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback);
760 : void ReportFailedAccessCheck(Handle<JSObject> receiver);
761 :
762 : // Exception throwing support. The caller should use the result
763 : // of Throw() as its return value.
764 : Object* Throw(Object* exception, MessageLocation* location = nullptr);
765 : Object* ThrowIllegalOperation();
766 :
767 : template <typename T>
768 : MUST_USE_RESULT MaybeHandle<T> Throw(Handle<Object> exception,
769 : MessageLocation* location = nullptr) {
770 359093 : Throw(*exception, location);
771 : return MaybeHandle<T>();
772 : }
773 :
774 : void set_console_delegate(debug::ConsoleDelegate* delegate) {
775 33698 : console_delegate_ = delegate;
776 : }
777 : debug::ConsoleDelegate* console_delegate() { return console_delegate_; }
778 :
779 : // Re-throw an exception. This involves no error reporting since error
780 : // reporting was handled when the exception was thrown originally.
781 : Object* ReThrow(Object* exception);
782 :
783 : // Find the correct handler for the current pending exception. This also
784 : // clears and returns the current pending exception.
785 : Object* UnwindAndFindHandler();
786 :
787 : // Tries to predict whether an exception will be caught. Note that this can
788 : // only produce an estimate, because it is undecidable whether a finally
789 : // clause will consume or re-throw an exception.
790 : enum CatchType {
791 : NOT_CAUGHT,
792 : CAUGHT_BY_JAVASCRIPT,
793 : CAUGHT_BY_EXTERNAL,
794 : CAUGHT_BY_DESUGARING,
795 : CAUGHT_BY_PROMISE,
796 : CAUGHT_BY_ASYNC_AWAIT
797 : };
798 : CatchType PredictExceptionCatcher();
799 :
800 : void ScheduleThrow(Object* exception);
801 : // Re-set pending message, script and positions reported to the TryCatch
802 : // back to the TLS for re-use when rethrowing.
803 : void RestorePendingMessageFromTryCatch(v8::TryCatch* handler);
804 : // Un-schedule an exception that was caught by a TryCatch handler.
805 : void CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler);
806 : void ReportPendingMessages();
807 : // Return pending location if any or unfilled structure.
808 : MessageLocation GetMessageLocation();
809 :
810 : // Promote a scheduled exception to pending. Asserts has_scheduled_exception.
811 : Object* PromoteScheduledException();
812 :
813 : // Attempts to compute the current source location, storing the
814 : // result in the target out parameter. The source location is attached to a
815 : // Message object as the location which should be shown to the user. It's
816 : // typically the top-most meaningful location on the stack.
817 : bool ComputeLocation(MessageLocation* target);
818 : bool ComputeLocationFromException(MessageLocation* target,
819 : Handle<Object> exception);
820 : bool ComputeLocationFromStackTrace(MessageLocation* target,
821 : Handle<Object> exception);
822 :
823 : Handle<JSMessageObject> CreateMessage(Handle<Object> exception,
824 : MessageLocation* location);
825 :
826 : // Out of resource exception helpers.
827 : Object* StackOverflow();
828 : Object* TerminateExecution();
829 : void CancelTerminateExecution();
830 :
831 : void RequestInterrupt(InterruptCallback callback, void* data);
832 : void InvokeApiInterruptCallbacks();
833 :
834 : // Administration
835 : void Iterate(RootVisitor* v);
836 : void Iterate(RootVisitor* v, ThreadLocalTop* t);
837 : char* Iterate(RootVisitor* v, char* t);
838 : void IterateThread(ThreadVisitor* v, char* t);
839 :
840 : // Returns the current native context.
841 : inline Handle<Context> native_context();
842 : inline Context* raw_native_context();
843 :
844 : // Returns the native context of the calling JavaScript code. That
845 : // is, the native context of the top-most JavaScript frame.
846 : Handle<Context> GetCallingNativeContext();
847 :
848 : Handle<Context> GetIncumbentContext();
849 :
850 : void RegisterTryCatchHandler(v8::TryCatch* that);
851 : void UnregisterTryCatchHandler(v8::TryCatch* that);
852 :
853 : char* ArchiveThread(char* to);
854 : char* RestoreThread(char* from);
855 :
856 : static const int kUC16AlphabetSize = 256; // See StringSearchBase.
857 : static const int kBMMaxShift = 250; // See StringSearchBase.
858 :
859 : // Accessors.
860 : #define GLOBAL_ACCESSOR(type, name, initialvalue) \
861 : inline type name() const { \
862 : DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
863 : return name##_; \
864 : } \
865 : inline void set_##name(type value) { \
866 : DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
867 : name##_ = value; \
868 : }
869 77376436 : ISOLATE_INIT_LIST(GLOBAL_ACCESSOR)
870 : #undef GLOBAL_ACCESSOR
871 :
872 : #define GLOBAL_ARRAY_ACCESSOR(type, name, length) \
873 : inline type* name() { \
874 : DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
875 : return &(name##_)[0]; \
876 : }
877 : ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_ACCESSOR)
878 : #undef GLOBAL_ARRAY_ACCESSOR
879 :
880 : #define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name) \
881 : inline Handle<type> name(); \
882 : inline bool is_##name(type* value);
883 : NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
884 : #undef NATIVE_CONTEXT_FIELD_ACCESSOR
885 :
886 20279 : Bootstrapper* bootstrapper() { return bootstrapper_; }
887 : // Use for updating counters on a foreground thread.
888 258396449 : Counters* counters() { return async_counters().get(); }
889 : // Use for updating counters on a background thread.
890 : const std::shared_ptr<Counters>& async_counters() {
891 : // Make sure InitializeCounters() has been called.
892 : DCHECK_NOT_NULL(async_counters_.get());
893 : return async_counters_;
894 : }
895 6632 : RuntimeProfiler* runtime_profiler() { return runtime_profiler_; }
896 : CompilationCache* compilation_cache() { return compilation_cache_; }
897 1037 : Logger* logger() {
898 : // Call InitializeLoggingAndCounters() if logging is needed before
899 : // the isolate is fully initialized.
900 : DCHECK_NOT_NULL(logger_);
901 1037 : return logger_;
902 : }
903 289850 : StackGuard* stack_guard() { return &stack_guard_; }
904 1666842604 : Heap* heap() { return &heap_; }
905 : StubCache* load_stub_cache() { return load_stub_cache_; }
906 : StubCache* store_stub_cache() { return store_stub_cache_; }
907 : DeoptimizerData* deoptimizer_data() { return deoptimizer_data_; }
908 : bool deoptimizer_lazy_throw() const { return deoptimizer_lazy_throw_; }
909 : void set_deoptimizer_lazy_throw(bool value) {
910 6258 : deoptimizer_lazy_throw_ = value;
911 : }
912 45144 : ThreadLocalTop* thread_local_top() { return &thread_local_top_; }
913 : MaterializedObjectStore* materialized_object_store() {
914 : return materialized_object_store_;
915 : }
916 :
917 : ContextSlotCache* context_slot_cache() {
918 : return context_slot_cache_;
919 : }
920 :
921 193623998 : DescriptorLookupCache* descriptor_lookup_cache() {
922 193623998 : return descriptor_lookup_cache_;
923 : }
924 :
925 1925931897 : HandleScopeData* handle_scope_data() { return &handle_scope_data_; }
926 :
927 : HandleScopeImplementer* handle_scope_implementer() {
928 : DCHECK(handle_scope_implementer_);
929 : return handle_scope_implementer_;
930 : }
931 :
932 584 : UnicodeCache* unicode_cache() {
933 584 : return unicode_cache_;
934 : }
935 :
936 : InnerPointerToCodeCache* inner_pointer_to_code_cache() {
937 : return inner_pointer_to_code_cache_;
938 : }
939 :
940 11314 : GlobalHandles* global_handles() { return global_handles_; }
941 :
942 146757 : EternalHandles* eternal_handles() { return eternal_handles_; }
943 :
944 : ThreadManager* thread_manager() { return thread_manager_; }
945 :
946 : unibrow::Mapping<unibrow::Ecma262UnCanonicalize>* jsregexp_uncanonicalize() {
947 : return &jsregexp_uncanonicalize_;
948 : }
949 :
950 : unibrow::Mapping<unibrow::CanonicalizationRange>* jsregexp_canonrange() {
951 : return &jsregexp_canonrange_;
952 : }
953 :
954 : RuntimeState* runtime_state() { return &runtime_state_; }
955 :
956 4013 : Builtins* builtins() { return &builtins_; }
957 :
958 : unibrow::Mapping<unibrow::Ecma262Canonicalize>*
959 : regexp_macro_assembler_canonicalize() {
960 : return ®exp_macro_assembler_canonicalize_;
961 : }
962 :
963 : RegExpStack* regexp_stack() { return regexp_stack_; }
964 :
965 : size_t total_regexp_code_generated() { return total_regexp_code_generated_; }
966 : void IncreaseTotalRegexpCodeGenerated(int size) {
967 93518 : total_regexp_code_generated_ += size;
968 : }
969 :
970 : std::vector<int>* regexp_indices() { return ®exp_indices_; }
971 :
972 : unibrow::Mapping<unibrow::Ecma262Canonicalize>*
973 : interp_canonicalize_mapping() {
974 : return ®exp_macro_assembler_canonicalize_;
975 : }
976 :
977 1389567 : Debug* debug() { return debug_; }
978 :
979 : bool* is_profiling_address() { return &is_profiling_; }
980 : CodeEventDispatcher* code_event_dispatcher() const {
981 : return code_event_dispatcher_.get();
982 : }
983 : HeapProfiler* heap_profiler() const { return heap_profiler_; }
984 :
985 : #ifdef DEBUG
986 : static size_t non_disposed_isolates() {
987 : return non_disposed_isolates_.Value();
988 : }
989 :
990 : HistogramInfo* heap_histograms() { return heap_histograms_; }
991 :
992 : JSObject::SpillInformation* js_spill_information() {
993 : return &js_spill_information_;
994 : }
995 : #endif
996 :
997 53499589 : Factory* factory() { return reinterpret_cast<Factory*>(this); }
998 :
999 : static const int kJSRegexpStaticOffsetsVectorSize = 128;
1000 :
1001 34501556 : THREAD_LOCAL_TOP_ACCESSOR(ExternalCallbackScope*, external_callback_scope)
1002 :
1003 544492281 : THREAD_LOCAL_TOP_ACCESSOR(StateTag, current_vm_state)
1004 :
1005 : void SetData(uint32_t slot, void* data) {
1006 : DCHECK_LT(slot, Internals::kNumIsolateDataSlots);
1007 : embedder_data_[slot] = data;
1008 : }
1009 : void* GetData(uint32_t slot) {
1010 : DCHECK_LT(slot, Internals::kNumIsolateDataSlots);
1011 60 : return embedder_data_[slot];
1012 : }
1013 :
1014 73337 : bool serializer_enabled() const { return serializer_enabled_; }
1015 : void set_serializer_enabled_for_test(bool serializer_enabled) {
1016 36 : serializer_enabled_ = serializer_enabled;
1017 : }
1018 : bool snapshot_available() const {
1019 303505 : return snapshot_blob_ != nullptr && snapshot_blob_->raw_size != 0;
1020 : }
1021 :
1022 : bool IsDead() { return has_fatal_error_; }
1023 10 : void SignalFatalError() { has_fatal_error_ = true; }
1024 :
1025 : bool use_optimizer();
1026 :
1027 : bool initialized_from_snapshot() { return initialized_from_snapshot_; }
1028 :
1029 : bool NeedsSourcePositionsForProfiling() const;
1030 :
1031 6330170 : bool is_best_effort_code_coverage() const {
1032 258 : return code_coverage_mode() == debug::Coverage::kBestEffort;
1033 : }
1034 :
1035 187168 : bool is_precise_count_code_coverage() const {
1036 : return code_coverage_mode() == debug::Coverage::kPreciseCount;
1037 : }
1038 :
1039 62619 : bool is_precise_binary_code_coverage() const {
1040 : return code_coverage_mode() == debug::Coverage::kPreciseBinary;
1041 : }
1042 :
1043 2806593 : bool is_block_count_code_coverage() const {
1044 : return code_coverage_mode() == debug::Coverage::kBlockCount;
1045 : }
1046 :
1047 : bool is_block_binary_code_coverage() const {
1048 : return code_coverage_mode() == debug::Coverage::kBlockBinary;
1049 : }
1050 :
1051 : bool is_block_code_coverage() const {
1052 2806593 : return is_block_count_code_coverage() || is_block_binary_code_coverage();
1053 : }
1054 :
1055 11942369 : bool is_collecting_type_profile() const {
1056 : return type_profile_mode() == debug::TypeProfile::kCollect;
1057 : }
1058 :
1059 : // Collect feedback vectors with data for code coverage or type profile.
1060 : // Reset the list, when both code coverage and type profile are not
1061 : // needed anymore. This keeps many feedback vectors alive, but code
1062 : // coverage or type profile are used for debugging only and increase in
1063 : // memory usage is expected.
1064 : void SetFeedbackVectorsForProfilingTools(Object* value);
1065 :
1066 : void InitializeVectorListFromHeap();
1067 :
1068 : double time_millis_since_init() {
1069 86517 : return heap_.MonotonicallyIncreasingTimeInMs() - time_millis_at_init_;
1070 : }
1071 :
1072 : DateCache* date_cache() {
1073 : return date_cache_;
1074 : }
1075 :
1076 : void set_date_cache(DateCache* date_cache) {
1077 6 : if (date_cache != date_cache_) {
1078 6 : delete date_cache_;
1079 : }
1080 6 : date_cache_ = date_cache;
1081 : }
1082 :
1083 : static const int kProtectorValid = 1;
1084 : static const int kProtectorInvalid = 0;
1085 :
1086 : inline bool IsArrayConstructorIntact();
1087 : bool IsFastArrayConstructorPrototypeChainIntact();
1088 : inline bool IsArraySpeciesLookupChainIntact();
1089 : bool IsIsConcatSpreadableLookupChainIntact();
1090 : bool IsIsConcatSpreadableLookupChainIntact(JSReceiver* receiver);
1091 : inline bool IsStringLengthOverflowIntact();
1092 : inline bool IsArrayIteratorLookupChainIntact();
1093 :
1094 : // Avoid deopt loops if fast Array Iterators migrate to slow Array Iterators.
1095 : inline bool IsFastArrayIterationIntact();
1096 :
1097 : // Make sure we do check for neutered array buffers.
1098 : inline bool IsArrayBufferNeuteringIntact();
1099 :
1100 : // On intent to set an element in object, make sure that appropriate
1101 : // notifications occur if the set is on the elements of the array or
1102 : // object prototype. Also ensure that changes to prototype chain between
1103 : // Array and Object fire notifications.
1104 : void UpdateArrayProtectorOnSetElement(Handle<JSObject> object);
1105 : void UpdateArrayProtectorOnSetLength(Handle<JSObject> object) {
1106 797635 : UpdateArrayProtectorOnSetElement(object);
1107 : }
1108 : void UpdateArrayProtectorOnSetPrototype(Handle<JSObject> object) {
1109 2649385 : UpdateArrayProtectorOnSetElement(object);
1110 : }
1111 : void UpdateArrayProtectorOnNormalizeElements(Handle<JSObject> object) {
1112 303118 : UpdateArrayProtectorOnSetElement(object);
1113 : }
1114 : void InvalidateArrayConstructorProtector();
1115 : void InvalidateArraySpeciesProtector();
1116 : void InvalidateIsConcatSpreadableProtector();
1117 : void InvalidateStringLengthOverflowProtector();
1118 : void InvalidateArrayIteratorProtector();
1119 : void InvalidateArrayBufferNeuteringProtector();
1120 :
1121 : // Returns true if array is the initial array prototype in any native context.
1122 : bool IsAnyInitialArrayPrototype(Handle<JSArray> array);
1123 :
1124 : V8_EXPORT_PRIVATE CallInterfaceDescriptorData* call_descriptor_data(
1125 : int index);
1126 :
1127 : AccessCompilerData* access_compiler_data() { return access_compiler_data_; }
1128 :
1129 : void IterateDeferredHandles(RootVisitor* visitor);
1130 : void LinkDeferredHandles(DeferredHandles* deferred_handles);
1131 : void UnlinkDeferredHandles(DeferredHandles* deferred_handles);
1132 :
1133 : #ifdef DEBUG
1134 : bool IsDeferredHandle(Object** location);
1135 : #endif // DEBUG
1136 :
1137 4666 : bool concurrent_recompilation_enabled() {
1138 : // Thread is only available with flag enabled.
1139 : DCHECK(optimizing_compile_dispatcher_ == nullptr ||
1140 : FLAG_concurrent_recompilation);
1141 4666 : return optimizing_compile_dispatcher_ != nullptr;
1142 : }
1143 :
1144 87 : OptimizingCompileDispatcher* optimizing_compile_dispatcher() {
1145 87 : return optimizing_compile_dispatcher_;
1146 : }
1147 :
1148 : int id() const { return static_cast<int>(id_); }
1149 :
1150 : CompilationStatistics* GetTurboStatistics();
1151 : CodeTracer* GetCodeTracer();
1152 :
1153 : void DumpAndResetStats();
1154 :
1155 : FunctionEntryHook function_entry_hook() { return function_entry_hook_; }
1156 : void set_function_entry_hook(FunctionEntryHook function_entry_hook) {
1157 0 : function_entry_hook_ = function_entry_hook;
1158 : }
1159 :
1160 : void* stress_deopt_count_address() { return &stress_deopt_count_; }
1161 :
1162 : V8_EXPORT_PRIVATE base::RandomNumberGenerator* random_number_generator();
1163 :
1164 : // Generates a random number that is non-zero when masked
1165 : // with the provided mask.
1166 : int GenerateIdentityHash(uint32_t mask);
1167 :
1168 : // Given an address occupied by a live code object, return that object.
1169 : Code* FindCodeObject(Address a);
1170 :
1171 : int NextOptimizationId() {
1172 461376 : int id = next_optimization_id_++;
1173 : if (!Smi::IsValid(next_optimization_id_)) {
1174 : next_optimization_id_ = 0;
1175 : }
1176 : return id;
1177 : }
1178 :
1179 : void AddCallCompletedCallback(CallCompletedCallback callback);
1180 : void RemoveCallCompletedCallback(CallCompletedCallback callback);
1181 : void FireCallCompletedCallback();
1182 :
1183 : void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1184 : void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1185 : inline void FireBeforeCallEnteredCallback();
1186 :
1187 : void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
1188 : void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
1189 : inline void FireMicrotasksCompletedCallback();
1190 :
1191 : void SetPromiseRejectCallback(PromiseRejectCallback callback);
1192 : void ReportPromiseReject(Handle<JSPromise> promise, Handle<Object> value,
1193 : v8::PromiseRejectEvent event);
1194 :
1195 : void PromiseReactionJob(Handle<PromiseReactionJobInfo> info,
1196 : MaybeHandle<Object>* result,
1197 : MaybeHandle<Object>* maybe_exception);
1198 : void PromiseResolveThenableJob(Handle<PromiseResolveThenableJobInfo> info,
1199 : MaybeHandle<Object>* result,
1200 : MaybeHandle<Object>* maybe_exception);
1201 : void EnqueueMicrotask(Handle<Object> microtask);
1202 : void RunMicrotasks();
1203 : bool IsRunningMicrotasks() const { return is_running_microtasks_; }
1204 :
1205 : Handle<Symbol> SymbolFor(Heap::RootListIndex dictionary_index,
1206 : Handle<String> name, bool private_symbol);
1207 :
1208 : void SetUseCounterCallback(v8::Isolate::UseCounterCallback callback);
1209 : void CountUsage(v8::Isolate::UseCounterFeature feature);
1210 :
1211 : BasicBlockProfiler* GetOrCreateBasicBlockProfiler();
1212 : BasicBlockProfiler* basic_block_profiler() { return basic_block_profiler_; }
1213 :
1214 : std::string GetTurboCfgFileName();
1215 :
1216 : #if V8_SFI_HAS_UNIQUE_ID
1217 : int GetNextUniqueSharedFunctionInfoId() { return next_unique_sfi_id_++; }
1218 : #endif
1219 :
1220 : Address promise_hook_or_debug_is_active_address() {
1221 : return reinterpret_cast<Address>(&promise_hook_or_debug_is_active_);
1222 : }
1223 :
1224 : void DebugStateUpdated();
1225 :
1226 : void SetPromiseHook(PromiseHook hook);
1227 : void RunPromiseHook(PromiseHookType type, Handle<JSPromise> promise,
1228 : Handle<Object> parent);
1229 :
1230 : void AddDetachedContext(Handle<Context> context);
1231 : void CheckDetachedContextsAfterGC();
1232 :
1233 : std::vector<Object*>* partial_snapshot_cache() {
1234 : return &partial_snapshot_cache_;
1235 : }
1236 :
1237 : void set_array_buffer_allocator(v8::ArrayBuffer::Allocator* allocator) {
1238 55094 : array_buffer_allocator_ = allocator;
1239 : }
1240 2006 : v8::ArrayBuffer::Allocator* array_buffer_allocator() const {
1241 2006 : return array_buffer_allocator_;
1242 : }
1243 :
1244 : FutexWaitListNode* futex_wait_list_node() { return &futex_wait_list_node_; }
1245 :
1246 : CancelableTaskManager* cancelable_task_manager() {
1247 : return cancelable_task_manager_;
1248 : }
1249 :
1250 : wasm::CompilationManager* wasm_compilation_manager() {
1251 : return wasm_compilation_manager_.get();
1252 : }
1253 :
1254 : const AstStringConstants* ast_string_constants() const {
1255 : return ast_string_constants_;
1256 : }
1257 :
1258 58332 : interpreter::Interpreter* interpreter() const { return interpreter_; }
1259 :
1260 371 : AccountingAllocator* allocator() { return allocator_; }
1261 :
1262 : CompilerDispatcher* compiler_dispatcher() const {
1263 : return compiler_dispatcher_;
1264 : }
1265 :
1266 : bool IsInAnyContext(Object* object, uint32_t index);
1267 :
1268 : void SetHostImportModuleDynamicallyCallback(
1269 : HostImportModuleDynamicallyCallback callback);
1270 : MaybeHandle<JSPromise> RunHostImportModuleDynamicallyCallback(
1271 : Handle<Script> referrer, Handle<Object> specifier);
1272 :
1273 : void SetHostInitializeImportMetaObjectCallback(
1274 : HostInitializeImportMetaObjectCallback callback);
1275 : Handle<JSObject> RunHostInitializeImportMetaObjectCallback(
1276 : Handle<Module> module);
1277 :
1278 : void SetRAILMode(RAILMode rail_mode);
1279 :
1280 : RAILMode rail_mode() { return rail_mode_.Value(); }
1281 :
1282 : double LoadStartTimeMs();
1283 :
1284 : void IsolateInForegroundNotification();
1285 :
1286 : void IsolateInBackgroundNotification();
1287 :
1288 : bool IsIsolateInBackground() { return is_isolate_in_background_; }
1289 :
1290 : PRINTF_FORMAT(2, 3) void PrintWithTimestamp(const char* format, ...);
1291 :
1292 : #ifdef USE_SIMULATOR
1293 : base::Mutex* simulator_i_cache_mutex() { return &simulator_i_cache_mutex_; }
1294 : base::Mutex* simulator_redirection_mutex() {
1295 : return &simulator_redirection_mutex_;
1296 : }
1297 : #endif
1298 :
1299 54841 : void set_allow_atomics_wait(bool set) { allow_atomics_wait_ = set; }
1300 : bool allow_atomics_wait() { return allow_atomics_wait_; }
1301 :
1302 : // List of native heap values allocated by the runtime as part of its
1303 : // implementation that must be freed at isolate deinit.
1304 : class ManagedObjectFinalizer {
1305 : public:
1306 : using Deleter = void (*)(ManagedObjectFinalizer*);
1307 :
1308 : ManagedObjectFinalizer(void* value, Deleter deleter)
1309 361401 : : value_(value), deleter_(deleter) {}
1310 :
1311 250991 : void Dispose() { deleter_(this); }
1312 :
1313 4624744 : void* value() const { return value_; }
1314 :
1315 : private:
1316 : friend class Isolate;
1317 :
1318 : ManagedObjectFinalizer() = default;
1319 :
1320 : void* value_ = nullptr;
1321 : Deleter deleter_ = nullptr;
1322 : ManagedObjectFinalizer* prev_ = nullptr;
1323 : ManagedObjectFinalizer* next_ = nullptr;
1324 : };
1325 :
1326 : static_assert(offsetof(ManagedObjectFinalizer, value_) == 0,
1327 : "value_ must be the first member");
1328 :
1329 : // Register a finalizer to be called at isolate teardown.
1330 : void RegisterForReleaseAtTeardown(ManagedObjectFinalizer*);
1331 :
1332 : // Unregister a previously registered value from release at
1333 : // isolate teardown.
1334 : // This transfers the responsibility of the previously managed value's
1335 : // deletion to the caller.
1336 : void UnregisterFromReleaseAtTeardown(ManagedObjectFinalizer*);
1337 :
1338 : size_t elements_deletion_counter() { return elements_deletion_counter_; }
1339 : void set_elements_deletion_counter(size_t value) {
1340 410 : elements_deletion_counter_ = value;
1341 : }
1342 :
1343 : const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope() const {
1344 : return top_backup_incumbent_scope_;
1345 : }
1346 : void set_top_backup_incumbent_scope(
1347 : const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope) {
1348 0 : top_backup_incumbent_scope_ = top_backup_incumbent_scope;
1349 : }
1350 :
1351 : protected:
1352 : explicit Isolate(bool enable_serializer);
1353 : bool IsArrayOrObjectPrototype(Object* object);
1354 :
1355 : private:
1356 : friend struct GlobalState;
1357 : friend struct InitializeGlobalState;
1358 :
1359 : // These fields are accessed through the API, offsets must be kept in sync
1360 : // with v8::internal::Internals (in include/v8.h) constants. This is also
1361 : // verified in Isolate::Init() using runtime checks.
1362 : void* embedder_data_[Internals::kNumIsolateDataSlots];
1363 : Heap heap_;
1364 :
1365 : // The per-process lock should be acquired before the ThreadDataTable is
1366 : // modified.
1367 : class ThreadDataTable {
1368 : public:
1369 : ThreadDataTable();
1370 : ~ThreadDataTable();
1371 :
1372 : PerIsolateThreadData* Lookup(Isolate* isolate, ThreadId thread_id);
1373 : void Insert(PerIsolateThreadData* data);
1374 : void Remove(PerIsolateThreadData* data);
1375 : void RemoveAllThreads(Isolate* isolate);
1376 :
1377 : private:
1378 : PerIsolateThreadData* list_;
1379 : };
1380 :
1381 : // These items form a stack synchronously with threads Enter'ing and Exit'ing
1382 : // the Isolate. The top of the stack points to a thread which is currently
1383 : // running the Isolate. When the stack is empty, the Isolate is considered
1384 : // not entered by any thread and can be Disposed.
1385 : // If the same thread enters the Isolate more than once, the entry_count_
1386 : // is incremented rather then a new item pushed to the stack.
1387 : class EntryStackItem {
1388 : public:
1389 : EntryStackItem(PerIsolateThreadData* previous_thread_data,
1390 : Isolate* previous_isolate,
1391 : EntryStackItem* previous_item)
1392 : : entry_count(1),
1393 : previous_thread_data(previous_thread_data),
1394 : previous_isolate(previous_isolate),
1395 177754 : previous_item(previous_item) { }
1396 :
1397 : int entry_count;
1398 : PerIsolateThreadData* previous_thread_data;
1399 : Isolate* previous_isolate;
1400 : EntryStackItem* previous_item;
1401 :
1402 : private:
1403 : DISALLOW_COPY_AND_ASSIGN(EntryStackItem);
1404 : };
1405 :
1406 : static base::LazyMutex thread_data_table_mutex_;
1407 :
1408 : static base::Thread::LocalStorageKey per_isolate_thread_data_key_;
1409 : static base::Thread::LocalStorageKey isolate_key_;
1410 : static base::Thread::LocalStorageKey thread_id_key_;
1411 : static ThreadDataTable* thread_data_table_;
1412 :
1413 : // A global counter for all generated Isolates, might overflow.
1414 : static base::Atomic32 isolate_counter_;
1415 :
1416 : #if DEBUG
1417 : static base::Atomic32 isolate_key_created_;
1418 : #endif
1419 :
1420 : void Deinit();
1421 :
1422 : static void SetIsolateThreadLocals(Isolate* isolate,
1423 : PerIsolateThreadData* data);
1424 :
1425 : // Find the PerThread for this particular (isolate, thread) combination.
1426 : // If one does not yet exist, allocate a new one.
1427 : PerIsolateThreadData* FindOrAllocatePerThreadDataForThisThread();
1428 :
1429 : // Initializes the current thread to run this Isolate.
1430 : // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
1431 : // at the same time, this should be prevented using external locking.
1432 : void Enter();
1433 :
1434 : // Exits the current thread. The previosuly entered Isolate is restored
1435 : // for the thread.
1436 : // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
1437 : // at the same time, this should be prevented using external locking.
1438 : void Exit();
1439 :
1440 : void InitializeThreadLocal();
1441 :
1442 : void MarkCompactPrologue(bool is_compacting,
1443 : ThreadLocalTop* archived_thread_data);
1444 : void MarkCompactEpilogue(bool is_compacting,
1445 : ThreadLocalTop* archived_thread_data);
1446 :
1447 : void FillCache();
1448 :
1449 : // Propagate pending exception message to the v8::TryCatch.
1450 : // If there is no external try-catch or message was successfully propagated,
1451 : // then return true.
1452 : bool PropagatePendingExceptionToExternalTryCatch();
1453 :
1454 : void RunMicrotasksInternal();
1455 :
1456 : const char* RAILModeName(RAILMode rail_mode) const {
1457 0 : switch (rail_mode) {
1458 : case PERFORMANCE_RESPONSE:
1459 : return "RESPONSE";
1460 : case PERFORMANCE_ANIMATION:
1461 : return "ANIMATION";
1462 : case PERFORMANCE_IDLE:
1463 : return "IDLE";
1464 : case PERFORMANCE_LOAD:
1465 : return "LOAD";
1466 : }
1467 : return "";
1468 : }
1469 :
1470 : // TODO(alph): Remove along with the deprecated GetCpuProfiler().
1471 : friend v8::CpuProfiler* v8::Isolate::GetCpuProfiler();
1472 : CpuProfiler* cpu_profiler() const { return cpu_profiler_; }
1473 :
1474 : base::Atomic32 id_;
1475 : EntryStackItem* entry_stack_;
1476 : int stack_trace_nesting_level_;
1477 : StringStream* incomplete_message_;
1478 : Address isolate_addresses_[kIsolateAddressCount + 1]; // NOLINT
1479 : Bootstrapper* bootstrapper_;
1480 : RuntimeProfiler* runtime_profiler_;
1481 : CompilationCache* compilation_cache_;
1482 : std::shared_ptr<Counters> async_counters_;
1483 : base::RecursiveMutex break_access_;
1484 : Logger* logger_;
1485 : StackGuard stack_guard_;
1486 : StubCache* load_stub_cache_;
1487 : StubCache* store_stub_cache_;
1488 : DeoptimizerData* deoptimizer_data_;
1489 : bool deoptimizer_lazy_throw_;
1490 : MaterializedObjectStore* materialized_object_store_;
1491 : ThreadLocalTop thread_local_top_;
1492 : bool capture_stack_trace_for_uncaught_exceptions_;
1493 : int stack_trace_for_uncaught_exceptions_frame_limit_;
1494 : StackTrace::StackTraceOptions stack_trace_for_uncaught_exceptions_options_;
1495 : ContextSlotCache* context_slot_cache_;
1496 : DescriptorLookupCache* descriptor_lookup_cache_;
1497 : HandleScopeData handle_scope_data_;
1498 : HandleScopeImplementer* handle_scope_implementer_;
1499 : UnicodeCache* unicode_cache_;
1500 : AccountingAllocator* allocator_;
1501 : InnerPointerToCodeCache* inner_pointer_to_code_cache_;
1502 : GlobalHandles* global_handles_;
1503 : EternalHandles* eternal_handles_;
1504 : ThreadManager* thread_manager_;
1505 : RuntimeState runtime_state_;
1506 : Builtins builtins_;
1507 : SetupIsolateDelegate* setup_delegate_;
1508 : unibrow::Mapping<unibrow::Ecma262UnCanonicalize> jsregexp_uncanonicalize_;
1509 : unibrow::Mapping<unibrow::CanonicalizationRange> jsregexp_canonrange_;
1510 : unibrow::Mapping<unibrow::Ecma262Canonicalize>
1511 : regexp_macro_assembler_canonicalize_;
1512 : RegExpStack* regexp_stack_;
1513 : std::vector<int> regexp_indices_;
1514 : DateCache* date_cache_;
1515 : CallInterfaceDescriptorData* call_descriptor_data_;
1516 : AccessCompilerData* access_compiler_data_;
1517 : base::RandomNumberGenerator* random_number_generator_;
1518 : base::AtomicValue<RAILMode> rail_mode_;
1519 : bool promise_hook_or_debug_is_active_;
1520 : PromiseHook promise_hook_;
1521 : HostImportModuleDynamicallyCallback host_import_module_dynamically_callback_;
1522 : HostInitializeImportMetaObjectCallback
1523 : host_initialize_import_meta_object_callback_;
1524 : base::Mutex rail_mutex_;
1525 : double load_start_time_ms_;
1526 :
1527 : // Whether the isolate has been created for snapshotting.
1528 : bool serializer_enabled_;
1529 :
1530 : // True if fatal error has been signaled for this isolate.
1531 : bool has_fatal_error_;
1532 :
1533 : // True if this isolate was initialized from a snapshot.
1534 : bool initialized_from_snapshot_;
1535 :
1536 : // True if ES2015 tail call elimination feature is enabled.
1537 : bool is_tail_call_elimination_enabled_;
1538 :
1539 : // True if the isolate is in background. This flag is used
1540 : // to prioritize between memory usage and latency.
1541 : bool is_isolate_in_background_;
1542 :
1543 : // Time stamp at initialization.
1544 : double time_millis_at_init_;
1545 :
1546 : #ifdef DEBUG
1547 : static base::AtomicNumber<size_t> non_disposed_isolates_;
1548 :
1549 : // A static array of histogram info for each type.
1550 : HistogramInfo heap_histograms_[LAST_TYPE + 1];
1551 : JSObject::SpillInformation js_spill_information_;
1552 : #endif
1553 :
1554 : Debug* debug_;
1555 : CpuProfiler* cpu_profiler_;
1556 : HeapProfiler* heap_profiler_;
1557 : std::unique_ptr<CodeEventDispatcher> code_event_dispatcher_;
1558 : FunctionEntryHook function_entry_hook_;
1559 :
1560 : const AstStringConstants* ast_string_constants_;
1561 :
1562 : interpreter::Interpreter* interpreter_;
1563 :
1564 : CompilerDispatcher* compiler_dispatcher_;
1565 :
1566 : typedef std::pair<InterruptCallback, void*> InterruptEntry;
1567 : std::queue<InterruptEntry> api_interrupts_queue_;
1568 :
1569 : #define GLOBAL_BACKING_STORE(type, name, initialvalue) \
1570 : type name##_;
1571 : ISOLATE_INIT_LIST(GLOBAL_BACKING_STORE)
1572 : #undef GLOBAL_BACKING_STORE
1573 :
1574 : #define GLOBAL_ARRAY_BACKING_STORE(type, name, length) \
1575 : type name##_[length];
1576 : ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_BACKING_STORE)
1577 : #undef GLOBAL_ARRAY_BACKING_STORE
1578 :
1579 : #ifdef DEBUG
1580 : // This class is huge and has a number of fields controlled by
1581 : // preprocessor defines. Make sure the offsets of these fields agree
1582 : // between compilation units.
1583 : #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1584 : static const intptr_t name##_debug_offset_;
1585 : ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
1586 : ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
1587 : #undef ISOLATE_FIELD_OFFSET
1588 : #endif
1589 :
1590 : DeferredHandles* deferred_handles_head_;
1591 : OptimizingCompileDispatcher* optimizing_compile_dispatcher_;
1592 :
1593 : // Counts deopt points if deopt_every_n_times is enabled.
1594 : unsigned int stress_deopt_count_;
1595 :
1596 : int next_optimization_id_;
1597 :
1598 : #if V8_SFI_HAS_UNIQUE_ID
1599 : int next_unique_sfi_id_;
1600 : #endif
1601 :
1602 : // Vector of callbacks before a Call starts execution.
1603 : std::vector<BeforeCallEnteredCallback> before_call_entered_callbacks_;
1604 :
1605 : // Vector of callbacks when a Call completes.
1606 : std::vector<CallCompletedCallback> call_completed_callbacks_;
1607 :
1608 : // Vector of callbacks after microtasks were run.
1609 : std::vector<MicrotasksCompletedCallback> microtasks_completed_callbacks_;
1610 : bool is_running_microtasks_;
1611 :
1612 : v8::Isolate::UseCounterCallback use_counter_callback_;
1613 : BasicBlockProfiler* basic_block_profiler_;
1614 :
1615 : std::vector<Object*> partial_snapshot_cache_;
1616 :
1617 : v8::ArrayBuffer::Allocator* array_buffer_allocator_;
1618 :
1619 : FutexWaitListNode futex_wait_list_node_;
1620 :
1621 : CancelableTaskManager* cancelable_task_manager_;
1622 :
1623 : std::unique_ptr<wasm::CompilationManager> wasm_compilation_manager_;
1624 :
1625 : debug::ConsoleDelegate* console_delegate_ = nullptr;
1626 :
1627 : v8::Isolate::AbortOnUncaughtExceptionCallback
1628 : abort_on_uncaught_exception_callback_;
1629 :
1630 : #ifdef USE_SIMULATOR
1631 : base::Mutex simulator_i_cache_mutex_;
1632 : base::Mutex simulator_redirection_mutex_;
1633 : #endif
1634 :
1635 : bool allow_atomics_wait_;
1636 :
1637 : ManagedObjectFinalizer managed_object_finalizers_list_;
1638 :
1639 : size_t total_regexp_code_generated_;
1640 :
1641 : size_t elements_deletion_counter_ = 0;
1642 :
1643 : // The top entry of the v8::Context::BackupIncumbentScope stack.
1644 : const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope_ =
1645 : nullptr;
1646 :
1647 : friend class ExecutionAccess;
1648 : friend class HandleScopeImplementer;
1649 : friend class heap::HeapTester;
1650 : friend class OptimizingCompileDispatcher;
1651 : friend class SweeperThread;
1652 : friend class ThreadManager;
1653 : friend class Simulator;
1654 : friend class StackGuard;
1655 : friend class TestIsolate;
1656 : friend class ThreadId;
1657 : friend class v8::Isolate;
1658 : friend class v8::Locker;
1659 : friend class v8::Unlocker;
1660 : friend class v8::SnapshotCreator;
1661 : friend v8::StartupData v8::V8::CreateSnapshotDataBlob(const char*);
1662 : friend v8::StartupData v8::V8::WarmUpSnapshotDataBlob(v8::StartupData,
1663 : const char*);
1664 :
1665 : DISALLOW_COPY_AND_ASSIGN(Isolate);
1666 : };
1667 :
1668 :
1669 : #undef FIELD_ACCESSOR
1670 : #undef THREAD_LOCAL_TOP_ACCESSOR
1671 :
1672 :
1673 : class PromiseOnStack {
1674 : public:
1675 : PromiseOnStack(Handle<JSObject> promise, PromiseOnStack* prev)
1676 19565 : : promise_(promise), prev_(prev) {}
1677 : Handle<JSObject> promise() { return promise_; }
1678 : PromiseOnStack* prev() { return prev_; }
1679 :
1680 : private:
1681 : Handle<JSObject> promise_;
1682 : PromiseOnStack* prev_;
1683 : };
1684 :
1685 :
1686 : // If the GCC version is 4.1.x or 4.2.x an additional field is added to the
1687 : // class as a work around for a bug in the generated code found with these
1688 : // versions of GCC. See V8 issue 122 for details.
1689 : class SaveContext BASE_EMBEDDED {
1690 : public:
1691 : explicit SaveContext(Isolate* isolate);
1692 : ~SaveContext();
1693 :
1694 30219 : Handle<Context> context() { return context_; }
1695 : SaveContext* prev() { return prev_; }
1696 :
1697 : // Returns true if this save context is below a given JavaScript frame.
1698 : bool IsBelowFrame(StandardFrame* frame);
1699 :
1700 : private:
1701 : Isolate* const isolate_;
1702 : Handle<Context> context_;
1703 : SaveContext* const prev_;
1704 : Address c_entry_fp_;
1705 : };
1706 :
1707 :
1708 : class AssertNoContextChange BASE_EMBEDDED {
1709 : #ifdef DEBUG
1710 : public:
1711 : explicit AssertNoContextChange(Isolate* isolate);
1712 : ~AssertNoContextChange() {
1713 : DCHECK(isolate_->context() == *context_);
1714 : }
1715 :
1716 : private:
1717 : Isolate* isolate_;
1718 : Handle<Context> context_;
1719 : #else
1720 : public:
1721 : explicit AssertNoContextChange(Isolate* isolate) { }
1722 : #endif
1723 : };
1724 :
1725 :
1726 : class ExecutionAccess BASE_EMBEDDED {
1727 : public:
1728 90874 : explicit ExecutionAccess(Isolate* isolate) : isolate_(isolate) {
1729 : Lock(isolate);
1730 : }
1731 90874 : ~ExecutionAccess() { Unlock(isolate_); }
1732 :
1733 8376912 : static void Lock(Isolate* isolate) { isolate->break_access()->Lock(); }
1734 8357008 : static void Unlock(Isolate* isolate) { isolate->break_access()->Unlock(); }
1735 :
1736 : static bool TryLock(Isolate* isolate) {
1737 : return isolate->break_access()->TryLock();
1738 : }
1739 :
1740 : private:
1741 : Isolate* isolate_;
1742 : };
1743 :
1744 :
1745 : // Support for checking for stack-overflows.
1746 : class StackLimitCheck BASE_EMBEDDED {
1747 : public:
1748 8169747 : explicit StackLimitCheck(Isolate* isolate) : isolate_(isolate) { }
1749 :
1750 : // Use this to check for stack-overflows in C++ code.
1751 : bool HasOverflowed() const {
1752 477911266 : StackGuard* stack_guard = isolate_->stack_guard();
1753 : return GetCurrentStackPosition() < stack_guard->real_climit();
1754 : }
1755 :
1756 : // Use this to check for interrupt request in C++ code.
1757 813330 : bool InterruptRequested() {
1758 813330 : StackGuard* stack_guard = isolate_->stack_guard();
1759 813330 : return GetCurrentStackPosition() < stack_guard->climit();
1760 : }
1761 :
1762 : // Use this to check for stack-overflow when entering runtime from JS code.
1763 : bool JsHasOverflowed(uintptr_t gap = 0) const;
1764 :
1765 : private:
1766 : Isolate* isolate_;
1767 : };
1768 :
1769 : #define STACK_CHECK(isolate, result_value) \
1770 : do { \
1771 : StackLimitCheck stack_check(isolate); \
1772 : if (stack_check.HasOverflowed()) { \
1773 : isolate->StackOverflow(); \
1774 : return result_value; \
1775 : } \
1776 : } while (false)
1777 :
1778 : // Support for temporarily postponing interrupts. When the outermost
1779 : // postpone scope is left the interrupts will be re-enabled and any
1780 : // interrupts that occurred while in the scope will be taken into
1781 : // account.
1782 : class PostponeInterruptsScope BASE_EMBEDDED {
1783 : public:
1784 : PostponeInterruptsScope(Isolate* isolate,
1785 : int intercept_mask = StackGuard::ALL_INTERRUPTS)
1786 3178443 : : stack_guard_(isolate->stack_guard()),
1787 : intercept_mask_(intercept_mask),
1788 3178443 : intercepted_flags_(0) {
1789 3178443 : stack_guard_->PushPostponeInterruptsScope(this);
1790 : }
1791 :
1792 : ~PostponeInterruptsScope() {
1793 3178444 : stack_guard_->PopPostponeInterruptsScope();
1794 : }
1795 :
1796 : // Find the bottom-most scope that intercepts this interrupt.
1797 : // Return whether the interrupt has been intercepted.
1798 : bool Intercept(StackGuard::InterruptFlag flag);
1799 :
1800 : private:
1801 : StackGuard* stack_guard_;
1802 : int intercept_mask_;
1803 : int intercepted_flags_;
1804 : PostponeInterruptsScope* prev_;
1805 :
1806 : friend class StackGuard;
1807 : };
1808 :
1809 :
1810 : class CodeTracer final : public Malloced {
1811 : public:
1812 0 : explicit CodeTracer(int isolate_id) : file_(nullptr), scope_depth_(0) {
1813 0 : if (!ShouldRedirect()) {
1814 0 : file_ = stdout;
1815 0 : return;
1816 : }
1817 :
1818 0 : if (FLAG_redirect_code_traces_to == nullptr) {
1819 : SNPrintF(filename_,
1820 : "code-%d-%d.asm",
1821 : base::OS::GetCurrentProcessId(),
1822 0 : isolate_id);
1823 : } else {
1824 0 : StrNCpy(filename_, FLAG_redirect_code_traces_to, filename_.length());
1825 : }
1826 :
1827 0 : WriteChars(filename_.start(), "", 0, false);
1828 : }
1829 :
1830 : class Scope {
1831 : public:
1832 0 : explicit Scope(CodeTracer* tracer) : tracer_(tracer) { tracer->OpenFile(); }
1833 0 : ~Scope() { tracer_->CloseFile(); }
1834 :
1835 0 : FILE* file() const { return tracer_->file(); }
1836 :
1837 : private:
1838 : CodeTracer* tracer_;
1839 : };
1840 :
1841 0 : void OpenFile() {
1842 0 : if (!ShouldRedirect()) {
1843 0 : return;
1844 : }
1845 :
1846 0 : if (file_ == nullptr) {
1847 0 : file_ = base::OS::FOpen(filename_.start(), "ab");
1848 : }
1849 :
1850 0 : scope_depth_++;
1851 : }
1852 :
1853 0 : void CloseFile() {
1854 0 : if (!ShouldRedirect()) {
1855 0 : return;
1856 : }
1857 :
1858 0 : if (--scope_depth_ == 0) {
1859 0 : fclose(file_);
1860 0 : file_ = nullptr;
1861 : }
1862 : }
1863 :
1864 : FILE* file() const { return file_; }
1865 :
1866 : private:
1867 : static bool ShouldRedirect() {
1868 0 : return FLAG_redirect_code_traces;
1869 : }
1870 :
1871 : EmbeddedVector<char, 128> filename_;
1872 : FILE* file_;
1873 : int scope_depth_;
1874 : };
1875 :
1876 : } // namespace internal
1877 : } // namespace v8
1878 :
1879 : #endif // V8_ISOLATE_H_
|