Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / 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   }
137   ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
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       deoptimizer_data_(NULL),
1429       materialized_object_store_(NULL),
1430       capture_stack_trace_for_uncaught_exceptions_(false),
1431       stack_trace_for_uncaught_exceptions_frame_limit_(0),
1432       stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1433       memory_allocator_(NULL),
1434       keyed_lookup_cache_(NULL),
1435       context_slot_cache_(NULL),
1436       descriptor_lookup_cache_(NULL),
1437       handle_scope_implementer_(NULL),
1438       unicode_cache_(NULL),
1439       runtime_zone_(this),
1440       inner_pointer_to_code_cache_(NULL),
1441       write_iterator_(NULL),
1442       global_handles_(NULL),
1443       eternal_handles_(NULL),
1444       thread_manager_(NULL),
1445       has_installed_extensions_(false),
1446       string_tracker_(NULL),
1447       regexp_stack_(NULL),
1448       date_cache_(NULL),
1449       code_stub_interface_descriptors_(NULL),
1450       call_descriptors_(NULL),
1451       // TODO(bmeurer) Initialized lazily because it depends on flags; can
1452       // be fixed once the default isolate cleanup is done.
1453       random_number_generator_(NULL),
1454       has_fatal_error_(false),
1455       use_crankshaft_(true),
1456       initialized_from_snapshot_(false),
1457       cpu_profiler_(NULL),
1458       heap_profiler_(NULL),
1459       function_entry_hook_(NULL),
1460       deferred_handles_head_(NULL),
1461       optimizing_compiler_thread_(NULL),
1462       sweeper_thread_(NULL),
1463       num_sweeper_threads_(0),
1464       stress_deopt_count_(0),
1465       next_optimization_id_(0) {
1466   id_ = NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1467   TRACE_ISOLATE(constructor);
1468
1469   memset(isolate_addresses_, 0,
1470       sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1471
1472   heap_.isolate_ = this;
1473   stack_guard_.isolate_ = this;
1474
1475   // ThreadManager is initialized early to support locking an isolate
1476   // before it is entered.
1477   thread_manager_ = new ThreadManager();
1478   thread_manager_->isolate_ = this;
1479
1480 #ifdef DEBUG
1481   // heap_histograms_ initializes itself.
1482   memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1483 #endif
1484
1485   handle_scope_data_.Initialize();
1486
1487 #define ISOLATE_INIT_EXECUTE(type, name, initial_value)                        \
1488   name##_ = (initial_value);
1489   ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1490 #undef ISOLATE_INIT_EXECUTE
1491
1492 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length)                         \
1493   memset(name##_, 0, sizeof(type) * length);
1494   ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1495 #undef ISOLATE_INIT_ARRAY_EXECUTE
1496
1497   InitializeLoggingAndCounters();
1498   debug_ = new Debug(this);
1499   debugger_ = new Debugger(this);
1500 }
1501
1502
1503 void Isolate::TearDown() {
1504   TRACE_ISOLATE(tear_down);
1505
1506   // Temporarily set this isolate as current so that various parts of
1507   // the isolate can access it in their destructors without having a
1508   // direct pointer. We don't use Enter/Exit here to avoid
1509   // initializing the thread data.
1510   PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1511   Isolate* saved_isolate = UncheckedCurrent();
1512   SetIsolateThreadLocals(this, NULL);
1513
1514   Deinit();
1515
1516   { LockGuard<Mutex> lock_guard(&process_wide_mutex_);
1517     thread_data_table_->RemoveAllThreads(this);
1518   }
1519
1520   if (serialize_partial_snapshot_cache_ != NULL) {
1521     delete[] serialize_partial_snapshot_cache_;
1522     serialize_partial_snapshot_cache_ = NULL;
1523   }
1524
1525   if (!IsDefaultIsolate()) {
1526     delete this;
1527   }
1528
1529   // Restore the previous current isolate.
1530   SetIsolateThreadLocals(saved_isolate, saved_data);
1531 }
1532
1533
1534 void Isolate::GlobalTearDown() {
1535   delete thread_data_table_;
1536 }
1537
1538
1539 void Isolate::Deinit() {
1540   if (state_ == INITIALIZED) {
1541     TRACE_ISOLATE(deinit);
1542
1543     debugger()->UnloadDebugger();
1544
1545     if (concurrent_recompilation_enabled()) {
1546       optimizing_compiler_thread_->Stop();
1547       delete optimizing_compiler_thread_;
1548       optimizing_compiler_thread_ = NULL;
1549     }
1550
1551     for (int i = 0; i < num_sweeper_threads_; i++) {
1552       sweeper_thread_[i]->Stop();
1553       delete sweeper_thread_[i];
1554       sweeper_thread_[i] = NULL;
1555     }
1556     delete[] sweeper_thread_;
1557     sweeper_thread_ = NULL;
1558
1559     if (FLAG_job_based_sweeping &&
1560         heap_.mark_compact_collector()->IsConcurrentSweepingInProgress()) {
1561       heap_.mark_compact_collector()->WaitUntilSweepingCompleted();
1562     }
1563
1564     if (FLAG_hydrogen_stats) GetHStatistics()->Print();
1565
1566     if (FLAG_print_deopt_stress) {
1567       PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1568     }
1569
1570     // We must stop the logger before we tear down other components.
1571     Sampler* sampler = logger_->sampler();
1572     if (sampler && sampler->IsActive()) sampler->Stop();
1573
1574     delete deoptimizer_data_;
1575     deoptimizer_data_ = NULL;
1576     builtins_.TearDown();
1577     bootstrapper_->TearDown();
1578
1579     if (runtime_profiler_ != NULL) {
1580       delete runtime_profiler_;
1581       runtime_profiler_ = NULL;
1582     }
1583     heap_.TearDown();
1584     logger_->TearDown();
1585
1586     delete heap_profiler_;
1587     heap_profiler_ = NULL;
1588     delete cpu_profiler_;
1589     cpu_profiler_ = NULL;
1590
1591     // The default isolate is re-initializable due to legacy API.
1592     state_ = UNINITIALIZED;
1593   }
1594 }
1595
1596
1597 void Isolate::PushToPartialSnapshotCache(Object* obj) {
1598   int length = serialize_partial_snapshot_cache_length();
1599   int capacity = serialize_partial_snapshot_cache_capacity();
1600
1601   if (length >= capacity) {
1602     int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1603     Object** new_array = new Object*[new_capacity];
1604     for (int i = 0; i < length; i++) {
1605       new_array[i] = serialize_partial_snapshot_cache()[i];
1606     }
1607     if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1608     set_serialize_partial_snapshot_cache(new_array);
1609     set_serialize_partial_snapshot_cache_capacity(new_capacity);
1610   }
1611
1612   serialize_partial_snapshot_cache()[length] = obj;
1613   set_serialize_partial_snapshot_cache_length(length + 1);
1614 }
1615
1616
1617 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1618                                      PerIsolateThreadData* data) {
1619   Thread::SetThreadLocal(isolate_key_, isolate);
1620   Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1621 }
1622
1623
1624 Isolate::~Isolate() {
1625   TRACE_ISOLATE(destructor);
1626
1627   // Has to be called while counters_ are still alive
1628   runtime_zone_.DeleteKeptSegment();
1629
1630   // The entry stack must be empty when we get here.
1631   ASSERT(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1632
1633   delete entry_stack_;
1634   entry_stack_ = NULL;
1635
1636   delete[] assembler_spare_buffer_;
1637   assembler_spare_buffer_ = NULL;
1638
1639   delete unicode_cache_;
1640   unicode_cache_ = NULL;
1641
1642   delete date_cache_;
1643   date_cache_ = NULL;
1644
1645   delete[] code_stub_interface_descriptors_;
1646   code_stub_interface_descriptors_ = NULL;
1647
1648   delete[] call_descriptors_;
1649   call_descriptors_ = NULL;
1650
1651   delete regexp_stack_;
1652   regexp_stack_ = NULL;
1653
1654   delete descriptor_lookup_cache_;
1655   descriptor_lookup_cache_ = NULL;
1656   delete context_slot_cache_;
1657   context_slot_cache_ = NULL;
1658   delete keyed_lookup_cache_;
1659   keyed_lookup_cache_ = NULL;
1660
1661   delete stub_cache_;
1662   stub_cache_ = NULL;
1663   delete stats_table_;
1664   stats_table_ = NULL;
1665
1666   delete materialized_object_store_;
1667   materialized_object_store_ = NULL;
1668
1669   delete logger_;
1670   logger_ = NULL;
1671
1672   delete counters_;
1673   counters_ = NULL;
1674
1675   delete handle_scope_implementer_;
1676   handle_scope_implementer_ = NULL;
1677
1678   delete compilation_cache_;
1679   compilation_cache_ = NULL;
1680   delete bootstrapper_;
1681   bootstrapper_ = NULL;
1682   delete inner_pointer_to_code_cache_;
1683   inner_pointer_to_code_cache_ = NULL;
1684   delete write_iterator_;
1685   write_iterator_ = NULL;
1686
1687   delete thread_manager_;
1688   thread_manager_ = NULL;
1689
1690   delete string_tracker_;
1691   string_tracker_ = NULL;
1692
1693   delete memory_allocator_;
1694   memory_allocator_ = NULL;
1695   delete code_range_;
1696   code_range_ = NULL;
1697   delete global_handles_;
1698   global_handles_ = NULL;
1699   delete eternal_handles_;
1700   eternal_handles_ = NULL;
1701
1702   delete string_stream_debug_object_cache_;
1703   string_stream_debug_object_cache_ = NULL;
1704
1705   delete external_reference_table_;
1706   external_reference_table_ = NULL;
1707
1708   delete random_number_generator_;
1709   random_number_generator_ = NULL;
1710
1711   delete debugger_;
1712   debugger_ = NULL;
1713   delete debug_;
1714   debug_ = NULL;
1715 }
1716
1717
1718 void Isolate::InitializeThreadLocal() {
1719   thread_local_top_.isolate_ = this;
1720   thread_local_top_.Initialize();
1721 }
1722
1723
1724 void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1725   ASSERT(has_pending_exception());
1726
1727   bool external_caught = IsExternallyCaught();
1728   thread_local_top_.external_caught_exception_ = external_caught;
1729
1730   if (!external_caught) return;
1731
1732   if (thread_local_top_.pending_exception_ ==
1733              heap()->termination_exception()) {
1734     try_catch_handler()->can_continue_ = false;
1735     try_catch_handler()->has_terminated_ = true;
1736     try_catch_handler()->exception_ = heap()->null_value();
1737   } else {
1738     v8::TryCatch* handler = try_catch_handler();
1739     ASSERT(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
1740            thread_local_top_.pending_message_obj_->IsTheHole());
1741     ASSERT(thread_local_top_.pending_message_script_->IsScript() ||
1742            thread_local_top_.pending_message_script_->IsTheHole());
1743     handler->can_continue_ = true;
1744     handler->has_terminated_ = false;
1745     handler->exception_ = pending_exception();
1746     // Propagate to the external try-catch only if we got an actual message.
1747     if (thread_local_top_.pending_message_obj_->IsTheHole()) return;
1748
1749     handler->message_obj_ = thread_local_top_.pending_message_obj_;
1750     handler->message_script_ = thread_local_top_.pending_message_script_;
1751     handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
1752     handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
1753   }
1754 }
1755
1756
1757 void Isolate::InitializeLoggingAndCounters() {
1758   if (logger_ == NULL) {
1759     logger_ = new Logger(this);
1760   }
1761   if (counters_ == NULL) {
1762     counters_ = new Counters(this);
1763   }
1764 }
1765
1766
1767 bool Isolate::Init(Deserializer* des) {
1768   ASSERT(state_ != INITIALIZED);
1769   TRACE_ISOLATE(init);
1770
1771   stress_deopt_count_ = FLAG_deopt_every_n_times;
1772
1773   has_fatal_error_ = false;
1774
1775   use_crankshaft_ = FLAG_crankshaft
1776       && !Serializer::enabled(this)
1777       && CpuFeatures::SupportsCrankshaft();
1778
1779   if (function_entry_hook() != NULL) {
1780     // When function entry hooking is in effect, we have to create the code
1781     // stubs from scratch to get entry hooks, rather than loading the previously
1782     // generated stubs from disk.
1783     // If this assert fires, the initialization path has regressed.
1784     ASSERT(des == NULL);
1785   }
1786
1787   // The initialization process does not handle memory exhaustion.
1788   DisallowAllocationFailure disallow_allocation_failure(this);
1789
1790   memory_allocator_ = new MemoryAllocator(this);
1791   code_range_ = new CodeRange(this);
1792
1793   // Safe after setting Heap::isolate_, and initializing StackGuard
1794   heap_.SetStackLimits();
1795
1796 #define ASSIGN_ELEMENT(CamelName, hacker_name)                  \
1797   isolate_addresses_[Isolate::k##CamelName##Address] =          \
1798       reinterpret_cast<Address>(hacker_name##_address());
1799   FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
1800 #undef ASSIGN_ELEMENT
1801
1802   string_tracker_ = new StringTracker();
1803   string_tracker_->isolate_ = this;
1804   compilation_cache_ = new CompilationCache(this);
1805   keyed_lookup_cache_ = new KeyedLookupCache();
1806   context_slot_cache_ = new ContextSlotCache();
1807   descriptor_lookup_cache_ = new DescriptorLookupCache();
1808   unicode_cache_ = new UnicodeCache();
1809   inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
1810   write_iterator_ = new ConsStringIteratorOp();
1811   global_handles_ = new GlobalHandles(this);
1812   eternal_handles_ = new EternalHandles();
1813   bootstrapper_ = new Bootstrapper(this);
1814   handle_scope_implementer_ = new HandleScopeImplementer(this);
1815   stub_cache_ = new StubCache(this);
1816   materialized_object_store_ = new MaterializedObjectStore(this);
1817   regexp_stack_ = new RegExpStack();
1818   regexp_stack_->isolate_ = this;
1819   date_cache_ = new DateCache();
1820   code_stub_interface_descriptors_ =
1821       new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
1822   call_descriptors_ =
1823       new CallInterfaceDescriptor[NUMBER_OF_CALL_DESCRIPTORS];
1824   cpu_profiler_ = new CpuProfiler(this);
1825   heap_profiler_ = new HeapProfiler(heap());
1826
1827   // Enable logging before setting up the heap
1828   logger_->SetUp(this);
1829
1830   // Initialize other runtime facilities
1831 #if defined(USE_SIMULATOR)
1832 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS
1833   Simulator::Initialize(this);
1834 #endif
1835 #endif
1836
1837   { // NOLINT
1838     // Ensure that the thread has a valid stack guard.  The v8::Locker object
1839     // will ensure this too, but we don't have to use lockers if we are only
1840     // using one thread.
1841     ExecutionAccess lock(this);
1842     stack_guard_.InitThread(lock);
1843   }
1844
1845   // SetUp the object heap.
1846   ASSERT(!heap_.HasBeenSetUp());
1847   if (!heap_.SetUp()) {
1848     V8::FatalProcessOutOfMemory("heap setup");
1849     return false;
1850   }
1851
1852   deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
1853
1854   const bool create_heap_objects = (des == NULL);
1855   if (create_heap_objects && !heap_.CreateHeapObjects()) {
1856     V8::FatalProcessOutOfMemory("heap object creation");
1857     return false;
1858   }
1859
1860   if (create_heap_objects) {
1861     // Terminate the cache array with the sentinel so we can iterate.
1862     PushToPartialSnapshotCache(heap_.undefined_value());
1863   }
1864
1865   InitializeThreadLocal();
1866
1867   bootstrapper_->Initialize(create_heap_objects);
1868   builtins_.SetUp(this, create_heap_objects);
1869
1870   if (FLAG_log_internal_timer_events) {
1871     set_event_logger(Logger::LogInternalEvents);
1872   } else {
1873     set_event_logger(Logger::EmptyLogInternalEvents);
1874   }
1875
1876   // Set default value if not yet set.
1877   // TODO(yangguo): move this to ResourceConstraints::ConfigureDefaults
1878   // once ResourceConstraints becomes an argument to the Isolate constructor.
1879   if (max_available_threads_ < 1) {
1880     // Choose the default between 1 and 4.
1881     max_available_threads_ = Max(Min(CPU::NumberOfProcessorsOnline(), 4), 1);
1882   }
1883
1884   if (!FLAG_job_based_sweeping) {
1885     num_sweeper_threads_ =
1886         SweeperThread::NumberOfThreads(max_available_threads_);
1887   }
1888
1889   if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
1890     PrintF("Concurrent recompilation has been disabled for tracing.\n");
1891   } else if (OptimizingCompilerThread::Enabled(max_available_threads_)) {
1892     optimizing_compiler_thread_ = new OptimizingCompilerThread(this);
1893     optimizing_compiler_thread_->Start();
1894   }
1895
1896   if (num_sweeper_threads_ > 0) {
1897     sweeper_thread_ = new SweeperThread*[num_sweeper_threads_];
1898     for (int i = 0; i < num_sweeper_threads_; i++) {
1899       sweeper_thread_[i] = new SweeperThread(this);
1900       sweeper_thread_[i]->Start();
1901     }
1902   }
1903
1904   // If we are deserializing, read the state into the now-empty heap.
1905   if (!create_heap_objects) {
1906     des->Deserialize(this);
1907   }
1908   stub_cache_->Initialize();
1909
1910   // Finish initialization of ThreadLocal after deserialization is done.
1911   clear_pending_exception();
1912   clear_pending_message();
1913   clear_scheduled_exception();
1914
1915   // Deserializing may put strange things in the root array's copy of the
1916   // stack guard.
1917   heap_.SetStackLimits();
1918
1919   // Quiet the heap NaN if needed on target platform.
1920   if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
1921
1922   runtime_profiler_ = new RuntimeProfiler(this);
1923
1924   // If we are deserializing, log non-function code objects and compiled
1925   // functions found in the snapshot.
1926   if (!create_heap_objects &&
1927       (FLAG_log_code ||
1928        FLAG_ll_prof ||
1929        FLAG_perf_jit_prof ||
1930        FLAG_perf_basic_prof ||
1931        logger_->is_logging_code_events())) {
1932     HandleScope scope(this);
1933     LOG(this, LogCodeObjects());
1934     LOG(this, LogCompiledFunctions());
1935   }
1936
1937   // If we are profiling with the Linux perf tool, we need to disable
1938   // code relocation.
1939   if (FLAG_perf_jit_prof || FLAG_perf_basic_prof) {
1940     FLAG_compact_code_space = false;
1941   }
1942
1943   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
1944            Internals::kIsolateEmbedderDataOffset);
1945   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
1946            Internals::kIsolateRootsOffset);
1947
1948   state_ = INITIALIZED;
1949   time_millis_at_init_ = OS::TimeCurrentMillis();
1950
1951   if (!create_heap_objects) {
1952     // Now that the heap is consistent, it's OK to generate the code for the
1953     // deopt entry table that might have been referred to by optimized code in
1954     // the snapshot.
1955     HandleScope scope(this);
1956     Deoptimizer::EnsureCodeForDeoptimizationEntry(
1957         this,
1958         Deoptimizer::LAZY,
1959         kDeoptTableSerializeEntryCount - 1);
1960   }
1961
1962   if (!Serializer::enabled(this)) {
1963     // Ensure that all stubs which need to be generated ahead of time, but
1964     // cannot be serialized into the snapshot have been generated.
1965     HandleScope scope(this);
1966     CodeStub::GenerateFPStubs(this);
1967     StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
1968     StubFailureTrampolineStub::GenerateAheadOfTime(this);
1969     // Ensure interface descriptors are initialized even when stubs have been
1970     // deserialized out of the snapshot without using the graph builder.
1971     FastCloneShallowArrayStub::InstallDescriptors(this);
1972     BinaryOpICStub::InstallDescriptors(this);
1973     BinaryOpWithAllocationSiteStub::InstallDescriptors(this);
1974     CompareNilICStub::InstallDescriptors(this);
1975     ToBooleanStub::InstallDescriptors(this);
1976     ToNumberStub::InstallDescriptors(this);
1977     ArrayConstructorStubBase::InstallDescriptors(this);
1978     InternalArrayConstructorStubBase::InstallDescriptors(this);
1979     FastNewClosureStub::InstallDescriptors(this);
1980     FastNewContextStub::InstallDescriptors(this);
1981     NumberToStringStub::InstallDescriptors(this);
1982     StringAddStub::InstallDescriptors(this);
1983     RegExpConstructResultStub::InstallDescriptors(this);
1984   }
1985
1986   CallDescriptors::InitializeForIsolate(this);
1987
1988   initialized_from_snapshot_ = (des != NULL);
1989
1990   return true;
1991 }
1992
1993
1994 // Initialized lazily to allow early
1995 // v8::V8::SetAddHistogramSampleFunction calls.
1996 StatsTable* Isolate::stats_table() {
1997   if (stats_table_ == NULL) {
1998     stats_table_ = new StatsTable;
1999   }
2000   return stats_table_;
2001 }
2002
2003
2004 void Isolate::Enter() {
2005   Isolate* current_isolate = NULL;
2006   PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2007   if (current_data != NULL) {
2008     current_isolate = current_data->isolate_;
2009     ASSERT(current_isolate != NULL);
2010     if (current_isolate == this) {
2011       ASSERT(Current() == this);
2012       ASSERT(entry_stack_ != NULL);
2013       ASSERT(entry_stack_->previous_thread_data == NULL ||
2014              entry_stack_->previous_thread_data->thread_id().Equals(
2015                  ThreadId::Current()));
2016       // Same thread re-enters the isolate, no need to re-init anything.
2017       entry_stack_->entry_count++;
2018       return;
2019     }
2020   }
2021
2022   // Threads can have default isolate set into TLS as Current but not yet have
2023   // PerIsolateThreadData for it, as it requires more advanced phase of the
2024   // initialization. For example, a thread might be the one that system used for
2025   // static initializers - in this case the default isolate is set in TLS but
2026   // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2027   // there, use the isolate set in TLS.
2028   if (current_isolate == NULL) {
2029     current_isolate = Isolate::UncheckedCurrent();
2030   }
2031
2032   PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2033   ASSERT(data != NULL);
2034   ASSERT(data->isolate_ == this);
2035
2036   EntryStackItem* item = new EntryStackItem(current_data,
2037                                             current_isolate,
2038                                             entry_stack_);
2039   entry_stack_ = item;
2040
2041   SetIsolateThreadLocals(this, data);
2042
2043   // In case it's the first time some thread enters the isolate.
2044   set_thread_id(data->thread_id());
2045 }
2046
2047
2048 void Isolate::Exit() {
2049   ASSERT(entry_stack_ != NULL);
2050   ASSERT(entry_stack_->previous_thread_data == NULL ||
2051          entry_stack_->previous_thread_data->thread_id().Equals(
2052              ThreadId::Current()));
2053
2054   if (--entry_stack_->entry_count > 0) return;
2055
2056   ASSERT(CurrentPerIsolateThreadData() != NULL);
2057   ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2058
2059   // Pop the stack.
2060   EntryStackItem* item = entry_stack_;
2061   entry_stack_ = item->previous_item;
2062
2063   PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2064   Isolate* previous_isolate = item->previous_isolate;
2065
2066   delete item;
2067
2068   // Reinit the current thread for the isolate it was running before this one.
2069   SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2070 }
2071
2072
2073 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2074   deferred->next_ = deferred_handles_head_;
2075   if (deferred_handles_head_ != NULL) {
2076     deferred_handles_head_->previous_ = deferred;
2077   }
2078   deferred_handles_head_ = deferred;
2079 }
2080
2081
2082 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2083 #ifdef DEBUG
2084   // In debug mode assert that the linked list is well-formed.
2085   DeferredHandles* deferred_iterator = deferred;
2086   while (deferred_iterator->previous_ != NULL) {
2087     deferred_iterator = deferred_iterator->previous_;
2088   }
2089   ASSERT(deferred_handles_head_ == deferred_iterator);
2090 #endif
2091   if (deferred_handles_head_ == deferred) {
2092     deferred_handles_head_ = deferred_handles_head_->next_;
2093   }
2094   if (deferred->next_ != NULL) {
2095     deferred->next_->previous_ = deferred->previous_;
2096   }
2097   if (deferred->previous_ != NULL) {
2098     deferred->previous_->next_ = deferred->next_;
2099   }
2100 }
2101
2102
2103 HStatistics* Isolate::GetHStatistics() {
2104   if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2105   return hstatistics();
2106 }
2107
2108
2109 HTracer* Isolate::GetHTracer() {
2110   if (htracer() == NULL) set_htracer(new HTracer(id()));
2111   return htracer();
2112 }
2113
2114
2115 CodeTracer* Isolate::GetCodeTracer() {
2116   if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2117   return code_tracer();
2118 }
2119
2120
2121 Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2122   Context* native_context = context()->native_context();
2123   Object* maybe_map_array = native_context->js_array_maps();
2124   if (!maybe_map_array->IsUndefined()) {
2125     Object* maybe_transitioned_map =
2126         FixedArray::cast(maybe_map_array)->get(kind);
2127     if (!maybe_transitioned_map->IsUndefined()) {
2128       return Map::cast(maybe_transitioned_map);
2129     }
2130   }
2131   return NULL;
2132 }
2133
2134
2135 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2136   Map* root_array_map =
2137       get_initial_js_array_map(GetInitialFastElementsKind());
2138   ASSERT(root_array_map != NULL);
2139   JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2140
2141   // Check that the array prototype hasn't been altered WRT empty elements.
2142   if (root_array_map->prototype() != initial_array_proto) return false;
2143   if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2144     return false;
2145   }
2146
2147   // Check that the object prototype hasn't been altered WRT empty elements.
2148   JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2149   Object* root_array_map_proto = initial_array_proto->GetPrototype();
2150   if (root_array_map_proto != initial_object_proto) return false;
2151   if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2152     return false;
2153   }
2154
2155   return initial_object_proto->GetPrototype()->IsNull();
2156 }
2157
2158
2159 CodeStubInterfaceDescriptor*
2160     Isolate::code_stub_interface_descriptor(int index) {
2161   return code_stub_interface_descriptors_ + index;
2162 }
2163
2164
2165 CallInterfaceDescriptor*
2166     Isolate::call_descriptor(CallDescriptorKey index) {
2167   ASSERT(0 <= index && index < NUMBER_OF_CALL_DESCRIPTORS);
2168   return &call_descriptors_[index];
2169 }
2170
2171
2172 Object* Isolate::FindCodeObject(Address a) {
2173   return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2174 }
2175
2176
2177 #ifdef DEBUG
2178 #define ISOLATE_FIELD_OFFSET(type, name, ignored)                       \
2179 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2180 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2181 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2182 #undef ISOLATE_FIELD_OFFSET
2183 #endif
2184
2185
2186 Handle<JSObject> Isolate::GetSymbolRegistry() {
2187   if (heap()->symbol_registry()->IsUndefined()) {
2188     Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2189     Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2190     heap()->set_symbol_registry(*registry);
2191
2192     static const char* nested[] = {
2193       "for", "for_api", "for_intern", "keyFor", "private_api", "private_intern"
2194     };
2195     for (unsigned i = 0; i < ARRAY_SIZE(nested); ++i) {
2196       Handle<String> name = factory()->InternalizeUtf8String(nested[i]);
2197       Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2198       JSObject::NormalizeProperties(obj, KEEP_INOBJECT_PROPERTIES, 8);
2199       JSObject::SetProperty(registry, name, obj, NONE, STRICT).Assert();
2200     }
2201   }
2202   return Handle<JSObject>::cast(factory()->symbol_registry());
2203 }
2204
2205
2206 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2207   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2208     if (callback == call_completed_callbacks_.at(i)) return;
2209   }
2210   call_completed_callbacks_.Add(callback);
2211 }
2212
2213
2214 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2215   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2216     if (callback == call_completed_callbacks_.at(i)) {
2217       call_completed_callbacks_.Remove(i);
2218     }
2219   }
2220 }
2221
2222
2223 void Isolate::FireCallCompletedCallback() {
2224   bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2225   bool run_microtasks = autorun_microtasks() && microtask_pending();
2226   if (!has_call_completed_callbacks && !run_microtasks) return;
2227
2228   if (!handle_scope_implementer()->CallDepthIsZero()) return;
2229   // Fire callbacks.  Increase call depth to prevent recursive callbacks.
2230   handle_scope_implementer()->IncrementCallDepth();
2231   if (run_microtasks) Execution::RunMicrotasks(this);
2232   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2233     call_completed_callbacks_.at(i)();
2234   }
2235   handle_scope_implementer()->DecrementCallDepth();
2236 }
2237
2238
2239 void Isolate::RunMicrotasks() {
2240   if (!microtask_pending())
2241     return;
2242
2243   ASSERT(handle_scope_implementer()->CallDepthIsZero());
2244
2245   // Increase call depth to prevent recursive callbacks.
2246   handle_scope_implementer()->IncrementCallDepth();
2247   Execution::RunMicrotasks(this);
2248   handle_scope_implementer()->DecrementCallDepth();
2249 }
2250
2251
2252 } }  // namespace v8::internal