4b242a3d5f51a021e6e8fbd9cb7f76d5ab5e328a
[platform/upstream/v8.git] / src / isolate.h
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 <queue>
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"
15 #include "src/date.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"
26 #include "src/zone.h"
27
28 namespace v8 {
29
30 namespace base {
31 class RandomNumberGenerator;
32 }
33
34 namespace internal {
35
36 class BasicBlockProfiler;
37 class Bootstrapper;
38 class CallInterfaceDescriptorData;
39 class CodeGenerator;
40 class CodeRange;
41 class CodeStubDescriptor;
42 class CodeTracer;
43 class CompilationCache;
44 class CompilationStatistics;
45 class ContextSlotCache;
46 class Counters;
47 class CpuFeatures;
48 class CpuProfiler;
49 class DeoptimizerData;
50 class Deserializer;
51 class EmptyStatement;
52 class ExternalCallbackScope;
53 class ExternalReferenceTable;
54 class Factory;
55 class FunctionInfoListener;
56 class HandleScopeImplementer;
57 class HeapProfiler;
58 class HStatistics;
59 class HTracer;
60 class InlineRuntimeFunctionsTable;
61 class InnerPointerToCodeCache;
62 class MaterializedObjectStore;
63 class CodeAgingHelper;
64 class RegExpStack;
65 class SaveContext;
66 class StringTracker;
67 class StubCache;
68 class SweeperThread;
69 class ThreadManager;
70 class ThreadState;
71 class ThreadVisitor;  // Defined in v8threads.h
72 class UnicodeCache;
73 template <StateTag Tag> class VMState;
74
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();
79
80
81 class Debug;
82 class Debugger;
83 class PromiseOnStack;
84 class Redirection;
85 class Simulator;
86
87
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;
95
96 #define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate)    \
97   do {                                                    \
98     Isolate* __isolate__ = (isolate);                     \
99     if (__isolate__->has_scheduled_exception()) {         \
100       return __isolate__->PromoteScheduledException();    \
101     }                                                     \
102   } while (false)
103
104 // Macros for MaybeHandle.
105
106 #define RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, value) \
107   do {                                                      \
108     Isolate* __isolate__ = (isolate);                       \
109     if (__isolate__->has_scheduled_exception()) {           \
110       __isolate__->PromoteScheduledException();             \
111       return value;                                         \
112     }                                                       \
113   } while (false)
114
115 #define RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, T) \
116   RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, MaybeHandle<T>())
117
118 #define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value)  \
119   do {                                                               \
120     if (!(call).ToHandle(&dst)) {                                    \
121       DCHECK((isolate)->has_pending_exception());                    \
122       return value;                                                  \
123     }                                                                \
124   } while (false)
125
126 #define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call)  \
127   ASSIGN_RETURN_ON_EXCEPTION_VALUE(                             \
128       isolate, dst, call, isolate->heap()->exception())
129
130 #define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T)  \
131   ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, MaybeHandle<T>())
132
133 #define THROW_NEW_ERROR(isolate, call, T)               \
134   do {                                                  \
135     return isolate->Throw<T>(isolate->factory()->call); \
136   } while (false)
137
138 #define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call) \
139   do {                                                \
140     return isolate->Throw(*isolate->factory()->call); \
141   } while (false)
142
143 #define RETURN_ON_EXCEPTION_VALUE(isolate, call, value)            \
144   do {                                                             \
145     if ((call).is_null()) {                                        \
146       DCHECK((isolate)->has_pending_exception());                  \
147       return value;                                                \
148     }                                                              \
149   } while (false)
150
151 #define RETURN_FAILURE_ON_EXCEPTION(isolate, call)  \
152   RETURN_ON_EXCEPTION_VALUE(isolate, call, isolate->heap()->exception())
153
154 #define RETURN_ON_EXCEPTION(isolate, call, T)  \
155   RETURN_ON_EXCEPTION_VALUE(isolate, call, MaybeHandle<T>())
156
157
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)
171
172
173 // Platform-independent, reliable thread identifier.
174 class ThreadId {
175  public:
176   // Creates an invalid ThreadId.
177   ThreadId() { base::NoBarrier_Store(&id_, kInvalidId); }
178
179   ThreadId& operator=(const ThreadId& other) {
180     base::NoBarrier_Store(&id_, base::NoBarrier_Load(&other.id_));
181     return *this;
182   }
183
184   // Returns ThreadId for current thread.
185   static ThreadId Current() { return ThreadId(GetCurrentThreadId()); }
186
187   // Returns invalid ThreadId (guaranteed not to be equal to any thread).
188   static ThreadId Invalid() { return ThreadId(kInvalidId); }
189
190   // Compares ThreadIds for equality.
191   INLINE(bool Equals(const ThreadId& other) const) {
192     return base::NoBarrier_Load(&id_) == base::NoBarrier_Load(&other.id_);
193   }
194
195   // Checks whether this ThreadId refers to any thread.
196   INLINE(bool IsValid() const) {
197     return base::NoBarrier_Load(&id_) != kInvalidId;
198   }
199
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_)); }
203
204   // Converts ThreadId to an integer representation
205   // (required for public API: V8::V8::TerminateExecution).
206   static ThreadId FromInteger(int id) { return ThreadId(id); }
207
208  private:
209   static const int kInvalidId = -1;
210
211   explicit ThreadId(int id) { base::NoBarrier_Store(&id_, id); }
212
213   static int AllocateThreadId();
214
215   static int GetCurrentThreadId();
216
217   base::Atomic32 id_;
218
219   static base::Atomic32 highest_thread_id_;
220
221   friend class Isolate;
222 };
223
224
225 #define FIELD_ACCESSOR(type, name)                 \
226   inline void set_##name(type v) { name##_ = v; }  \
227   inline type name() const { return name##_; }
228
229
230 class ThreadLocalTop BASE_EMBEDDED {
231  public:
232   // Does early low-level initialization that does not depend on the
233   // isolate being present.
234   ThreadLocalTop();
235
236   // Initialize the thread data.
237   void Initialize();
238
239   // Get the top C++ try catch handler or NULL if none are registered.
240   //
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)
245
246   // Get the address of the top C++ try catch handler or NULL if
247   // none are registered.
248   //
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()));
259   }
260
261   void Free();
262
263   Isolate* isolate_;
264   // The context where the current execution method is created and for variable
265   // lookups.
266   Context* context_;
267   ThreadId thread_id_;
268   Object* pending_exception_;
269
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_;
276
277   // Communication channel between Isolate::Throw and message consumers.
278   bool rethrowing_message_;
279   Object* pending_message_obj_;
280
281   // Use a separate value for scheduled exceptions to preserve the
282   // invariants that hold about pending_exception.  We may want to
283   // unify them later.
284   Object* scheduled_exception_;
285   bool external_caught_exception_;
286   SaveContext* save_context_;
287
288   // Stack.
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.
292
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_;
297
298 #ifdef USE_SIMULATOR
299   Simulator* simulator_;
300 #endif
301
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_;
306
307   // Call back function to report unsafe JS accesses.
308   v8::FailedAccessCheckCallback failed_access_check_callback_;
309
310  private:
311   void InitializeInternal();
312
313   v8::TryCatch* try_catch_handler_;
314 };
315
316
317 #if USE_SIMULATOR
318
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)
323 #else
324
325 #define ISOLATE_INIT_SIMULATOR_LIST(V)
326
327 #endif
328
329
330 #ifdef DEBUG
331
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)
336 #else
337
338 #define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)
339
340 #endif
341
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)
350
351 typedef List<HeapObject*> DebugObjectCache;
352
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)
383
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##_; }
387
388 #define THREAD_LOCAL_TOP_ADDRESS(type, name) \
389   type* name##_address() { return &thread_local_top_.name##_; }
390
391
392 class Isolate {
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;
397  public:
398   ~Isolate();
399
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 {
404    public:
405     PerIsolateThreadData(Isolate* isolate, ThreadId thread_id)
406         : isolate_(isolate),
407           thread_id_(thread_id),
408           stack_limit_(0),
409           thread_state_(NULL),
410 #if USE_SIMULATOR
411           simulator_(NULL),
412 #endif
413           next_(NULL),
414           prev_(NULL) { }
415     ~PerIsolateThreadData();
416     Isolate* isolate() const { return isolate_; }
417     ThreadId thread_id() const { return thread_id_; }
418
419     FIELD_ACCESSOR(uintptr_t, stack_limit)
420     FIELD_ACCESSOR(ThreadState*, thread_state)
421
422 #if USE_SIMULATOR
423     FIELD_ACCESSOR(Simulator*, simulator)
424 #endif
425
426     bool Matches(Isolate* isolate, ThreadId thread_id) const {
427       return isolate_ == isolate && thread_id_.Equals(thread_id);
428     }
429
430    private:
431     Isolate* isolate_;
432     ThreadId thread_id_;
433     uintptr_t stack_limit_;
434     ThreadState* thread_state_;
435
436 #if USE_SIMULATOR
437     Simulator* simulator_;
438 #endif
439
440     PerIsolateThreadData* next_;
441     PerIsolateThreadData* prev_;
442
443     friend class Isolate;
444     friend class ThreadDataTable;
445     friend class EntryStackItem;
446
447     DISALLOW_COPY_AND_ASSIGN(PerIsolateThreadData);
448   };
449
450
451   enum AddressId {
452 #define DECLARE_ENUM(CamelName, hacker_name) k##CamelName##Address,
453     FOR_EACH_ISOLATE_ADDRESS_NAME(DECLARE_ENUM)
454 #undef DECLARE_ENUM
455     kIsolateAddressCount
456   };
457
458   static void InitializeOncePerProcess();
459
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_));
465   }
466
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);
473     return isolate;
474   }
475
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_));
480   }
481
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_));
487   }
488
489   // Usually called by Init(), but can be called early e.g. to allow
490   // testing components that require logging but not the whole
491   // isolate.
492   //
493   // Safe to call more than once.
494   void InitializeLoggingAndCounters();
495
496   bool Init(Deserializer* des);
497
498   // True if at least one thread Enter'ed this isolate.
499   bool IsInUse() { return entry_stack_ != NULL; }
500
501   // Destroys the non-default isolates.
502   // Sets default isolate into "has_been_disposed" state rather then destroying,
503   // for legacy API reasons.
504   void TearDown();
505
506   static void GlobalTearDown();
507
508   void ClearSerializerData();
509
510   // Find the PerThread for this particular (isolate, thread) combination
511   // If one does not yet exist, return null.
512   PerIsolateThreadData* FindPerThreadDataForThisThread();
513
514   // Find the PerThread for given (isolate, thread) combination
515   // If one does not yet exist, return null.
516   PerIsolateThreadData* FindPerThreadDataForThread(ThreadId thread_id);
517
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() {
522     return isolate_key_;
523   }
524
525   // Returns the key used to store process-wide thread IDs.
526   static base::Thread::LocalStorageKey thread_id_key() {
527     return thread_id_key_;
528   }
529
530   static base::Thread::LocalStorageKey per_isolate_thread_data_key();
531
532   // Mutex for serializing access to break control structures.
533   base::RecursiveMutex* break_access() { return &break_access_; }
534
535   Address get_address_from_id(AddressId id);
536
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;
542   }
543   Context** context_address() { return &thread_local_top_.context_; }
544
545   THREAD_LOCAL_TOP_ACCESSOR(SaveContext*, save_context)
546
547   // Access to current thread id.
548   THREAD_LOCAL_TOP_ACCESSOR(ThreadId, thread_id)
549
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_;
555   }
556
557   void set_pending_exception(Object* exception_obj) {
558     DCHECK(!exception_obj->IsException());
559     thread_local_top_.pending_exception_ = exception_obj;
560   }
561
562   void clear_pending_exception() {
563     DCHECK(!thread_local_top_.pending_exception_->IsException());
564     thread_local_top_.pending_exception_ = heap_.the_hole_value();
565   }
566
567   THREAD_LOCAL_TOP_ADDRESS(Object*, pending_exception)
568
569   bool has_pending_exception() {
570     DCHECK(!thread_local_top_.pending_exception_->IsException());
571     return !thread_local_top_.pending_exception_->IsTheHole();
572   }
573
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)
579
580   THREAD_LOCAL_TOP_ACCESSOR(bool, external_caught_exception)
581
582   void clear_pending_message() {
583     thread_local_top_.pending_message_obj_ = heap_.the_hole_value();
584   }
585   v8::TryCatch* try_catch_handler() {
586     return thread_local_top_.try_catch_handler();
587   }
588   bool* external_caught_exception_address() {
589     return &thread_local_top_.external_caught_exception_;
590   }
591
592   THREAD_LOCAL_TOP_ADDRESS(Object*, scheduled_exception)
593
594   Address pending_message_obj_address() {
595     return reinterpret_cast<Address>(&thread_local_top_.pending_message_obj_);
596   }
597
598   Object* scheduled_exception() {
599     DCHECK(has_scheduled_exception());
600     DCHECK(!thread_local_top_.scheduled_exception_->IsException());
601     return thread_local_top_.scheduled_exception_;
602   }
603   bool has_scheduled_exception() {
604     DCHECK(!thread_local_top_.scheduled_exception_->IsException());
605     return thread_local_top_.scheduled_exception_ != heap_.the_hole_value();
606   }
607   void clear_scheduled_exception() {
608     DCHECK(!thread_local_top_.scheduled_exception_->IsException());
609     thread_local_top_.scheduled_exception_ = heap_.the_hole_value();
610   }
611
612   bool IsJavaScriptHandlerOnTop(Object* exception);
613   bool IsExternalHandlerOnTop(Object* exception);
614
615   bool is_catchable_by_javascript(Object* exception) {
616     return exception != heap()->termination_exception();
617   }
618
619   // JS execution stack (see frames.h).
620   static Address c_entry_fp(ThreadLocalTop* thread) {
621     return thread->c_entry_fp_;
622   }
623   static Address handler(ThreadLocalTop* thread) { return thread->handler_; }
624   Address c_function() { return thread_local_top_.c_function_; }
625
626   inline Address* c_entry_fp_address() {
627     return &thread_local_top_.c_entry_fp_;
628   }
629   inline Address* handler_address() { return &thread_local_top_.handler_; }
630   inline Address* c_function_address() {
631     return &thread_local_top_.c_function_;
632   }
633
634   // Bottom JS entry.
635   Address js_entry_sp() {
636     return thread_local_top_.js_entry_sp_;
637   }
638   inline Address* js_entry_sp_address() {
639     return &thread_local_top_.js_entry_sp_;
640   }
641
642   // Returns the global object of the current context. It could be
643   // a builtin object, or a JS global object.
644   Handle<GlobalObject> global_object() {
645     return Handle<GlobalObject>(context()->global_object());
646   }
647
648   // Returns the global proxy object of the current context.
649   JSObject* global_proxy() {
650     return context()->global_proxy();
651   }
652
653   Handle<JSBuiltinsObject> js_builtins_object() {
654     return Handle<JSBuiltinsObject>(thread_local_top_.context_->builtins());
655   }
656
657   static int ArchiveSpacePerThread() { return sizeof(ThreadLocalTop); }
658   void FreeThreadResources() { thread_local_top_.Free(); }
659
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);
665
666   // Push and pop a promise and the current try-catch handler.
667   void PushPromise(Handle<JSObject> promise, Handle<JSFunction> function);
668   void PopPromise();
669   Handle<Object> GetPromiseOnStackOnThrow();
670
671   class ExceptionScope {
672    public:
673     // Scope currently can only be used for regular exceptions,
674     // not termination exception.
675     explicit ExceptionScope(Isolate* isolate)
676         : isolate_(isolate),
677           pending_exception_(isolate_->pending_exception(), isolate_) {}
678
679     ~ExceptionScope() {
680       isolate_->set_pending_exception(*pending_exception_);
681     }
682
683    private:
684     Isolate* isolate_;
685     Handle<Object> pending_exception_;
686   };
687
688   void SetCaptureStackTraceForUncaughtExceptions(
689       bool capture,
690       int frame_limit,
691       StackTrace::StackTraceOptions options);
692
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(
702       int frame_limit,
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);
713
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
716   // set.
717
718   bool MayAccess(Handle<JSObject> receiver);
719   bool IsInternallyUsedPropertyName(Handle<Object> name);
720   bool IsInternallyUsedPropertyName(Object* name);
721
722   void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback);
723   void ReportFailedAccessCheck(Handle<JSObject> receiver);
724
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();
729
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>();
735   }
736
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);
740
741   // Find the correct handler for the current pending exception. This also
742   // clears and returns the current pending exception.
743   Object* UnwindAndFindHandler();
744
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();
751
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();
761
762   // Promote a scheduled exception to pending. Asserts has_scheduled_exception.
763   Object* PromoteScheduledException();
764
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);
772
773   Handle<JSMessageObject> CreateMessage(Handle<Object> exception,
774                                         MessageLocation* location);
775
776   // Out of resource exception helpers.
777   Object* StackOverflow();
778   Object* TerminateExecution();
779   void CancelTerminateExecution();
780
781   void RequestInterrupt(InterruptCallback callback, void* data);
782   void InvokeApiInterruptCallbacks();
783
784   // Administration
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);
789
790   // Returns the current native context.
791   Handle<Context> native_context();
792
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();
796
797   void RegisterTryCatchHandler(v8::TryCatch* that);
798   void UnregisterTryCatchHandler(v8::TryCatch* that);
799
800   char* ArchiveThread(char* to);
801   char* RestoreThread(char* from);
802
803   static const char* const kStackOverflowMessage;
804
805   static const int kUC16AlphabetSize = 256;  // See StringSearchBase.
806   static const int kBMMaxShift = 250;        // See StringSearchBase.
807
808   // Accessors.
809 #define GLOBAL_ACCESSOR(type, name, initialvalue)                       \
810   inline type name() const {                                            \
811     DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_);        \
812     return name##_;                                                     \
813   }                                                                     \
814   inline void set_##name(type value) {                                  \
815     DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_);        \
816     name##_ = value;                                                    \
817   }
818   ISOLATE_INIT_LIST(GLOBAL_ACCESSOR)
819 #undef GLOBAL_ACCESSOR
820
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];                                               \
825   }
826   ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_ACCESSOR)
827 #undef GLOBAL_ARRAY_ACCESSOR
828
829 #define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name)            \
830   Handle<type> name() {                                             \
831     return Handle<type>(native_context()->name(), this);            \
832   }                                                                 \
833   bool is_##name(type* value) {                                     \
834     return native_context()->is_##name(value);                      \
835   }
836   NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
837 #undef NATIVE_CONTEXT_FIELD_ACCESSOR
838
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);
844     return counters_;
845   }
846   CodeRange* code_range() { return code_range_; }
847   RuntimeProfiler* runtime_profiler() { return runtime_profiler_; }
848   CompilationCache* compilation_cache() { return compilation_cache_; }
849   Logger* logger() {
850     // Call InitializeLoggingAndCounters() if logging is needed before
851     // the isolate is fully initialized.
852     DCHECK(logger_ != NULL);
853     return logger_;
854   }
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_;
864   }
865
866   MemoryAllocator* memory_allocator() {
867     return memory_allocator_;
868   }
869
870   KeyedLookupCache* keyed_lookup_cache() {
871     return keyed_lookup_cache_;
872   }
873
874   ContextSlotCache* context_slot_cache() {
875     return context_slot_cache_;
876   }
877
878   DescriptorLookupCache* descriptor_lookup_cache() {
879     return descriptor_lookup_cache_;
880   }
881
882   HandleScopeData* handle_scope_data() { return &handle_scope_data_; }
883
884   HandleScopeImplementer* handle_scope_implementer() {
885     DCHECK(handle_scope_implementer_);
886     return handle_scope_implementer_;
887   }
888   Zone* runtime_zone() { return &runtime_zone_; }
889
890   UnicodeCache* unicode_cache() {
891     return unicode_cache_;
892   }
893
894   InnerPointerToCodeCache* inner_pointer_to_code_cache() {
895     return inner_pointer_to_code_cache_;
896   }
897
898   GlobalHandles* global_handles() { return global_handles_; }
899
900   EternalHandles* eternal_handles() { return eternal_handles_; }
901
902   ThreadManager* thread_manager() { return thread_manager_; }
903
904   StringTracker* string_tracker() { return string_tracker_; }
905
906   unibrow::Mapping<unibrow::Ecma262UnCanonicalize>* jsregexp_uncanonicalize() {
907     return &jsregexp_uncanonicalize_;
908   }
909
910   unibrow::Mapping<unibrow::CanonicalizationRange>* jsregexp_canonrange() {
911     return &jsregexp_canonrange_;
912   }
913
914   RuntimeState* runtime_state() { return &runtime_state_; }
915
916   Builtins* builtins() { return &builtins_; }
917
918   void NotifyExtensionInstalled() {
919     has_installed_extensions_ = true;
920   }
921
922   bool has_installed_extensions() { return has_installed_extensions_; }
923
924   unibrow::Mapping<unibrow::Ecma262Canonicalize>*
925       regexp_macro_assembler_canonicalize() {
926     return &regexp_macro_assembler_canonicalize_;
927   }
928
929   RegExpStack* regexp_stack() { return regexp_stack_; }
930
931   unibrow::Mapping<unibrow::Ecma262Canonicalize>*
932       interp_canonicalize_mapping() {
933     return &interp_canonicalize_mapping_;
934   }
935
936   Debug* debug() { return debug_; }
937
938   CpuProfiler* cpu_profiler() const { return cpu_profiler_; }
939   HeapProfiler* heap_profiler() const { return heap_profiler_; }
940
941 #ifdef DEBUG
942   HistogramInfo* heap_histograms() { return heap_histograms_; }
943
944   JSObject::SpillInformation* js_spill_information() {
945     return &js_spill_information_;
946   }
947 #endif
948
949   Factory* factory() { return reinterpret_cast<Factory*>(this); }
950
951   static const int kJSRegexpStaticOffsetsVectorSize = 128;
952
953   THREAD_LOCAL_TOP_ACCESSOR(ExternalCallbackScope*, external_callback_scope)
954
955   THREAD_LOCAL_TOP_ACCESSOR(StateTag, current_vm_state)
956
957   void SetData(uint32_t slot, void* data) {
958     DCHECK(slot < Internals::kNumIsolateDataSlots);
959     embedder_data_[slot] = data;
960   }
961   void* GetData(uint32_t slot) {
962     DCHECK(slot < Internals::kNumIsolateDataSlots);
963     return embedder_data_[slot];
964   }
965
966   bool serializer_enabled() const { return serializer_enabled_; }
967   bool snapshot_available() const {
968     return snapshot_blob_ != NULL && snapshot_blob_->raw_size != 0;
969   }
970
971   bool IsDead() { return has_fatal_error_; }
972   void SignalFatalError() { has_fatal_error_ = true; }
973
974   bool use_crankshaft() const;
975
976   bool initialized_from_snapshot() { return initialized_from_snapshot_; }
977
978   double time_millis_since_init() {
979     return base::OS::TimeCurrentMillis() - time_millis_at_init_;
980   }
981
982   DateCache* date_cache() {
983     return date_cache_;
984   }
985
986   void set_date_cache(DateCache* date_cache) {
987     if (date_cache != date_cache_) {
988       delete date_cache_;
989     }
990     date_cache_ = date_cache;
991   }
992
993   Map* get_initial_js_array_map(ElementsKind kind,
994                                 ObjectStrength strength = WEAK);
995
996   static const int kArrayProtectorValid = 1;
997   static const int kArrayProtectorInvalid = 0;
998
999   bool IsFastArrayConstructorPrototypeChainIntact();
1000
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);
1008   }
1009   void UpdateArrayProtectorOnSetPrototype(Handle<JSObject> object) {
1010     UpdateArrayProtectorOnSetElement(object);
1011   }
1012   void UpdateArrayProtectorOnNormalizeElements(Handle<JSObject> object) {
1013     UpdateArrayProtectorOnSetElement(object);
1014   }
1015
1016   // Returns true if array is the initial array prototype in any native context.
1017   bool IsAnyInitialArrayPrototype(Handle<JSArray> array);
1018
1019   CallInterfaceDescriptorData* call_descriptor_data(int index);
1020
1021   void IterateDeferredHandles(ObjectVisitor* visitor);
1022   void LinkDeferredHandles(DeferredHandles* deferred_handles);
1023   void UnlinkDeferredHandles(DeferredHandles* deferred_handles);
1024
1025 #ifdef DEBUG
1026   bool IsDeferredHandle(Object** location);
1027 #endif  // DEBUG
1028
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;
1034   }
1035
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;
1041   }
1042
1043   OptimizingCompileDispatcher* optimizing_compile_dispatcher() {
1044     return optimizing_compile_dispatcher_;
1045   }
1046
1047   int id() const { return static_cast<int>(id_); }
1048
1049   HStatistics* GetHStatistics();
1050   CompilationStatistics* GetTurboStatistics();
1051   HTracer* GetHTracer();
1052   CodeTracer* GetCodeTracer();
1053
1054   void DumpAndResetCompilationStats();
1055
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;
1059   }
1060
1061   void* stress_deopt_count_address() { return &stress_deopt_count_; }
1062
1063   base::RandomNumberGenerator* random_number_generator();
1064
1065   // Given an address occupied by a live code object, return that object.
1066   Object* FindCodeObject(Address a);
1067
1068   int NextOptimizationId() {
1069     int id = next_optimization_id_++;
1070     if (!Smi::IsValid(next_optimization_id_)) {
1071       next_optimization_id_ = 0;
1072     }
1073     return id;
1074   }
1075
1076   // Get (and lazily initialize) the registry for per-isolate symbols.
1077   Handle<JSObject> GetSymbolRegistry();
1078
1079   void AddCallCompletedCallback(CallCompletedCallback callback);
1080   void RemoveCallCompletedCallback(CallCompletedCallback callback);
1081   void FireCallCompletedCallback();
1082
1083   void SetPromiseRejectCallback(PromiseRejectCallback callback);
1084   void ReportPromiseReject(Handle<JSObject> promise, Handle<Object> value,
1085                            v8::PromiseRejectEvent event);
1086
1087   void EnqueueMicrotask(Handle<Object> microtask);
1088   void RunMicrotasks();
1089
1090   void SetUseCounterCallback(v8::Isolate::UseCounterCallback callback);
1091   void CountUsage(v8::Isolate::UseCounterFeature feature);
1092
1093   BasicBlockProfiler* GetOrCreateBasicBlockProfiler();
1094   BasicBlockProfiler* basic_block_profiler() { return basic_block_profiler_; }
1095
1096   std::string GetTurboCfgFileName();
1097
1098 #if TRACE_MAPS
1099   int GetNextUniqueSharedFunctionInfoId() { return next_unique_sfi_id_++; }
1100 #endif
1101
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;
1105   }
1106
1107   uintptr_t* store_buffer_hash_set_1_address() {
1108     return store_buffer_hash_set_1_address_;
1109   }
1110
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;
1114   }
1115
1116   uintptr_t* store_buffer_hash_set_2_address() {
1117     return store_buffer_hash_set_2_address_;
1118   }
1119
1120   void AddDetachedContext(Handle<Context> context);
1121   void CheckDetachedContextsAfterGC();
1122
1123   List<Object*>* partial_snapshot_cache() { return &partial_snapshot_cache_; }
1124
1125   void set_array_buffer_allocator(v8::ArrayBuffer::Allocator* allocator) {
1126     array_buffer_allocator_ = allocator;
1127   }
1128   v8::ArrayBuffer::Allocator* array_buffer_allocator() const {
1129     return array_buffer_allocator_;
1130   }
1131
1132  protected:
1133   explicit Isolate(bool enable_serializer);
1134
1135  private:
1136   friend struct GlobalState;
1137   friend struct InitializeGlobalState;
1138   Handle<JSObject> SetUpSubregistry(Handle<JSObject> registry, Handle<Map> map,
1139                                     const char* name);
1140
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];
1145   Heap heap_;
1146
1147   // The per-process lock should be acquired before the ThreadDataTable is
1148   // modified.
1149   class ThreadDataTable {
1150    public:
1151     ThreadDataTable();
1152     ~ThreadDataTable();
1153
1154     PerIsolateThreadData* Lookup(Isolate* isolate, ThreadId thread_id);
1155     void Insert(PerIsolateThreadData* data);
1156     void Remove(PerIsolateThreadData* data);
1157     void RemoveAllThreads(Isolate* isolate);
1158
1159    private:
1160     PerIsolateThreadData* list_;
1161   };
1162
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 {
1170    public:
1171     EntryStackItem(PerIsolateThreadData* previous_thread_data,
1172                    Isolate* previous_isolate,
1173                    EntryStackItem* previous_item)
1174         : entry_count(1),
1175           previous_thread_data(previous_thread_data),
1176           previous_isolate(previous_isolate),
1177           previous_item(previous_item) { }
1178
1179     int entry_count;
1180     PerIsolateThreadData* previous_thread_data;
1181     Isolate* previous_isolate;
1182     EntryStackItem* previous_item;
1183
1184    private:
1185     DISALLOW_COPY_AND_ASSIGN(EntryStackItem);
1186   };
1187
1188   static base::LazyMutex thread_data_table_mutex_;
1189
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_;
1194
1195   // A global counter for all generated Isolates, might overflow.
1196   static base::Atomic32 isolate_counter_;
1197
1198 #if DEBUG
1199   static base::Atomic32 isolate_key_created_;
1200 #endif
1201
1202   void Deinit();
1203
1204   static void SetIsolateThreadLocals(Isolate* isolate,
1205                                      PerIsolateThreadData* data);
1206
1207   // Find the PerThread for this particular (isolate, thread) combination.
1208   // If one does not yet exist, allocate a new one.
1209   PerIsolateThreadData* FindOrAllocatePerThreadDataForThisThread();
1210
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.
1214   void Enter();
1215
1216   // Exits the current thread. The previosuly entered Isolate is restored
1217   // for the thread.
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.
1220   void Exit();
1221
1222   void InitializeThreadLocal();
1223
1224   void MarkCompactPrologue(bool is_compacting,
1225                            ThreadLocalTop* archived_thread_data);
1226   void MarkCompactEpilogue(bool is_compacting,
1227                            ThreadLocalTop* archived_thread_data);
1228
1229   void FillCache();
1230
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();
1235
1236   // Remove per-frame stored materialized objects when we are unwinding
1237   // the frame.
1238   void RemoveMaterializedObjectsOnUnwind(StackFrame* frame);
1239
1240   // Traverse prototype chain to find out whether the object is derived from
1241   // the Error object.
1242   bool IsErrorObject(Handle<Object> obj);
1243
1244   base::Atomic32 id_;
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_;
1255   Logger* logger_;
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_;
1273   Zone runtime_zone_;
1274   InnerPointerToCodeCache* inner_pointer_to_code_cache_;
1275   GlobalHandles* global_handles_;
1276   EternalHandles* eternal_handles_;
1277   ThreadManager* thread_manager_;
1278   RuntimeState runtime_state_;
1279   Builtins builtins_;
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_;
1294
1295   // Whether the isolate has been created for snapshotting.
1296   bool serializer_enabled_;
1297
1298   // True if fatal error has been signaled for this isolate.
1299   bool has_fatal_error_;
1300
1301   // True if this isolate was initialized from a snapshot.
1302   bool initialized_from_snapshot_;
1303
1304   // Time stamp at initialization.
1305   double time_millis_at_init_;
1306
1307 #ifdef DEBUG
1308   // A static array of histogram info for each type.
1309   HistogramInfo heap_histograms_[LAST_TYPE + 1];
1310   JSObject::SpillInformation js_spill_information_;
1311 #endif
1312
1313   Debug* debug_;
1314   CpuProfiler* cpu_profiler_;
1315   HeapProfiler* heap_profiler_;
1316   FunctionEntryHook function_entry_hook_;
1317
1318   typedef std::pair<InterruptCallback, void*> InterruptEntry;
1319   std::queue<InterruptEntry> api_interrupts_queue_;
1320
1321 #define GLOBAL_BACKING_STORE(type, name, initialvalue)                         \
1322   type name##_;
1323   ISOLATE_INIT_LIST(GLOBAL_BACKING_STORE)
1324 #undef GLOBAL_BACKING_STORE
1325
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
1330
1331 #ifdef DEBUG
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
1340 #endif
1341
1342   DeferredHandles* deferred_handles_head_;
1343   OptimizingCompileDispatcher* optimizing_compile_dispatcher_;
1344
1345   // Counts deopt points if deopt_every_n_times is enabled.
1346   unsigned int stress_deopt_count_;
1347
1348   int next_optimization_id_;
1349
1350 #if TRACE_MAPS
1351   int next_unique_sfi_id_;
1352 #endif
1353
1354   // List of callbacks when a Call completes.
1355   List<CallCompletedCallback> call_completed_callbacks_;
1356
1357   v8::Isolate::UseCounterCallback use_counter_callback_;
1358   BasicBlockProfiler* basic_block_profiler_;
1359
1360   List<Object*> partial_snapshot_cache_;
1361
1362   v8::ArrayBuffer::Allocator* array_buffer_allocator_;
1363
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*);
1378
1379   DISALLOW_COPY_AND_ASSIGN(Isolate);
1380 };
1381
1382
1383 #undef FIELD_ACCESSOR
1384 #undef THREAD_LOCAL_TOP_ACCESSOR
1385
1386
1387 class PromiseOnStack {
1388  public:
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_; }
1395
1396  private:
1397   Handle<JSFunction> function_;
1398   Handle<JSObject> promise_;
1399   PromiseOnStack* prev_;
1400 };
1401
1402
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 {
1407  public:
1408   explicit SaveContext(Isolate* isolate);
1409
1410   ~SaveContext() {
1411     isolate_->set_context(context_.is_null() ? NULL : *context_);
1412     isolate_->set_save_context(prev_);
1413   }
1414
1415   Handle<Context> context() { return context_; }
1416   SaveContext* prev() { return prev_; }
1417
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());
1421   }
1422
1423  private:
1424   Isolate* isolate_;
1425   Handle<Context> context_;
1426   SaveContext* prev_;
1427   Address c_entry_fp_;
1428 };
1429
1430
1431 class AssertNoContextChange BASE_EMBEDDED {
1432 #ifdef DEBUG
1433  public:
1434   explicit AssertNoContextChange(Isolate* isolate)
1435     : isolate_(isolate),
1436       context_(isolate->context(), isolate) { }
1437   ~AssertNoContextChange() {
1438     DCHECK(isolate_->context() == *context_);
1439   }
1440
1441  private:
1442   Isolate* isolate_;
1443   Handle<Context> context_;
1444 #else
1445  public:
1446   explicit AssertNoContextChange(Isolate* isolate) { }
1447 #endif
1448 };
1449
1450
1451 class ExecutionAccess BASE_EMBEDDED {
1452  public:
1453   explicit ExecutionAccess(Isolate* isolate) : isolate_(isolate) {
1454     Lock(isolate);
1455   }
1456   ~ExecutionAccess() { Unlock(isolate_); }
1457
1458   static void Lock(Isolate* isolate) { isolate->break_access()->Lock(); }
1459   static void Unlock(Isolate* isolate) { isolate->break_access()->Unlock(); }
1460
1461   static bool TryLock(Isolate* isolate) {
1462     return isolate->break_access()->TryLock();
1463   }
1464
1465  private:
1466   Isolate* isolate_;
1467 };
1468
1469
1470 // Support for checking for stack-overflows.
1471 class StackLimitCheck BASE_EMBEDDED {
1472  public:
1473   explicit StackLimitCheck(Isolate* isolate) : isolate_(isolate) { }
1474
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();
1479   }
1480
1481   // Use this to check for stack-overflow when entering runtime from JS code.
1482   bool JsHasOverflowed() const;
1483
1484  private:
1485   Isolate* isolate_;
1486 };
1487
1488
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
1492 // account.
1493 class PostponeInterruptsScope BASE_EMBEDDED {
1494  public:
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);
1501   }
1502
1503   ~PostponeInterruptsScope() {
1504     stack_guard_->PopPostponeInterruptsScope();
1505   }
1506
1507   // Find the bottom-most scope that intercepts this interrupt.
1508   // Return whether the interrupt has been intercepted.
1509   bool Intercept(StackGuard::InterruptFlag flag);
1510
1511  private:
1512   StackGuard* stack_guard_;
1513   int intercept_mask_;
1514   int intercepted_flags_;
1515   PostponeInterruptsScope* prev_;
1516
1517   friend class StackGuard;
1518 };
1519
1520
1521 class CodeTracer final : public Malloced {
1522  public:
1523   explicit CodeTracer(int isolate_id)
1524       : file_(NULL),
1525         scope_depth_(0) {
1526     if (!ShouldRedirect()) {
1527       file_ = stdout;
1528       return;
1529     }
1530
1531     if (FLAG_redirect_code_traces_to == NULL) {
1532       SNPrintF(filename_,
1533                "code-%d-%d.asm",
1534                base::OS::GetCurrentProcessId(),
1535                isolate_id);
1536     } else {
1537       StrNCpy(filename_, FLAG_redirect_code_traces_to, filename_.length());
1538     }
1539
1540     WriteChars(filename_.start(), "", 0, false);
1541   }
1542
1543   class Scope {
1544    public:
1545     explicit Scope(CodeTracer* tracer) : tracer_(tracer) { tracer->OpenFile(); }
1546     ~Scope() { tracer_->CloseFile();  }
1547
1548     FILE* file() const { return tracer_->file(); }
1549
1550    private:
1551     CodeTracer* tracer_;
1552   };
1553
1554   void OpenFile() {
1555     if (!ShouldRedirect()) {
1556       return;
1557     }
1558
1559     if (file_ == NULL) {
1560       file_ = base::OS::FOpen(filename_.start(), "ab");
1561     }
1562
1563     scope_depth_++;
1564   }
1565
1566   void CloseFile() {
1567     if (!ShouldRedirect()) {
1568       return;
1569     }
1570
1571     if (--scope_depth_ == 0) {
1572       fclose(file_);
1573       file_ = NULL;
1574     }
1575   }
1576
1577   FILE* file() const { return file_; }
1578
1579  private:
1580   static bool ShouldRedirect() {
1581     return FLAG_redirect_code_traces;
1582   }
1583
1584   EmbeddedVector<char, 128> filename_;
1585   FILE* file_;
1586   int scope_depth_;
1587 };
1588
1589 } }  // namespace v8::internal
1590
1591 #endif  // V8_ISOLATE_H_