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