Merge remote-tracking branch 'upstream/v0.10' into v0.12
[platform/upstream/nodejs.git] / deps / v8 / src / isolate.cc
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 #include <stdlib.h>
6
7 #include "v8.h"
8
9 #include "ast.h"
10 #include "bootstrapper.h"
11 #include "codegen.h"
12 #include "compilation-cache.h"
13 #include "cpu-profiler.h"
14 #include "debug.h"
15 #include "deoptimizer.h"
16 #include "heap-profiler.h"
17 #include "hydrogen.h"
18 #include "isolate-inl.h"
19 #include "lithium-allocator.h"
20 #include "log.h"
21 #include "messages.h"
22 #include "platform.h"
23 #include "regexp-stack.h"
24 #include "runtime-profiler.h"
25 #include "sampler.h"
26 #include "scopeinfo.h"
27 #include "serialize.h"
28 #include "simulator.h"
29 #include "spaces.h"
30 #include "stub-cache.h"
31 #include "sweeper-thread.h"
32 #include "utils/random-number-generator.h"
33 #include "version.h"
34 #include "vm-state-inl.h"
35
36
37 namespace v8 {
38 namespace internal {
39
40 Atomic32 ThreadId::highest_thread_id_ = 0;
41
42 int ThreadId::AllocateThreadId() {
43   int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
44   return new_id;
45 }
46
47
48 int ThreadId::GetCurrentThreadId() {
49   int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
50   if (thread_id == 0) {
51     thread_id = AllocateThreadId();
52     Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
53   }
54   return thread_id;
55 }
56
57
58 ThreadLocalTop::ThreadLocalTop() {
59   InitializeInternal();
60 }
61
62
63 void ThreadLocalTop::InitializeInternal() {
64   c_entry_fp_ = 0;
65   handler_ = 0;
66 #ifdef USE_SIMULATOR
67   simulator_ = NULL;
68 #endif
69   js_entry_sp_ = NULL;
70   external_callback_scope_ = NULL;
71   current_vm_state_ = EXTERNAL;
72   try_catch_handler_address_ = NULL;
73   context_ = NULL;
74   thread_id_ = ThreadId::Invalid();
75   external_caught_exception_ = false;
76   failed_access_check_callback_ = NULL;
77   save_context_ = NULL;
78   catcher_ = NULL;
79   top_lookup_result_ = NULL;
80
81   // These members are re-initialized later after deserialization
82   // is complete.
83   pending_exception_ = NULL;
84   has_pending_message_ = false;
85   rethrowing_message_ = false;
86   pending_message_obj_ = NULL;
87   pending_message_script_ = NULL;
88   scheduled_exception_ = NULL;
89 }
90
91
92 void ThreadLocalTop::Initialize() {
93   InitializeInternal();
94 #ifdef USE_SIMULATOR
95   simulator_ = Simulator::current(isolate_);
96 #endif
97   thread_id_ = ThreadId::Current();
98 }
99
100
101 v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
102   return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
103 }
104
105
106 Isolate* Isolate::default_isolate_ = NULL;
107 Thread::LocalStorageKey Isolate::isolate_key_;
108 Thread::LocalStorageKey Isolate::thread_id_key_;
109 Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
110 #ifdef DEBUG
111 Thread::LocalStorageKey PerThreadAssertScopeBase::thread_local_key;
112 #endif  // DEBUG
113 Mutex Isolate::process_wide_mutex_;
114 // TODO(dcarney): Remove with default isolate.
115 enum DefaultIsolateStatus {
116   kDefaultIsolateUninitialized,
117   kDefaultIsolateInitialized,
118   kDefaultIsolateCrashIfInitialized
119 };
120 static DefaultIsolateStatus default_isolate_status_
121     = kDefaultIsolateUninitialized;
122 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
123 Atomic32 Isolate::isolate_counter_ = 0;
124
125 Isolate::PerIsolateThreadData*
126     Isolate::FindOrAllocatePerThreadDataForThisThread() {
127   ThreadId thread_id = ThreadId::Current();
128   PerIsolateThreadData* per_thread = NULL;
129   {
130     LockGuard<Mutex> lock_guard(&process_wide_mutex_);
131     per_thread = thread_data_table_->Lookup(this, thread_id);
132     if (per_thread == NULL) {
133       per_thread = new PerIsolateThreadData(this, thread_id);
134       thread_data_table_->Insert(per_thread);
135     }
136     ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
137   }
138   return per_thread;
139 }
140
141
142 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
143   ThreadId thread_id = ThreadId::Current();
144   return FindPerThreadDataForThread(thread_id);
145 }
146
147
148 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
149     ThreadId thread_id) {
150   PerIsolateThreadData* per_thread = NULL;
151   {
152     LockGuard<Mutex> lock_guard(&process_wide_mutex_);
153     per_thread = thread_data_table_->Lookup(this, thread_id);
154   }
155   return per_thread;
156 }
157
158
159 void Isolate::SetCrashIfDefaultIsolateInitialized() {
160   LockGuard<Mutex> lock_guard(&process_wide_mutex_);
161   CHECK(default_isolate_status_ != kDefaultIsolateInitialized);
162   default_isolate_status_ = kDefaultIsolateCrashIfInitialized;
163 }
164
165
166 void Isolate::EnsureDefaultIsolate() {
167   LockGuard<Mutex> lock_guard(&process_wide_mutex_);
168   CHECK(default_isolate_status_ != kDefaultIsolateCrashIfInitialized);
169   if (default_isolate_ == NULL) {
170     isolate_key_ = Thread::CreateThreadLocalKey();
171     thread_id_key_ = Thread::CreateThreadLocalKey();
172     per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
173 #ifdef DEBUG
174     PerThreadAssertScopeBase::thread_local_key = Thread::CreateThreadLocalKey();
175 #endif  // DEBUG
176     thread_data_table_ = new Isolate::ThreadDataTable();
177     default_isolate_ = new Isolate();
178   }
179   // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
180   // because a non-null thread data may be already set.
181   if (Thread::GetThreadLocal(isolate_key_) == NULL) {
182     Thread::SetThreadLocal(isolate_key_, default_isolate_);
183   }
184 }
185
186 struct StaticInitializer {
187   StaticInitializer() {
188     Isolate::EnsureDefaultIsolate();
189   }
190 } static_initializer;
191
192
193 Address Isolate::get_address_from_id(Isolate::AddressId id) {
194   return isolate_addresses_[id];
195 }
196
197
198 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
199   ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
200   Iterate(v, thread);
201   return thread_storage + sizeof(ThreadLocalTop);
202 }
203
204
205 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
206   ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
207   v->VisitThread(this, thread);
208 }
209
210
211 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
212   // Visit the roots from the top for a given thread.
213   v->VisitPointer(&thread->pending_exception_);
214   v->VisitPointer(&(thread->pending_message_obj_));
215   v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
216   v->VisitPointer(BitCast<Object**>(&(thread->context_)));
217   v->VisitPointer(&thread->scheduled_exception_);
218
219   for (v8::TryCatch* block = thread->TryCatchHandler();
220        block != NULL;
221        block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
222     v->VisitPointer(BitCast<Object**>(&(block->exception_)));
223     v->VisitPointer(BitCast<Object**>(&(block->message_obj_)));
224     v->VisitPointer(BitCast<Object**>(&(block->message_script_)));
225   }
226
227   // Iterate over pointers on native execution stack.
228   for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
229     it.frame()->Iterate(v);
230   }
231
232   // Iterate pointers in live lookup results.
233   thread->top_lookup_result_->Iterate(v);
234 }
235
236
237 void Isolate::Iterate(ObjectVisitor* v) {
238   ThreadLocalTop* current_t = thread_local_top();
239   Iterate(v, current_t);
240 }
241
242
243 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
244   for (DeferredHandles* deferred = deferred_handles_head_;
245        deferred != NULL;
246        deferred = deferred->next_) {
247     deferred->Iterate(visitor);
248   }
249 }
250
251
252 #ifdef DEBUG
253 bool Isolate::IsDeferredHandle(Object** handle) {
254   // Each DeferredHandles instance keeps the handles to one job in the
255   // concurrent recompilation queue, containing a list of blocks.  Each block
256   // contains kHandleBlockSize handles except for the first block, which may
257   // not be fully filled.
258   // We iterate through all the blocks to see whether the argument handle
259   // belongs to one of the blocks.  If so, it is deferred.
260   for (DeferredHandles* deferred = deferred_handles_head_;
261        deferred != NULL;
262        deferred = deferred->next_) {
263     List<Object**>* blocks = &deferred->blocks_;
264     for (int i = 0; i < blocks->length(); i++) {
265       Object** block_limit = (i == 0) ? deferred->first_block_limit_
266                                       : blocks->at(i) + kHandleBlockSize;
267       if (blocks->at(i) <= handle && handle < block_limit) return true;
268     }
269   }
270   return false;
271 }
272 #endif  // DEBUG
273
274
275 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
276   // The ARM simulator has a separate JS stack.  We therefore register
277   // the C++ try catch handler with the simulator and get back an
278   // address that can be used for comparisons with addresses into the
279   // JS stack.  When running without the simulator, the address
280   // returned will be the address of the C++ try catch handler itself.
281   Address address = reinterpret_cast<Address>(
282       SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
283   thread_local_top()->set_try_catch_handler_address(address);
284 }
285
286
287 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
288   ASSERT(thread_local_top()->TryCatchHandler() == that);
289   thread_local_top()->set_try_catch_handler_address(
290       reinterpret_cast<Address>(that->next_));
291   thread_local_top()->catcher_ = NULL;
292   SimulatorStack::UnregisterCTryCatch();
293 }
294
295
296 Handle<String> Isolate::StackTraceString() {
297   if (stack_trace_nesting_level_ == 0) {
298     stack_trace_nesting_level_++;
299     HeapStringAllocator allocator;
300     StringStream::ClearMentionedObjectCache(this);
301     StringStream accumulator(&allocator);
302     incomplete_message_ = &accumulator;
303     PrintStack(&accumulator);
304     Handle<String> stack_trace = accumulator.ToString(this);
305     incomplete_message_ = NULL;
306     stack_trace_nesting_level_ = 0;
307     return stack_trace;
308   } else if (stack_trace_nesting_level_ == 1) {
309     stack_trace_nesting_level_++;
310     OS::PrintError(
311       "\n\nAttempt to print stack while printing stack (double fault)\n");
312     OS::PrintError(
313       "If you are lucky you may find a partial stack dump on stdout.\n\n");
314     incomplete_message_->OutputToStdOut();
315     return factory()->empty_string();
316   } else {
317     OS::Abort();
318     // Unreachable
319     return factory()->empty_string();
320   }
321 }
322
323
324 void Isolate::PushStackTraceAndDie(unsigned int magic,
325                                    Object* object,
326                                    Map* map,
327                                    unsigned int magic2) {
328   const int kMaxStackTraceSize = 8192;
329   Handle<String> trace = StackTraceString();
330   uint8_t buffer[kMaxStackTraceSize];
331   int length = Min(kMaxStackTraceSize - 1, trace->length());
332   String::WriteToFlat(*trace, buffer, 0, length);
333   buffer[length] = '\0';
334   // TODO(dcarney): convert buffer to utf8?
335   OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n",
336                  magic, magic2,
337                  static_cast<void*>(object), static_cast<void*>(map),
338                  reinterpret_cast<char*>(buffer));
339   OS::Abort();
340 }
341
342
343 // Determines whether the given stack frame should be displayed in
344 // a stack trace.  The caller is the error constructor that asked
345 // for the stack trace to be collected.  The first time a construct
346 // call to this function is encountered it is skipped.  The seen_caller
347 // in/out parameter is used to remember if the caller has been seen
348 // yet.
349 static bool IsVisibleInStackTrace(StackFrame* raw_frame,
350                                   Object* caller,
351                                   bool* seen_caller) {
352   // Only display JS frames.
353   if (!raw_frame->is_java_script()) return false;
354   JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
355   JSFunction* fun = frame->function();
356   if ((fun == caller) && !(*seen_caller)) {
357     *seen_caller = true;
358     return false;
359   }
360   // Skip all frames until we've seen the caller.
361   if (!(*seen_caller)) return false;
362   // Also, skip non-visible built-in functions and any call with the builtins
363   // object as receiver, so as to not reveal either the builtins object or
364   // an internal function.
365   // The --builtins-in-stack-traces command line flag allows including
366   // internal call sites in the stack trace for debugging purposes.
367   if (!FLAG_builtins_in_stack_traces) {
368     if (frame->receiver()->IsJSBuiltinsObject() ||
369         (fun->IsBuiltin() && !fun->shared()->native())) {
370       return false;
371     }
372   }
373   return true;
374 }
375
376
377 Handle<JSArray> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
378                                                  Handle<Object> caller,
379                                                  int limit) {
380   limit = Max(limit, 0);  // Ensure that limit is not negative.
381   int initial_size = Min(limit, 10);
382   Handle<FixedArray> elements =
383       factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
384
385   // If the caller parameter is a function we skip frames until we're
386   // under it before starting to collect.
387   bool seen_caller = !caller->IsJSFunction();
388   // First element is reserved to store the number of sloppy frames.
389   int cursor = 1;
390   int frames_seen = 0;
391   int sloppy_frames = 0;
392   bool encountered_strict_function = false;
393   for (StackFrameIterator iter(this);
394        !iter.done() && frames_seen < limit;
395        iter.Advance()) {
396     StackFrame* raw_frame = iter.frame();
397     if (IsVisibleInStackTrace(raw_frame, *caller, &seen_caller)) {
398       frames_seen++;
399       JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
400       // Set initial size to the maximum inlining level + 1 for the outermost
401       // function.
402       List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
403       frame->Summarize(&frames);
404       for (int i = frames.length() - 1; i >= 0; i--) {
405         if (cursor + 4 > elements->length()) {
406           int new_capacity = JSObject::NewElementsCapacity(elements->length());
407           Handle<FixedArray> new_elements =
408               factory()->NewFixedArrayWithHoles(new_capacity);
409           for (int i = 0; i < cursor; i++) {
410             new_elements->set(i, elements->get(i));
411           }
412           elements = new_elements;
413         }
414         ASSERT(cursor + 4 <= elements->length());
415
416         Handle<Object> recv = frames[i].receiver();
417         Handle<JSFunction> fun = frames[i].function();
418         Handle<Code> code = frames[i].code();
419         Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
420         // The stack trace API should not expose receivers and function
421         // objects on frames deeper than the top-most one with a strict
422         // mode function.  The number of sloppy frames is stored as
423         // first element in the result array.
424         if (!encountered_strict_function) {
425           if (fun->shared()->strict_mode() == STRICT) {
426             encountered_strict_function = true;
427           } else {
428             sloppy_frames++;
429           }
430         }
431         elements->set(cursor++, *recv);
432         elements->set(cursor++, *fun);
433         elements->set(cursor++, *code);
434         elements->set(cursor++, *offset);
435       }
436     }
437   }
438   elements->set(0, Smi::FromInt(sloppy_frames));
439   Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
440   result->set_length(Smi::FromInt(cursor));
441   return result;
442 }
443
444
445 void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
446   if (capture_stack_trace_for_uncaught_exceptions_) {
447     // Capture stack trace for a detailed exception message.
448     Handle<String> key = factory()->hidden_stack_trace_string();
449     Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
450         stack_trace_for_uncaught_exceptions_frame_limit_,
451         stack_trace_for_uncaught_exceptions_options_);
452     JSObject::SetHiddenProperty(error_object, key, stack_trace);
453   }
454 }
455
456
457 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
458     int frame_limit, StackTrace::StackTraceOptions options) {
459   // Ensure no negative values.
460   int limit = Max(frame_limit, 0);
461   Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
462
463   Handle<String> column_key =
464       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("column"));
465   Handle<String> line_key =
466       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("lineNumber"));
467   Handle<String> script_id_key =
468       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptId"));
469   Handle<String> script_name_key =
470       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptName"));
471   Handle<String> script_name_or_source_url_key =
472       factory()->InternalizeOneByteString(
473           STATIC_ASCII_VECTOR("scriptNameOrSourceURL"));
474   Handle<String> function_key =
475       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("functionName"));
476   Handle<String> eval_key =
477       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isEval"));
478   Handle<String> constructor_key =
479       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isConstructor"));
480
481   StackTraceFrameIterator it(this);
482   int frames_seen = 0;
483   while (!it.done() && (frames_seen < limit)) {
484     JavaScriptFrame* frame = it.frame();
485     // Set initial size to the maximum inlining level + 1 for the outermost
486     // function.
487     List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
488     frame->Summarize(&frames);
489     for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
490       // Create a JSObject to hold the information for the StackFrame.
491       Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
492
493       Handle<JSFunction> fun = frames[i].function();
494       Handle<Script> script(Script::cast(fun->shared()->script()));
495
496       if (options & StackTrace::kLineNumber) {
497         int script_line_offset = script->line_offset()->value();
498         int position = frames[i].code()->SourcePosition(frames[i].pc());
499         int line_number = Script::GetLineNumber(script, position);
500         // line_number is already shifted by the script_line_offset.
501         int relative_line_number = line_number - script_line_offset;
502         if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
503           Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
504           int start = (relative_line_number == 0) ? 0 :
505               Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
506           int column_offset = position - start;
507           if (relative_line_number == 0) {
508             // For the case where the code is on the same line as the script
509             // tag.
510             column_offset += script->column_offset()->value();
511           }
512           JSObject::SetLocalPropertyIgnoreAttributes(
513               stack_frame, column_key,
514               Handle<Smi>(Smi::FromInt(column_offset + 1), this), NONE).Check();
515         }
516        JSObject::SetLocalPropertyIgnoreAttributes(
517             stack_frame, line_key,
518             Handle<Smi>(Smi::FromInt(line_number + 1), this), NONE).Check();
519       }
520
521       if (options & StackTrace::kScriptId) {
522         Handle<Smi> script_id(script->id(), this);
523         JSObject::SetLocalPropertyIgnoreAttributes(
524             stack_frame, script_id_key, script_id, NONE).Check();
525       }
526
527       if (options & StackTrace::kScriptName) {
528         Handle<Object> script_name(script->name(), this);
529         JSObject::SetLocalPropertyIgnoreAttributes(
530             stack_frame, script_name_key, script_name, NONE).Check();
531       }
532
533       if (options & StackTrace::kScriptNameOrSourceURL) {
534         Handle<Object> result = Script::GetNameOrSourceURL(script);
535         JSObject::SetLocalPropertyIgnoreAttributes(
536             stack_frame, script_name_or_source_url_key, result, NONE).Check();
537       }
538
539       if (options & StackTrace::kFunctionName) {
540         Handle<Object> fun_name(fun->shared()->name(), this);
541         if (!fun_name->BooleanValue()) {
542           fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
543         }
544         JSObject::SetLocalPropertyIgnoreAttributes(
545             stack_frame, function_key, fun_name, NONE).Check();
546       }
547
548       if (options & StackTrace::kIsEval) {
549         Handle<Object> is_eval =
550             script->compilation_type() == Script::COMPILATION_TYPE_EVAL ?
551                 factory()->true_value() : factory()->false_value();
552         JSObject::SetLocalPropertyIgnoreAttributes(
553             stack_frame, eval_key, is_eval, NONE).Check();
554       }
555
556       if (options & StackTrace::kIsConstructor) {
557         Handle<Object> is_constructor = (frames[i].is_constructor()) ?
558             factory()->true_value() : factory()->false_value();
559         JSObject::SetLocalPropertyIgnoreAttributes(
560             stack_frame, constructor_key, is_constructor, NONE).Check();
561       }
562
563       FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
564       frames_seen++;
565     }
566     it.Advance();
567   }
568
569   stack_trace->set_length(Smi::FromInt(frames_seen));
570   return stack_trace;
571 }
572
573
574 void Isolate::PrintStack(FILE* out) {
575   if (stack_trace_nesting_level_ == 0) {
576     stack_trace_nesting_level_++;
577     StringStream::ClearMentionedObjectCache(this);
578     HeapStringAllocator allocator;
579     StringStream accumulator(&allocator);
580     incomplete_message_ = &accumulator;
581     PrintStack(&accumulator);
582     accumulator.OutputToFile(out);
583     InitializeLoggingAndCounters();
584     accumulator.Log(this);
585     incomplete_message_ = NULL;
586     stack_trace_nesting_level_ = 0;
587   } else if (stack_trace_nesting_level_ == 1) {
588     stack_trace_nesting_level_++;
589     OS::PrintError(
590       "\n\nAttempt to print stack while printing stack (double fault)\n");
591     OS::PrintError(
592       "If you are lucky you may find a partial stack dump on stdout.\n\n");
593     incomplete_message_->OutputToFile(out);
594   }
595 }
596
597
598 static void PrintFrames(Isolate* isolate,
599                         StringStream* accumulator,
600                         StackFrame::PrintMode mode) {
601   StackFrameIterator it(isolate);
602   for (int i = 0; !it.done(); it.Advance()) {
603     it.frame()->Print(accumulator, mode, i++);
604   }
605 }
606
607
608 void Isolate::PrintStack(StringStream* accumulator) {
609   if (!IsInitialized()) {
610     accumulator->Add(
611         "\n==== JS stack trace is not available =======================\n\n");
612     accumulator->Add(
613         "\n==== Isolate for the thread is not initialized =============\n\n");
614     return;
615   }
616   // The MentionedObjectCache is not GC-proof at the moment.
617   DisallowHeapAllocation no_gc;
618   ASSERT(StringStream::IsMentionedObjectCacheClear(this));
619
620   // Avoid printing anything if there are no frames.
621   if (c_entry_fp(thread_local_top()) == 0) return;
622
623   accumulator->Add(
624       "\n==== JS stack trace =========================================\n\n");
625   PrintFrames(this, accumulator, StackFrame::OVERVIEW);
626
627   accumulator->Add(
628       "\n==== Details ================================================\n\n");
629   PrintFrames(this, accumulator, StackFrame::DETAILS);
630
631   accumulator->PrintMentionedObjectCache(this);
632   accumulator->Add("=====================\n\n");
633 }
634
635
636 void Isolate::SetFailedAccessCheckCallback(
637     v8::FailedAccessCheckCallback callback) {
638   thread_local_top()->failed_access_check_callback_ = callback;
639 }
640
641
642 static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
643                                                   Handle<JSObject> receiver) {
644   JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
645   if (!constructor->shared()->IsApiFunction()) return NULL;
646
647   Object* data_obj =
648      constructor->shared()->get_api_func_data()->access_check_info();
649   if (data_obj == isolate->heap()->undefined_value()) return NULL;
650
651   return AccessCheckInfo::cast(data_obj);
652 }
653
654
655 void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver,
656                                       v8::AccessType type) {
657   if (!thread_local_top()->failed_access_check_callback_) return;
658
659   ASSERT(receiver->IsAccessCheckNeeded());
660   ASSERT(context());
661
662   // Get the data object from access check info.
663   HandleScope scope(this);
664   Handle<Object> data;
665   { DisallowHeapAllocation no_gc;
666     AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
667     if (!access_check_info) return;
668     data = handle(access_check_info->data(), this);
669   }
670
671   // Leaving JavaScript.
672   VMState<EXTERNAL> state(this);
673   thread_local_top()->failed_access_check_callback_(
674       v8::Utils::ToLocal(receiver),
675       type,
676       v8::Utils::ToLocal(data));
677 }
678
679
680 enum MayAccessDecision {
681   YES, NO, UNKNOWN
682 };
683
684
685 static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
686                                            Handle<JSObject> receiver,
687                                            v8::AccessType type) {
688   DisallowHeapAllocation no_gc;
689   // During bootstrapping, callback functions are not enabled yet.
690   if (isolate->bootstrapper()->IsActive()) return YES;
691
692   if (receiver->IsJSGlobalProxy()) {
693     Object* receiver_context = JSGlobalProxy::cast(*receiver)->native_context();
694     if (!receiver_context->IsContext()) return NO;
695
696     // Get the native context of current top context.
697     // avoid using Isolate::native_context() because it uses Handle.
698     Context* native_context =
699         isolate->context()->global_object()->native_context();
700     if (receiver_context == native_context) return YES;
701
702     if (Context::cast(receiver_context)->security_token() ==
703         native_context->security_token())
704       return YES;
705   }
706
707   return UNKNOWN;
708 }
709
710
711 bool Isolate::MayNamedAccess(Handle<JSObject> receiver,
712                              Handle<Object> key,
713                              v8::AccessType type) {
714   ASSERT(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
715
716   // Skip checks for hidden properties access.  Note, we do not
717   // require existence of a context in this case.
718   if (key.is_identical_to(factory()->hidden_string())) return true;
719
720   // Check for compatibility between the security tokens in the
721   // current lexical context and the accessed object.
722   ASSERT(context());
723
724   MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
725   if (decision != UNKNOWN) return decision == YES;
726
727   HandleScope scope(this);
728   Handle<Object> data;
729   v8::NamedSecurityCallback callback;
730   { DisallowHeapAllocation no_gc;
731     AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
732     if (!access_check_info) return false;
733     Object* fun_obj = access_check_info->named_callback();
734     callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
735     if (!callback) return false;
736     data = handle(access_check_info->data(), this);
737   }
738
739   LOG(this, ApiNamedSecurityCheck(*key));
740
741   // Leaving JavaScript.
742   VMState<EXTERNAL> state(this);
743   return callback(v8::Utils::ToLocal(receiver),
744                   v8::Utils::ToLocal(key),
745                   type,
746                   v8::Utils::ToLocal(data));
747 }
748
749
750 bool Isolate::MayIndexedAccess(Handle<JSObject> receiver,
751                                uint32_t index,
752                                v8::AccessType type) {
753   ASSERT(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
754   // Check for compatibility between the security tokens in the
755   // current lexical context and the accessed object.
756   ASSERT(context());
757
758   MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
759   if (decision != UNKNOWN) return decision == YES;
760
761   HandleScope scope(this);
762   Handle<Object> data;
763   v8::IndexedSecurityCallback callback;
764   { DisallowHeapAllocation no_gc;
765     // Get named access check callback
766     AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
767     if (!access_check_info) return false;
768     Object* fun_obj = access_check_info->indexed_callback();
769     callback = v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
770     if (!callback) return false;
771     data = handle(access_check_info->data(), this);
772   }
773
774   LOG(this, ApiIndexedSecurityCheck(index));
775
776   // Leaving JavaScript.
777   VMState<EXTERNAL> state(this);
778   return callback(
779       v8::Utils::ToLocal(receiver), index, type, v8::Utils::ToLocal(data));
780 }
781
782
783 const char* const Isolate::kStackOverflowMessage =
784   "Uncaught RangeError: Maximum call stack size exceeded";
785
786
787 Object* Isolate::StackOverflow() {
788   HandleScope scope(this);
789   // At this point we cannot create an Error object using its javascript
790   // constructor.  Instead, we copy the pre-constructed boilerplate and
791   // attach the stack trace as a hidden property.
792   Handle<String> key = factory()->stack_overflow_string();
793   Handle<JSObject> boilerplate = Handle<JSObject>::cast(
794       Object::GetProperty(js_builtins_object(), key).ToHandleChecked());
795   Handle<JSObject> exception = factory()->CopyJSObject(boilerplate);
796   DoThrow(*exception, NULL);
797
798   // Get stack trace limit.
799   Handle<Object> error = Object::GetProperty(
800       this, js_builtins_object(), "$Error").ToHandleChecked();
801   if (!error->IsJSObject()) return heap()->exception();
802
803   Handle<String> stackTraceLimit =
804       factory()->InternalizeUtf8String("stackTraceLimit");
805   ASSERT(!stackTraceLimit.is_null());
806   Handle<Object> stack_trace_limit =
807       JSObject::GetDataProperty(Handle<JSObject>::cast(error),
808                                 stackTraceLimit);
809   if (!stack_trace_limit->IsNumber()) return heap()->exception();
810   double dlimit = stack_trace_limit->Number();
811   int limit = std::isnan(dlimit) ? 0 : static_cast<int>(dlimit);
812
813   Handle<JSArray> stack_trace = CaptureSimpleStackTrace(
814       exception, factory()->undefined_value(), limit);
815   JSObject::SetHiddenProperty(exception,
816                               factory()->hidden_stack_trace_string(),
817                               stack_trace);
818   return heap()->exception();
819 }
820
821
822 Object* Isolate::TerminateExecution() {
823   DoThrow(heap_.termination_exception(), NULL);
824   return heap()->exception();
825 }
826
827
828 void Isolate::CancelTerminateExecution() {
829   if (try_catch_handler()) {
830     try_catch_handler()->has_terminated_ = false;
831   }
832   if (has_pending_exception() &&
833       pending_exception() == heap_.termination_exception()) {
834     thread_local_top()->external_caught_exception_ = false;
835     clear_pending_exception();
836   }
837   if (has_scheduled_exception() &&
838       scheduled_exception() == heap_.termination_exception()) {
839     thread_local_top()->external_caught_exception_ = false;
840     clear_scheduled_exception();
841   }
842 }
843
844
845 Object* Isolate::Throw(Object* exception, MessageLocation* location) {
846   DoThrow(exception, location);
847   return heap()->exception();
848 }
849
850
851 Object* Isolate::ReThrow(Object* exception) {
852   bool can_be_caught_externally = false;
853   bool catchable_by_javascript = is_catchable_by_javascript(exception);
854   ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
855
856   thread_local_top()->catcher_ = can_be_caught_externally ?
857       try_catch_handler() : NULL;
858
859   // Set the exception being re-thrown.
860   set_pending_exception(exception);
861   return heap()->exception();
862 }
863
864
865 Object* Isolate::ThrowIllegalOperation() {
866   if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
867   return Throw(heap_.illegal_access_string());
868 }
869
870
871 Object* Isolate::ThrowInvalidStringLength() {
872   return Throw(*factory()->NewRangeError(
873       "invalid_string_length", HandleVector<Object>(NULL, 0)));
874 }
875
876
877 void Isolate::ScheduleThrow(Object* exception) {
878   // When scheduling a throw we first throw the exception to get the
879   // error reporting if it is uncaught before rescheduling it.
880   Throw(exception);
881   PropagatePendingExceptionToExternalTryCatch();
882   if (has_pending_exception()) {
883     thread_local_top()->scheduled_exception_ = pending_exception();
884     thread_local_top()->external_caught_exception_ = false;
885     clear_pending_exception();
886   }
887 }
888
889
890 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
891   ASSERT(handler == try_catch_handler());
892   ASSERT(handler->HasCaught());
893   ASSERT(handler->rethrow_);
894   ASSERT(handler->capture_message_);
895   Object* message = reinterpret_cast<Object*>(handler->message_obj_);
896   Object* script = reinterpret_cast<Object*>(handler->message_script_);
897   ASSERT(message->IsJSMessageObject() || message->IsTheHole());
898   ASSERT(script->IsScript() || script->IsTheHole());
899   thread_local_top()->pending_message_obj_ = message;
900   thread_local_top()->pending_message_script_ = script;
901   thread_local_top()->pending_message_start_pos_ = handler->message_start_pos_;
902   thread_local_top()->pending_message_end_pos_ = handler->message_end_pos_;
903 }
904
905
906 Object* Isolate::PromoteScheduledException() {
907   Object* thrown = scheduled_exception();
908   clear_scheduled_exception();
909   // Re-throw the exception to avoid getting repeated error reporting.
910   return ReThrow(thrown);
911 }
912
913
914 void Isolate::PrintCurrentStackTrace(FILE* out) {
915   StackTraceFrameIterator it(this);
916   while (!it.done()) {
917     HandleScope scope(this);
918     // Find code position if recorded in relocation info.
919     JavaScriptFrame* frame = it.frame();
920     int pos = frame->LookupCode()->SourcePosition(frame->pc());
921     Handle<Object> pos_obj(Smi::FromInt(pos), this);
922     // Fetch function and receiver.
923     Handle<JSFunction> fun(frame->function());
924     Handle<Object> recv(frame->receiver(), this);
925     // Advance to the next JavaScript frame and determine if the
926     // current frame is the top-level frame.
927     it.Advance();
928     Handle<Object> is_top_level = it.done()
929         ? factory()->true_value()
930         : factory()->false_value();
931     // Generate and print stack trace line.
932     Handle<String> line =
933         Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
934     if (line->length() > 0) {
935       line->PrintOn(out);
936       PrintF(out, "\n");
937     }
938   }
939 }
940
941
942 void Isolate::ComputeLocation(MessageLocation* target) {
943   *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
944   StackTraceFrameIterator it(this);
945   if (!it.done()) {
946     JavaScriptFrame* frame = it.frame();
947     JSFunction* fun = frame->function();
948     Object* script = fun->shared()->script();
949     if (script->IsScript() &&
950         !(Script::cast(script)->source()->IsUndefined())) {
951       int pos = frame->LookupCode()->SourcePosition(frame->pc());
952       // Compute the location from the function and the reloc info.
953       Handle<Script> casted_script(Script::cast(script));
954       *target = MessageLocation(casted_script, pos, pos + 1);
955     }
956   }
957 }
958
959
960 bool Isolate::ShouldReportException(bool* can_be_caught_externally,
961                                     bool catchable_by_javascript) {
962   // Find the top-most try-catch handler.
963   StackHandler* handler =
964       StackHandler::FromAddress(Isolate::handler(thread_local_top()));
965   while (handler != NULL && !handler->is_catch()) {
966     handler = handler->next();
967   }
968
969   // Get the address of the external handler so we can compare the address to
970   // determine which one is closer to the top of the stack.
971   Address external_handler_address =
972       thread_local_top()->try_catch_handler_address();
973
974   // The exception has been externally caught if and only if there is
975   // an external handler which is on top of the top-most try-catch
976   // handler.
977   *can_be_caught_externally = external_handler_address != NULL &&
978       (handler == NULL || handler->address() > external_handler_address ||
979        !catchable_by_javascript);
980
981   if (*can_be_caught_externally) {
982     // Only report the exception if the external handler is verbose.
983     return try_catch_handler()->is_verbose_;
984   } else {
985     // Report the exception if it isn't caught by JavaScript code.
986     return handler == NULL;
987   }
988 }
989
990
991 bool Isolate::IsErrorObject(Handle<Object> obj) {
992   if (!obj->IsJSObject()) return false;
993
994   Handle<String> error_key =
995       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("$Error"));
996   Handle<Object> error_constructor = Object::GetProperty(
997       js_builtins_object(), error_key).ToHandleChecked();
998
999   DisallowHeapAllocation no_gc;
1000   for (Object* prototype = *obj; !prototype->IsNull();
1001        prototype = prototype->GetPrototype(this)) {
1002     if (!prototype->IsJSObject()) return false;
1003     if (JSObject::cast(prototype)->map()->constructor() ==
1004         *error_constructor) {
1005       return true;
1006     }
1007   }
1008   return false;
1009 }
1010
1011 static int fatal_exception_depth = 0;
1012
1013 void Isolate::DoThrow(Object* exception, MessageLocation* location) {
1014   ASSERT(!has_pending_exception());
1015
1016   HandleScope scope(this);
1017   Handle<Object> exception_handle(exception, this);
1018
1019   // Determine reporting and whether the exception is caught externally.
1020   bool catchable_by_javascript = is_catchable_by_javascript(exception);
1021   bool can_be_caught_externally = false;
1022   bool should_report_exception =
1023       ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1024   bool report_exception = catchable_by_javascript && should_report_exception;
1025   bool try_catch_needs_message =
1026       can_be_caught_externally && try_catch_handler()->capture_message_ &&
1027       !thread_local_top()->rethrowing_message_;
1028   bool bootstrapping = bootstrapper()->IsActive();
1029
1030   thread_local_top()->rethrowing_message_ = false;
1031
1032   // Notify debugger of exception.
1033   if (catchable_by_javascript) {
1034     debugger_->OnException(exception_handle, report_exception);
1035   }
1036
1037   // Generate the message if required.
1038   if (report_exception || try_catch_needs_message) {
1039     MessageLocation potential_computed_location;
1040     if (location == NULL) {
1041       // If no location was specified we use a computed one instead.
1042       ComputeLocation(&potential_computed_location);
1043       location = &potential_computed_location;
1044     }
1045     // It's not safe to try to make message objects or collect stack traces
1046     // while the bootstrapper is active since the infrastructure may not have
1047     // been properly initialized.
1048     if (!bootstrapping) {
1049       Handle<JSArray> stack_trace_object;
1050       if (capture_stack_trace_for_uncaught_exceptions_) {
1051         if (IsErrorObject(exception_handle)) {
1052           // We fetch the stack trace that corresponds to this error object.
1053           Handle<String> key = factory()->hidden_stack_trace_string();
1054           Object* stack_property =
1055               JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1056           // Property lookup may have failed.  In this case it's probably not
1057           // a valid Error object.
1058           if (stack_property->IsJSArray()) {
1059             stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1060           }
1061         }
1062         if (stack_trace_object.is_null()) {
1063           // Not an error object, we capture at throw site.
1064           stack_trace_object = CaptureCurrentStackTrace(
1065               stack_trace_for_uncaught_exceptions_frame_limit_,
1066               stack_trace_for_uncaught_exceptions_options_);
1067         }
1068       }
1069
1070       Handle<Object> exception_arg = exception_handle;
1071       // If the exception argument is a custom object, turn it into a string
1072       // before throwing as uncaught exception.  Note that the pending
1073       // exception object to be set later must not be turned into a string.
1074       if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
1075         MaybeHandle<Object> maybe_exception =
1076             Execution::ToDetailString(this, exception_arg);
1077         if (!maybe_exception.ToHandle(&exception_arg)) {
1078           exception_arg = factory()->InternalizeOneByteString(
1079               STATIC_ASCII_VECTOR("exception"));
1080         }
1081       }
1082       Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1083           this,
1084           "uncaught_exception",
1085           location,
1086           HandleVector<Object>(&exception_arg, 1),
1087           stack_trace_object);
1088       thread_local_top()->pending_message_obj_ = *message_obj;
1089       if (location != NULL) {
1090         thread_local_top()->pending_message_script_ = *location->script();
1091         thread_local_top()->pending_message_start_pos_ = location->start_pos();
1092         thread_local_top()->pending_message_end_pos_ = location->end_pos();
1093       }
1094
1095       // If the abort-on-uncaught-exception flag is specified, abort on any
1096       // exception not caught by JavaScript, even when an external handler is
1097       // present.  This flag is intended for use by JavaScript developers, so
1098       // print a user-friendly stack trace (not an internal one).
1099       if (fatal_exception_depth == 0 &&
1100           FLAG_abort_on_uncaught_exception &&
1101           (report_exception || can_be_caught_externally)) {
1102         fatal_exception_depth++;
1103         PrintF(stderr,
1104                "%s\n\nFROM\n",
1105                MessageHandler::GetLocalizedMessage(this, message_obj).get());
1106         PrintCurrentStackTrace(stderr);
1107         OS::Abort();
1108       }
1109     } else if (location != NULL && !location->script().is_null()) {
1110       // We are bootstrapping and caught an error where the location is set
1111       // and we have a script for the location.
1112       // In this case we could have an extension (or an internal error
1113       // somewhere) and we print out the line number at which the error occured
1114       // to the console for easier debugging.
1115       int line_number =
1116           location->script()->GetLineNumber(location->start_pos()) + 1;
1117       if (exception->IsString() && location->script()->name()->IsString()) {
1118         OS::PrintError(
1119             "Extension or internal compilation error: %s in %s at line %d.\n",
1120             String::cast(exception)->ToCString().get(),
1121             String::cast(location->script()->name())->ToCString().get(),
1122             line_number);
1123       } else if (location->script()->name()->IsString()) {
1124         OS::PrintError(
1125             "Extension or internal compilation error in %s at line %d.\n",
1126             String::cast(location->script()->name())->ToCString().get(),
1127             line_number);
1128       } else {
1129         OS::PrintError("Extension or internal compilation error.\n");
1130       }
1131     }
1132   }
1133
1134   // Save the message for reporting if the the exception remains uncaught.
1135   thread_local_top()->has_pending_message_ = report_exception;
1136
1137   // Do not forget to clean catcher_ if currently thrown exception cannot
1138   // be caught.  If necessary, ReThrow will update the catcher.
1139   thread_local_top()->catcher_ = can_be_caught_externally ?
1140       try_catch_handler() : NULL;
1141
1142   set_pending_exception(*exception_handle);
1143 }
1144
1145
1146 bool Isolate::IsExternallyCaught() {
1147   ASSERT(has_pending_exception());
1148
1149   if ((thread_local_top()->catcher_ == NULL) ||
1150       (try_catch_handler() != thread_local_top()->catcher_)) {
1151     // When throwing the exception, we found no v8::TryCatch
1152     // which should care about this exception.
1153     return false;
1154   }
1155
1156   if (!is_catchable_by_javascript(pending_exception())) {
1157     return true;
1158   }
1159
1160   // Get the address of the external handler so we can compare the address to
1161   // determine which one is closer to the top of the stack.
1162   Address external_handler_address =
1163       thread_local_top()->try_catch_handler_address();
1164   ASSERT(external_handler_address != NULL);
1165
1166   // The exception has been externally caught if and only if there is
1167   // an external handler which is on top of the top-most try-finally
1168   // handler.
1169   // There should be no try-catch blocks as they would prohibit us from
1170   // finding external catcher in the first place (see catcher_ check above).
1171   //
1172   // Note, that finally clause would rethrow an exception unless it's
1173   // aborted by jumps in control flow like return, break, etc. and we'll
1174   // have another chances to set proper v8::TryCatch.
1175   StackHandler* handler =
1176       StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1177   while (handler != NULL && handler->address() < external_handler_address) {
1178     ASSERT(!handler->is_catch());
1179     if (handler->is_finally()) return false;
1180
1181     handler = handler->next();
1182   }
1183
1184   return true;
1185 }
1186
1187
1188 void Isolate::ReportPendingMessages() {
1189   ASSERT(has_pending_exception());
1190   PropagatePendingExceptionToExternalTryCatch();
1191
1192   HandleScope scope(this);
1193   if (thread_local_top_.pending_exception_ ==
1194           heap()->termination_exception()) {
1195     // Do nothing: if needed, the exception has been already propagated to
1196     // v8::TryCatch.
1197   } else {
1198     if (thread_local_top_.has_pending_message_) {
1199       thread_local_top_.has_pending_message_ = false;
1200       if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1201         HandleScope scope(this);
1202         Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1203                                    this);
1204         if (!thread_local_top_.pending_message_script_->IsTheHole()) {
1205           Handle<Script> script(
1206               Script::cast(thread_local_top_.pending_message_script_));
1207           int start_pos = thread_local_top_.pending_message_start_pos_;
1208           int end_pos = thread_local_top_.pending_message_end_pos_;
1209           MessageLocation location(script, start_pos, end_pos);
1210           MessageHandler::ReportMessage(this, &location, message_obj);
1211         } else {
1212           MessageHandler::ReportMessage(this, NULL, message_obj);
1213         }
1214       }
1215     }
1216   }
1217   clear_pending_message();
1218 }
1219
1220
1221 MessageLocation Isolate::GetMessageLocation() {
1222   ASSERT(has_pending_exception());
1223
1224   if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1225       thread_local_top_.has_pending_message_ &&
1226       !thread_local_top_.pending_message_obj_->IsTheHole() &&
1227       !thread_local_top_.pending_message_obj_->IsTheHole()) {
1228     Handle<Script> script(
1229         Script::cast(thread_local_top_.pending_message_script_));
1230     int start_pos = thread_local_top_.pending_message_start_pos_;
1231     int end_pos = thread_local_top_.pending_message_end_pos_;
1232     return MessageLocation(script, start_pos, end_pos);
1233   }
1234
1235   return MessageLocation();
1236 }
1237
1238
1239 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1240   ASSERT(has_pending_exception());
1241   PropagatePendingExceptionToExternalTryCatch();
1242
1243   bool is_termination_exception =
1244       pending_exception() == heap_.termination_exception();
1245
1246   // Do not reschedule the exception if this is the bottom call.
1247   bool clear_exception = is_bottom_call;
1248
1249   if (is_termination_exception) {
1250     if (is_bottom_call) {
1251       thread_local_top()->external_caught_exception_ = false;
1252       clear_pending_exception();
1253       return false;
1254     }
1255   } else if (thread_local_top()->external_caught_exception_) {
1256     // If the exception is externally caught, clear it if there are no
1257     // JavaScript frames on the way to the C++ frame that has the
1258     // external handler.
1259     ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1260     Address external_handler_address =
1261         thread_local_top()->try_catch_handler_address();
1262     JavaScriptFrameIterator it(this);
1263     if (it.done() || (it.frame()->sp() > external_handler_address)) {
1264       clear_exception = true;
1265     }
1266   }
1267
1268   // Clear the exception if needed.
1269   if (clear_exception) {
1270     thread_local_top()->external_caught_exception_ = false;
1271     clear_pending_exception();
1272     return false;
1273   }
1274
1275   // Reschedule the exception.
1276   thread_local_top()->scheduled_exception_ = pending_exception();
1277   clear_pending_exception();
1278   return true;
1279 }
1280
1281
1282 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1283       bool capture,
1284       int frame_limit,
1285       StackTrace::StackTraceOptions options) {
1286   capture_stack_trace_for_uncaught_exceptions_ = capture;
1287   stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1288   stack_trace_for_uncaught_exceptions_options_ = options;
1289 }
1290
1291
1292 Handle<Context> Isolate::native_context() {
1293   return Handle<Context>(context()->global_object()->native_context());
1294 }
1295
1296
1297 Handle<Context> Isolate::global_context() {
1298   return Handle<Context>(context()->global_object()->global_context());
1299 }
1300
1301
1302 Handle<Context> Isolate::GetCallingNativeContext() {
1303   JavaScriptFrameIterator it(this);
1304   if (debug_->InDebugger()) {
1305     while (!it.done()) {
1306       JavaScriptFrame* frame = it.frame();
1307       Context* context = Context::cast(frame->context());
1308       if (context->native_context() == *debug_->debug_context()) {
1309         it.Advance();
1310       } else {
1311         break;
1312       }
1313     }
1314   }
1315   if (it.done()) return Handle<Context>::null();
1316   JavaScriptFrame* frame = it.frame();
1317   Context* context = Context::cast(frame->context());
1318   return Handle<Context>(context->native_context());
1319 }
1320
1321
1322 char* Isolate::ArchiveThread(char* to) {
1323   OS::MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1324               sizeof(ThreadLocalTop));
1325   InitializeThreadLocal();
1326   clear_pending_exception();
1327   clear_pending_message();
1328   clear_scheduled_exception();
1329   return to + sizeof(ThreadLocalTop);
1330 }
1331
1332
1333 char* Isolate::RestoreThread(char* from) {
1334   OS::MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1335               sizeof(ThreadLocalTop));
1336   // This might be just paranoia, but it seems to be needed in case a
1337   // thread_local_top_ is restored on a separate OS thread.
1338 #ifdef USE_SIMULATOR
1339   thread_local_top()->simulator_ = Simulator::current(this);
1340 #endif
1341   ASSERT(context() == NULL || context()->IsContext());
1342   return from + sizeof(ThreadLocalTop);
1343 }
1344
1345
1346 Isolate::ThreadDataTable::ThreadDataTable()
1347     : list_(NULL) {
1348 }
1349
1350
1351 Isolate::ThreadDataTable::~ThreadDataTable() {
1352   // TODO(svenpanne) The assertion below would fire if an embedder does not
1353   // cleanly dispose all Isolates before disposing v8, so we are conservative
1354   // and leave it out for now.
1355   // ASSERT_EQ(NULL, list_);
1356 }
1357
1358
1359 Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1360 #if defined(USE_SIMULATOR)
1361   delete simulator_;
1362 #endif
1363 }
1364
1365
1366 Isolate::PerIsolateThreadData*
1367     Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1368                                      ThreadId thread_id) {
1369   for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1370     if (data->Matches(isolate, thread_id)) return data;
1371   }
1372   return NULL;
1373 }
1374
1375
1376 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1377   if (list_ != NULL) list_->prev_ = data;
1378   data->next_ = list_;
1379   list_ = data;
1380 }
1381
1382
1383 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1384   if (list_ == data) list_ = data->next_;
1385   if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1386   if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1387   delete data;
1388 }
1389
1390
1391 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1392   PerIsolateThreadData* data = list_;
1393   while (data != NULL) {
1394     PerIsolateThreadData* next = data->next_;
1395     if (data->isolate() == isolate) Remove(data);
1396     data = next;
1397   }
1398 }
1399
1400
1401 #ifdef DEBUG
1402 #define TRACE_ISOLATE(tag)                                              \
1403   do {                                                                  \
1404     if (FLAG_trace_isolates) {                                          \
1405       PrintF("Isolate %p (id %d)" #tag "\n",                            \
1406              reinterpret_cast<void*>(this), id());                      \
1407     }                                                                   \
1408   } while (false)
1409 #else
1410 #define TRACE_ISOLATE(tag)
1411 #endif
1412
1413
1414 Isolate::Isolate()
1415     : embedder_data_(),
1416       state_(UNINITIALIZED),
1417       entry_stack_(NULL),
1418       stack_trace_nesting_level_(0),
1419       incomplete_message_(NULL),
1420       bootstrapper_(NULL),
1421       runtime_profiler_(NULL),
1422       compilation_cache_(NULL),
1423       counters_(NULL),
1424       code_range_(NULL),
1425       logger_(NULL),
1426       stats_table_(NULL),
1427       stub_cache_(NULL),
1428       code_aging_helper_(NULL),
1429       deoptimizer_data_(NULL),
1430       materialized_object_store_(NULL),
1431       capture_stack_trace_for_uncaught_exceptions_(false),
1432       stack_trace_for_uncaught_exceptions_frame_limit_(0),
1433       stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1434       memory_allocator_(NULL),
1435       keyed_lookup_cache_(NULL),
1436       context_slot_cache_(NULL),
1437       descriptor_lookup_cache_(NULL),
1438       handle_scope_implementer_(NULL),
1439       unicode_cache_(NULL),
1440       runtime_zone_(this),
1441       inner_pointer_to_code_cache_(NULL),
1442       write_iterator_(NULL),
1443       global_handles_(NULL),
1444       eternal_handles_(NULL),
1445       thread_manager_(NULL),
1446       has_installed_extensions_(false),
1447       string_tracker_(NULL),
1448       regexp_stack_(NULL),
1449       date_cache_(NULL),
1450       code_stub_interface_descriptors_(NULL),
1451       call_descriptors_(NULL),
1452       // TODO(bmeurer) Initialized lazily because it depends on flags; can
1453       // be fixed once the default isolate cleanup is done.
1454       random_number_generator_(NULL),
1455       has_fatal_error_(false),
1456       use_crankshaft_(true),
1457       initialized_from_snapshot_(false),
1458       cpu_profiler_(NULL),
1459       heap_profiler_(NULL),
1460       function_entry_hook_(NULL),
1461       deferred_handles_head_(NULL),
1462       optimizing_compiler_thread_(NULL),
1463       sweeper_thread_(NULL),
1464       num_sweeper_threads_(0),
1465       stress_deopt_count_(0),
1466       next_optimization_id_(0) {
1467   id_ = NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1468   TRACE_ISOLATE(constructor);
1469
1470   memset(isolate_addresses_, 0,
1471       sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1472
1473   heap_.isolate_ = this;
1474   stack_guard_.isolate_ = this;
1475
1476   // ThreadManager is initialized early to support locking an isolate
1477   // before it is entered.
1478   thread_manager_ = new ThreadManager();
1479   thread_manager_->isolate_ = this;
1480
1481 #ifdef DEBUG
1482   // heap_histograms_ initializes itself.
1483   memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1484 #endif
1485
1486   handle_scope_data_.Initialize();
1487
1488 #define ISOLATE_INIT_EXECUTE(type, name, initial_value)                        \
1489   name##_ = (initial_value);
1490   ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1491 #undef ISOLATE_INIT_EXECUTE
1492
1493 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length)                         \
1494   memset(name##_, 0, sizeof(type) * length);
1495   ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1496 #undef ISOLATE_INIT_ARRAY_EXECUTE
1497
1498   InitializeLoggingAndCounters();
1499   debug_ = new Debug(this);
1500   debugger_ = new Debugger(this);
1501 }
1502
1503
1504 void Isolate::TearDown() {
1505   TRACE_ISOLATE(tear_down);
1506
1507   // Temporarily set this isolate as current so that various parts of
1508   // the isolate can access it in their destructors without having a
1509   // direct pointer. We don't use Enter/Exit here to avoid
1510   // initializing the thread data.
1511   PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1512   Isolate* saved_isolate = UncheckedCurrent();
1513   SetIsolateThreadLocals(this, NULL);
1514
1515   Deinit();
1516
1517   { LockGuard<Mutex> lock_guard(&process_wide_mutex_);
1518     thread_data_table_->RemoveAllThreads(this);
1519   }
1520
1521   if (serialize_partial_snapshot_cache_ != NULL) {
1522     delete[] serialize_partial_snapshot_cache_;
1523     serialize_partial_snapshot_cache_ = NULL;
1524   }
1525
1526   if (!IsDefaultIsolate()) {
1527     delete this;
1528   }
1529
1530   // Restore the previous current isolate.
1531   SetIsolateThreadLocals(saved_isolate, saved_data);
1532 }
1533
1534
1535 void Isolate::GlobalTearDown() {
1536   delete thread_data_table_;
1537 }
1538
1539
1540 void Isolate::Deinit() {
1541   if (state_ == INITIALIZED) {
1542     TRACE_ISOLATE(deinit);
1543
1544     debugger()->UnloadDebugger();
1545
1546     if (concurrent_recompilation_enabled()) {
1547       optimizing_compiler_thread_->Stop();
1548       delete optimizing_compiler_thread_;
1549       optimizing_compiler_thread_ = NULL;
1550     }
1551
1552     for (int i = 0; i < num_sweeper_threads_; i++) {
1553       sweeper_thread_[i]->Stop();
1554       delete sweeper_thread_[i];
1555       sweeper_thread_[i] = NULL;
1556     }
1557     delete[] sweeper_thread_;
1558     sweeper_thread_ = NULL;
1559
1560     if (FLAG_job_based_sweeping &&
1561         heap_.mark_compact_collector()->IsConcurrentSweepingInProgress()) {
1562       heap_.mark_compact_collector()->WaitUntilSweepingCompleted();
1563     }
1564
1565     if (FLAG_hydrogen_stats) GetHStatistics()->Print();
1566
1567     if (FLAG_print_deopt_stress) {
1568       PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1569     }
1570
1571     // We must stop the logger before we tear down other components.
1572     Sampler* sampler = logger_->sampler();
1573     if (sampler && sampler->IsActive()) sampler->Stop();
1574
1575     delete deoptimizer_data_;
1576     deoptimizer_data_ = NULL;
1577     builtins_.TearDown();
1578     bootstrapper_->TearDown();
1579
1580     if (runtime_profiler_ != NULL) {
1581       delete runtime_profiler_;
1582       runtime_profiler_ = NULL;
1583     }
1584     heap_.TearDown();
1585     logger_->TearDown();
1586
1587     delete heap_profiler_;
1588     heap_profiler_ = NULL;
1589     delete cpu_profiler_;
1590     cpu_profiler_ = NULL;
1591
1592     // The default isolate is re-initializable due to legacy API.
1593     state_ = UNINITIALIZED;
1594   }
1595 }
1596
1597
1598 void Isolate::PushToPartialSnapshotCache(Object* obj) {
1599   int length = serialize_partial_snapshot_cache_length();
1600   int capacity = serialize_partial_snapshot_cache_capacity();
1601
1602   if (length >= capacity) {
1603     int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1604     Object** new_array = new Object*[new_capacity];
1605     for (int i = 0; i < length; i++) {
1606       new_array[i] = serialize_partial_snapshot_cache()[i];
1607     }
1608     if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1609     set_serialize_partial_snapshot_cache(new_array);
1610     set_serialize_partial_snapshot_cache_capacity(new_capacity);
1611   }
1612
1613   serialize_partial_snapshot_cache()[length] = obj;
1614   set_serialize_partial_snapshot_cache_length(length + 1);
1615 }
1616
1617
1618 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1619                                      PerIsolateThreadData* data) {
1620   Thread::SetThreadLocal(isolate_key_, isolate);
1621   Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1622 }
1623
1624
1625 Isolate::~Isolate() {
1626   TRACE_ISOLATE(destructor);
1627
1628   // Has to be called while counters_ are still alive
1629   runtime_zone_.DeleteKeptSegment();
1630
1631   // The entry stack must be empty when we get here.
1632   ASSERT(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1633
1634   delete entry_stack_;
1635   entry_stack_ = NULL;
1636
1637   delete[] assembler_spare_buffer_;
1638   assembler_spare_buffer_ = NULL;
1639
1640   delete unicode_cache_;
1641   unicode_cache_ = NULL;
1642
1643   delete date_cache_;
1644   date_cache_ = NULL;
1645
1646   delete[] code_stub_interface_descriptors_;
1647   code_stub_interface_descriptors_ = NULL;
1648
1649   delete[] call_descriptors_;
1650   call_descriptors_ = NULL;
1651
1652   delete regexp_stack_;
1653   regexp_stack_ = NULL;
1654
1655   delete descriptor_lookup_cache_;
1656   descriptor_lookup_cache_ = NULL;
1657   delete context_slot_cache_;
1658   context_slot_cache_ = NULL;
1659   delete keyed_lookup_cache_;
1660   keyed_lookup_cache_ = NULL;
1661
1662   delete stub_cache_;
1663   stub_cache_ = NULL;
1664   delete code_aging_helper_;
1665   code_aging_helper_ = NULL;
1666   delete stats_table_;
1667   stats_table_ = NULL;
1668
1669   delete materialized_object_store_;
1670   materialized_object_store_ = NULL;
1671
1672   delete logger_;
1673   logger_ = NULL;
1674
1675   delete counters_;
1676   counters_ = NULL;
1677
1678   delete handle_scope_implementer_;
1679   handle_scope_implementer_ = NULL;
1680
1681   delete compilation_cache_;
1682   compilation_cache_ = NULL;
1683   delete bootstrapper_;
1684   bootstrapper_ = NULL;
1685   delete inner_pointer_to_code_cache_;
1686   inner_pointer_to_code_cache_ = NULL;
1687   delete write_iterator_;
1688   write_iterator_ = NULL;
1689
1690   delete thread_manager_;
1691   thread_manager_ = NULL;
1692
1693   delete string_tracker_;
1694   string_tracker_ = NULL;
1695
1696   delete memory_allocator_;
1697   memory_allocator_ = NULL;
1698   delete code_range_;
1699   code_range_ = NULL;
1700   delete global_handles_;
1701   global_handles_ = NULL;
1702   delete eternal_handles_;
1703   eternal_handles_ = NULL;
1704
1705   delete string_stream_debug_object_cache_;
1706   string_stream_debug_object_cache_ = NULL;
1707
1708   delete external_reference_table_;
1709   external_reference_table_ = NULL;
1710
1711   delete random_number_generator_;
1712   random_number_generator_ = NULL;
1713
1714   delete debugger_;
1715   debugger_ = NULL;
1716   delete debug_;
1717   debug_ = NULL;
1718 }
1719
1720
1721 void Isolate::InitializeThreadLocal() {
1722   thread_local_top_.isolate_ = this;
1723   thread_local_top_.Initialize();
1724 }
1725
1726
1727 void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1728   ASSERT(has_pending_exception());
1729
1730   bool external_caught = IsExternallyCaught();
1731   thread_local_top_.external_caught_exception_ = external_caught;
1732
1733   if (!external_caught) return;
1734
1735   if (thread_local_top_.pending_exception_ ==
1736              heap()->termination_exception()) {
1737     try_catch_handler()->can_continue_ = false;
1738     try_catch_handler()->has_terminated_ = true;
1739     try_catch_handler()->exception_ = heap()->null_value();
1740   } else {
1741     v8::TryCatch* handler = try_catch_handler();
1742     ASSERT(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
1743            thread_local_top_.pending_message_obj_->IsTheHole());
1744     ASSERT(thread_local_top_.pending_message_script_->IsScript() ||
1745            thread_local_top_.pending_message_script_->IsTheHole());
1746     handler->can_continue_ = true;
1747     handler->has_terminated_ = false;
1748     handler->exception_ = pending_exception();
1749     // Propagate to the external try-catch only if we got an actual message.
1750     if (thread_local_top_.pending_message_obj_->IsTheHole()) return;
1751
1752     handler->message_obj_ = thread_local_top_.pending_message_obj_;
1753     handler->message_script_ = thread_local_top_.pending_message_script_;
1754     handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
1755     handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
1756   }
1757 }
1758
1759
1760 void Isolate::InitializeLoggingAndCounters() {
1761   if (logger_ == NULL) {
1762     logger_ = new Logger(this);
1763   }
1764   if (counters_ == NULL) {
1765     counters_ = new Counters(this);
1766   }
1767 }
1768
1769
1770 bool Isolate::Init(Deserializer* des) {
1771   ASSERT(state_ != INITIALIZED);
1772   TRACE_ISOLATE(init);
1773
1774   stress_deopt_count_ = FLAG_deopt_every_n_times;
1775
1776   has_fatal_error_ = false;
1777
1778   use_crankshaft_ = FLAG_crankshaft
1779       && !Serializer::enabled(this)
1780       && CpuFeatures::SupportsCrankshaft();
1781
1782   if (function_entry_hook() != NULL) {
1783     // When function entry hooking is in effect, we have to create the code
1784     // stubs from scratch to get entry hooks, rather than loading the previously
1785     // generated stubs from disk.
1786     // If this assert fires, the initialization path has regressed.
1787     ASSERT(des == NULL);
1788   }
1789
1790   // The initialization process does not handle memory exhaustion.
1791   DisallowAllocationFailure disallow_allocation_failure(this);
1792
1793   memory_allocator_ = new MemoryAllocator(this);
1794   code_range_ = new CodeRange(this);
1795
1796   // Safe after setting Heap::isolate_, and initializing StackGuard
1797   heap_.SetStackLimits();
1798
1799 #define ASSIGN_ELEMENT(CamelName, hacker_name)                  \
1800   isolate_addresses_[Isolate::k##CamelName##Address] =          \
1801       reinterpret_cast<Address>(hacker_name##_address());
1802   FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
1803 #undef ASSIGN_ELEMENT
1804
1805   string_tracker_ = new StringTracker();
1806   string_tracker_->isolate_ = this;
1807   compilation_cache_ = new CompilationCache(this);
1808   keyed_lookup_cache_ = new KeyedLookupCache();
1809   context_slot_cache_ = new ContextSlotCache();
1810   descriptor_lookup_cache_ = new DescriptorLookupCache();
1811   unicode_cache_ = new UnicodeCache();
1812   inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
1813   write_iterator_ = new ConsStringIteratorOp();
1814   global_handles_ = new GlobalHandles(this);
1815   eternal_handles_ = new EternalHandles();
1816   bootstrapper_ = new Bootstrapper(this);
1817   handle_scope_implementer_ = new HandleScopeImplementer(this);
1818   stub_cache_ = new StubCache(this);
1819   materialized_object_store_ = new MaterializedObjectStore(this);
1820   regexp_stack_ = new RegExpStack();
1821   regexp_stack_->isolate_ = this;
1822   date_cache_ = new DateCache();
1823   code_stub_interface_descriptors_ =
1824       new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
1825   call_descriptors_ =
1826       new CallInterfaceDescriptor[NUMBER_OF_CALL_DESCRIPTORS];
1827   cpu_profiler_ = new CpuProfiler(this);
1828   heap_profiler_ = new HeapProfiler(heap());
1829
1830   // Enable logging before setting up the heap
1831   logger_->SetUp(this);
1832
1833   // Initialize other runtime facilities
1834 #if defined(USE_SIMULATOR)
1835 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS
1836   Simulator::Initialize(this);
1837 #endif
1838 #endif
1839
1840   code_aging_helper_ = new CodeAgingHelper();
1841
1842   { // NOLINT
1843     // Ensure that the thread has a valid stack guard.  The v8::Locker object
1844     // will ensure this too, but we don't have to use lockers if we are only
1845     // using one thread.
1846     ExecutionAccess lock(this);
1847     stack_guard_.InitThread(lock);
1848   }
1849
1850   // SetUp the object heap.
1851   ASSERT(!heap_.HasBeenSetUp());
1852   if (!heap_.SetUp()) {
1853     V8::FatalProcessOutOfMemory("heap setup");
1854     return false;
1855   }
1856
1857   deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
1858
1859   const bool create_heap_objects = (des == NULL);
1860   if (create_heap_objects && !heap_.CreateHeapObjects()) {
1861     V8::FatalProcessOutOfMemory("heap object creation");
1862     return false;
1863   }
1864
1865   if (create_heap_objects) {
1866     // Terminate the cache array with the sentinel so we can iterate.
1867     PushToPartialSnapshotCache(heap_.undefined_value());
1868   }
1869
1870   InitializeThreadLocal();
1871
1872   bootstrapper_->Initialize(create_heap_objects);
1873   builtins_.SetUp(this, create_heap_objects);
1874
1875   if (FLAG_log_internal_timer_events) {
1876     set_event_logger(Logger::LogInternalEvents);
1877   } else {
1878     set_event_logger(Logger::EmptyLogInternalEvents);
1879   }
1880
1881   // Set default value if not yet set.
1882   // TODO(yangguo): move this to ResourceConstraints::ConfigureDefaults
1883   // once ResourceConstraints becomes an argument to the Isolate constructor.
1884   if (max_available_threads_ < 1) {
1885     // Choose the default between 1 and 4.
1886     max_available_threads_ = Max(Min(CPU::NumberOfProcessorsOnline(), 4), 1);
1887   }
1888
1889   if (!FLAG_job_based_sweeping) {
1890     num_sweeper_threads_ =
1891         SweeperThread::NumberOfThreads(max_available_threads_);
1892   }
1893
1894   if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
1895     PrintF("Concurrent recompilation has been disabled for tracing.\n");
1896   } else if (OptimizingCompilerThread::Enabled(max_available_threads_)) {
1897     optimizing_compiler_thread_ = new OptimizingCompilerThread(this);
1898     optimizing_compiler_thread_->Start();
1899   }
1900
1901   if (num_sweeper_threads_ > 0) {
1902     sweeper_thread_ = new SweeperThread*[num_sweeper_threads_];
1903     for (int i = 0; i < num_sweeper_threads_; i++) {
1904       sweeper_thread_[i] = new SweeperThread(this);
1905       sweeper_thread_[i]->Start();
1906     }
1907   }
1908
1909   // If we are deserializing, read the state into the now-empty heap.
1910   if (!create_heap_objects) {
1911     des->Deserialize(this);
1912   }
1913   stub_cache_->Initialize();
1914
1915   // Finish initialization of ThreadLocal after deserialization is done.
1916   clear_pending_exception();
1917   clear_pending_message();
1918   clear_scheduled_exception();
1919
1920   // Deserializing may put strange things in the root array's copy of the
1921   // stack guard.
1922   heap_.SetStackLimits();
1923
1924   // Quiet the heap NaN if needed on target platform.
1925   if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
1926
1927   runtime_profiler_ = new RuntimeProfiler(this);
1928
1929   // If we are deserializing, log non-function code objects and compiled
1930   // functions found in the snapshot.
1931   if (!create_heap_objects &&
1932       (FLAG_log_code ||
1933        FLAG_ll_prof ||
1934        FLAG_perf_jit_prof ||
1935        FLAG_perf_basic_prof ||
1936        logger_->is_logging_code_events())) {
1937     HandleScope scope(this);
1938     LOG(this, LogCodeObjects());
1939     LOG(this, LogCompiledFunctions());
1940   }
1941
1942   // If we are profiling with the Linux perf tool, we need to disable
1943   // code relocation.
1944   if (FLAG_perf_jit_prof || FLAG_perf_basic_prof) {
1945     FLAG_compact_code_space = false;
1946   }
1947
1948   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
1949            Internals::kIsolateEmbedderDataOffset);
1950   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
1951            Internals::kIsolateRootsOffset);
1952
1953   state_ = INITIALIZED;
1954   time_millis_at_init_ = OS::TimeCurrentMillis();
1955
1956   if (!create_heap_objects) {
1957     // Now that the heap is consistent, it's OK to generate the code for the
1958     // deopt entry table that might have been referred to by optimized code in
1959     // the snapshot.
1960     HandleScope scope(this);
1961     Deoptimizer::EnsureCodeForDeoptimizationEntry(
1962         this,
1963         Deoptimizer::LAZY,
1964         kDeoptTableSerializeEntryCount - 1);
1965   }
1966
1967   if (!Serializer::enabled(this)) {
1968     // Ensure that all stubs which need to be generated ahead of time, but
1969     // cannot be serialized into the snapshot have been generated.
1970     HandleScope scope(this);
1971     CodeStub::GenerateFPStubs(this);
1972     StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
1973     StubFailureTrampolineStub::GenerateAheadOfTime(this);
1974     // Ensure interface descriptors are initialized even when stubs have been
1975     // deserialized out of the snapshot without using the graph builder.
1976     FastCloneShallowArrayStub::InstallDescriptors(this);
1977     BinaryOpICStub::InstallDescriptors(this);
1978     BinaryOpWithAllocationSiteStub::InstallDescriptors(this);
1979     CompareNilICStub::InstallDescriptors(this);
1980     ToBooleanStub::InstallDescriptors(this);
1981     ToNumberStub::InstallDescriptors(this);
1982     ArrayConstructorStubBase::InstallDescriptors(this);
1983     InternalArrayConstructorStubBase::InstallDescriptors(this);
1984     FastNewClosureStub::InstallDescriptors(this);
1985     FastNewContextStub::InstallDescriptors(this);
1986     NumberToStringStub::InstallDescriptors(this);
1987     StringAddStub::InstallDescriptors(this);
1988     RegExpConstructResultStub::InstallDescriptors(this);
1989   }
1990
1991   CallDescriptors::InitializeForIsolate(this);
1992
1993   initialized_from_snapshot_ = (des != NULL);
1994
1995   return true;
1996 }
1997
1998
1999 // Initialized lazily to allow early
2000 // v8::V8::SetAddHistogramSampleFunction calls.
2001 StatsTable* Isolate::stats_table() {
2002   if (stats_table_ == NULL) {
2003     stats_table_ = new StatsTable;
2004   }
2005   return stats_table_;
2006 }
2007
2008
2009 void Isolate::Enter() {
2010   Isolate* current_isolate = NULL;
2011   PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2012   if (current_data != NULL) {
2013     current_isolate = current_data->isolate_;
2014     ASSERT(current_isolate != NULL);
2015     if (current_isolate == this) {
2016       ASSERT(Current() == this);
2017       ASSERT(entry_stack_ != NULL);
2018       ASSERT(entry_stack_->previous_thread_data == NULL ||
2019              entry_stack_->previous_thread_data->thread_id().Equals(
2020                  ThreadId::Current()));
2021       // Same thread re-enters the isolate, no need to re-init anything.
2022       entry_stack_->entry_count++;
2023       return;
2024     }
2025   }
2026
2027   // Threads can have default isolate set into TLS as Current but not yet have
2028   // PerIsolateThreadData for it, as it requires more advanced phase of the
2029   // initialization. For example, a thread might be the one that system used for
2030   // static initializers - in this case the default isolate is set in TLS but
2031   // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2032   // there, use the isolate set in TLS.
2033   if (current_isolate == NULL) {
2034     current_isolate = Isolate::UncheckedCurrent();
2035   }
2036
2037   PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2038   ASSERT(data != NULL);
2039   ASSERT(data->isolate_ == this);
2040
2041   EntryStackItem* item = new EntryStackItem(current_data,
2042                                             current_isolate,
2043                                             entry_stack_);
2044   entry_stack_ = item;
2045
2046   SetIsolateThreadLocals(this, data);
2047
2048   // In case it's the first time some thread enters the isolate.
2049   set_thread_id(data->thread_id());
2050 }
2051
2052
2053 void Isolate::Exit() {
2054   ASSERT(entry_stack_ != NULL);
2055   ASSERT(entry_stack_->previous_thread_data == NULL ||
2056          entry_stack_->previous_thread_data->thread_id().Equals(
2057              ThreadId::Current()));
2058
2059   if (--entry_stack_->entry_count > 0) return;
2060
2061   ASSERT(CurrentPerIsolateThreadData() != NULL);
2062   ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2063
2064   // Pop the stack.
2065   EntryStackItem* item = entry_stack_;
2066   entry_stack_ = item->previous_item;
2067
2068   PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2069   Isolate* previous_isolate = item->previous_isolate;
2070
2071   delete item;
2072
2073   // Reinit the current thread for the isolate it was running before this one.
2074   SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2075 }
2076
2077
2078 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2079   deferred->next_ = deferred_handles_head_;
2080   if (deferred_handles_head_ != NULL) {
2081     deferred_handles_head_->previous_ = deferred;
2082   }
2083   deferred_handles_head_ = deferred;
2084 }
2085
2086
2087 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2088 #ifdef DEBUG
2089   // In debug mode assert that the linked list is well-formed.
2090   DeferredHandles* deferred_iterator = deferred;
2091   while (deferred_iterator->previous_ != NULL) {
2092     deferred_iterator = deferred_iterator->previous_;
2093   }
2094   ASSERT(deferred_handles_head_ == deferred_iterator);
2095 #endif
2096   if (deferred_handles_head_ == deferred) {
2097     deferred_handles_head_ = deferred_handles_head_->next_;
2098   }
2099   if (deferred->next_ != NULL) {
2100     deferred->next_->previous_ = deferred->previous_;
2101   }
2102   if (deferred->previous_ != NULL) {
2103     deferred->previous_->next_ = deferred->next_;
2104   }
2105 }
2106
2107
2108 HStatistics* Isolate::GetHStatistics() {
2109   if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2110   return hstatistics();
2111 }
2112
2113
2114 HTracer* Isolate::GetHTracer() {
2115   if (htracer() == NULL) set_htracer(new HTracer(id()));
2116   return htracer();
2117 }
2118
2119
2120 CodeTracer* Isolate::GetCodeTracer() {
2121   if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2122   return code_tracer();
2123 }
2124
2125
2126 Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2127   Context* native_context = context()->native_context();
2128   Object* maybe_map_array = native_context->js_array_maps();
2129   if (!maybe_map_array->IsUndefined()) {
2130     Object* maybe_transitioned_map =
2131         FixedArray::cast(maybe_map_array)->get(kind);
2132     if (!maybe_transitioned_map->IsUndefined()) {
2133       return Map::cast(maybe_transitioned_map);
2134     }
2135   }
2136   return NULL;
2137 }
2138
2139
2140 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2141   Map* root_array_map =
2142       get_initial_js_array_map(GetInitialFastElementsKind());
2143   ASSERT(root_array_map != NULL);
2144   JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2145
2146   // Check that the array prototype hasn't been altered WRT empty elements.
2147   if (root_array_map->prototype() != initial_array_proto) return false;
2148   if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2149     return false;
2150   }
2151
2152   // Check that the object prototype hasn't been altered WRT empty elements.
2153   JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2154   Object* root_array_map_proto = initial_array_proto->GetPrototype();
2155   if (root_array_map_proto != initial_object_proto) return false;
2156   if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2157     return false;
2158   }
2159
2160   return initial_object_proto->GetPrototype()->IsNull();
2161 }
2162
2163
2164 CodeStubInterfaceDescriptor*
2165     Isolate::code_stub_interface_descriptor(int index) {
2166   return code_stub_interface_descriptors_ + index;
2167 }
2168
2169
2170 CallInterfaceDescriptor*
2171     Isolate::call_descriptor(CallDescriptorKey index) {
2172   ASSERT(0 <= index && index < NUMBER_OF_CALL_DESCRIPTORS);
2173   return &call_descriptors_[index];
2174 }
2175
2176
2177 Object* Isolate::FindCodeObject(Address a) {
2178   return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2179 }
2180
2181
2182 #ifdef DEBUG
2183 #define ISOLATE_FIELD_OFFSET(type, name, ignored)                       \
2184 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2185 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2186 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2187 #undef ISOLATE_FIELD_OFFSET
2188 #endif
2189
2190
2191 Handle<JSObject> Isolate::GetSymbolRegistry() {
2192   if (heap()->symbol_registry()->IsUndefined()) {
2193     Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2194     Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2195     heap()->set_symbol_registry(*registry);
2196
2197     static const char* nested[] = {
2198       "for", "for_api", "for_intern", "keyFor", "private_api", "private_intern"
2199     };
2200     for (unsigned i = 0; i < ARRAY_SIZE(nested); ++i) {
2201       Handle<String> name = factory()->InternalizeUtf8String(nested[i]);
2202       Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2203       JSObject::NormalizeProperties(obj, KEEP_INOBJECT_PROPERTIES, 8);
2204       JSObject::SetProperty(registry, name, obj, NONE, STRICT).Assert();
2205     }
2206   }
2207   return Handle<JSObject>::cast(factory()->symbol_registry());
2208 }
2209
2210
2211 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2212   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2213     if (callback == call_completed_callbacks_.at(i)) return;
2214   }
2215   call_completed_callbacks_.Add(callback);
2216 }
2217
2218
2219 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2220   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2221     if (callback == call_completed_callbacks_.at(i)) {
2222       call_completed_callbacks_.Remove(i);
2223     }
2224   }
2225 }
2226
2227
2228 void Isolate::FireCallCompletedCallback() {
2229   bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2230   bool run_microtasks = autorun_microtasks() && microtask_pending();
2231   if (!has_call_completed_callbacks && !run_microtasks) return;
2232
2233   if (!handle_scope_implementer()->CallDepthIsZero()) return;
2234   // Fire callbacks.  Increase call depth to prevent recursive callbacks.
2235   handle_scope_implementer()->IncrementCallDepth();
2236   if (run_microtasks) Execution::RunMicrotasks(this);
2237   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2238     call_completed_callbacks_.at(i)();
2239   }
2240   handle_scope_implementer()->DecrementCallDepth();
2241 }
2242
2243
2244 void Isolate::RunMicrotasks() {
2245   if (!microtask_pending())
2246     return;
2247
2248   ASSERT(handle_scope_implementer()->CallDepthIsZero());
2249
2250   // Increase call depth to prevent recursive callbacks.
2251   handle_scope_implementer()->IncrementCallDepth();
2252   Execution::RunMicrotasks(this);
2253   handle_scope_implementer()->DecrementCallDepth();
2254 }
2255
2256
2257 } }  // namespace v8::internal