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.
9 #include "include/v8-debug.h"
10 #include "src/allocation.h"
11 #include "src/assert-scope.h"
12 #include "src/base/atomicops.h"
13 #include "src/builtins.h"
14 #include "src/contexts.h"
16 #include "src/execution.h"
17 #include "src/frames.h"
18 #include "src/global-handles.h"
19 #include "src/handles.h"
20 #include "src/hashmap.h"
21 #include "src/heap/heap.h"
22 #include "src/optimizing-compile-dispatcher.h"
23 #include "src/regexp-stack.h"
24 #include "src/runtime/runtime.h"
25 #include "src/runtime-profiler.h"
31 class RandomNumberGenerator;
36 class BasicBlockProfiler;
38 class CallInterfaceDescriptorData;
41 class CodeStubDescriptor;
43 class CompilationCache;
44 class CompilationStatistics;
45 class ContextSlotCache;
49 class DeoptimizerData;
52 class ExternalCallbackScope;
53 class ExternalReferenceTable;
55 class FunctionInfoListener;
56 class HandleScopeImplementer;
60 class InlineRuntimeFunctionsTable;
61 class InnerPointerToCodeCache;
62 class MaterializedObjectStore;
63 class CodeAgingHelper;
71 class ThreadVisitor; // Defined in v8threads.h
73 template <StateTag Tag> class VMState;
75 // 'void function pointer', used to roundtrip the
76 // ExternalReference::ExternalReferenceRedirector since we can not include
77 // assembler.h, where it is defined, here.
78 typedef void* ExternalReferenceRedirectorPointer();
88 // Static indirection table for handles to constants. If a frame
89 // element represents a constant, the data contains an index into
90 // this table of handles to the actual constants.
91 // Static indirection table for handles to constants. If a Result
92 // represents a constant, the data contains an index into this table
93 // of handles to the actual constants.
94 typedef ZoneList<Handle<Object> > ZoneObjectList;
96 #define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate) \
98 Isolate* __isolate__ = (isolate); \
99 if (__isolate__->has_scheduled_exception()) { \
100 return __isolate__->PromoteScheduledException(); \
104 // Macros for MaybeHandle.
106 #define RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, value) \
108 Isolate* __isolate__ = (isolate); \
109 if (__isolate__->has_scheduled_exception()) { \
110 __isolate__->PromoteScheduledException(); \
115 #define RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, T) \
116 RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, MaybeHandle<T>())
118 #define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value) \
120 if (!(call).ToHandle(&dst)) { \
121 DCHECK((isolate)->has_pending_exception()); \
126 #define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call) \
127 ASSIGN_RETURN_ON_EXCEPTION_VALUE( \
128 isolate, dst, call, isolate->heap()->exception())
130 #define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T) \
131 ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, MaybeHandle<T>())
133 #define THROW_NEW_ERROR(isolate, call, T) \
135 return isolate->Throw<T>(isolate->factory()->call); \
138 #define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call) \
140 return isolate->Throw(*isolate->factory()->call); \
143 #define RETURN_ON_EXCEPTION_VALUE(isolate, call, value) \
145 if ((call).is_null()) { \
146 DCHECK((isolate)->has_pending_exception()); \
151 #define RETURN_FAILURE_ON_EXCEPTION(isolate, call) \
152 RETURN_ON_EXCEPTION_VALUE(isolate, call, isolate->heap()->exception())
154 #define RETURN_ON_EXCEPTION(isolate, call, T) \
155 RETURN_ON_EXCEPTION_VALUE(isolate, call, MaybeHandle<T>())
158 #define FOR_EACH_ISOLATE_ADDRESS_NAME(C) \
159 C(Handler, handler) \
160 C(CEntryFP, c_entry_fp) \
161 C(CFunction, c_function) \
162 C(Context, context) \
163 C(PendingException, pending_exception) \
164 C(PendingHandlerContext, pending_handler_context) \
165 C(PendingHandlerCode, pending_handler_code) \
166 C(PendingHandlerOffset, pending_handler_offset) \
167 C(PendingHandlerFP, pending_handler_fp) \
168 C(PendingHandlerSP, pending_handler_sp) \
169 C(ExternalCaughtException, external_caught_exception) \
170 C(JSEntrySP, js_entry_sp)
173 // Platform-independent, reliable thread identifier.
176 // Creates an invalid ThreadId.
177 ThreadId() { base::NoBarrier_Store(&id_, kInvalidId); }
179 ThreadId& operator=(const ThreadId& other) {
180 base::NoBarrier_Store(&id_, base::NoBarrier_Load(&other.id_));
184 // Returns ThreadId for current thread.
185 static ThreadId Current() { return ThreadId(GetCurrentThreadId()); }
187 // Returns invalid ThreadId (guaranteed not to be equal to any thread).
188 static ThreadId Invalid() { return ThreadId(kInvalidId); }
190 // Compares ThreadIds for equality.
191 INLINE(bool Equals(const ThreadId& other) const) {
192 return base::NoBarrier_Load(&id_) == base::NoBarrier_Load(&other.id_);
195 // Checks whether this ThreadId refers to any thread.
196 INLINE(bool IsValid() const) {
197 return base::NoBarrier_Load(&id_) != kInvalidId;
200 // Converts ThreadId to an integer representation
201 // (required for public API: V8::V8::GetCurrentThreadId).
202 int ToInteger() const { return static_cast<int>(base::NoBarrier_Load(&id_)); }
204 // Converts ThreadId to an integer representation
205 // (required for public API: V8::V8::TerminateExecution).
206 static ThreadId FromInteger(int id) { return ThreadId(id); }
209 static const int kInvalidId = -1;
211 explicit ThreadId(int id) { base::NoBarrier_Store(&id_, id); }
213 static int AllocateThreadId();
215 static int GetCurrentThreadId();
219 static base::Atomic32 highest_thread_id_;
221 friend class Isolate;
225 #define FIELD_ACCESSOR(type, name) \
226 inline void set_##name(type v) { name##_ = v; } \
227 inline type name() const { return name##_; }
230 class ThreadLocalTop BASE_EMBEDDED {
232 // Does early low-level initialization that does not depend on the
233 // isolate being present.
236 // Initialize the thread data.
239 // Get the top C++ try catch handler or NULL if none are registered.
241 // This method is not guaranteed to return an address that can be
242 // used for comparison with addresses into the JS stack. If such an
243 // address is needed, use try_catch_handler_address.
244 FIELD_ACCESSOR(v8::TryCatch*, try_catch_handler)
246 // Get the address of the top C++ try catch handler or NULL if
247 // none are registered.
249 // This method always returns an address that can be compared to
250 // pointers into the JavaScript stack. When running on actual
251 // hardware, try_catch_handler_address and TryCatchHandler return
252 // the same pointer. When running on a simulator with a separate JS
253 // stack, try_catch_handler_address returns a JS stack address that
254 // corresponds to the place on the JS stack where the C++ handler
255 // would have been if the stack were not separate.
256 Address try_catch_handler_address() {
257 return reinterpret_cast<Address>(
258 v8::TryCatch::JSStackComparableAddress(try_catch_handler()));
264 // The context where the current execution method is created and for variable
268 Object* pending_exception_;
270 // Communication channel between Isolate::FindHandler and the CEntryStub.
271 Context* pending_handler_context_;
272 Code* pending_handler_code_;
273 intptr_t pending_handler_offset_;
274 Address pending_handler_fp_;
275 Address pending_handler_sp_;
277 // Communication channel between Isolate::Throw and message consumers.
278 bool rethrowing_message_;
279 Object* pending_message_obj_;
281 // Use a separate value for scheduled exceptions to preserve the
282 // invariants that hold about pending_exception. We may want to
284 Object* scheduled_exception_;
285 bool external_caught_exception_;
286 SaveContext* save_context_;
289 Address c_entry_fp_; // the frame pointer of the top c entry frame
290 Address handler_; // try-blocks are chained through the stack
291 Address c_function_; // C function that was called at c entry.
293 // Throwing an exception may cause a Promise rejection. For this purpose
294 // we keep track of a stack of nested promises and the corresponding
295 // try-catch handlers.
296 PromiseOnStack* promise_on_stack_;
299 Simulator* simulator_;
302 Address js_entry_sp_; // the stack pointer of the bottom JS entry frame
303 // the external callback we're currently in
304 ExternalCallbackScope* external_callback_scope_;
305 StateTag current_vm_state_;
307 // Call back function to report unsafe JS accesses.
308 v8::FailedAccessCheckCallback failed_access_check_callback_;
311 void InitializeInternal();
313 v8::TryCatch* try_catch_handler_;
319 #define ISOLATE_INIT_SIMULATOR_LIST(V) \
320 V(bool, simulator_initialized, false) \
321 V(HashMap*, simulator_i_cache, NULL) \
322 V(Redirection*, simulator_redirection, NULL)
325 #define ISOLATE_INIT_SIMULATOR_LIST(V)
332 #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V) \
333 V(CommentStatistic, paged_space_comments_statistics, \
334 CommentStatistic::kMaxComments + 1) \
335 V(int, code_kind_statistics, Code::NUMBER_OF_KINDS)
338 #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
342 #define ISOLATE_INIT_ARRAY_LIST(V) \
343 /* SerializerDeserializer state. */ \
344 V(int32_t, jsregexp_static_offsets_vector, kJSRegexpStaticOffsetsVectorSize) \
345 V(int, bad_char_shift_table, kUC16AlphabetSize) \
346 V(int, good_suffix_shift_table, (kBMMaxShift + 1)) \
347 V(int, suffix_table, (kBMMaxShift + 1)) \
348 V(uint32_t, private_random_seed, 2) \
349 ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
351 typedef List<HeapObject*> DebugObjectCache;
353 #define ISOLATE_INIT_LIST(V) \
354 /* Assembler state. */ \
355 V(FatalErrorCallback, exception_behavior, NULL) \
356 V(LogEventCallback, event_logger, NULL) \
357 V(AllowCodeGenerationFromStringsCallback, allow_code_gen_callback, NULL) \
358 /* To distinguish the function templates, so that we can find them in the */ \
359 /* function cache of the native context. */ \
360 V(int, next_serial_number, 0) \
361 V(ExternalReferenceRedirectorPointer*, external_reference_redirector, NULL) \
362 /* Part of the state of liveedit. */ \
363 V(FunctionInfoListener*, active_function_info_listener, NULL) \
364 /* State for Relocatable. */ \
365 V(Relocatable*, relocatable_top, NULL) \
366 V(DebugObjectCache*, string_stream_debug_object_cache, NULL) \
367 V(Object*, string_stream_current_security_token, NULL) \
368 V(ExternalReferenceTable*, external_reference_table, NULL) \
369 V(HashMap*, external_reference_map, NULL) \
370 V(HashMap*, root_index_map, NULL) \
371 V(int, pending_microtask_count, 0) \
372 V(bool, autorun_microtasks, true) \
373 V(HStatistics*, hstatistics, NULL) \
374 V(CompilationStatistics*, turbo_statistics, NULL) \
375 V(HTracer*, htracer, NULL) \
376 V(CodeTracer*, code_tracer, NULL) \
377 V(bool, fp_stubs_generated, false) \
378 V(uint32_t, per_isolate_assert_data, 0xFFFFFFFFu) \
379 V(PromiseRejectCallback, promise_reject_callback, NULL) \
380 V(const v8::StartupData*, snapshot_blob, NULL) \
381 V(bool, creating_default_snapshot, false) \
382 ISOLATE_INIT_SIMULATOR_LIST(V)
384 #define THREAD_LOCAL_TOP_ACCESSOR(type, name) \
385 inline void set_##name(type v) { thread_local_top_.name##_ = v; } \
386 inline type name() const { return thread_local_top_.name##_; }
388 #define THREAD_LOCAL_TOP_ADDRESS(type, name) \
389 type* name##_address() { return &thread_local_top_.name##_; }
393 // These forward declarations are required to make the friend declarations in
394 // PerIsolateThreadData work on some older versions of gcc.
395 class ThreadDataTable;
396 class EntryStackItem;
400 // A thread has a PerIsolateThreadData instance for each isolate that it has
401 // entered. That instance is allocated when the isolate is initially entered
402 // and reused on subsequent entries.
403 class PerIsolateThreadData {
405 PerIsolateThreadData(Isolate* isolate, ThreadId thread_id)
407 thread_id_(thread_id),
415 ~PerIsolateThreadData();
416 Isolate* isolate() const { return isolate_; }
417 ThreadId thread_id() const { return thread_id_; }
419 FIELD_ACCESSOR(uintptr_t, stack_limit)
420 FIELD_ACCESSOR(ThreadState*, thread_state)
423 FIELD_ACCESSOR(Simulator*, simulator)
426 bool Matches(Isolate* isolate, ThreadId thread_id) const {
427 return isolate_ == isolate && thread_id_.Equals(thread_id);
433 uintptr_t stack_limit_;
434 ThreadState* thread_state_;
437 Simulator* simulator_;
440 PerIsolateThreadData* next_;
441 PerIsolateThreadData* prev_;
443 friend class Isolate;
444 friend class ThreadDataTable;
445 friend class EntryStackItem;
447 DISALLOW_COPY_AND_ASSIGN(PerIsolateThreadData);
452 #define DECLARE_ENUM(CamelName, hacker_name) k##CamelName##Address,
453 FOR_EACH_ISOLATE_ADDRESS_NAME(DECLARE_ENUM)
458 static void InitializeOncePerProcess();
460 // Returns the PerIsolateThreadData for the current thread (or NULL if one is
461 // not currently set).
462 static PerIsolateThreadData* CurrentPerIsolateThreadData() {
463 return reinterpret_cast<PerIsolateThreadData*>(
464 base::Thread::GetThreadLocal(per_isolate_thread_data_key_));
467 // Returns the isolate inside which the current thread is running.
468 INLINE(static Isolate* Current()) {
469 DCHECK(base::NoBarrier_Load(&isolate_key_created_) == 1);
470 Isolate* isolate = reinterpret_cast<Isolate*>(
471 base::Thread::GetExistingThreadLocal(isolate_key_));
472 DCHECK(isolate != NULL);
476 INLINE(static Isolate* UncheckedCurrent()) {
477 DCHECK(base::NoBarrier_Load(&isolate_key_created_) == 1);
478 return reinterpret_cast<Isolate*>(
479 base::Thread::GetThreadLocal(isolate_key_));
482 // Like UncheckedCurrent, but skips the check that |isolate_key_| was
483 // initialized. Callers have to ensure that themselves.
484 INLINE(static Isolate* UnsafeCurrent()) {
485 return reinterpret_cast<Isolate*>(
486 base::Thread::GetThreadLocal(isolate_key_));
489 // Usually called by Init(), but can be called early e.g. to allow
490 // testing components that require logging but not the whole
493 // Safe to call more than once.
494 void InitializeLoggingAndCounters();
496 bool Init(Deserializer* des);
498 // True if at least one thread Enter'ed this isolate.
499 bool IsInUse() { return entry_stack_ != NULL; }
501 // Destroys the non-default isolates.
502 // Sets default isolate into "has_been_disposed" state rather then destroying,
503 // for legacy API reasons.
506 static void GlobalTearDown();
508 void ClearSerializerData();
510 // Find the PerThread for this particular (isolate, thread) combination
511 // If one does not yet exist, return null.
512 PerIsolateThreadData* FindPerThreadDataForThisThread();
514 // Find the PerThread for given (isolate, thread) combination
515 // If one does not yet exist, return null.
516 PerIsolateThreadData* FindPerThreadDataForThread(ThreadId thread_id);
518 // Returns the key used to store the pointer to the current isolate.
519 // Used internally for V8 threads that do not execute JavaScript but still
520 // are part of the domain of an isolate (like the context switcher).
521 static base::Thread::LocalStorageKey isolate_key() {
525 // Returns the key used to store process-wide thread IDs.
526 static base::Thread::LocalStorageKey thread_id_key() {
527 return thread_id_key_;
530 static base::Thread::LocalStorageKey per_isolate_thread_data_key();
532 // Mutex for serializing access to break control structures.
533 base::RecursiveMutex* break_access() { return &break_access_; }
535 Address get_address_from_id(AddressId id);
537 // Access to top context (where the current function object was created).
538 Context* context() { return thread_local_top_.context_; }
539 void set_context(Context* context) {
540 DCHECK(context == NULL || context->IsContext());
541 thread_local_top_.context_ = context;
543 Context** context_address() { return &thread_local_top_.context_; }
545 THREAD_LOCAL_TOP_ACCESSOR(SaveContext*, save_context)
547 // Access to current thread id.
548 THREAD_LOCAL_TOP_ACCESSOR(ThreadId, thread_id)
550 // Interface to pending exception.
551 Object* pending_exception() {
552 DCHECK(has_pending_exception());
553 DCHECK(!thread_local_top_.pending_exception_->IsException());
554 return thread_local_top_.pending_exception_;
557 void set_pending_exception(Object* exception_obj) {
558 DCHECK(!exception_obj->IsException());
559 thread_local_top_.pending_exception_ = exception_obj;
562 void clear_pending_exception() {
563 DCHECK(!thread_local_top_.pending_exception_->IsException());
564 thread_local_top_.pending_exception_ = heap_.the_hole_value();
567 THREAD_LOCAL_TOP_ADDRESS(Object*, pending_exception)
569 bool has_pending_exception() {
570 DCHECK(!thread_local_top_.pending_exception_->IsException());
571 return !thread_local_top_.pending_exception_->IsTheHole();
574 THREAD_LOCAL_TOP_ADDRESS(Context*, pending_handler_context)
575 THREAD_LOCAL_TOP_ADDRESS(Code*, pending_handler_code)
576 THREAD_LOCAL_TOP_ADDRESS(intptr_t, pending_handler_offset)
577 THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_fp)
578 THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_sp)
580 THREAD_LOCAL_TOP_ACCESSOR(bool, external_caught_exception)
582 void clear_pending_message() {
583 thread_local_top_.pending_message_obj_ = heap_.the_hole_value();
585 v8::TryCatch* try_catch_handler() {
586 return thread_local_top_.try_catch_handler();
588 bool* external_caught_exception_address() {
589 return &thread_local_top_.external_caught_exception_;
592 THREAD_LOCAL_TOP_ADDRESS(Object*, scheduled_exception)
594 Address pending_message_obj_address() {
595 return reinterpret_cast<Address>(&thread_local_top_.pending_message_obj_);
598 Object* scheduled_exception() {
599 DCHECK(has_scheduled_exception());
600 DCHECK(!thread_local_top_.scheduled_exception_->IsException());
601 return thread_local_top_.scheduled_exception_;
603 bool has_scheduled_exception() {
604 DCHECK(!thread_local_top_.scheduled_exception_->IsException());
605 return thread_local_top_.scheduled_exception_ != heap_.the_hole_value();
607 void clear_scheduled_exception() {
608 DCHECK(!thread_local_top_.scheduled_exception_->IsException());
609 thread_local_top_.scheduled_exception_ = heap_.the_hole_value();
612 bool IsJavaScriptHandlerOnTop(Object* exception);
613 bool IsExternalHandlerOnTop(Object* exception);
615 bool is_catchable_by_javascript(Object* exception) {
616 return exception != heap()->termination_exception();
619 // JS execution stack (see frames.h).
620 static Address c_entry_fp(ThreadLocalTop* thread) {
621 return thread->c_entry_fp_;
623 static Address handler(ThreadLocalTop* thread) { return thread->handler_; }
624 Address c_function() { return thread_local_top_.c_function_; }
626 inline Address* c_entry_fp_address() {
627 return &thread_local_top_.c_entry_fp_;
629 inline Address* handler_address() { return &thread_local_top_.handler_; }
630 inline Address* c_function_address() {
631 return &thread_local_top_.c_function_;
635 Address js_entry_sp() {
636 return thread_local_top_.js_entry_sp_;
638 inline Address* js_entry_sp_address() {
639 return &thread_local_top_.js_entry_sp_;
642 // Returns the global object of the current context. It could be
643 // a builtin object, or a JS global object.
644 Handle<GlobalObject> global_object() {
645 return Handle<GlobalObject>(context()->global_object());
648 // Returns the global proxy object of the current context.
649 JSObject* global_proxy() {
650 return context()->global_proxy();
653 Handle<JSBuiltinsObject> js_builtins_object() {
654 return Handle<JSBuiltinsObject>(thread_local_top_.context_->builtins());
657 static int ArchiveSpacePerThread() { return sizeof(ThreadLocalTop); }
658 void FreeThreadResources() { thread_local_top_.Free(); }
660 // This method is called by the api after operations that may throw
661 // exceptions. If an exception was thrown and not handled by an external
662 // handler the exception is scheduled to be rethrown when we return to running
663 // JavaScript code. If an exception is scheduled true is returned.
664 bool OptionalRescheduleException(bool is_bottom_call);
666 // Push and pop a promise and the current try-catch handler.
667 void PushPromise(Handle<JSObject> promise, Handle<JSFunction> function);
669 Handle<Object> GetPromiseOnStackOnThrow();
671 class ExceptionScope {
673 // Scope currently can only be used for regular exceptions,
674 // not termination exception.
675 explicit ExceptionScope(Isolate* isolate)
677 pending_exception_(isolate_->pending_exception(), isolate_) {}
680 isolate_->set_pending_exception(*pending_exception_);
685 Handle<Object> pending_exception_;
688 void SetCaptureStackTraceForUncaughtExceptions(
691 StackTrace::StackTraceOptions options);
693 enum PrintStackMode { kPrintStackConcise, kPrintStackVerbose };
694 void PrintCurrentStackTrace(FILE* out);
695 void PrintStack(StringStream* accumulator,
696 PrintStackMode mode = kPrintStackVerbose);
697 void PrintStack(FILE* out, PrintStackMode mode = kPrintStackVerbose);
698 Handle<String> StackTraceString();
699 NO_INLINE(void PushStackTraceAndDie(unsigned int magic, void* ptr1,
700 void* ptr2, unsigned int magic2));
701 Handle<JSArray> CaptureCurrentStackTrace(
703 StackTrace::StackTraceOptions options);
704 Handle<Object> CaptureSimpleStackTrace(Handle<JSObject> error_object,
705 Handle<Object> caller);
706 MaybeHandle<JSObject> CaptureAndSetDetailedStackTrace(
707 Handle<JSObject> error_object);
708 MaybeHandle<JSObject> CaptureAndSetSimpleStackTrace(
709 Handle<JSObject> error_object, Handle<Object> caller);
710 Handle<JSArray> GetDetailedStackTrace(Handle<JSObject> error_object);
711 Handle<JSArray> GetDetailedFromSimpleStackTrace(
712 Handle<JSObject> error_object);
714 // Returns if the top context may access the given global object. If
715 // the result is false, the pending exception is guaranteed to be
718 bool MayAccess(Handle<JSObject> receiver);
719 bool IsInternallyUsedPropertyName(Handle<Object> name);
720 bool IsInternallyUsedPropertyName(Object* name);
722 void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback);
723 void ReportFailedAccessCheck(Handle<JSObject> receiver);
725 // Exception throwing support. The caller should use the result
726 // of Throw() as its return value.
727 Object* Throw(Object* exception, MessageLocation* location = NULL);
728 Object* ThrowIllegalOperation();
730 template <typename T>
731 MUST_USE_RESULT MaybeHandle<T> Throw(Handle<Object> exception,
732 MessageLocation* location = NULL) {
733 Throw(*exception, location);
734 return MaybeHandle<T>();
737 // Re-throw an exception. This involves no error reporting since error
738 // reporting was handled when the exception was thrown originally.
739 Object* ReThrow(Object* exception);
741 // Find the correct handler for the current pending exception. This also
742 // clears and returns the current pending exception.
743 Object* UnwindAndFindHandler();
745 // Tries to predict whether an exception will be caught. Note that this can
746 // only produce an estimate, because it is undecidable whether a finally
747 // clause will consume or re-throw an exception. We conservatively assume any
748 // finally clause will behave as if the exception were consumed.
749 enum CatchType { NOT_CAUGHT, CAUGHT_BY_JAVASCRIPT, CAUGHT_BY_EXTERNAL };
750 CatchType PredictExceptionCatcher();
752 void ScheduleThrow(Object* exception);
753 // Re-set pending message, script and positions reported to the TryCatch
754 // back to the TLS for re-use when rethrowing.
755 void RestorePendingMessageFromTryCatch(v8::TryCatch* handler);
756 // Un-schedule an exception that was caught by a TryCatch handler.
757 void CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler);
758 void ReportPendingMessages();
759 // Return pending location if any or unfilled structure.
760 MessageLocation GetMessageLocation();
762 // Promote a scheduled exception to pending. Asserts has_scheduled_exception.
763 Object* PromoteScheduledException();
765 // Attempts to compute the current source location, storing the
766 // result in the target out parameter.
767 void ComputeLocation(MessageLocation* target);
768 bool ComputeLocationFromException(MessageLocation* target,
769 Handle<Object> exception);
770 bool ComputeLocationFromStackTrace(MessageLocation* target,
771 Handle<Object> exception);
773 Handle<JSMessageObject> CreateMessage(Handle<Object> exception,
774 MessageLocation* location);
776 // Out of resource exception helpers.
777 Object* StackOverflow();
778 Object* TerminateExecution();
779 void CancelTerminateExecution();
781 void RequestInterrupt(InterruptCallback callback, void* data);
782 void InvokeApiInterruptCallbacks();
785 void Iterate(ObjectVisitor* v);
786 void Iterate(ObjectVisitor* v, ThreadLocalTop* t);
787 char* Iterate(ObjectVisitor* v, char* t);
788 void IterateThread(ThreadVisitor* v, char* t);
790 // Returns the current native context.
791 Handle<Context> native_context();
793 // Returns the native context of the calling JavaScript code. That
794 // is, the native context of the top-most JavaScript frame.
795 Handle<Context> GetCallingNativeContext();
797 void RegisterTryCatchHandler(v8::TryCatch* that);
798 void UnregisterTryCatchHandler(v8::TryCatch* that);
800 char* ArchiveThread(char* to);
801 char* RestoreThread(char* from);
803 static const char* const kStackOverflowMessage;
805 static const int kUC16AlphabetSize = 256; // See StringSearchBase.
806 static const int kBMMaxShift = 250; // See StringSearchBase.
809 #define GLOBAL_ACCESSOR(type, name, initialvalue) \
810 inline type name() const { \
811 DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
814 inline void set_##name(type value) { \
815 DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
818 ISOLATE_INIT_LIST(GLOBAL_ACCESSOR)
819 #undef GLOBAL_ACCESSOR
821 #define GLOBAL_ARRAY_ACCESSOR(type, name, length) \
822 inline type* name() { \
823 DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
824 return &(name##_)[0]; \
826 ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_ACCESSOR)
827 #undef GLOBAL_ARRAY_ACCESSOR
829 #define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name) \
830 Handle<type> name() { \
831 return Handle<type>(native_context()->name(), this); \
833 bool is_##name(type* value) { \
834 return native_context()->is_##name(value); \
836 NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
837 #undef NATIVE_CONTEXT_FIELD_ACCESSOR
839 Bootstrapper* bootstrapper() { return bootstrapper_; }
840 Counters* counters() {
841 // Call InitializeLoggingAndCounters() if logging is needed before
842 // the isolate is fully initialized.
843 DCHECK(counters_ != NULL);
846 CodeRange* code_range() { return code_range_; }
847 RuntimeProfiler* runtime_profiler() { return runtime_profiler_; }
848 CompilationCache* compilation_cache() { return compilation_cache_; }
850 // Call InitializeLoggingAndCounters() if logging is needed before
851 // the isolate is fully initialized.
852 DCHECK(logger_ != NULL);
855 StackGuard* stack_guard() { return &stack_guard_; }
856 Heap* heap() { return &heap_; }
857 StatsTable* stats_table();
858 StubCache* stub_cache() { return stub_cache_; }
859 CodeAgingHelper* code_aging_helper() { return code_aging_helper_; }
860 DeoptimizerData* deoptimizer_data() { return deoptimizer_data_; }
861 ThreadLocalTop* thread_local_top() { return &thread_local_top_; }
862 MaterializedObjectStore* materialized_object_store() {
863 return materialized_object_store_;
866 MemoryAllocator* memory_allocator() {
867 return memory_allocator_;
870 KeyedLookupCache* keyed_lookup_cache() {
871 return keyed_lookup_cache_;
874 ContextSlotCache* context_slot_cache() {
875 return context_slot_cache_;
878 DescriptorLookupCache* descriptor_lookup_cache() {
879 return descriptor_lookup_cache_;
882 HandleScopeData* handle_scope_data() { return &handle_scope_data_; }
884 HandleScopeImplementer* handle_scope_implementer() {
885 DCHECK(handle_scope_implementer_);
886 return handle_scope_implementer_;
888 Zone* runtime_zone() { return &runtime_zone_; }
890 UnicodeCache* unicode_cache() {
891 return unicode_cache_;
894 InnerPointerToCodeCache* inner_pointer_to_code_cache() {
895 return inner_pointer_to_code_cache_;
898 GlobalHandles* global_handles() { return global_handles_; }
900 EternalHandles* eternal_handles() { return eternal_handles_; }
902 ThreadManager* thread_manager() { return thread_manager_; }
904 StringTracker* string_tracker() { return string_tracker_; }
906 unibrow::Mapping<unibrow::Ecma262UnCanonicalize>* jsregexp_uncanonicalize() {
907 return &jsregexp_uncanonicalize_;
910 unibrow::Mapping<unibrow::CanonicalizationRange>* jsregexp_canonrange() {
911 return &jsregexp_canonrange_;
914 RuntimeState* runtime_state() { return &runtime_state_; }
916 Builtins* builtins() { return &builtins_; }
918 void NotifyExtensionInstalled() {
919 has_installed_extensions_ = true;
922 bool has_installed_extensions() { return has_installed_extensions_; }
924 unibrow::Mapping<unibrow::Ecma262Canonicalize>*
925 regexp_macro_assembler_canonicalize() {
926 return ®exp_macro_assembler_canonicalize_;
929 RegExpStack* regexp_stack() { return regexp_stack_; }
931 unibrow::Mapping<unibrow::Ecma262Canonicalize>*
932 interp_canonicalize_mapping() {
933 return &interp_canonicalize_mapping_;
936 Debug* debug() { return debug_; }
938 CpuProfiler* cpu_profiler() const { return cpu_profiler_; }
939 HeapProfiler* heap_profiler() const { return heap_profiler_; }
942 HistogramInfo* heap_histograms() { return heap_histograms_; }
944 JSObject::SpillInformation* js_spill_information() {
945 return &js_spill_information_;
949 Factory* factory() { return reinterpret_cast<Factory*>(this); }
951 static const int kJSRegexpStaticOffsetsVectorSize = 128;
953 THREAD_LOCAL_TOP_ACCESSOR(ExternalCallbackScope*, external_callback_scope)
955 THREAD_LOCAL_TOP_ACCESSOR(StateTag, current_vm_state)
957 void SetData(uint32_t slot, void* data) {
958 DCHECK(slot < Internals::kNumIsolateDataSlots);
959 embedder_data_[slot] = data;
961 void* GetData(uint32_t slot) {
962 DCHECK(slot < Internals::kNumIsolateDataSlots);
963 return embedder_data_[slot];
966 bool serializer_enabled() const { return serializer_enabled_; }
967 bool snapshot_available() const {
968 return snapshot_blob_ != NULL && snapshot_blob_->raw_size != 0;
971 bool IsDead() { return has_fatal_error_; }
972 void SignalFatalError() { has_fatal_error_ = true; }
974 bool use_crankshaft() const;
976 bool initialized_from_snapshot() { return initialized_from_snapshot_; }
978 double time_millis_since_init() {
979 return base::OS::TimeCurrentMillis() - time_millis_at_init_;
982 DateCache* date_cache() {
986 void set_date_cache(DateCache* date_cache) {
987 if (date_cache != date_cache_) {
990 date_cache_ = date_cache;
993 Map* get_initial_js_array_map(ElementsKind kind,
994 ObjectStrength strength = WEAK);
996 static const int kArrayProtectorValid = 1;
997 static const int kArrayProtectorInvalid = 0;
999 bool IsFastArrayConstructorPrototypeChainIntact();
1001 // On intent to set an element in object, make sure that appropriate
1002 // notifications occur if the set is on the elements of the array or
1003 // object prototype. Also ensure that changes to prototype chain between
1004 // Array and Object fire notifications.
1005 void UpdateArrayProtectorOnSetElement(Handle<JSObject> object);
1006 void UpdateArrayProtectorOnSetLength(Handle<JSObject> object) {
1007 UpdateArrayProtectorOnSetElement(object);
1009 void UpdateArrayProtectorOnSetPrototype(Handle<JSObject> object) {
1010 UpdateArrayProtectorOnSetElement(object);
1012 void UpdateArrayProtectorOnNormalizeElements(Handle<JSObject> object) {
1013 UpdateArrayProtectorOnSetElement(object);
1016 // Returns true if array is the initial array prototype in any native context.
1017 bool IsAnyInitialArrayPrototype(Handle<JSArray> array);
1019 CallInterfaceDescriptorData* call_descriptor_data(int index);
1021 void IterateDeferredHandles(ObjectVisitor* visitor);
1022 void LinkDeferredHandles(DeferredHandles* deferred_handles);
1023 void UnlinkDeferredHandles(DeferredHandles* deferred_handles);
1026 bool IsDeferredHandle(Object** location);
1029 bool concurrent_recompilation_enabled() {
1030 // Thread is only available with flag enabled.
1031 DCHECK(optimizing_compile_dispatcher_ == NULL ||
1032 FLAG_concurrent_recompilation);
1033 return optimizing_compile_dispatcher_ != NULL;
1036 bool concurrent_osr_enabled() const {
1037 // Thread is only available with flag enabled.
1038 DCHECK(optimizing_compile_dispatcher_ == NULL ||
1039 FLAG_concurrent_recompilation);
1040 return optimizing_compile_dispatcher_ != NULL && FLAG_concurrent_osr;
1043 OptimizingCompileDispatcher* optimizing_compile_dispatcher() {
1044 return optimizing_compile_dispatcher_;
1047 int id() const { return static_cast<int>(id_); }
1049 HStatistics* GetHStatistics();
1050 CompilationStatistics* GetTurboStatistics();
1051 HTracer* GetHTracer();
1052 CodeTracer* GetCodeTracer();
1054 void DumpAndResetCompilationStats();
1056 FunctionEntryHook function_entry_hook() { return function_entry_hook_; }
1057 void set_function_entry_hook(FunctionEntryHook function_entry_hook) {
1058 function_entry_hook_ = function_entry_hook;
1061 void* stress_deopt_count_address() { return &stress_deopt_count_; }
1063 base::RandomNumberGenerator* random_number_generator();
1065 // Given an address occupied by a live code object, return that object.
1066 Object* FindCodeObject(Address a);
1068 int NextOptimizationId() {
1069 int id = next_optimization_id_++;
1070 if (!Smi::IsValid(next_optimization_id_)) {
1071 next_optimization_id_ = 0;
1076 // Get (and lazily initialize) the registry for per-isolate symbols.
1077 Handle<JSObject> GetSymbolRegistry();
1079 void AddCallCompletedCallback(CallCompletedCallback callback);
1080 void RemoveCallCompletedCallback(CallCompletedCallback callback);
1081 void FireCallCompletedCallback();
1083 void SetPromiseRejectCallback(PromiseRejectCallback callback);
1084 void ReportPromiseReject(Handle<JSObject> promise, Handle<Object> value,
1085 v8::PromiseRejectEvent event);
1087 void EnqueueMicrotask(Handle<Object> microtask);
1088 void RunMicrotasks();
1090 void SetUseCounterCallback(v8::Isolate::UseCounterCallback callback);
1091 void CountUsage(v8::Isolate::UseCounterFeature feature);
1093 BasicBlockProfiler* GetOrCreateBasicBlockProfiler();
1094 BasicBlockProfiler* basic_block_profiler() { return basic_block_profiler_; }
1096 std::string GetTurboCfgFileName();
1099 int GetNextUniqueSharedFunctionInfoId() { return next_unique_sfi_id_++; }
1102 void set_store_buffer_hash_set_1_address(
1103 uintptr_t* store_buffer_hash_set_1_address) {
1104 store_buffer_hash_set_1_address_ = store_buffer_hash_set_1_address;
1107 uintptr_t* store_buffer_hash_set_1_address() {
1108 return store_buffer_hash_set_1_address_;
1111 void set_store_buffer_hash_set_2_address(
1112 uintptr_t* store_buffer_hash_set_2_address) {
1113 store_buffer_hash_set_2_address_ = store_buffer_hash_set_2_address;
1116 uintptr_t* store_buffer_hash_set_2_address() {
1117 return store_buffer_hash_set_2_address_;
1120 void AddDetachedContext(Handle<Context> context);
1121 void CheckDetachedContextsAfterGC();
1123 List<Object*>* partial_snapshot_cache() { return &partial_snapshot_cache_; }
1125 void set_array_buffer_allocator(v8::ArrayBuffer::Allocator* allocator) {
1126 array_buffer_allocator_ = allocator;
1128 v8::ArrayBuffer::Allocator* array_buffer_allocator() const {
1129 return array_buffer_allocator_;
1133 explicit Isolate(bool enable_serializer);
1136 friend struct GlobalState;
1137 friend struct InitializeGlobalState;
1138 Handle<JSObject> SetUpSubregistry(Handle<JSObject> registry, Handle<Map> map,
1141 // These fields are accessed through the API, offsets must be kept in sync
1142 // with v8::internal::Internals (in include/v8.h) constants. This is also
1143 // verified in Isolate::Init() using runtime checks.
1144 void* embedder_data_[Internals::kNumIsolateDataSlots];
1147 // The per-process lock should be acquired before the ThreadDataTable is
1149 class ThreadDataTable {
1154 PerIsolateThreadData* Lookup(Isolate* isolate, ThreadId thread_id);
1155 void Insert(PerIsolateThreadData* data);
1156 void Remove(PerIsolateThreadData* data);
1157 void RemoveAllThreads(Isolate* isolate);
1160 PerIsolateThreadData* list_;
1163 // These items form a stack synchronously with threads Enter'ing and Exit'ing
1164 // the Isolate. The top of the stack points to a thread which is currently
1165 // running the Isolate. When the stack is empty, the Isolate is considered
1166 // not entered by any thread and can be Disposed.
1167 // If the same thread enters the Isolate more then once, the entry_count_
1168 // is incremented rather then a new item pushed to the stack.
1169 class EntryStackItem {
1171 EntryStackItem(PerIsolateThreadData* previous_thread_data,
1172 Isolate* previous_isolate,
1173 EntryStackItem* previous_item)
1175 previous_thread_data(previous_thread_data),
1176 previous_isolate(previous_isolate),
1177 previous_item(previous_item) { }
1180 PerIsolateThreadData* previous_thread_data;
1181 Isolate* previous_isolate;
1182 EntryStackItem* previous_item;
1185 DISALLOW_COPY_AND_ASSIGN(EntryStackItem);
1188 static base::LazyMutex thread_data_table_mutex_;
1190 static base::Thread::LocalStorageKey per_isolate_thread_data_key_;
1191 static base::Thread::LocalStorageKey isolate_key_;
1192 static base::Thread::LocalStorageKey thread_id_key_;
1193 static ThreadDataTable* thread_data_table_;
1195 // A global counter for all generated Isolates, might overflow.
1196 static base::Atomic32 isolate_counter_;
1199 static base::Atomic32 isolate_key_created_;
1204 static void SetIsolateThreadLocals(Isolate* isolate,
1205 PerIsolateThreadData* data);
1207 // Find the PerThread for this particular (isolate, thread) combination.
1208 // If one does not yet exist, allocate a new one.
1209 PerIsolateThreadData* FindOrAllocatePerThreadDataForThisThread();
1211 // Initializes the current thread to run this Isolate.
1212 // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
1213 // at the same time, this should be prevented using external locking.
1216 // Exits the current thread. The previosuly entered Isolate is restored
1218 // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
1219 // at the same time, this should be prevented using external locking.
1222 void InitializeThreadLocal();
1224 void MarkCompactPrologue(bool is_compacting,
1225 ThreadLocalTop* archived_thread_data);
1226 void MarkCompactEpilogue(bool is_compacting,
1227 ThreadLocalTop* archived_thread_data);
1231 // Propagate pending exception message to the v8::TryCatch.
1232 // If there is no external try-catch or message was successfully propagated,
1233 // then return true.
1234 bool PropagatePendingExceptionToExternalTryCatch();
1236 // Remove per-frame stored materialized objects when we are unwinding
1238 void RemoveMaterializedObjectsOnUnwind(StackFrame* frame);
1240 // Traverse prototype chain to find out whether the object is derived from
1241 // the Error object.
1242 bool IsErrorObject(Handle<Object> obj);
1245 EntryStackItem* entry_stack_;
1246 int stack_trace_nesting_level_;
1247 StringStream* incomplete_message_;
1248 Address isolate_addresses_[kIsolateAddressCount + 1]; // NOLINT
1249 Bootstrapper* bootstrapper_;
1250 RuntimeProfiler* runtime_profiler_;
1251 CompilationCache* compilation_cache_;
1252 Counters* counters_;
1253 CodeRange* code_range_;
1254 base::RecursiveMutex break_access_;
1256 StackGuard stack_guard_;
1257 StatsTable* stats_table_;
1258 StubCache* stub_cache_;
1259 CodeAgingHelper* code_aging_helper_;
1260 DeoptimizerData* deoptimizer_data_;
1261 MaterializedObjectStore* materialized_object_store_;
1262 ThreadLocalTop thread_local_top_;
1263 bool capture_stack_trace_for_uncaught_exceptions_;
1264 int stack_trace_for_uncaught_exceptions_frame_limit_;
1265 StackTrace::StackTraceOptions stack_trace_for_uncaught_exceptions_options_;
1266 MemoryAllocator* memory_allocator_;
1267 KeyedLookupCache* keyed_lookup_cache_;
1268 ContextSlotCache* context_slot_cache_;
1269 DescriptorLookupCache* descriptor_lookup_cache_;
1270 HandleScopeData handle_scope_data_;
1271 HandleScopeImplementer* handle_scope_implementer_;
1272 UnicodeCache* unicode_cache_;
1274 InnerPointerToCodeCache* inner_pointer_to_code_cache_;
1275 GlobalHandles* global_handles_;
1276 EternalHandles* eternal_handles_;
1277 ThreadManager* thread_manager_;
1278 RuntimeState runtime_state_;
1280 bool has_installed_extensions_;
1281 StringTracker* string_tracker_;
1282 unibrow::Mapping<unibrow::Ecma262UnCanonicalize> jsregexp_uncanonicalize_;
1283 unibrow::Mapping<unibrow::CanonicalizationRange> jsregexp_canonrange_;
1284 unibrow::Mapping<unibrow::Ecma262Canonicalize>
1285 regexp_macro_assembler_canonicalize_;
1286 RegExpStack* regexp_stack_;
1287 DateCache* date_cache_;
1288 unibrow::Mapping<unibrow::Ecma262Canonicalize> interp_canonicalize_mapping_;
1289 CallInterfaceDescriptorData* call_descriptor_data_;
1290 base::RandomNumberGenerator* random_number_generator_;
1291 // TODO(hpayer): Remove the following store buffer addresses.
1292 uintptr_t* store_buffer_hash_set_1_address_;
1293 uintptr_t* store_buffer_hash_set_2_address_;
1295 // Whether the isolate has been created for snapshotting.
1296 bool serializer_enabled_;
1298 // True if fatal error has been signaled for this isolate.
1299 bool has_fatal_error_;
1301 // True if this isolate was initialized from a snapshot.
1302 bool initialized_from_snapshot_;
1304 // Time stamp at initialization.
1305 double time_millis_at_init_;
1308 // A static array of histogram info for each type.
1309 HistogramInfo heap_histograms_[LAST_TYPE + 1];
1310 JSObject::SpillInformation js_spill_information_;
1314 CpuProfiler* cpu_profiler_;
1315 HeapProfiler* heap_profiler_;
1316 FunctionEntryHook function_entry_hook_;
1318 typedef std::pair<InterruptCallback, void*> InterruptEntry;
1319 std::queue<InterruptEntry> api_interrupts_queue_;
1321 #define GLOBAL_BACKING_STORE(type, name, initialvalue) \
1323 ISOLATE_INIT_LIST(GLOBAL_BACKING_STORE)
1324 #undef GLOBAL_BACKING_STORE
1326 #define GLOBAL_ARRAY_BACKING_STORE(type, name, length) \
1327 type name##_[length];
1328 ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_BACKING_STORE)
1329 #undef GLOBAL_ARRAY_BACKING_STORE
1332 // This class is huge and has a number of fields controlled by
1333 // preprocessor defines. Make sure the offsets of these fields agree
1334 // between compilation units.
1335 #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1336 static const intptr_t name##_debug_offset_;
1337 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
1338 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
1339 #undef ISOLATE_FIELD_OFFSET
1342 DeferredHandles* deferred_handles_head_;
1343 OptimizingCompileDispatcher* optimizing_compile_dispatcher_;
1345 // Counts deopt points if deopt_every_n_times is enabled.
1346 unsigned int stress_deopt_count_;
1348 int next_optimization_id_;
1351 int next_unique_sfi_id_;
1354 // List of callbacks when a Call completes.
1355 List<CallCompletedCallback> call_completed_callbacks_;
1357 v8::Isolate::UseCounterCallback use_counter_callback_;
1358 BasicBlockProfiler* basic_block_profiler_;
1360 List<Object*> partial_snapshot_cache_;
1362 v8::ArrayBuffer::Allocator* array_buffer_allocator_;
1364 friend class ExecutionAccess;
1365 friend class HandleScopeImplementer;
1366 friend class OptimizingCompileDispatcher;
1367 friend class SweeperThread;
1368 friend class ThreadManager;
1369 friend class Simulator;
1370 friend class StackGuard;
1371 friend class ThreadId;
1372 friend class TestMemoryAllocatorScope;
1373 friend class TestCodeRangeScope;
1374 friend class v8::Isolate;
1375 friend class v8::Locker;
1376 friend class v8::Unlocker;
1377 friend v8::StartupData v8::V8::CreateSnapshotDataBlob(const char*);
1379 DISALLOW_COPY_AND_ASSIGN(Isolate);
1383 #undef FIELD_ACCESSOR
1384 #undef THREAD_LOCAL_TOP_ACCESSOR
1387 class PromiseOnStack {
1389 PromiseOnStack(Handle<JSFunction> function, Handle<JSObject> promise,
1390 PromiseOnStack* prev)
1391 : function_(function), promise_(promise), prev_(prev) {}
1392 Handle<JSFunction> function() { return function_; }
1393 Handle<JSObject> promise() { return promise_; }
1394 PromiseOnStack* prev() { return prev_; }
1397 Handle<JSFunction> function_;
1398 Handle<JSObject> promise_;
1399 PromiseOnStack* prev_;
1403 // If the GCC version is 4.1.x or 4.2.x an additional field is added to the
1404 // class as a work around for a bug in the generated code found with these
1405 // versions of GCC. See V8 issue 122 for details.
1406 class SaveContext BASE_EMBEDDED {
1408 explicit SaveContext(Isolate* isolate);
1411 isolate_->set_context(context_.is_null() ? NULL : *context_);
1412 isolate_->set_save_context(prev_);
1415 Handle<Context> context() { return context_; }
1416 SaveContext* prev() { return prev_; }
1418 // Returns true if this save context is below a given JavaScript frame.
1419 bool IsBelowFrame(JavaScriptFrame* frame) {
1420 return (c_entry_fp_ == 0) || (c_entry_fp_ > frame->sp());
1425 Handle<Context> context_;
1427 Address c_entry_fp_;
1431 class AssertNoContextChange BASE_EMBEDDED {
1434 explicit AssertNoContextChange(Isolate* isolate)
1435 : isolate_(isolate),
1436 context_(isolate->context(), isolate) { }
1437 ~AssertNoContextChange() {
1438 DCHECK(isolate_->context() == *context_);
1443 Handle<Context> context_;
1446 explicit AssertNoContextChange(Isolate* isolate) { }
1451 class ExecutionAccess BASE_EMBEDDED {
1453 explicit ExecutionAccess(Isolate* isolate) : isolate_(isolate) {
1456 ~ExecutionAccess() { Unlock(isolate_); }
1458 static void Lock(Isolate* isolate) { isolate->break_access()->Lock(); }
1459 static void Unlock(Isolate* isolate) { isolate->break_access()->Unlock(); }
1461 static bool TryLock(Isolate* isolate) {
1462 return isolate->break_access()->TryLock();
1470 // Support for checking for stack-overflows.
1471 class StackLimitCheck BASE_EMBEDDED {
1473 explicit StackLimitCheck(Isolate* isolate) : isolate_(isolate) { }
1475 // Use this to check for stack-overflows in C++ code.
1476 inline bool HasOverflowed() const {
1477 StackGuard* stack_guard = isolate_->stack_guard();
1478 return GetCurrentStackPosition() < stack_guard->real_climit();
1481 // Use this to check for stack-overflow when entering runtime from JS code.
1482 bool JsHasOverflowed() const;
1489 // Support for temporarily postponing interrupts. When the outermost
1490 // postpone scope is left the interrupts will be re-enabled and any
1491 // interrupts that occurred while in the scope will be taken into
1493 class PostponeInterruptsScope BASE_EMBEDDED {
1495 PostponeInterruptsScope(Isolate* isolate,
1496 int intercept_mask = StackGuard::ALL_INTERRUPTS)
1497 : stack_guard_(isolate->stack_guard()),
1498 intercept_mask_(intercept_mask),
1499 intercepted_flags_(0) {
1500 stack_guard_->PushPostponeInterruptsScope(this);
1503 ~PostponeInterruptsScope() {
1504 stack_guard_->PopPostponeInterruptsScope();
1507 // Find the bottom-most scope that intercepts this interrupt.
1508 // Return whether the interrupt has been intercepted.
1509 bool Intercept(StackGuard::InterruptFlag flag);
1512 StackGuard* stack_guard_;
1513 int intercept_mask_;
1514 int intercepted_flags_;
1515 PostponeInterruptsScope* prev_;
1517 friend class StackGuard;
1521 class CodeTracer final : public Malloced {
1523 explicit CodeTracer(int isolate_id)
1526 if (!ShouldRedirect()) {
1531 if (FLAG_redirect_code_traces_to == NULL) {
1534 base::OS::GetCurrentProcessId(),
1537 StrNCpy(filename_, FLAG_redirect_code_traces_to, filename_.length());
1540 WriteChars(filename_.start(), "", 0, false);
1545 explicit Scope(CodeTracer* tracer) : tracer_(tracer) { tracer->OpenFile(); }
1546 ~Scope() { tracer_->CloseFile(); }
1548 FILE* file() const { return tracer_->file(); }
1551 CodeTracer* tracer_;
1555 if (!ShouldRedirect()) {
1559 if (file_ == NULL) {
1560 file_ = base::OS::FOpen(filename_.start(), "ab");
1567 if (!ShouldRedirect()) {
1571 if (--scope_depth_ == 0) {
1577 FILE* file() const { return file_; }
1580 static bool ShouldRedirect() {
1581 return FLAG_redirect_code_traces;
1584 EmbeddedVector<char, 128> filename_;
1589 } } // namespace v8::internal
1591 #endif // V8_ISOLATE_H_