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