966b73b3ea2706cabec6744d96642a93b17e2b9f
[platform/upstream/v8.git] / 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 <fstream>  // NOLINT(readability/streams)
8 #include <sstream>
9
10 #include "src/v8.h"
11
12 #include "src/ast.h"
13 #include "src/base/platform/platform.h"
14 #include "src/base/sys-info.h"
15 #include "src/base/utils/random-number-generator.h"
16 #include "src/basic-block-profiler.h"
17 #include "src/bootstrapper.h"
18 #include "src/codegen.h"
19 #include "src/compilation-cache.h"
20 #include "src/compilation-statistics.h"
21 #include "src/cpu-profiler.h"
22 #include "src/debug.h"
23 #include "src/deoptimizer.h"
24 #include "src/heap/spaces.h"
25 #include "src/heap-profiler.h"
26 #include "src/hydrogen.h"
27 #include "src/ic/stub-cache.h"
28 #include "src/lithium-allocator.h"
29 #include "src/log.h"
30 #include "src/messages.h"
31 #include "src/prototype.h"
32 #include "src/regexp-stack.h"
33 #include "src/runtime-profiler.h"
34 #include "src/sampler.h"
35 #include "src/scopeinfo.h"
36 #include "src/simulator.h"
37 #include "src/snapshot/serialize.h"
38 #include "src/version.h"
39 #include "src/vm-state-inl.h"
40
41
42 namespace v8 {
43 namespace internal {
44
45 base::Atomic32 ThreadId::highest_thread_id_ = 0;
46
47 int ThreadId::AllocateThreadId() {
48   int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
49   return new_id;
50 }
51
52
53 int ThreadId::GetCurrentThreadId() {
54   int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
55   if (thread_id == 0) {
56     thread_id = AllocateThreadId();
57     base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
58   }
59   return thread_id;
60 }
61
62
63 ThreadLocalTop::ThreadLocalTop() {
64   InitializeInternal();
65 }
66
67
68 void ThreadLocalTop::InitializeInternal() {
69   c_entry_fp_ = 0;
70   c_function_ = 0;
71   handler_ = 0;
72 #ifdef USE_SIMULATOR
73   simulator_ = NULL;
74 #endif
75   js_entry_sp_ = NULL;
76   external_callback_scope_ = NULL;
77   current_vm_state_ = EXTERNAL;
78   try_catch_handler_ = NULL;
79   context_ = NULL;
80   thread_id_ = ThreadId::Invalid();
81   external_caught_exception_ = false;
82   failed_access_check_callback_ = NULL;
83   save_context_ = NULL;
84   promise_on_stack_ = NULL;
85
86   // These members are re-initialized later after deserialization
87   // is complete.
88   pending_exception_ = NULL;
89   rethrowing_message_ = false;
90   pending_message_obj_ = NULL;
91   scheduled_exception_ = NULL;
92 }
93
94
95 void ThreadLocalTop::Initialize() {
96   InitializeInternal();
97 #ifdef USE_SIMULATOR
98   simulator_ = Simulator::current(isolate_);
99 #endif
100   thread_id_ = ThreadId::Current();
101 }
102
103
104 void ThreadLocalTop::Free() {
105   // Match unmatched PopPromise calls.
106   while (promise_on_stack_) isolate_->PopPromise();
107 }
108
109
110 base::Thread::LocalStorageKey Isolate::isolate_key_;
111 base::Thread::LocalStorageKey Isolate::thread_id_key_;
112 base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
113 base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER;
114 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
115 base::Atomic32 Isolate::isolate_counter_ = 0;
116 #if DEBUG
117 base::Atomic32 Isolate::isolate_key_created_ = 0;
118 #endif
119
120 Isolate::PerIsolateThreadData*
121     Isolate::FindOrAllocatePerThreadDataForThisThread() {
122   ThreadId thread_id = ThreadId::Current();
123   PerIsolateThreadData* per_thread = NULL;
124   {
125     base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
126     per_thread = thread_data_table_->Lookup(this, thread_id);
127     if (per_thread == NULL) {
128       per_thread = new PerIsolateThreadData(this, thread_id);
129       thread_data_table_->Insert(per_thread);
130     }
131     DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
132   }
133   return per_thread;
134 }
135
136
137 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
138   ThreadId thread_id = ThreadId::Current();
139   return FindPerThreadDataForThread(thread_id);
140 }
141
142
143 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
144     ThreadId thread_id) {
145   PerIsolateThreadData* per_thread = NULL;
146   {
147     base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
148     per_thread = thread_data_table_->Lookup(this, thread_id);
149   }
150   return per_thread;
151 }
152
153
154 void Isolate::InitializeOncePerProcess() {
155   base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
156   CHECK(thread_data_table_ == NULL);
157   isolate_key_ = base::Thread::CreateThreadLocalKey();
158 #if DEBUG
159   base::NoBarrier_Store(&isolate_key_created_, 1);
160 #endif
161   thread_id_key_ = base::Thread::CreateThreadLocalKey();
162   per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
163   thread_data_table_ = new Isolate::ThreadDataTable();
164 }
165
166
167 Address Isolate::get_address_from_id(Isolate::AddressId id) {
168   return isolate_addresses_[id];
169 }
170
171
172 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
173   ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
174   Iterate(v, thread);
175   return thread_storage + sizeof(ThreadLocalTop);
176 }
177
178
179 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
180   ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
181   v->VisitThread(this, thread);
182 }
183
184
185 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
186   // Visit the roots from the top for a given thread.
187   v->VisitPointer(&thread->pending_exception_);
188   v->VisitPointer(&(thread->pending_message_obj_));
189   v->VisitPointer(bit_cast<Object**>(&(thread->context_)));
190   v->VisitPointer(&thread->scheduled_exception_);
191
192   for (v8::TryCatch* block = thread->try_catch_handler();
193        block != NULL;
194        block = block->next_) {
195     v->VisitPointer(bit_cast<Object**>(&(block->exception_)));
196     v->VisitPointer(bit_cast<Object**>(&(block->message_obj_)));
197   }
198
199   // Iterate over pointers on native execution stack.
200   for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
201     it.frame()->Iterate(v);
202   }
203 }
204
205
206 void Isolate::Iterate(ObjectVisitor* v) {
207   ThreadLocalTop* current_t = thread_local_top();
208   Iterate(v, current_t);
209 }
210
211
212 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
213   for (DeferredHandles* deferred = deferred_handles_head_;
214        deferred != NULL;
215        deferred = deferred->next_) {
216     deferred->Iterate(visitor);
217   }
218 }
219
220
221 #ifdef DEBUG
222 bool Isolate::IsDeferredHandle(Object** handle) {
223   // Each DeferredHandles instance keeps the handles to one job in the
224   // concurrent recompilation queue, containing a list of blocks.  Each block
225   // contains kHandleBlockSize handles except for the first block, which may
226   // not be fully filled.
227   // We iterate through all the blocks to see whether the argument handle
228   // belongs to one of the blocks.  If so, it is deferred.
229   for (DeferredHandles* deferred = deferred_handles_head_;
230        deferred != NULL;
231        deferred = deferred->next_) {
232     List<Object**>* blocks = &deferred->blocks_;
233     for (int i = 0; i < blocks->length(); i++) {
234       Object** block_limit = (i == 0) ? deferred->first_block_limit_
235                                       : blocks->at(i) + kHandleBlockSize;
236       if (blocks->at(i) <= handle && handle < block_limit) return true;
237     }
238   }
239   return false;
240 }
241 #endif  // DEBUG
242
243
244 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
245   thread_local_top()->set_try_catch_handler(that);
246 }
247
248
249 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
250   DCHECK(thread_local_top()->try_catch_handler() == that);
251   thread_local_top()->set_try_catch_handler(that->next_);
252 }
253
254
255 Handle<String> Isolate::StackTraceString() {
256   if (stack_trace_nesting_level_ == 0) {
257     stack_trace_nesting_level_++;
258     HeapStringAllocator allocator;
259     StringStream::ClearMentionedObjectCache(this);
260     StringStream accumulator(&allocator);
261     incomplete_message_ = &accumulator;
262     PrintStack(&accumulator);
263     Handle<String> stack_trace = accumulator.ToString(this);
264     incomplete_message_ = NULL;
265     stack_trace_nesting_level_ = 0;
266     return stack_trace;
267   } else if (stack_trace_nesting_level_ == 1) {
268     stack_trace_nesting_level_++;
269     base::OS::PrintError(
270       "\n\nAttempt to print stack while printing stack (double fault)\n");
271     base::OS::PrintError(
272       "If you are lucky you may find a partial stack dump on stdout.\n\n");
273     incomplete_message_->OutputToStdOut();
274     return factory()->empty_string();
275   } else {
276     base::OS::Abort();
277     // Unreachable
278     return factory()->empty_string();
279   }
280 }
281
282
283 void Isolate::PushStackTraceAndDie(unsigned int magic, void* ptr1, void* ptr2,
284                                    unsigned int magic2) {
285   const int kMaxStackTraceSize = 32 * KB;
286   Handle<String> trace = StackTraceString();
287   uint8_t buffer[kMaxStackTraceSize];
288   int length = Min(kMaxStackTraceSize - 1, trace->length());
289   String::WriteToFlat(*trace, buffer, 0, length);
290   buffer[length] = '\0';
291   // TODO(dcarney): convert buffer to utf8?
292   base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2, ptr1,
293                        ptr2, reinterpret_cast<char*>(buffer));
294   base::OS::Abort();
295 }
296
297
298 // Determines whether the given stack frame should be displayed in
299 // a stack trace.  The caller is the error constructor that asked
300 // for the stack trace to be collected.  The first time a construct
301 // call to this function is encountered it is skipped.  The seen_caller
302 // in/out parameter is used to remember if the caller has been seen
303 // yet.
304 static bool IsVisibleInStackTrace(JSFunction* fun,
305                                   Object* caller,
306                                   Object* receiver,
307                                   bool* seen_caller) {
308   if ((fun == caller) && !(*seen_caller)) {
309     *seen_caller = true;
310     return false;
311   }
312   // Skip all frames until we've seen the caller.
313   if (!(*seen_caller)) return false;
314   // Also, skip non-visible built-in functions and any call with the builtins
315   // object as receiver, so as to not reveal either the builtins object or
316   // an internal function.
317   // The --builtins-in-stack-traces command line flag allows including
318   // internal call sites in the stack trace for debugging purposes.
319   if (!FLAG_builtins_in_stack_traces) {
320     if (receiver->IsJSBuiltinsObject()) return false;
321     if (fun->IsBuiltin()) {
322       return fun->shared()->native();
323     } else if (fun->IsFromNativeScript() || fun->IsFromExtensionScript()) {
324       return false;
325     }
326   }
327   return true;
328 }
329
330
331 Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
332                                                 Handle<Object> caller) {
333   // Get stack trace limit.
334   Handle<Object> error = Object::GetProperty(
335       this, js_builtins_object(), "$Error").ToHandleChecked();
336   if (!error->IsJSObject()) return factory()->undefined_value();
337
338   Handle<String> stackTraceLimit =
339       factory()->InternalizeUtf8String("stackTraceLimit");
340   DCHECK(!stackTraceLimit.is_null());
341   Handle<Object> stack_trace_limit = JSReceiver::GetDataProperty(
342       Handle<JSObject>::cast(error), stackTraceLimit);
343   if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
344   int limit = FastD2IChecked(stack_trace_limit->Number());
345   limit = Max(limit, 0);  // Ensure that limit is not negative.
346
347   int initial_size = Min(limit, 10);
348   Handle<FixedArray> elements =
349       factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
350
351   // If the caller parameter is a function we skip frames until we're
352   // under it before starting to collect.
353   bool seen_caller = !caller->IsJSFunction();
354   // First element is reserved to store the number of sloppy frames.
355   int cursor = 1;
356   int frames_seen = 0;
357   int sloppy_frames = 0;
358   bool encountered_strict_function = false;
359   for (JavaScriptFrameIterator iter(this);
360        !iter.done() && frames_seen < limit;
361        iter.Advance()) {
362     JavaScriptFrame* frame = iter.frame();
363     // Set initial size to the maximum inlining level + 1 for the outermost
364     // function.
365     List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
366     frame->Summarize(&frames);
367     for (int i = frames.length() - 1; i >= 0; i--) {
368       Handle<JSFunction> fun = frames[i].function();
369       Handle<Object> recv = frames[i].receiver();
370       // Filter out internal frames that we do not want to show.
371       if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) continue;
372       // Filter out frames from other security contexts.
373       if (!this->context()->HasSameSecurityTokenAs(fun->context())) continue;
374       if (cursor + 4 > elements->length()) {
375         int new_capacity = JSObject::NewElementsCapacity(elements->length());
376         Handle<FixedArray> new_elements =
377             factory()->NewFixedArrayWithHoles(new_capacity);
378         for (int i = 0; i < cursor; i++) {
379           new_elements->set(i, elements->get(i));
380         }
381         elements = new_elements;
382       }
383       DCHECK(cursor + 4 <= elements->length());
384
385       Handle<Code> code = frames[i].code();
386       Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
387       // The stack trace API should not expose receivers and function
388       // objects on frames deeper than the top-most one with a strict
389       // mode function.  The number of sloppy frames is stored as
390       // first element in the result array.
391       if (!encountered_strict_function) {
392         if (is_strict(fun->shared()->language_mode())) {
393           encountered_strict_function = true;
394         } else {
395           sloppy_frames++;
396         }
397       }
398       elements->set(cursor++, *recv);
399       elements->set(cursor++, *fun);
400       elements->set(cursor++, *code);
401       elements->set(cursor++, *offset);
402       frames_seen++;
403     }
404   }
405   elements->set(0, Smi::FromInt(sloppy_frames));
406   elements->Shrink(cursor);
407   Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
408   result->set_length(Smi::FromInt(cursor));
409   // TODO(yangguo): Queue this structured stack trace for preprocessing on GC.
410   return result;
411 }
412
413
414 MaybeHandle<JSObject> Isolate::CaptureAndSetDetailedStackTrace(
415     Handle<JSObject> error_object) {
416   if (capture_stack_trace_for_uncaught_exceptions_) {
417     // Capture stack trace for a detailed exception message.
418     Handle<Name> key = factory()->detailed_stack_trace_symbol();
419     Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
420         stack_trace_for_uncaught_exceptions_frame_limit_,
421         stack_trace_for_uncaught_exceptions_options_);
422     RETURN_ON_EXCEPTION(
423         this, JSObject::SetProperty(error_object, key, stack_trace, STRICT),
424         JSObject);
425   }
426   return error_object;
427 }
428
429
430 MaybeHandle<JSObject> Isolate::CaptureAndSetSimpleStackTrace(
431     Handle<JSObject> error_object, Handle<Object> caller) {
432   // Capture stack trace for simple stack trace string formatting.
433   Handle<Name> key = factory()->stack_trace_symbol();
434   Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
435   RETURN_ON_EXCEPTION(
436       this, JSObject::SetProperty(error_object, key, stack_trace, STRICT),
437       JSObject);
438   return error_object;
439 }
440
441
442 Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
443   Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
444   Handle<Object> stack_trace =
445       JSReceiver::GetDataProperty(error_object, key_detailed);
446   if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
447
448   if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
449
450   // Try to get details from simple stack trace.
451   Handle<JSArray> detailed_stack_trace =
452       GetDetailedFromSimpleStackTrace(error_object);
453   if (!detailed_stack_trace.is_null()) {
454     // Save the detailed stack since the simple one might be withdrawn later.
455     JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
456                           STRICT).Assert();
457   }
458   return detailed_stack_trace;
459 }
460
461
462 class CaptureStackTraceHelper {
463  public:
464   CaptureStackTraceHelper(Isolate* isolate,
465                           StackTrace::StackTraceOptions options)
466       : isolate_(isolate) {
467     if (options & StackTrace::kColumnOffset) {
468       column_key_ =
469           factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
470     }
471     if (options & StackTrace::kLineNumber) {
472       line_key_ =
473           factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
474     }
475     if (options & StackTrace::kScriptId) {
476       script_id_key_ =
477           factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
478     }
479     if (options & StackTrace::kScriptName) {
480       script_name_key_ =
481           factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
482     }
483     if (options & StackTrace::kScriptNameOrSourceURL) {
484       script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
485           STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
486     }
487     if (options & StackTrace::kFunctionName) {
488       function_key_ = factory()->InternalizeOneByteString(
489           STATIC_CHAR_VECTOR("functionName"));
490     }
491     if (options & StackTrace::kIsEval) {
492       eval_key_ =
493           factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
494     }
495     if (options & StackTrace::kIsConstructor) {
496       constructor_key_ = factory()->InternalizeOneByteString(
497           STATIC_CHAR_VECTOR("isConstructor"));
498     }
499   }
500
501   Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun, int position,
502                                        bool is_constructor) {
503     Handle<JSObject> stack_frame =
504         factory()->NewJSObject(isolate_->object_function());
505
506     Handle<Script> script(Script::cast(fun->shared()->script()));
507
508     if (!line_key_.is_null()) {
509       int script_line_offset = script->line_offset()->value();
510       int line_number = Script::GetLineNumber(script, position);
511       // line_number is already shifted by the script_line_offset.
512       int relative_line_number = line_number - script_line_offset;
513       if (!column_key_.is_null() && relative_line_number >= 0) {
514         int column = Script::GetColumnNumber(script, position);
515         JSObject::AddProperty(stack_frame, column_key_,
516                               handle(Smi::FromInt(column + 1), isolate_), NONE);
517       }
518       JSObject::AddProperty(stack_frame, line_key_,
519                             handle(Smi::FromInt(line_number + 1), isolate_),
520                             NONE);
521     }
522
523     if (!script_id_key_.is_null()) {
524       JSObject::AddProperty(stack_frame, script_id_key_,
525                             handle(script->id(), isolate_), NONE);
526     }
527
528     if (!script_name_key_.is_null()) {
529       JSObject::AddProperty(stack_frame, script_name_key_,
530                             handle(script->name(), isolate_), NONE);
531     }
532
533     if (!script_name_or_source_url_key_.is_null()) {
534       Handle<Object> result = Script::GetNameOrSourceURL(script);
535       JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
536                             NONE);
537     }
538
539     if (!function_key_.is_null()) {
540       Handle<Object> fun_name = JSFunction::GetDebugName(fun);
541       JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
542     }
543
544     if (!eval_key_.is_null()) {
545       Handle<Object> is_eval = factory()->ToBoolean(
546           script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
547       JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
548     }
549
550     if (!constructor_key_.is_null()) {
551       Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
552       JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
553                             NONE);
554     }
555
556     return stack_frame;
557   }
558
559  private:
560   inline Factory* factory() { return isolate_->factory(); }
561
562   Isolate* isolate_;
563   Handle<String> column_key_;
564   Handle<String> line_key_;
565   Handle<String> script_id_key_;
566   Handle<String> script_name_key_;
567   Handle<String> script_name_or_source_url_key_;
568   Handle<String> function_key_;
569   Handle<String> eval_key_;
570   Handle<String> constructor_key_;
571 };
572
573
574 int PositionFromStackTrace(Handle<FixedArray> elements, int index) {
575   DisallowHeapAllocation no_gc;
576   Object* maybe_code = elements->get(index + 2);
577   if (maybe_code->IsSmi()) {
578     return Smi::cast(maybe_code)->value();
579   } else {
580     Code* code = Code::cast(maybe_code);
581     Address pc = code->address() + Smi::cast(elements->get(index + 3))->value();
582     return code->SourcePosition(pc);
583   }
584 }
585
586
587 Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
588     Handle<JSObject> error_object) {
589   Handle<Name> key = factory()->stack_trace_symbol();
590   Handle<Object> property = JSReceiver::GetDataProperty(error_object, key);
591   if (!property->IsJSArray()) return Handle<JSArray>();
592   Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
593
594   CaptureStackTraceHelper helper(this,
595                                  stack_trace_for_uncaught_exceptions_options_);
596
597   int frames_seen = 0;
598   Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
599   int elements_limit = Smi::cast(simple_stack_trace->length())->value();
600
601   int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
602   if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
603
604   Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
605   for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
606     Handle<Object> recv = handle(elements->get(i), this);
607     Handle<JSFunction> fun =
608         handle(JSFunction::cast(elements->get(i + 1)), this);
609     bool is_constructor =
610         recv->IsJSObject() &&
611         Handle<JSObject>::cast(recv)->map()->GetConstructor() == *fun;
612     int position = PositionFromStackTrace(elements, i);
613
614     Handle<JSObject> stack_frame =
615         helper.NewStackFrameObject(fun, position, is_constructor);
616
617     FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
618     frames_seen++;
619   }
620
621   stack_trace->set_length(Smi::FromInt(frames_seen));
622   return stack_trace;
623 }
624
625
626 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
627     int frame_limit, StackTrace::StackTraceOptions options) {
628   CaptureStackTraceHelper helper(this, options);
629
630   // Ensure no negative values.
631   int limit = Max(frame_limit, 0);
632   Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
633
634   StackTraceFrameIterator it(this);
635   int frames_seen = 0;
636   while (!it.done() && (frames_seen < limit)) {
637     JavaScriptFrame* frame = it.frame();
638     // Set initial size to the maximum inlining level + 1 for the outermost
639     // function.
640     List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
641     frame->Summarize(&frames);
642     for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
643       Handle<JSFunction> fun = frames[i].function();
644       // Filter frames from other security contexts.
645       if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
646           !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
647       int position = frames[i].code()->SourcePosition(frames[i].pc());
648       Handle<JSObject> stack_frame =
649           helper.NewStackFrameObject(fun, position, frames[i].is_constructor());
650
651       FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
652       frames_seen++;
653     }
654     it.Advance();
655   }
656
657   stack_trace->set_length(Smi::FromInt(frames_seen));
658   return stack_trace;
659 }
660
661
662 void Isolate::PrintStack(FILE* out, PrintStackMode mode) {
663   if (stack_trace_nesting_level_ == 0) {
664     stack_trace_nesting_level_++;
665     StringStream::ClearMentionedObjectCache(this);
666     HeapStringAllocator allocator;
667     StringStream accumulator(&allocator);
668     incomplete_message_ = &accumulator;
669     PrintStack(&accumulator, mode);
670     accumulator.OutputToFile(out);
671     InitializeLoggingAndCounters();
672     accumulator.Log(this);
673     incomplete_message_ = NULL;
674     stack_trace_nesting_level_ = 0;
675   } else if (stack_trace_nesting_level_ == 1) {
676     stack_trace_nesting_level_++;
677     base::OS::PrintError(
678       "\n\nAttempt to print stack while printing stack (double fault)\n");
679     base::OS::PrintError(
680       "If you are lucky you may find a partial stack dump on stdout.\n\n");
681     incomplete_message_->OutputToFile(out);
682   }
683 }
684
685
686 static void PrintFrames(Isolate* isolate,
687                         StringStream* accumulator,
688                         StackFrame::PrintMode mode) {
689   StackFrameIterator it(isolate);
690   for (int i = 0; !it.done(); it.Advance()) {
691     it.frame()->Print(accumulator, mode, i++);
692   }
693 }
694
695
696 void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) {
697   // The MentionedObjectCache is not GC-proof at the moment.
698   DisallowHeapAllocation no_gc;
699   DCHECK(accumulator->IsMentionedObjectCacheClear(this));
700
701   // Avoid printing anything if there are no frames.
702   if (c_entry_fp(thread_local_top()) == 0) return;
703
704   accumulator->Add(
705       "\n==== JS stack trace =========================================\n\n");
706   PrintFrames(this, accumulator, StackFrame::OVERVIEW);
707   if (mode == kPrintStackVerbose) {
708     accumulator->Add(
709         "\n==== Details ================================================\n\n");
710     PrintFrames(this, accumulator, StackFrame::DETAILS);
711     accumulator->PrintMentionedObjectCache(this);
712   }
713   accumulator->Add("=====================\n\n");
714 }
715
716
717 void Isolate::SetFailedAccessCheckCallback(
718     v8::FailedAccessCheckCallback callback) {
719   thread_local_top()->failed_access_check_callback_ = callback;
720 }
721
722
723 static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
724                                                   Handle<JSObject> receiver) {
725   Object* maybe_constructor = receiver->map()->GetConstructor();
726   if (!maybe_constructor->IsJSFunction()) return NULL;
727   JSFunction* constructor = JSFunction::cast(maybe_constructor);
728   if (!constructor->shared()->IsApiFunction()) return NULL;
729
730   Object* data_obj =
731      constructor->shared()->get_api_func_data()->access_check_info();
732   if (data_obj == isolate->heap()->undefined_value()) return NULL;
733
734   return AccessCheckInfo::cast(data_obj);
735 }
736
737
738 void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) {
739   if (!thread_local_top()->failed_access_check_callback_) {
740     return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess));
741   }
742
743   DCHECK(receiver->IsAccessCheckNeeded());
744   DCHECK(context());
745
746   // Get the data object from access check info.
747   HandleScope scope(this);
748   Handle<Object> data;
749   { DisallowHeapAllocation no_gc;
750     AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
751     if (!access_check_info) {
752       AllowHeapAllocation doesnt_matter_anymore;
753       return ScheduleThrow(
754           *factory()->NewTypeError(MessageTemplate::kNoAccess));
755     }
756     data = handle(access_check_info->data(), this);
757   }
758
759   // Leaving JavaScript.
760   VMState<EXTERNAL> state(this);
761   thread_local_top()->failed_access_check_callback_(
762       v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data));
763 }
764
765
766 bool Isolate::IsInternallyUsedPropertyName(Handle<Object> name) {
767   if (name->IsSymbol()) {
768     return Handle<Symbol>::cast(name)->is_private() &&
769            Handle<Symbol>::cast(name)->is_own();
770   }
771   return name.is_identical_to(factory()->hidden_string());
772 }
773
774
775 bool Isolate::IsInternallyUsedPropertyName(Object* name) {
776   if (name->IsSymbol()) {
777     return Symbol::cast(name)->is_private() && Symbol::cast(name)->is_own();
778   }
779   return name == heap()->hidden_string();
780 }
781
782
783 bool Isolate::MayAccess(Handle<JSObject> receiver) {
784   DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
785
786   // Check for compatibility between the security tokens in the
787   // current lexical context and the accessed object.
788   DCHECK(context());
789
790   {
791     DisallowHeapAllocation no_gc;
792     // During bootstrapping, callback functions are not enabled yet.
793     if (bootstrapper()->IsActive()) return true;
794
795     if (receiver->IsJSGlobalProxy()) {
796       Object* receiver_context =
797           JSGlobalProxy::cast(*receiver)->native_context();
798       if (!receiver_context->IsContext()) return false;
799
800       // Get the native context of current top context.
801       // avoid using Isolate::native_context() because it uses Handle.
802       Context* native_context = context()->global_object()->native_context();
803       if (receiver_context == native_context) return true;
804
805       if (Context::cast(receiver_context)->security_token() ==
806           native_context->security_token())
807         return true;
808     }
809   }
810
811   HandleScope scope(this);
812   Handle<Object> data;
813   v8::NamedSecurityCallback callback;
814   { DisallowHeapAllocation no_gc;
815     AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
816     if (!access_check_info) return false;
817     Object* fun_obj = access_check_info->named_callback();
818     callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
819     if (!callback) return false;
820     data = handle(access_check_info->data(), this);
821   }
822
823   LOG(this, ApiSecurityCheck());
824
825   // Leaving JavaScript.
826   VMState<EXTERNAL> state(this);
827   Handle<Object> key = factory()->undefined_value();
828   return callback(v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(key),
829                   v8::ACCESS_HAS, v8::Utils::ToLocal(data));
830 }
831
832
833 const char* const Isolate::kStackOverflowMessage =
834   "Uncaught RangeError: Maximum call stack size exceeded";
835
836
837 Object* Isolate::StackOverflow() {
838   HandleScope scope(this);
839   // At this point we cannot create an Error object using its javascript
840   // constructor.  Instead, we copy the pre-constructed boilerplate and
841   // attach the stack trace as a hidden property.
842   Handle<String> key = factory()->stack_overflow_string();
843   Handle<Object> boilerplate =
844       Object::GetProperty(js_builtins_object(), key).ToHandleChecked();
845   if (boilerplate->IsUndefined()) {
846     return Throw(heap()->undefined_value(), nullptr);
847   }
848   Handle<JSObject> exception =
849       factory()->CopyJSObject(Handle<JSObject>::cast(boilerplate));
850   Throw(*exception, nullptr);
851
852   CaptureAndSetSimpleStackTrace(exception, factory()->undefined_value());
853 #ifdef VERIFY_HEAP
854   if (FLAG_verify_heap && FLAG_stress_compaction) {
855     heap()->CollectAllAvailableGarbage("trigger compaction");
856   }
857 #endif  // VERIFY_HEAP
858
859   return heap()->exception();
860 }
861
862
863 Object* Isolate::TerminateExecution() {
864   return Throw(heap_.termination_exception(), nullptr);
865 }
866
867
868 void Isolate::CancelTerminateExecution() {
869   if (try_catch_handler()) {
870     try_catch_handler()->has_terminated_ = false;
871   }
872   if (has_pending_exception() &&
873       pending_exception() == heap_.termination_exception()) {
874     thread_local_top()->external_caught_exception_ = false;
875     clear_pending_exception();
876   }
877   if (has_scheduled_exception() &&
878       scheduled_exception() == heap_.termination_exception()) {
879     thread_local_top()->external_caught_exception_ = false;
880     clear_scheduled_exception();
881   }
882 }
883
884
885 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
886   ExecutionAccess access(this);
887   api_interrupts_queue_.push(InterruptEntry(callback, data));
888   stack_guard()->RequestApiInterrupt();
889 }
890
891
892 void Isolate::InvokeApiInterruptCallbacks() {
893   // Note: callback below should be called outside of execution access lock.
894   while (true) {
895     InterruptEntry entry;
896     {
897       ExecutionAccess access(this);
898       if (api_interrupts_queue_.empty()) return;
899       entry = api_interrupts_queue_.front();
900       api_interrupts_queue_.pop();
901     }
902     VMState<EXTERNAL> state(this);
903     HandleScope handle_scope(this);
904     entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
905   }
906 }
907
908
909 void ReportBootstrappingException(Handle<Object> exception,
910                                   MessageLocation* location) {
911   base::OS::PrintError("Exception thrown during bootstrapping\n");
912   if (location == NULL || location->script().is_null()) return;
913   // We are bootstrapping and caught an error where the location is set
914   // and we have a script for the location.
915   // In this case we could have an extension (or an internal error
916   // somewhere) and we print out the line number at which the error occured
917   // to the console for easier debugging.
918   int line_number =
919       location->script()->GetLineNumber(location->start_pos()) + 1;
920   if (exception->IsString() && location->script()->name()->IsString()) {
921     base::OS::PrintError(
922         "Extension or internal compilation error: %s in %s at line %d.\n",
923         String::cast(*exception)->ToCString().get(),
924         String::cast(location->script()->name())->ToCString().get(),
925         line_number);
926   } else if (location->script()->name()->IsString()) {
927     base::OS::PrintError(
928         "Extension or internal compilation error in %s at line %d.\n",
929         String::cast(location->script()->name())->ToCString().get(),
930         line_number);
931   } else {
932     base::OS::PrintError("Extension or internal compilation error.\n");
933   }
934 #ifdef OBJECT_PRINT
935   // Since comments and empty lines have been stripped from the source of
936   // builtins, print the actual source here so that line numbers match.
937   if (location->script()->source()->IsString()) {
938     Handle<String> src(String::cast(location->script()->source()));
939     PrintF("Failing script:");
940     int len = src->length();
941     if (len == 0) {
942       PrintF(" <not available>\n");
943     } else {
944       PrintF("\n");
945       int line_number = 1;
946       PrintF("%5d: ", line_number);
947       for (int i = 0; i < len; i++) {
948         uint16_t character = src->Get(i);
949         PrintF("%c", character);
950         if (character == '\n' && i < len - 2) {
951           PrintF("%5d: ", ++line_number);
952         }
953       }
954       PrintF("\n");
955     }
956   }
957 #endif
958 }
959
960
961 Object* Isolate::Throw(Object* exception, MessageLocation* location) {
962   DCHECK(!has_pending_exception());
963
964   HandleScope scope(this);
965   Handle<Object> exception_handle(exception, this);
966
967   // Determine whether a message needs to be created for the given exception
968   // depending on the following criteria:
969   // 1) External v8::TryCatch missing: Always create a message because any
970   //    JavaScript handler for a finally-block might re-throw to top-level.
971   // 2) External v8::TryCatch exists: Only create a message if the handler
972   //    captures messages or is verbose (which reports despite the catch).
973   // 3) ReThrow from v8::TryCatch: The message from a previous throw still
974   //    exists and we preserve it instead of creating a new message.
975   bool requires_message = try_catch_handler() == nullptr ||
976                           try_catch_handler()->is_verbose_ ||
977                           try_catch_handler()->capture_message_;
978   bool rethrowing_message = thread_local_top()->rethrowing_message_;
979
980   thread_local_top()->rethrowing_message_ = false;
981
982   // Notify debugger of exception.
983   if (is_catchable_by_javascript(exception)) {
984     debug()->OnThrow(exception_handle);
985   }
986
987   // Generate the message if required.
988   if (requires_message && !rethrowing_message) {
989     MessageLocation potential_computed_location;
990     if (location == NULL) {
991       // If no location was specified we use a computed one instead.
992       ComputeLocation(&potential_computed_location);
993       location = &potential_computed_location;
994     }
995
996     if (bootstrapper()->IsActive()) {
997       // It's not safe to try to make message objects or collect stack traces
998       // while the bootstrapper is active since the infrastructure may not have
999       // been properly initialized.
1000       ReportBootstrappingException(exception_handle, location);
1001     } else {
1002       Handle<Object> message_obj = CreateMessage(exception_handle, location);
1003       thread_local_top()->pending_message_obj_ = *message_obj;
1004
1005       // If the abort-on-uncaught-exception flag is specified, abort on any
1006       // exception not caught by JavaScript, even when an external handler is
1007       // present.  This flag is intended for use by JavaScript developers, so
1008       // print a user-friendly stack trace (not an internal one).
1009       if (FLAG_abort_on_uncaught_exception &&
1010           PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) {
1011         FLAG_abort_on_uncaught_exception = false;  // Prevent endless recursion.
1012         PrintF(stderr, "%s\n\nFROM\n",
1013                MessageHandler::GetLocalizedMessage(this, message_obj).get());
1014         PrintCurrentStackTrace(stderr);
1015         base::OS::Abort();
1016       }
1017     }
1018   }
1019
1020   // Set the exception being thrown.
1021   set_pending_exception(*exception_handle);
1022   return heap()->exception();
1023 }
1024
1025
1026 Object* Isolate::ReThrow(Object* exception) {
1027   DCHECK(!has_pending_exception());
1028
1029   // Set the exception being re-thrown.
1030   set_pending_exception(exception);
1031   return heap()->exception();
1032 }
1033
1034
1035 Object* Isolate::UnwindAndFindHandler() {
1036   Object* exception = pending_exception();
1037
1038   Code* code = nullptr;
1039   Context* context = nullptr;
1040   intptr_t offset = 0;
1041   Address handler_sp = nullptr;
1042   Address handler_fp = nullptr;
1043
1044   // Special handling of termination exceptions, uncatchable by JavaScript code,
1045   // we unwind the handlers until the top ENTRY handler is found.
1046   bool catchable_by_js = is_catchable_by_javascript(exception);
1047
1048   // Compute handler and stack unwinding information by performing a full walk
1049   // over the stack and dispatching according to the frame type.
1050   for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1051     StackFrame* frame = iter.frame();
1052
1053     // For JSEntryStub frames we always have a handler.
1054     if (frame->is_entry() || frame->is_entry_construct()) {
1055       StackHandler* handler = frame->top_handler();
1056
1057       // Restore the next handler.
1058       thread_local_top()->handler_ = handler->next()->address();
1059
1060       // Gather information from the handler.
1061       code = frame->LookupCode();
1062       handler_sp = handler->address() + StackHandlerConstants::kSize;
1063       offset = Smi::cast(code->handler_table()->get(0))->value();
1064       break;
1065     }
1066
1067     // For optimized frames we perform a lookup in the handler table.
1068     if (frame->is_optimized() && catchable_by_js) {
1069       OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
1070       int stack_slots = 0;  // Will contain stack slot count of frame.
1071       offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, NULL);
1072       if (offset >= 0) {
1073         // Compute the stack pointer from the frame pointer. This ensures that
1074         // argument slots on the stack are dropped as returning would.
1075         Address return_sp = frame->fp() -
1076                             StandardFrameConstants::kFixedFrameSizeFromFp -
1077                             stack_slots * kPointerSize;
1078
1079         // Gather information from the frame.
1080         code = frame->LookupCode();
1081         handler_sp = return_sp;
1082         handler_fp = frame->fp();
1083         break;
1084       }
1085     }
1086
1087     // For JavaScript frames we perform a range lookup in the handler table.
1088     if (frame->is_java_script() && catchable_by_js) {
1089       JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
1090       int stack_slots = 0;  // Will contain operand stack depth of handler.
1091       offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, NULL);
1092       if (offset >= 0) {
1093         // Compute the stack pointer from the frame pointer. This ensures that
1094         // operand stack slots are dropped for nested statements. Also restore
1095         // correct context for the handler which is pushed within the try-block.
1096         Address return_sp = frame->fp() -
1097                             StandardFrameConstants::kFixedFrameSizeFromFp -
1098                             stack_slots * kPointerSize;
1099         STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1100         context = Context::cast(Memory::Object_at(return_sp - kPointerSize));
1101
1102         // Gather information from the frame.
1103         code = frame->LookupCode();
1104         handler_sp = return_sp;
1105         handler_fp = frame->fp();
1106         break;
1107       }
1108     }
1109
1110     RemoveMaterializedObjectsOnUnwind(frame);
1111   }
1112
1113   // Handler must exist.
1114   CHECK(code != nullptr);
1115
1116   // Store information to be consumed by the CEntryStub.
1117   thread_local_top()->pending_handler_context_ = context;
1118   thread_local_top()->pending_handler_code_ = code;
1119   thread_local_top()->pending_handler_offset_ = offset;
1120   thread_local_top()->pending_handler_fp_ = handler_fp;
1121   thread_local_top()->pending_handler_sp_ = handler_sp;
1122
1123   // Return and clear pending exception.
1124   clear_pending_exception();
1125   return exception;
1126 }
1127
1128
1129 Isolate::CatchType Isolate::PredictExceptionCatcher() {
1130   Address external_handler = thread_local_top()->try_catch_handler_address();
1131   Address entry_handler = Isolate::handler(thread_local_top());
1132   if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL;
1133
1134   // Search for an exception handler by performing a full walk over the stack.
1135   for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1136     StackFrame* frame = iter.frame();
1137
1138     // For JSEntryStub frames we update the JS_ENTRY handler.
1139     if (frame->is_entry() || frame->is_entry_construct()) {
1140       entry_handler = frame->top_handler()->next()->address();
1141     }
1142
1143     // For JavaScript frames we perform a lookup in the handler table.
1144     if (frame->is_java_script()) {
1145       JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
1146       int stack_slots = 0;  // The computed stack slot count is not used.
1147       HandlerTable::CatchPrediction prediction;
1148       if (js_frame->LookupExceptionHandlerInTable(&stack_slots, &prediction) >
1149           0) {
1150         // We are conservative with our prediction: try-finally is considered
1151         // to always rethrow, to meet the expectation of the debugger.
1152         if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT;
1153       }
1154     }
1155
1156     // The exception has been externally caught if and only if there is an
1157     // external handler which is on top of the top-most JS_ENTRY handler.
1158     if (external_handler != nullptr && !try_catch_handler()->is_verbose_) {
1159       if (entry_handler == nullptr || entry_handler > external_handler) {
1160         return CAUGHT_BY_EXTERNAL;
1161       }
1162     }
1163   }
1164
1165   // Handler not found.
1166   return NOT_CAUGHT;
1167 }
1168
1169
1170 void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) {
1171   if (frame->is_optimized()) {
1172     bool removed = materialized_object_store_->Remove(frame->fp());
1173     USE(removed);
1174     // If there were any materialized objects, the code should be
1175     // marked for deopt.
1176     DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization());
1177   }
1178 }
1179
1180
1181 Object* Isolate::ThrowIllegalOperation() {
1182   if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
1183   return Throw(heap()->illegal_access_string());
1184 }
1185
1186
1187 void Isolate::ScheduleThrow(Object* exception) {
1188   // When scheduling a throw we first throw the exception to get the
1189   // error reporting if it is uncaught before rescheduling it.
1190   Throw(exception);
1191   PropagatePendingExceptionToExternalTryCatch();
1192   if (has_pending_exception()) {
1193     thread_local_top()->scheduled_exception_ = pending_exception();
1194     thread_local_top()->external_caught_exception_ = false;
1195     clear_pending_exception();
1196   }
1197 }
1198
1199
1200 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1201   DCHECK(handler == try_catch_handler());
1202   DCHECK(handler->HasCaught());
1203   DCHECK(handler->rethrow_);
1204   DCHECK(handler->capture_message_);
1205   Object* message = reinterpret_cast<Object*>(handler->message_obj_);
1206   DCHECK(message->IsJSMessageObject() || message->IsTheHole());
1207   thread_local_top()->pending_message_obj_ = message;
1208 }
1209
1210
1211 void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1212   DCHECK(has_scheduled_exception());
1213   if (scheduled_exception() == handler->exception_) {
1214     DCHECK(scheduled_exception() != heap()->termination_exception());
1215     clear_scheduled_exception();
1216   }
1217 }
1218
1219
1220 Object* Isolate::PromoteScheduledException() {
1221   Object* thrown = scheduled_exception();
1222   clear_scheduled_exception();
1223   // Re-throw the exception to avoid getting repeated error reporting.
1224   return ReThrow(thrown);
1225 }
1226
1227
1228 void Isolate::PrintCurrentStackTrace(FILE* out) {
1229   StackTraceFrameIterator it(this);
1230   while (!it.done()) {
1231     HandleScope scope(this);
1232     // Find code position if recorded in relocation info.
1233     JavaScriptFrame* frame = it.frame();
1234     int pos = frame->LookupCode()->SourcePosition(frame->pc());
1235     Handle<Object> pos_obj(Smi::FromInt(pos), this);
1236     // Fetch function and receiver.
1237     Handle<JSFunction> fun(frame->function());
1238     Handle<Object> recv(frame->receiver(), this);
1239     // Advance to the next JavaScript frame and determine if the
1240     // current frame is the top-level frame.
1241     it.Advance();
1242     Handle<Object> is_top_level = factory()->ToBoolean(it.done());
1243     // Generate and print stack trace line.
1244     Handle<String> line =
1245         Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1246     if (line->length() > 0) {
1247       line->PrintOn(out);
1248       PrintF(out, "\n");
1249     }
1250   }
1251 }
1252
1253
1254 void Isolate::ComputeLocation(MessageLocation* target) {
1255   *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1256   StackTraceFrameIterator it(this);
1257   if (!it.done()) {
1258     JavaScriptFrame* frame = it.frame();
1259     JSFunction* fun = frame->function();
1260     Object* script = fun->shared()->script();
1261     if (script->IsScript() &&
1262         !(Script::cast(script)->source()->IsUndefined())) {
1263       int pos = frame->LookupCode()->SourcePosition(frame->pc());
1264       // Compute the location from the function and the reloc info.
1265       Handle<Script> casted_script(Script::cast(script));
1266       *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1267     }
1268   }
1269 }
1270
1271
1272 bool Isolate::ComputeLocationFromException(MessageLocation* target,
1273                                            Handle<Object> exception) {
1274   if (!exception->IsJSObject()) return false;
1275
1276   Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1277   Handle<Object> start_pos = JSReceiver::GetDataProperty(
1278       Handle<JSObject>::cast(exception), start_pos_symbol);
1279   if (!start_pos->IsSmi()) return false;
1280   int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1281
1282   Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1283   Handle<Object> end_pos = JSReceiver::GetDataProperty(
1284       Handle<JSObject>::cast(exception), end_pos_symbol);
1285   if (!end_pos->IsSmi()) return false;
1286   int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1287
1288   Handle<Name> script_symbol = factory()->error_script_symbol();
1289   Handle<Object> script = JSReceiver::GetDataProperty(
1290       Handle<JSObject>::cast(exception), script_symbol);
1291   if (!script->IsScript()) return false;
1292
1293   Handle<Script> cast_script(Script::cast(*script));
1294   *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1295   return true;
1296 }
1297
1298
1299 bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1300                                             Handle<Object> exception) {
1301   *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1302
1303   if (!exception->IsJSObject()) return false;
1304   Handle<Name> key = factory()->stack_trace_symbol();
1305   Handle<Object> property =
1306       JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key);
1307   if (!property->IsJSArray()) return false;
1308   Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1309
1310   Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1311   int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1312
1313   for (int i = 1; i < elements_limit; i += 4) {
1314     Handle<JSFunction> fun =
1315         handle(JSFunction::cast(elements->get(i + 1)), this);
1316     if (fun->IsFromNativeScript()) continue;
1317
1318     Object* script = fun->shared()->script();
1319     if (script->IsScript() &&
1320         !(Script::cast(script)->source()->IsUndefined())) {
1321       int pos = PositionFromStackTrace(elements, i);
1322       Handle<Script> casted_script(Script::cast(script));
1323       *target = MessageLocation(casted_script, pos, pos + 1);
1324       return true;
1325     }
1326   }
1327   return false;
1328 }
1329
1330
1331 // Traverse prototype chain to find out whether the object is derived from
1332 // the Error object.
1333 bool Isolate::IsErrorObject(Handle<Object> obj) {
1334   if (!obj->IsJSObject()) return false;
1335
1336   Handle<String> error_key =
1337       factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("$Error"));
1338   Handle<Object> error_constructor = Object::GetProperty(
1339       js_builtins_object(), error_key).ToHandleChecked();
1340
1341   DisallowHeapAllocation no_gc;
1342   for (PrototypeIterator iter(this, *obj, PrototypeIterator::START_AT_RECEIVER);
1343        !iter.IsAtEnd(); iter.Advance()) {
1344     if (iter.GetCurrent()->IsJSProxy()) return false;
1345     if (JSObject::cast(iter.GetCurrent())->map()->GetConstructor() ==
1346         *error_constructor) {
1347       return true;
1348     }
1349   }
1350   return false;
1351 }
1352
1353
1354 Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1355                                                MessageLocation* location) {
1356   Handle<JSArray> stack_trace_object;
1357   MessageLocation potential_computed_location;
1358   if (capture_stack_trace_for_uncaught_exceptions_) {
1359     if (IsErrorObject(exception)) {
1360       // We fetch the stack trace that corresponds to this error object.
1361       // If the lookup fails, the exception is probably not a valid Error
1362       // object. In that case, we fall through and capture the stack trace
1363       // at this throw site.
1364       stack_trace_object =
1365           GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1366     }
1367     if (stack_trace_object.is_null()) {
1368       // Not an error object, we capture stack and location at throw site.
1369       stack_trace_object = CaptureCurrentStackTrace(
1370           stack_trace_for_uncaught_exceptions_frame_limit_,
1371           stack_trace_for_uncaught_exceptions_options_);
1372     }
1373   }
1374   if (!location) {
1375     if (!ComputeLocationFromException(&potential_computed_location,
1376                                       exception)) {
1377       if (!ComputeLocationFromStackTrace(&potential_computed_location,
1378                                          exception)) {
1379         ComputeLocation(&potential_computed_location);
1380       }
1381     }
1382     location = &potential_computed_location;
1383   }
1384
1385   return MessageHandler::MakeMessageObject(
1386       this, MessageTemplate::kUncaughtException, location, exception,
1387       stack_trace_object);
1388 }
1389
1390
1391 bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) {
1392   DCHECK_NE(heap()->the_hole_value(), exception);
1393
1394   // For uncatchable exceptions, the JavaScript handler cannot be on top.
1395   if (!is_catchable_by_javascript(exception)) return false;
1396
1397   // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1398   Address entry_handler = Isolate::handler(thread_local_top());
1399   if (entry_handler == nullptr) return false;
1400
1401   // Get the address of the external handler so we can compare the address to
1402   // determine which one is closer to the top of the stack.
1403   Address external_handler = thread_local_top()->try_catch_handler_address();
1404   if (external_handler == nullptr) return true;
1405
1406   // The exception has been externally caught if and only if there is an
1407   // external handler which is on top of the top-most JS_ENTRY handler.
1408   //
1409   // Note, that finally clauses would re-throw an exception unless it's aborted
1410   // by jumps in control flow (like return, break, etc.) and we'll have another
1411   // chance to set proper v8::TryCatch later.
1412   return (entry_handler < external_handler);
1413 }
1414
1415
1416 bool Isolate::IsExternalHandlerOnTop(Object* exception) {
1417   DCHECK_NE(heap()->the_hole_value(), exception);
1418
1419   // Get the address of the external handler so we can compare the address to
1420   // determine which one is closer to the top of the stack.
1421   Address external_handler = thread_local_top()->try_catch_handler_address();
1422   if (external_handler == nullptr) return false;
1423
1424   // For uncatchable exceptions, the external handler is always on top.
1425   if (!is_catchable_by_javascript(exception)) return true;
1426
1427   // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1428   Address entry_handler = Isolate::handler(thread_local_top());
1429   if (entry_handler == nullptr) return true;
1430
1431   // The exception has been externally caught if and only if there is an
1432   // external handler which is on top of the top-most JS_ENTRY handler.
1433   //
1434   // Note, that finally clauses would re-throw an exception unless it's aborted
1435   // by jumps in control flow (like return, break, etc.) and we'll have another
1436   // chance to set proper v8::TryCatch later.
1437   return (entry_handler > external_handler);
1438 }
1439
1440
1441 void Isolate::ReportPendingMessages() {
1442   Object* exception = pending_exception();
1443
1444   // Try to propagate the exception to an external v8::TryCatch handler. If
1445   // propagation was unsuccessful, then we will get another chance at reporting
1446   // the pending message if the exception is re-thrown.
1447   bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch();
1448   if (!has_been_propagated) return;
1449
1450   // Clear the pending message object early to avoid endless recursion.
1451   Object* message_obj = thread_local_top_.pending_message_obj_;
1452   clear_pending_message();
1453
1454   // For uncatchable exceptions we do nothing. If needed, the exception and the
1455   // message have already been propagated to v8::TryCatch.
1456   if (!is_catchable_by_javascript(exception)) return;
1457
1458   // Determine whether the message needs to be reported to all message handlers
1459   // depending on whether and external v8::TryCatch or an internal JavaScript
1460   // handler is on top.
1461   bool should_report_exception;
1462   if (IsExternalHandlerOnTop(exception)) {
1463     // Only report the exception if the external handler is verbose.
1464     should_report_exception = try_catch_handler()->is_verbose_;
1465   } else {
1466     // Report the exception if it isn't caught by JavaScript code.
1467     should_report_exception = !IsJavaScriptHandlerOnTop(exception);
1468   }
1469
1470   // Actually report the pending message to all message handlers.
1471   if (!message_obj->IsTheHole() && should_report_exception) {
1472     HandleScope scope(this);
1473     Handle<JSMessageObject> message(JSMessageObject::cast(message_obj));
1474     Handle<JSValue> script_wrapper(JSValue::cast(message->script()));
1475     Handle<Script> script(Script::cast(script_wrapper->value()));
1476     int start_pos = message->start_position();
1477     int end_pos = message->end_position();
1478     MessageLocation location(script, start_pos, end_pos);
1479     MessageHandler::ReportMessage(this, &location, message);
1480   }
1481 }
1482
1483
1484 MessageLocation Isolate::GetMessageLocation() {
1485   DCHECK(has_pending_exception());
1486
1487   if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1488       !thread_local_top_.pending_message_obj_->IsTheHole()) {
1489     Handle<JSMessageObject> message_obj(
1490         JSMessageObject::cast(thread_local_top_.pending_message_obj_));
1491     Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script()));
1492     Handle<Script> script(Script::cast(script_wrapper->value()));
1493     int start_pos = message_obj->start_position();
1494     int end_pos = message_obj->end_position();
1495     return MessageLocation(script, start_pos, end_pos);
1496   }
1497
1498   return MessageLocation();
1499 }
1500
1501
1502 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1503   DCHECK(has_pending_exception());
1504   PropagatePendingExceptionToExternalTryCatch();
1505
1506   bool is_termination_exception =
1507       pending_exception() == heap_.termination_exception();
1508
1509   // Do not reschedule the exception if this is the bottom call.
1510   bool clear_exception = is_bottom_call;
1511
1512   if (is_termination_exception) {
1513     if (is_bottom_call) {
1514       thread_local_top()->external_caught_exception_ = false;
1515       clear_pending_exception();
1516       return false;
1517     }
1518   } else if (thread_local_top()->external_caught_exception_) {
1519     // If the exception is externally caught, clear it if there are no
1520     // JavaScript frames on the way to the C++ frame that has the
1521     // external handler.
1522     DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1523     Address external_handler_address =
1524         thread_local_top()->try_catch_handler_address();
1525     JavaScriptFrameIterator it(this);
1526     if (it.done() || (it.frame()->sp() > external_handler_address)) {
1527       clear_exception = true;
1528     }
1529   }
1530
1531   // Clear the exception if needed.
1532   if (clear_exception) {
1533     thread_local_top()->external_caught_exception_ = false;
1534     clear_pending_exception();
1535     return false;
1536   }
1537
1538   // Reschedule the exception.
1539   thread_local_top()->scheduled_exception_ = pending_exception();
1540   clear_pending_exception();
1541   return true;
1542 }
1543
1544
1545 void Isolate::PushPromise(Handle<JSObject> promise,
1546                           Handle<JSFunction> function) {
1547   ThreadLocalTop* tltop = thread_local_top();
1548   PromiseOnStack* prev = tltop->promise_on_stack_;
1549   Handle<JSObject> global_promise =
1550       Handle<JSObject>::cast(global_handles()->Create(*promise));
1551   Handle<JSFunction> global_function =
1552       Handle<JSFunction>::cast(global_handles()->Create(*function));
1553   tltop->promise_on_stack_ =
1554       new PromiseOnStack(global_function, global_promise, prev);
1555 }
1556
1557
1558 void Isolate::PopPromise() {
1559   ThreadLocalTop* tltop = thread_local_top();
1560   if (tltop->promise_on_stack_ == NULL) return;
1561   PromiseOnStack* prev = tltop->promise_on_stack_->prev();
1562   Handle<Object> global_function = tltop->promise_on_stack_->function();
1563   Handle<Object> global_promise = tltop->promise_on_stack_->promise();
1564   delete tltop->promise_on_stack_;
1565   tltop->promise_on_stack_ = prev;
1566   global_handles()->Destroy(global_function.location());
1567   global_handles()->Destroy(global_promise.location());
1568 }
1569
1570
1571 Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1572   Handle<Object> undefined = factory()->undefined_value();
1573   ThreadLocalTop* tltop = thread_local_top();
1574   if (tltop->promise_on_stack_ == NULL) return undefined;
1575   Handle<JSFunction> promise_function = tltop->promise_on_stack_->function();
1576   // Find the top-most try-catch or try-finally handler.
1577   if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined;
1578   for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
1579     JavaScriptFrame* frame = it.frame();
1580     int stack_slots = 0;  // The computed stack slot count is not used.
1581     if (frame->LookupExceptionHandlerInTable(&stack_slots, NULL) > 0) {
1582       // Throwing inside a Promise only leads to a reject if not caught by an
1583       // inner try-catch or try-finally.
1584       if (frame->function() == *promise_function) {
1585         return tltop->promise_on_stack_->promise();
1586       }
1587       return undefined;
1588     }
1589   }
1590   return undefined;
1591 }
1592
1593
1594 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1595       bool capture,
1596       int frame_limit,
1597       StackTrace::StackTraceOptions options) {
1598   capture_stack_trace_for_uncaught_exceptions_ = capture;
1599   stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1600   stack_trace_for_uncaught_exceptions_options_ = options;
1601 }
1602
1603
1604 Handle<Context> Isolate::native_context() {
1605   return handle(context()->native_context());
1606 }
1607
1608
1609 Handle<Context> Isolate::GetCallingNativeContext() {
1610   JavaScriptFrameIterator it(this);
1611   if (debug_->in_debug_scope()) {
1612     while (!it.done()) {
1613       JavaScriptFrame* frame = it.frame();
1614       Context* context = Context::cast(frame->context());
1615       if (context->native_context() == *debug_->debug_context()) {
1616         it.Advance();
1617       } else {
1618         break;
1619       }
1620     }
1621   }
1622   if (it.done()) return Handle<Context>::null();
1623   JavaScriptFrame* frame = it.frame();
1624   Context* context = Context::cast(frame->context());
1625   return Handle<Context>(context->native_context());
1626 }
1627
1628
1629 char* Isolate::ArchiveThread(char* to) {
1630   MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1631           sizeof(ThreadLocalTop));
1632   InitializeThreadLocal();
1633   clear_pending_exception();
1634   clear_pending_message();
1635   clear_scheduled_exception();
1636   return to + sizeof(ThreadLocalTop);
1637 }
1638
1639
1640 char* Isolate::RestoreThread(char* from) {
1641   MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1642           sizeof(ThreadLocalTop));
1643 // This might be just paranoia, but it seems to be needed in case a
1644 // thread_local_top_ is restored on a separate OS thread.
1645 #ifdef USE_SIMULATOR
1646   thread_local_top()->simulator_ = Simulator::current(this);
1647 #endif
1648   DCHECK(context() == NULL || context()->IsContext());
1649   return from + sizeof(ThreadLocalTop);
1650 }
1651
1652
1653 Isolate::ThreadDataTable::ThreadDataTable()
1654     : list_(NULL) {
1655 }
1656
1657
1658 Isolate::ThreadDataTable::~ThreadDataTable() {
1659   // TODO(svenpanne) The assertion below would fire if an embedder does not
1660   // cleanly dispose all Isolates before disposing v8, so we are conservative
1661   // and leave it out for now.
1662   // DCHECK_NULL(list_);
1663 }
1664
1665
1666 Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1667 #if defined(USE_SIMULATOR)
1668   delete simulator_;
1669 #endif
1670 }
1671
1672
1673 Isolate::PerIsolateThreadData*
1674     Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1675                                      ThreadId thread_id) {
1676   for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1677     if (data->Matches(isolate, thread_id)) return data;
1678   }
1679   return NULL;
1680 }
1681
1682
1683 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1684   if (list_ != NULL) list_->prev_ = data;
1685   data->next_ = list_;
1686   list_ = data;
1687 }
1688
1689
1690 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1691   if (list_ == data) list_ = data->next_;
1692   if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1693   if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1694   delete data;
1695 }
1696
1697
1698 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1699   PerIsolateThreadData* data = list_;
1700   while (data != NULL) {
1701     PerIsolateThreadData* next = data->next_;
1702     if (data->isolate() == isolate) Remove(data);
1703     data = next;
1704   }
1705 }
1706
1707
1708 #ifdef DEBUG
1709 #define TRACE_ISOLATE(tag)                                              \
1710   do {                                                                  \
1711     if (FLAG_trace_isolates) {                                          \
1712       PrintF("Isolate %p (id %d)" #tag "\n",                            \
1713              reinterpret_cast<void*>(this), id());                      \
1714     }                                                                   \
1715   } while (false)
1716 #else
1717 #define TRACE_ISOLATE(tag)
1718 #endif
1719
1720
1721 Isolate::Isolate(bool enable_serializer)
1722     : embedder_data_(),
1723       entry_stack_(NULL),
1724       stack_trace_nesting_level_(0),
1725       incomplete_message_(NULL),
1726       bootstrapper_(NULL),
1727       runtime_profiler_(NULL),
1728       compilation_cache_(NULL),
1729       counters_(NULL),
1730       code_range_(NULL),
1731       logger_(NULL),
1732       stats_table_(NULL),
1733       stub_cache_(NULL),
1734       code_aging_helper_(NULL),
1735       deoptimizer_data_(NULL),
1736       materialized_object_store_(NULL),
1737       capture_stack_trace_for_uncaught_exceptions_(false),
1738       stack_trace_for_uncaught_exceptions_frame_limit_(0),
1739       stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1740       memory_allocator_(NULL),
1741       keyed_lookup_cache_(NULL),
1742       context_slot_cache_(NULL),
1743       descriptor_lookup_cache_(NULL),
1744       handle_scope_implementer_(NULL),
1745       unicode_cache_(NULL),
1746       inner_pointer_to_code_cache_(NULL),
1747       global_handles_(NULL),
1748       eternal_handles_(NULL),
1749       thread_manager_(NULL),
1750       has_installed_extensions_(false),
1751       string_tracker_(NULL),
1752       regexp_stack_(NULL),
1753       date_cache_(NULL),
1754       call_descriptor_data_(NULL),
1755       // TODO(bmeurer) Initialized lazily because it depends on flags; can
1756       // be fixed once the default isolate cleanup is done.
1757       random_number_generator_(NULL),
1758       store_buffer_hash_set_1_address_(NULL),
1759       store_buffer_hash_set_2_address_(NULL),
1760       serializer_enabled_(enable_serializer),
1761       has_fatal_error_(false),
1762       initialized_from_snapshot_(false),
1763       cpu_profiler_(NULL),
1764       heap_profiler_(NULL),
1765       function_entry_hook_(NULL),
1766       deferred_handles_head_(NULL),
1767       optimizing_compile_dispatcher_(NULL),
1768       stress_deopt_count_(0),
1769       next_optimization_id_(0),
1770 #if TRACE_MAPS
1771       next_unique_sfi_id_(0),
1772 #endif
1773       use_counter_callback_(NULL),
1774       basic_block_profiler_(NULL) {
1775   {
1776     base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1777     CHECK(thread_data_table_);
1778   }
1779   id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1780   TRACE_ISOLATE(constructor);
1781
1782   memset(isolate_addresses_, 0,
1783       sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1784
1785   heap_.isolate_ = this;
1786   stack_guard_.isolate_ = this;
1787
1788   // ThreadManager is initialized early to support locking an isolate
1789   // before it is entered.
1790   thread_manager_ = new ThreadManager();
1791   thread_manager_->isolate_ = this;
1792
1793 #ifdef DEBUG
1794   // heap_histograms_ initializes itself.
1795   memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1796 #endif
1797
1798   handle_scope_data_.Initialize();
1799
1800 #define ISOLATE_INIT_EXECUTE(type, name, initial_value)                        \
1801   name##_ = (initial_value);
1802   ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1803 #undef ISOLATE_INIT_EXECUTE
1804
1805 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length)                         \
1806   memset(name##_, 0, sizeof(type) * length);
1807   ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1808 #undef ISOLATE_INIT_ARRAY_EXECUTE
1809
1810   InitializeLoggingAndCounters();
1811   debug_ = new Debug(this);
1812 }
1813
1814
1815 void Isolate::TearDown() {
1816   TRACE_ISOLATE(tear_down);
1817
1818   // Temporarily set this isolate as current so that various parts of
1819   // the isolate can access it in their destructors without having a
1820   // direct pointer. We don't use Enter/Exit here to avoid
1821   // initializing the thread data.
1822   PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1823   Isolate* saved_isolate = UncheckedCurrent();
1824   SetIsolateThreadLocals(this, NULL);
1825
1826   Deinit();
1827
1828   {
1829     base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1830     thread_data_table_->RemoveAllThreads(this);
1831   }
1832
1833   delete this;
1834
1835   // Restore the previous current isolate.
1836   SetIsolateThreadLocals(saved_isolate, saved_data);
1837 }
1838
1839
1840 void Isolate::GlobalTearDown() {
1841   delete thread_data_table_;
1842   thread_data_table_ = NULL;
1843 }
1844
1845
1846 void Isolate::ClearSerializerData() {
1847   delete external_reference_table_;
1848   external_reference_table_ = NULL;
1849   delete external_reference_map_;
1850   external_reference_map_ = NULL;
1851   delete root_index_map_;
1852   root_index_map_ = NULL;
1853 }
1854
1855
1856 void Isolate::Deinit() {
1857   TRACE_ISOLATE(deinit);
1858
1859   debug()->Unload();
1860
1861   FreeThreadResources();
1862
1863   if (concurrent_recompilation_enabled()) {
1864     optimizing_compile_dispatcher_->Stop();
1865     delete optimizing_compile_dispatcher_;
1866     optimizing_compile_dispatcher_ = NULL;
1867   }
1868
1869   if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1870     heap_.mark_compact_collector()->EnsureSweepingCompleted();
1871   }
1872
1873   DumpAndResetCompilationStats();
1874
1875   if (FLAG_print_deopt_stress) {
1876     PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1877   }
1878
1879   // We must stop the logger before we tear down other components.
1880   Sampler* sampler = logger_->sampler();
1881   if (sampler && sampler->IsActive()) sampler->Stop();
1882
1883   delete deoptimizer_data_;
1884   deoptimizer_data_ = NULL;
1885   builtins_.TearDown();
1886   bootstrapper_->TearDown();
1887
1888   if (runtime_profiler_ != NULL) {
1889     delete runtime_profiler_;
1890     runtime_profiler_ = NULL;
1891   }
1892
1893   delete basic_block_profiler_;
1894   basic_block_profiler_ = NULL;
1895
1896   heap_.TearDown();
1897   logger_->TearDown();
1898
1899   delete heap_profiler_;
1900   heap_profiler_ = NULL;
1901   delete cpu_profiler_;
1902   cpu_profiler_ = NULL;
1903
1904   ClearSerializerData();
1905 }
1906
1907
1908 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1909                                      PerIsolateThreadData* data) {
1910   base::Thread::SetThreadLocal(isolate_key_, isolate);
1911   base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1912 }
1913
1914
1915 Isolate::~Isolate() {
1916   TRACE_ISOLATE(destructor);
1917
1918   // Has to be called while counters_ are still alive
1919   runtime_zone_.DeleteKeptSegment();
1920
1921   // The entry stack must be empty when we get here.
1922   DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1923
1924   delete entry_stack_;
1925   entry_stack_ = NULL;
1926
1927   delete unicode_cache_;
1928   unicode_cache_ = NULL;
1929
1930   delete date_cache_;
1931   date_cache_ = NULL;
1932
1933   delete[] call_descriptor_data_;
1934   call_descriptor_data_ = NULL;
1935
1936   delete regexp_stack_;
1937   regexp_stack_ = NULL;
1938
1939   delete descriptor_lookup_cache_;
1940   descriptor_lookup_cache_ = NULL;
1941   delete context_slot_cache_;
1942   context_slot_cache_ = NULL;
1943   delete keyed_lookup_cache_;
1944   keyed_lookup_cache_ = NULL;
1945
1946   delete stub_cache_;
1947   stub_cache_ = NULL;
1948   delete code_aging_helper_;
1949   code_aging_helper_ = NULL;
1950   delete stats_table_;
1951   stats_table_ = NULL;
1952
1953   delete materialized_object_store_;
1954   materialized_object_store_ = NULL;
1955
1956   delete logger_;
1957   logger_ = NULL;
1958
1959   delete counters_;
1960   counters_ = NULL;
1961
1962   delete handle_scope_implementer_;
1963   handle_scope_implementer_ = NULL;
1964
1965   delete code_tracer();
1966   set_code_tracer(NULL);
1967
1968   delete compilation_cache_;
1969   compilation_cache_ = NULL;
1970   delete bootstrapper_;
1971   bootstrapper_ = NULL;
1972   delete inner_pointer_to_code_cache_;
1973   inner_pointer_to_code_cache_ = NULL;
1974
1975   delete thread_manager_;
1976   thread_manager_ = NULL;
1977
1978   delete string_tracker_;
1979   string_tracker_ = NULL;
1980
1981   delete memory_allocator_;
1982   memory_allocator_ = NULL;
1983   delete code_range_;
1984   code_range_ = NULL;
1985   delete global_handles_;
1986   global_handles_ = NULL;
1987   delete eternal_handles_;
1988   eternal_handles_ = NULL;
1989
1990   delete string_stream_debug_object_cache_;
1991   string_stream_debug_object_cache_ = NULL;
1992
1993   delete random_number_generator_;
1994   random_number_generator_ = NULL;
1995
1996   delete debug_;
1997   debug_ = NULL;
1998
1999 #if USE_SIMULATOR
2000   Simulator::TearDown(simulator_i_cache_, simulator_redirection_);
2001   simulator_i_cache_ = nullptr;
2002   simulator_redirection_ = nullptr;
2003 #endif
2004 }
2005
2006
2007 void Isolate::InitializeThreadLocal() {
2008   thread_local_top_.isolate_ = this;
2009   thread_local_top_.Initialize();
2010 }
2011
2012
2013 bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
2014   Object* exception = pending_exception();
2015
2016   if (IsJavaScriptHandlerOnTop(exception)) {
2017     thread_local_top_.external_caught_exception_ = false;
2018     return false;
2019   }
2020
2021   if (!IsExternalHandlerOnTop(exception)) {
2022     thread_local_top_.external_caught_exception_ = false;
2023     return true;
2024   }
2025
2026   thread_local_top_.external_caught_exception_ = true;
2027   if (!is_catchable_by_javascript(exception)) {
2028     try_catch_handler()->can_continue_ = false;
2029     try_catch_handler()->has_terminated_ = true;
2030     try_catch_handler()->exception_ = heap()->null_value();
2031   } else {
2032     v8::TryCatch* handler = try_catch_handler();
2033     DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2034            thread_local_top_.pending_message_obj_->IsTheHole());
2035     handler->can_continue_ = true;
2036     handler->has_terminated_ = false;
2037     handler->exception_ = pending_exception();
2038     // Propagate to the external try-catch only if we got an actual message.
2039     if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
2040
2041     handler->message_obj_ = thread_local_top_.pending_message_obj_;
2042   }
2043   return true;
2044 }
2045
2046
2047 void Isolate::InitializeLoggingAndCounters() {
2048   if (logger_ == NULL) {
2049     logger_ = new Logger(this);
2050   }
2051   if (counters_ == NULL) {
2052     counters_ = new Counters(this);
2053   }
2054 }
2055
2056
2057 bool Isolate::Init(Deserializer* des) {
2058   TRACE_ISOLATE(init);
2059
2060   stress_deopt_count_ = FLAG_deopt_every_n_times;
2061
2062   has_fatal_error_ = false;
2063
2064   if (function_entry_hook() != NULL) {
2065     // When function entry hooking is in effect, we have to create the code
2066     // stubs from scratch to get entry hooks, rather than loading the previously
2067     // generated stubs from disk.
2068     // If this assert fires, the initialization path has regressed.
2069     DCHECK(des == NULL);
2070   }
2071
2072   // The initialization process does not handle memory exhaustion.
2073   DisallowAllocationFailure disallow_allocation_failure(this);
2074
2075   memory_allocator_ = new MemoryAllocator(this);
2076   code_range_ = new CodeRange(this);
2077
2078   // Safe after setting Heap::isolate_, and initializing StackGuard
2079   heap_.SetStackLimits();
2080
2081 #define ASSIGN_ELEMENT(CamelName, hacker_name)                  \
2082   isolate_addresses_[Isolate::k##CamelName##Address] =          \
2083       reinterpret_cast<Address>(hacker_name##_address());
2084   FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
2085 #undef ASSIGN_ELEMENT
2086
2087   string_tracker_ = new StringTracker();
2088   string_tracker_->isolate_ = this;
2089   compilation_cache_ = new CompilationCache(this);
2090   keyed_lookup_cache_ = new KeyedLookupCache();
2091   context_slot_cache_ = new ContextSlotCache();
2092   descriptor_lookup_cache_ = new DescriptorLookupCache();
2093   unicode_cache_ = new UnicodeCache();
2094   inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
2095   global_handles_ = new GlobalHandles(this);
2096   eternal_handles_ = new EternalHandles();
2097   bootstrapper_ = new Bootstrapper(this);
2098   handle_scope_implementer_ = new HandleScopeImplementer(this);
2099   stub_cache_ = new StubCache(this);
2100   materialized_object_store_ = new MaterializedObjectStore(this);
2101   regexp_stack_ = new RegExpStack();
2102   regexp_stack_->isolate_ = this;
2103   date_cache_ = new DateCache();
2104   call_descriptor_data_ =
2105       new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2106   cpu_profiler_ = new CpuProfiler(this);
2107   heap_profiler_ = new HeapProfiler(heap());
2108
2109   // Enable logging before setting up the heap
2110   logger_->SetUp(this);
2111
2112   // Initialize other runtime facilities
2113 #if defined(USE_SIMULATOR)
2114 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
2115     V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC
2116   Simulator::Initialize(this);
2117 #endif
2118 #endif
2119
2120   code_aging_helper_ = new CodeAgingHelper();
2121
2122   { // NOLINT
2123     // Ensure that the thread has a valid stack guard.  The v8::Locker object
2124     // will ensure this too, but we don't have to use lockers if we are only
2125     // using one thread.
2126     ExecutionAccess lock(this);
2127     stack_guard_.InitThread(lock);
2128   }
2129
2130   // SetUp the object heap.
2131   DCHECK(!heap_.HasBeenSetUp());
2132   if (!heap_.SetUp()) {
2133     V8::FatalProcessOutOfMemory("heap setup");
2134     return false;
2135   }
2136
2137   deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2138
2139   const bool create_heap_objects = (des == NULL);
2140   if (create_heap_objects && !heap_.CreateHeapObjects()) {
2141     V8::FatalProcessOutOfMemory("heap object creation");
2142     return false;
2143   }
2144
2145   if (create_heap_objects) {
2146     // Terminate the cache array with the sentinel so we can iterate.
2147     partial_snapshot_cache_.Add(heap_.undefined_value());
2148   }
2149
2150   InitializeThreadLocal();
2151
2152   bootstrapper_->Initialize(create_heap_objects);
2153   builtins_.SetUp(this, create_heap_objects);
2154
2155   if (FLAG_log_internal_timer_events) {
2156     set_event_logger(Logger::DefaultEventLoggerSentinel);
2157   }
2158
2159   if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2160     PrintF("Concurrent recompilation has been disabled for tracing.\n");
2161   } else if (OptimizingCompileDispatcher::Enabled()) {
2162     optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
2163   }
2164
2165   // Initialize runtime profiler before deserialization, because collections may
2166   // occur, clearing/updating ICs.
2167   runtime_profiler_ = new RuntimeProfiler(this);
2168
2169   // If we are deserializing, read the state into the now-empty heap.
2170   if (!create_heap_objects) {
2171     des->Deserialize(this);
2172   }
2173   stub_cache_->Initialize();
2174
2175   // Finish initialization of ThreadLocal after deserialization is done.
2176   clear_pending_exception();
2177   clear_pending_message();
2178   clear_scheduled_exception();
2179
2180   // Deserializing may put strange things in the root array's copy of the
2181   // stack guard.
2182   heap_.SetStackLimits();
2183
2184   // Quiet the heap NaN if needed on target platform.
2185   if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
2186
2187   if (FLAG_trace_turbo) {
2188     // Create an empty file.
2189     std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2190   }
2191
2192   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2193            Internals::kIsolateEmbedderDataOffset);
2194   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2195            Internals::kIsolateRootsOffset);
2196   CHECK_EQ(static_cast<int>(
2197                OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2198            Internals::kAmountOfExternalAllocatedMemoryOffset);
2199   CHECK_EQ(static_cast<int>(OFFSET_OF(
2200                Isolate,
2201                heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2202            Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2203
2204   time_millis_at_init_ = base::OS::TimeCurrentMillis();
2205
2206   heap_.NotifyDeserializationComplete();
2207
2208   if (!create_heap_objects) {
2209     // Now that the heap is consistent, it's OK to generate the code for the
2210     // deopt entry table that might have been referred to by optimized code in
2211     // the snapshot.
2212     HandleScope scope(this);
2213     Deoptimizer::EnsureCodeForDeoptimizationEntry(
2214         this,
2215         Deoptimizer::LAZY,
2216         kDeoptTableSerializeEntryCount - 1);
2217   }
2218
2219   if (!serializer_enabled()) {
2220     // Ensure that all stubs which need to be generated ahead of time, but
2221     // cannot be serialized into the snapshot have been generated.
2222     HandleScope scope(this);
2223     CodeStub::GenerateFPStubs(this);
2224     StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2225     StubFailureTrampolineStub::GenerateAheadOfTime(this);
2226   }
2227
2228   initialized_from_snapshot_ = (des != NULL);
2229
2230   if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2231
2232   return true;
2233 }
2234
2235
2236 // Initialized lazily to allow early
2237 // v8::V8::SetAddHistogramSampleFunction calls.
2238 StatsTable* Isolate::stats_table() {
2239   if (stats_table_ == NULL) {
2240     stats_table_ = new StatsTable;
2241   }
2242   return stats_table_;
2243 }
2244
2245
2246 void Isolate::Enter() {
2247   Isolate* current_isolate = NULL;
2248   PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2249   if (current_data != NULL) {
2250     current_isolate = current_data->isolate_;
2251     DCHECK(current_isolate != NULL);
2252     if (current_isolate == this) {
2253       DCHECK(Current() == this);
2254       DCHECK(entry_stack_ != NULL);
2255       DCHECK(entry_stack_->previous_thread_data == NULL ||
2256              entry_stack_->previous_thread_data->thread_id().Equals(
2257                  ThreadId::Current()));
2258       // Same thread re-enters the isolate, no need to re-init anything.
2259       entry_stack_->entry_count++;
2260       return;
2261     }
2262   }
2263
2264   PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2265   DCHECK(data != NULL);
2266   DCHECK(data->isolate_ == this);
2267
2268   EntryStackItem* item = new EntryStackItem(current_data,
2269                                             current_isolate,
2270                                             entry_stack_);
2271   entry_stack_ = item;
2272
2273   SetIsolateThreadLocals(this, data);
2274
2275   // In case it's the first time some thread enters the isolate.
2276   set_thread_id(data->thread_id());
2277 }
2278
2279
2280 void Isolate::Exit() {
2281   DCHECK(entry_stack_ != NULL);
2282   DCHECK(entry_stack_->previous_thread_data == NULL ||
2283          entry_stack_->previous_thread_data->thread_id().Equals(
2284              ThreadId::Current()));
2285
2286   if (--entry_stack_->entry_count > 0) return;
2287
2288   DCHECK(CurrentPerIsolateThreadData() != NULL);
2289   DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
2290
2291   // Pop the stack.
2292   EntryStackItem* item = entry_stack_;
2293   entry_stack_ = item->previous_item;
2294
2295   PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2296   Isolate* previous_isolate = item->previous_isolate;
2297
2298   delete item;
2299
2300   // Reinit the current thread for the isolate it was running before this one.
2301   SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2302 }
2303
2304
2305 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2306   deferred->next_ = deferred_handles_head_;
2307   if (deferred_handles_head_ != NULL) {
2308     deferred_handles_head_->previous_ = deferred;
2309   }
2310   deferred_handles_head_ = deferred;
2311 }
2312
2313
2314 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2315 #ifdef DEBUG
2316   // In debug mode assert that the linked list is well-formed.
2317   DeferredHandles* deferred_iterator = deferred;
2318   while (deferred_iterator->previous_ != NULL) {
2319     deferred_iterator = deferred_iterator->previous_;
2320   }
2321   DCHECK(deferred_handles_head_ == deferred_iterator);
2322 #endif
2323   if (deferred_handles_head_ == deferred) {
2324     deferred_handles_head_ = deferred_handles_head_->next_;
2325   }
2326   if (deferred->next_ != NULL) {
2327     deferred->next_->previous_ = deferred->previous_;
2328   }
2329   if (deferred->previous_ != NULL) {
2330     deferred->previous_->next_ = deferred->next_;
2331   }
2332 }
2333
2334
2335 void Isolate::DumpAndResetCompilationStats() {
2336   if (turbo_statistics() != nullptr) {
2337     OFStream os(stdout);
2338     os << *turbo_statistics() << std::endl;
2339   }
2340   if (hstatistics() != nullptr) hstatistics()->Print();
2341   delete turbo_statistics_;
2342   turbo_statistics_ = nullptr;
2343   delete hstatistics_;
2344   hstatistics_ = nullptr;
2345 }
2346
2347
2348 HStatistics* Isolate::GetHStatistics() {
2349   if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2350   return hstatistics();
2351 }
2352
2353
2354 CompilationStatistics* Isolate::GetTurboStatistics() {
2355   if (turbo_statistics() == NULL)
2356     set_turbo_statistics(new CompilationStatistics());
2357   return turbo_statistics();
2358 }
2359
2360
2361 HTracer* Isolate::GetHTracer() {
2362   if (htracer() == NULL) set_htracer(new HTracer(id()));
2363   return htracer();
2364 }
2365
2366
2367 CodeTracer* Isolate::GetCodeTracer() {
2368   if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2369   return code_tracer();
2370 }
2371
2372
2373 Map* Isolate::get_initial_js_array_map(ElementsKind kind,
2374                                        ObjectStrength strength) {
2375   Context* native_context = context()->native_context();
2376   Object* maybe_map_array = strength ? native_context->js_array_strong_maps()
2377                                      : native_context->js_array_maps();
2378   if (!maybe_map_array->IsUndefined()) {
2379     Object* maybe_transitioned_map =
2380         FixedArray::cast(maybe_map_array)->get(kind);
2381     if (!maybe_transitioned_map->IsUndefined()) {
2382       return Map::cast(maybe_transitioned_map);
2383     }
2384   }
2385   return NULL;
2386 }
2387
2388
2389 bool Isolate::use_crankshaft() const {
2390   return FLAG_crankshaft &&
2391          !serializer_enabled_ &&
2392          CpuFeatures::SupportsCrankshaft();
2393 }
2394
2395
2396 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2397   PropertyCell* no_elements_cell = heap()->array_protector();
2398   bool cell_reports_intact =
2399       no_elements_cell->value()->IsSmi() &&
2400       Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid;
2401
2402 #ifdef DEBUG
2403   Map* root_array_map =
2404       get_initial_js_array_map(GetInitialFastElementsKind());
2405   Context* native_context = context()->native_context();
2406   JSObject* initial_array_proto = JSObject::cast(
2407       native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX));
2408   JSObject* initial_object_proto = JSObject::cast(
2409       native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX));
2410
2411   if (root_array_map == NULL || initial_array_proto == initial_object_proto) {
2412     // We are in the bootstrapping process, and the entire check sequence
2413     // shouldn't be performed.
2414     return cell_reports_intact;
2415   }
2416
2417   // Check that the array prototype hasn't been altered WRT empty elements.
2418   if (root_array_map->prototype() != initial_array_proto) {
2419     DCHECK_EQ(false, cell_reports_intact);
2420     return cell_reports_intact;
2421   }
2422
2423   if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2424     DCHECK_EQ(false, cell_reports_intact);
2425     return cell_reports_intact;
2426   }
2427
2428   // Check that the object prototype hasn't been altered WRT empty elements.
2429   PrototypeIterator iter(this, initial_array_proto);
2430   if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
2431     DCHECK_EQ(false, cell_reports_intact);
2432     return cell_reports_intact;
2433   }
2434   if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2435     DCHECK_EQ(false, cell_reports_intact);
2436     return cell_reports_intact;
2437   }
2438
2439   iter.Advance();
2440   if (!iter.IsAtEnd()) {
2441     DCHECK_EQ(false, cell_reports_intact);
2442     return cell_reports_intact;
2443   }
2444
2445 #endif
2446
2447   return cell_reports_intact;
2448 }
2449
2450
2451 void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) {
2452   if (IsFastArrayConstructorPrototypeChainIntact() &&
2453       object->map()->is_prototype_map()) {
2454     Object* context = heap()->native_contexts_list();
2455     while (!context->IsUndefined()) {
2456       Context* current_context = Context::cast(context);
2457       if (current_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX) ==
2458               *object ||
2459           current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2460               *object) {
2461         PropertyCell::SetValueWithInvalidation(
2462             factory()->array_protector(),
2463             handle(Smi::FromInt(kArrayProtectorInvalid), this));
2464         break;
2465       }
2466       context = current_context->get(Context::NEXT_CONTEXT_LINK);
2467     }
2468   }
2469 }
2470
2471
2472 bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) {
2473   if (array->map()->is_prototype_map()) {
2474     Object* context = heap()->native_contexts_list();
2475     while (!context->IsUndefined()) {
2476       Context* current_context = Context::cast(context);
2477       if (current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2478           *array) {
2479         return true;
2480       }
2481       context = current_context->get(Context::NEXT_CONTEXT_LINK);
2482     }
2483   }
2484   return false;
2485 }
2486
2487
2488 CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2489   DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2490   return &call_descriptor_data_[index];
2491 }
2492
2493
2494 base::RandomNumberGenerator* Isolate::random_number_generator() {
2495   if (random_number_generator_ == NULL) {
2496     if (FLAG_random_seed != 0) {
2497       random_number_generator_ =
2498           new base::RandomNumberGenerator(FLAG_random_seed);
2499     } else {
2500       random_number_generator_ = new base::RandomNumberGenerator();
2501     }
2502   }
2503   return random_number_generator_;
2504 }
2505
2506
2507 Object* Isolate::FindCodeObject(Address a) {
2508   return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2509 }
2510
2511
2512 #ifdef DEBUG
2513 #define ISOLATE_FIELD_OFFSET(type, name, ignored)                       \
2514 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2515 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2516 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2517 #undef ISOLATE_FIELD_OFFSET
2518 #endif
2519
2520
2521 Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry,
2522                                            Handle<Map> map, const char* cname) {
2523   Handle<String> name = factory()->InternalizeUtf8String(cname);
2524   Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2525   JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0,
2526                                 "SetupSymbolRegistry");
2527   JSObject::AddProperty(registry, name, obj, NONE);
2528   return obj;
2529 }
2530
2531
2532 Handle<JSObject> Isolate::GetSymbolRegistry() {
2533   if (heap()->symbol_registry()->IsSmi()) {
2534     Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2535     Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2536     heap()->set_symbol_registry(*registry);
2537
2538     SetUpSubregistry(registry, map, "for");
2539     SetUpSubregistry(registry, map, "for_api");
2540     SetUpSubregistry(registry, map, "keyFor");
2541     SetUpSubregistry(registry, map, "private_api");
2542     heap()->AddPrivateGlobalSymbols(
2543         SetUpSubregistry(registry, map, "private_intern"));
2544   }
2545   return Handle<JSObject>::cast(factory()->symbol_registry());
2546 }
2547
2548
2549 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2550   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2551     if (callback == call_completed_callbacks_.at(i)) return;
2552   }
2553   call_completed_callbacks_.Add(callback);
2554 }
2555
2556
2557 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2558   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2559     if (callback == call_completed_callbacks_.at(i)) {
2560       call_completed_callbacks_.Remove(i);
2561     }
2562   }
2563 }
2564
2565
2566 void Isolate::FireCallCompletedCallback() {
2567   bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2568   bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2569   if (!has_call_completed_callbacks && !run_microtasks) return;
2570
2571   if (!handle_scope_implementer()->CallDepthIsZero()) return;
2572   if (run_microtasks) RunMicrotasks();
2573   // Fire callbacks.  Increase call depth to prevent recursive callbacks.
2574   v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2575       reinterpret_cast<v8::Isolate*>(this));
2576   for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2577     call_completed_callbacks_.at(i)();
2578   }
2579 }
2580
2581
2582 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2583   promise_reject_callback_ = callback;
2584 }
2585
2586
2587 void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2588                                   Handle<Object> value,
2589                                   v8::PromiseRejectEvent event) {
2590   if (promise_reject_callback_ == NULL) return;
2591   Handle<JSArray> stack_trace;
2592   if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2593     stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2594   }
2595   promise_reject_callback_(v8::PromiseRejectMessage(
2596       v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2597       v8::Utils::StackTraceToLocal(stack_trace)));
2598 }
2599
2600
2601 void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2602   DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2603   Handle<FixedArray> queue(heap()->microtask_queue(), this);
2604   int num_tasks = pending_microtask_count();
2605   DCHECK(num_tasks <= queue->length());
2606   if (num_tasks == 0) {
2607     queue = factory()->NewFixedArray(8);
2608     heap()->set_microtask_queue(*queue);
2609   } else if (num_tasks == queue->length()) {
2610     queue = FixedArray::CopySize(queue, num_tasks * 2);
2611     heap()->set_microtask_queue(*queue);
2612   }
2613   DCHECK(queue->get(num_tasks)->IsUndefined());
2614   queue->set(num_tasks, *microtask);
2615   set_pending_microtask_count(num_tasks + 1);
2616 }
2617
2618
2619 void Isolate::RunMicrotasks() {
2620   // %RunMicrotasks may be called in mjsunit tests, which violates
2621   // this assertion, hence the check for --allow-natives-syntax.
2622   // TODO(adamk): However, this also fails some layout tests.
2623   //
2624   // DCHECK(FLAG_allow_natives_syntax ||
2625   //        handle_scope_implementer()->CallDepthIsZero());
2626
2627   // Increase call depth to prevent recursive callbacks.
2628   v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2629       reinterpret_cast<v8::Isolate*>(this));
2630
2631   while (pending_microtask_count() > 0) {
2632     HandleScope scope(this);
2633     int num_tasks = pending_microtask_count();
2634     Handle<FixedArray> queue(heap()->microtask_queue(), this);
2635     DCHECK(num_tasks <= queue->length());
2636     set_pending_microtask_count(0);
2637     heap()->set_microtask_queue(heap()->empty_fixed_array());
2638
2639     for (int i = 0; i < num_tasks; i++) {
2640       HandleScope scope(this);
2641       Handle<Object> microtask(queue->get(i), this);
2642       if (microtask->IsJSFunction()) {
2643         Handle<JSFunction> microtask_function =
2644             Handle<JSFunction>::cast(microtask);
2645         SaveContext save(this);
2646         set_context(microtask_function->context()->native_context());
2647         MaybeHandle<Object> maybe_exception;
2648         MaybeHandle<Object> result =
2649             Execution::TryCall(microtask_function, factory()->undefined_value(),
2650                                0, NULL, &maybe_exception);
2651         // If execution is terminating, just bail out.
2652         Handle<Object> exception;
2653         if (result.is_null() && maybe_exception.is_null()) {
2654           // Clear out any remaining callbacks in the queue.
2655           heap()->set_microtask_queue(heap()->empty_fixed_array());
2656           set_pending_microtask_count(0);
2657           return;
2658         }
2659       } else {
2660         Handle<CallHandlerInfo> callback_info =
2661             Handle<CallHandlerInfo>::cast(microtask);
2662         v8::MicrotaskCallback callback =
2663             v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2664         void* data = v8::ToCData<void*>(callback_info->data());
2665         callback(data);
2666       }
2667     }
2668   }
2669 }
2670
2671
2672 void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2673   DCHECK(!use_counter_callback_);
2674   use_counter_callback_ = callback;
2675 }
2676
2677
2678 void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
2679   // The counter callback may cause the embedder to call into V8, which is not
2680   // generally possible during GC.
2681   if (heap_.gc_state() == Heap::NOT_IN_GC) {
2682     if (use_counter_callback_) {
2683       HandleScope handle_scope(this);
2684       use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2685     }
2686   } else {
2687     heap_.IncrementDeferredCount(feature);
2688   }
2689 }
2690
2691
2692 BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2693   if (basic_block_profiler_ == NULL) {
2694     basic_block_profiler_ = new BasicBlockProfiler();
2695   }
2696   return basic_block_profiler_;
2697 }
2698
2699
2700 std::string Isolate::GetTurboCfgFileName() {
2701   if (FLAG_trace_turbo_cfg_file == NULL) {
2702     std::ostringstream os;
2703     os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2704     return os.str();
2705   } else {
2706     return FLAG_trace_turbo_cfg_file;
2707   }
2708 }
2709
2710
2711 // Heap::detached_contexts tracks detached contexts as pairs
2712 // (number of GC since the context was detached, the context).
2713 void Isolate::AddDetachedContext(Handle<Context> context) {
2714   HandleScope scope(this);
2715   Handle<WeakCell> cell = factory()->NewWeakCell(context);
2716   Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2717   int length = detached_contexts->length();
2718   detached_contexts = FixedArray::CopySize(detached_contexts, length + 2);
2719   detached_contexts->set(length, Smi::FromInt(0));
2720   detached_contexts->set(length + 1, *cell);
2721   heap()->set_detached_contexts(*detached_contexts);
2722 }
2723
2724
2725 void Isolate::CheckDetachedContextsAfterGC() {
2726   HandleScope scope(this);
2727   Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2728   int length = detached_contexts->length();
2729   if (length == 0) return;
2730   int new_length = 0;
2731   for (int i = 0; i < length; i += 2) {
2732     int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2733     DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2734     WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2735     if (!cell->cleared()) {
2736       detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2737       detached_contexts->set(new_length + 1, cell);
2738       new_length += 2;
2739     }
2740     counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
2741   }
2742   if (FLAG_trace_detached_contexts) {
2743     PrintF("%d detached contexts are collected out of %d\n",
2744            length - new_length, length);
2745     for (int i = 0; i < new_length; i += 2) {
2746       int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2747       DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2748       WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2749       if (mark_sweeps > 3) {
2750         PrintF("detached context 0x%p\n survived %d GCs (leak?)\n",
2751                static_cast<void*>(cell->value()), mark_sweeps);
2752       }
2753     }
2754   }
2755   if (new_length == 0) {
2756     heap()->set_detached_contexts(heap()->empty_fixed_array());
2757   } else if (new_length < length) {
2758     heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
2759         *detached_contexts, length - new_length);
2760   }
2761 }
2762
2763
2764 bool StackLimitCheck::JsHasOverflowed() const {
2765   StackGuard* stack_guard = isolate_->stack_guard();
2766 #ifdef USE_SIMULATOR
2767   // The simulator uses a separate JS stack.
2768   Address jssp_address = Simulator::current(isolate_)->get_sp();
2769   uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
2770   if (jssp < stack_guard->real_jslimit()) return true;
2771 #endif  // USE_SIMULATOR
2772   return GetCurrentStackPosition() < stack_guard->real_climit();
2773 }
2774
2775
2776 SaveContext::SaveContext(Isolate* isolate)
2777     : isolate_(isolate), prev_(isolate->save_context()) {
2778   if (isolate->context() != NULL) {
2779     context_ = Handle<Context>(isolate->context());
2780   }
2781   isolate->set_save_context(this);
2782
2783   c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
2784 }
2785
2786
2787 bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2788   // First check whether the previous scope intercepts.
2789   if (prev_ && prev_->Intercept(flag)) return true;
2790   // Then check whether this scope intercepts.
2791   if ((flag & intercept_mask_)) {
2792     intercepted_flags_ |= flag;
2793     return true;
2794   }
2795   return false;
2796 }
2797
2798 }  // namespace internal
2799 }  // namespace v8