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.
7 #include <fstream> // NOLINT(readability/streams)
13 #include "src/base/platform/platform.h"
14 #include "src/base/sys-info.h"
15 #include "src/base/utils/random-number-generator.h"
16 #include "src/basic-block-profiler.h"
17 #include "src/bootstrapper.h"
18 #include "src/codegen.h"
19 #include "src/compilation-cache.h"
20 #include "src/compilation-statistics.h"
21 #include "src/cpu-profiler.h"
22 #include "src/debug.h"
23 #include "src/deoptimizer.h"
24 #include "src/heap/spaces.h"
25 #include "src/heap-profiler.h"
26 #include "src/hydrogen.h"
27 #include "src/ic/stub-cache.h"
28 #include "src/lithium-allocator.h"
30 #include "src/messages.h"
31 #include "src/prototype.h"
32 #include "src/regexp-stack.h"
33 #include "src/runtime-profiler.h"
34 #include "src/sampler.h"
35 #include "src/scopeinfo.h"
36 #include "src/simulator.h"
37 #include "src/snapshot/serialize.h"
38 #include "src/version.h"
39 #include "src/vm-state-inl.h"
45 base::Atomic32 ThreadId::highest_thread_id_ = 0;
47 int ThreadId::AllocateThreadId() {
48 int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
53 int ThreadId::GetCurrentThreadId() {
54 int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
56 thread_id = AllocateThreadId();
57 base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
63 ThreadLocalTop::ThreadLocalTop() {
68 void ThreadLocalTop::InitializeInternal() {
76 external_callback_scope_ = NULL;
77 current_vm_state_ = EXTERNAL;
78 try_catch_handler_ = NULL;
80 thread_id_ = ThreadId::Invalid();
81 external_caught_exception_ = false;
82 failed_access_check_callback_ = NULL;
84 promise_on_stack_ = NULL;
86 // These members are re-initialized later after deserialization
88 pending_exception_ = NULL;
89 rethrowing_message_ = false;
90 pending_message_obj_ = NULL;
91 scheduled_exception_ = NULL;
95 void ThreadLocalTop::Initialize() {
98 simulator_ = Simulator::current(isolate_);
100 thread_id_ = ThreadId::Current();
104 void ThreadLocalTop::Free() {
105 // Match unmatched PopPromise calls.
106 while (promise_on_stack_) isolate_->PopPromise();
110 base::Thread::LocalStorageKey Isolate::isolate_key_;
111 base::Thread::LocalStorageKey Isolate::thread_id_key_;
112 base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
113 base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER;
114 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
115 base::Atomic32 Isolate::isolate_counter_ = 0;
117 base::Atomic32 Isolate::isolate_key_created_ = 0;
120 Isolate::PerIsolateThreadData*
121 Isolate::FindOrAllocatePerThreadDataForThisThread() {
122 ThreadId thread_id = ThreadId::Current();
123 PerIsolateThreadData* per_thread = NULL;
125 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
126 per_thread = thread_data_table_->Lookup(this, thread_id);
127 if (per_thread == NULL) {
128 per_thread = new PerIsolateThreadData(this, thread_id);
129 thread_data_table_->Insert(per_thread);
131 DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
137 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
138 ThreadId thread_id = ThreadId::Current();
139 return FindPerThreadDataForThread(thread_id);
143 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
144 ThreadId thread_id) {
145 PerIsolateThreadData* per_thread = NULL;
147 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
148 per_thread = thread_data_table_->Lookup(this, thread_id);
154 void Isolate::InitializeOncePerProcess() {
155 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
156 CHECK(thread_data_table_ == NULL);
157 isolate_key_ = base::Thread::CreateThreadLocalKey();
159 base::NoBarrier_Store(&isolate_key_created_, 1);
161 thread_id_key_ = base::Thread::CreateThreadLocalKey();
162 per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
163 thread_data_table_ = new Isolate::ThreadDataTable();
167 Address Isolate::get_address_from_id(Isolate::AddressId id) {
168 return isolate_addresses_[id];
172 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
173 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
175 return thread_storage + sizeof(ThreadLocalTop);
179 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
180 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
181 v->VisitThread(this, thread);
185 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
186 // Visit the roots from the top for a given thread.
187 v->VisitPointer(&thread->pending_exception_);
188 v->VisitPointer(&(thread->pending_message_obj_));
189 v->VisitPointer(bit_cast<Object**>(&(thread->context_)));
190 v->VisitPointer(&thread->scheduled_exception_);
192 for (v8::TryCatch* block = thread->try_catch_handler();
194 block = block->next_) {
195 v->VisitPointer(bit_cast<Object**>(&(block->exception_)));
196 v->VisitPointer(bit_cast<Object**>(&(block->message_obj_)));
199 // Iterate over pointers on native execution stack.
200 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
201 it.frame()->Iterate(v);
206 void Isolate::Iterate(ObjectVisitor* v) {
207 ThreadLocalTop* current_t = thread_local_top();
208 Iterate(v, current_t);
212 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
213 for (DeferredHandles* deferred = deferred_handles_head_;
215 deferred = deferred->next_) {
216 deferred->Iterate(visitor);
222 bool Isolate::IsDeferredHandle(Object** handle) {
223 // Each DeferredHandles instance keeps the handles to one job in the
224 // concurrent recompilation queue, containing a list of blocks. Each block
225 // contains kHandleBlockSize handles except for the first block, which may
226 // not be fully filled.
227 // We iterate through all the blocks to see whether the argument handle
228 // belongs to one of the blocks. If so, it is deferred.
229 for (DeferredHandles* deferred = deferred_handles_head_;
231 deferred = deferred->next_) {
232 List<Object**>* blocks = &deferred->blocks_;
233 for (int i = 0; i < blocks->length(); i++) {
234 Object** block_limit = (i == 0) ? deferred->first_block_limit_
235 : blocks->at(i) + kHandleBlockSize;
236 if (blocks->at(i) <= handle && handle < block_limit) return true;
244 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
245 thread_local_top()->set_try_catch_handler(that);
249 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
250 DCHECK(thread_local_top()->try_catch_handler() == that);
251 thread_local_top()->set_try_catch_handler(that->next_);
255 Handle<String> Isolate::StackTraceString() {
256 if (stack_trace_nesting_level_ == 0) {
257 stack_trace_nesting_level_++;
258 HeapStringAllocator allocator;
259 StringStream::ClearMentionedObjectCache(this);
260 StringStream accumulator(&allocator);
261 incomplete_message_ = &accumulator;
262 PrintStack(&accumulator);
263 Handle<String> stack_trace = accumulator.ToString(this);
264 incomplete_message_ = NULL;
265 stack_trace_nesting_level_ = 0;
267 } else if (stack_trace_nesting_level_ == 1) {
268 stack_trace_nesting_level_++;
269 base::OS::PrintError(
270 "\n\nAttempt to print stack while printing stack (double fault)\n");
271 base::OS::PrintError(
272 "If you are lucky you may find a partial stack dump on stdout.\n\n");
273 incomplete_message_->OutputToStdOut();
274 return factory()->empty_string();
278 return factory()->empty_string();
283 void Isolate::PushStackTraceAndDie(unsigned int magic, void* ptr1, void* ptr2,
284 unsigned int magic2) {
285 const int kMaxStackTraceSize = 32 * KB;
286 Handle<String> trace = StackTraceString();
287 uint8_t buffer[kMaxStackTraceSize];
288 int length = Min(kMaxStackTraceSize - 1, trace->length());
289 String::WriteToFlat(*trace, buffer, 0, length);
290 buffer[length] = '\0';
291 // TODO(dcarney): convert buffer to utf8?
292 base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2, ptr1,
293 ptr2, reinterpret_cast<char*>(buffer));
298 // Determines whether the given stack frame should be displayed in
299 // a stack trace. The caller is the error constructor that asked
300 // for the stack trace to be collected. The first time a construct
301 // call to this function is encountered it is skipped. The seen_caller
302 // in/out parameter is used to remember if the caller has been seen
304 static bool IsVisibleInStackTrace(JSFunction* fun,
308 if ((fun == caller) && !(*seen_caller)) {
312 // Skip all frames until we've seen the caller.
313 if (!(*seen_caller)) return false;
314 // Also, skip non-visible built-in functions and any call with the builtins
315 // object as receiver, so as to not reveal either the builtins object or
316 // an internal function.
317 // The --builtins-in-stack-traces command line flag allows including
318 // internal call sites in the stack trace for debugging purposes.
319 if (!FLAG_builtins_in_stack_traces) {
320 if (receiver->IsJSBuiltinsObject()) return false;
321 if (fun->IsBuiltin()) {
322 return fun->shared()->native();
323 } else if (!fun->IsSubjectToDebugging()) {
331 Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
332 Handle<Object> caller) {
333 // Get stack trace limit.
334 Handle<Object> error = Object::GetProperty(
335 this, js_builtins_object(), "$Error").ToHandleChecked();
336 if (!error->IsJSObject()) return factory()->undefined_value();
338 Handle<String> stackTraceLimit =
339 factory()->InternalizeUtf8String("stackTraceLimit");
340 DCHECK(!stackTraceLimit.is_null());
341 Handle<Object> stack_trace_limit = JSReceiver::GetDataProperty(
342 Handle<JSObject>::cast(error), stackTraceLimit);
343 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
344 int limit = FastD2IChecked(stack_trace_limit->Number());
345 limit = Max(limit, 0); // Ensure that limit is not negative.
347 int initial_size = Min(limit, 10);
348 Handle<FixedArray> elements =
349 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
351 // If the caller parameter is a function we skip frames until we're
352 // under it before starting to collect.
353 bool seen_caller = !caller->IsJSFunction();
354 // First element is reserved to store the number of sloppy frames.
357 int sloppy_frames = 0;
358 bool encountered_strict_function = false;
359 for (JavaScriptFrameIterator iter(this);
360 !iter.done() && frames_seen < limit;
362 JavaScriptFrame* frame = iter.frame();
363 // Set initial size to the maximum inlining level + 1 for the outermost
365 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
366 frame->Summarize(&frames);
367 for (int i = frames.length() - 1; i >= 0; i--) {
368 Handle<JSFunction> fun = frames[i].function();
369 Handle<Object> recv = frames[i].receiver();
370 // Filter out internal frames that we do not want to show.
371 if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) continue;
372 // Filter out frames from other security contexts.
373 if (!this->context()->HasSameSecurityTokenAs(fun->context())) continue;
374 if (cursor + 4 > elements->length()) {
375 int new_capacity = JSObject::NewElementsCapacity(elements->length());
376 Handle<FixedArray> new_elements =
377 factory()->NewFixedArrayWithHoles(new_capacity);
378 for (int i = 0; i < cursor; i++) {
379 new_elements->set(i, elements->get(i));
381 elements = new_elements;
383 DCHECK(cursor + 4 <= elements->length());
385 Handle<Code> code = frames[i].code();
386 Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
387 // The stack trace API should not expose receivers and function
388 // objects on frames deeper than the top-most one with a strict
389 // mode function. The number of sloppy frames is stored as
390 // first element in the result array.
391 if (!encountered_strict_function) {
392 if (is_strict(fun->shared()->language_mode())) {
393 encountered_strict_function = true;
398 elements->set(cursor++, *recv);
399 elements->set(cursor++, *fun);
400 elements->set(cursor++, *code);
401 elements->set(cursor++, *offset);
405 elements->set(0, Smi::FromInt(sloppy_frames));
406 elements->Shrink(cursor);
407 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
408 result->set_length(Smi::FromInt(cursor));
409 // TODO(yangguo): Queue this structured stack trace for preprocessing on GC.
414 MaybeHandle<JSObject> Isolate::CaptureAndSetDetailedStackTrace(
415 Handle<JSObject> error_object) {
416 if (capture_stack_trace_for_uncaught_exceptions_) {
417 // Capture stack trace for a detailed exception message.
418 Handle<Name> key = factory()->detailed_stack_trace_symbol();
419 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
420 stack_trace_for_uncaught_exceptions_frame_limit_,
421 stack_trace_for_uncaught_exceptions_options_);
423 this, JSObject::SetProperty(error_object, key, stack_trace, STRICT),
430 MaybeHandle<JSObject> Isolate::CaptureAndSetSimpleStackTrace(
431 Handle<JSObject> error_object, Handle<Object> caller) {
432 // Capture stack trace for simple stack trace string formatting.
433 Handle<Name> key = factory()->stack_trace_symbol();
434 Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
436 this, JSObject::SetProperty(error_object, key, stack_trace, STRICT),
442 Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
443 Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
444 Handle<Object> stack_trace =
445 JSReceiver::GetDataProperty(error_object, key_detailed);
446 if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
448 if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
450 // Try to get details from simple stack trace.
451 Handle<JSArray> detailed_stack_trace =
452 GetDetailedFromSimpleStackTrace(error_object);
453 if (!detailed_stack_trace.is_null()) {
454 // Save the detailed stack since the simple one might be withdrawn later.
455 JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
458 return detailed_stack_trace;
462 class CaptureStackTraceHelper {
464 CaptureStackTraceHelper(Isolate* isolate,
465 StackTrace::StackTraceOptions options)
466 : isolate_(isolate) {
467 if (options & StackTrace::kColumnOffset) {
469 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
471 if (options & StackTrace::kLineNumber) {
473 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
475 if (options & StackTrace::kScriptId) {
477 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
479 if (options & StackTrace::kScriptName) {
481 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
483 if (options & StackTrace::kScriptNameOrSourceURL) {
484 script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
485 STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
487 if (options & StackTrace::kFunctionName) {
488 function_key_ = factory()->InternalizeOneByteString(
489 STATIC_CHAR_VECTOR("functionName"));
491 if (options & StackTrace::kIsEval) {
493 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
495 if (options & StackTrace::kIsConstructor) {
496 constructor_key_ = factory()->InternalizeOneByteString(
497 STATIC_CHAR_VECTOR("isConstructor"));
501 Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun, int position,
502 bool is_constructor) {
503 Handle<JSObject> stack_frame =
504 factory()->NewJSObject(isolate_->object_function());
506 Handle<Script> script(Script::cast(fun->shared()->script()));
508 if (!line_key_.is_null()) {
509 int script_line_offset = script->line_offset()->value();
510 int line_number = Script::GetLineNumber(script, position);
511 // line_number is already shifted by the script_line_offset.
512 int relative_line_number = line_number - script_line_offset;
513 if (!column_key_.is_null() && relative_line_number >= 0) {
514 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
515 int start = (relative_line_number == 0) ? 0 :
516 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
517 int column_offset = position - start;
518 if (relative_line_number == 0) {
519 // For the case where the code is on the same line as the script
521 column_offset += script->column_offset()->value();
523 JSObject::AddProperty(stack_frame, column_key_,
524 handle(Smi::FromInt(column_offset + 1), isolate_),
527 JSObject::AddProperty(stack_frame, line_key_,
528 handle(Smi::FromInt(line_number + 1), isolate_),
532 if (!script_id_key_.is_null()) {
533 JSObject::AddProperty(stack_frame, script_id_key_,
534 handle(script->id(), isolate_), NONE);
537 if (!script_name_key_.is_null()) {
538 JSObject::AddProperty(stack_frame, script_name_key_,
539 handle(script->name(), isolate_), NONE);
542 if (!script_name_or_source_url_key_.is_null()) {
543 Handle<Object> result = Script::GetNameOrSourceURL(script);
544 JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
548 if (!function_key_.is_null()) {
549 Handle<Object> fun_name = JSFunction::GetDebugName(fun);
550 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
553 if (!eval_key_.is_null()) {
554 Handle<Object> is_eval = factory()->ToBoolean(
555 script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
556 JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
559 if (!constructor_key_.is_null()) {
560 Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
561 JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
569 inline Factory* factory() { return isolate_->factory(); }
572 Handle<String> column_key_;
573 Handle<String> line_key_;
574 Handle<String> script_id_key_;
575 Handle<String> script_name_key_;
576 Handle<String> script_name_or_source_url_key_;
577 Handle<String> function_key_;
578 Handle<String> eval_key_;
579 Handle<String> constructor_key_;
583 int PositionFromStackTrace(Handle<FixedArray> elements, int index) {
584 DisallowHeapAllocation no_gc;
585 Object* maybe_code = elements->get(index + 2);
586 if (maybe_code->IsSmi()) {
587 return Smi::cast(maybe_code)->value();
589 Code* code = Code::cast(maybe_code);
590 Address pc = code->address() + Smi::cast(elements->get(index + 3))->value();
591 return code->SourcePosition(pc);
596 Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
597 Handle<JSObject> error_object) {
598 Handle<Name> key = factory()->stack_trace_symbol();
599 Handle<Object> property = JSReceiver::GetDataProperty(error_object, key);
600 if (!property->IsJSArray()) return Handle<JSArray>();
601 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
603 CaptureStackTraceHelper helper(this,
604 stack_trace_for_uncaught_exceptions_options_);
607 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
608 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
610 int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
611 if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
613 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
614 for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
615 Handle<Object> recv = handle(elements->get(i), this);
616 Handle<JSFunction> fun =
617 handle(JSFunction::cast(elements->get(i + 1)), this);
618 bool is_constructor =
619 recv->IsJSObject() &&
620 Handle<JSObject>::cast(recv)->map()->GetConstructor() == *fun;
621 int position = PositionFromStackTrace(elements, i);
623 Handle<JSObject> stack_frame =
624 helper.NewStackFrameObject(fun, position, is_constructor);
626 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
630 stack_trace->set_length(Smi::FromInt(frames_seen));
635 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
636 int frame_limit, StackTrace::StackTraceOptions options) {
637 CaptureStackTraceHelper helper(this, options);
639 // Ensure no negative values.
640 int limit = Max(frame_limit, 0);
641 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
643 StackTraceFrameIterator it(this);
645 while (!it.done() && (frames_seen < limit)) {
646 JavaScriptFrame* frame = it.frame();
647 // Set initial size to the maximum inlining level + 1 for the outermost
649 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
650 frame->Summarize(&frames);
651 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
652 Handle<JSFunction> fun = frames[i].function();
653 // Filter frames from other security contexts.
654 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
655 !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
656 int position = frames[i].code()->SourcePosition(frames[i].pc());
657 Handle<JSObject> stack_frame =
658 helper.NewStackFrameObject(fun, position, frames[i].is_constructor());
660 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
666 stack_trace->set_length(Smi::FromInt(frames_seen));
671 void Isolate::PrintStack(FILE* out, PrintStackMode mode) {
672 if (stack_trace_nesting_level_ == 0) {
673 stack_trace_nesting_level_++;
674 StringStream::ClearMentionedObjectCache(this);
675 HeapStringAllocator allocator;
676 StringStream accumulator(&allocator);
677 incomplete_message_ = &accumulator;
678 PrintStack(&accumulator, mode);
679 accumulator.OutputToFile(out);
680 InitializeLoggingAndCounters();
681 accumulator.Log(this);
682 incomplete_message_ = NULL;
683 stack_trace_nesting_level_ = 0;
684 } else if (stack_trace_nesting_level_ == 1) {
685 stack_trace_nesting_level_++;
686 base::OS::PrintError(
687 "\n\nAttempt to print stack while printing stack (double fault)\n");
688 base::OS::PrintError(
689 "If you are lucky you may find a partial stack dump on stdout.\n\n");
690 incomplete_message_->OutputToFile(out);
695 static void PrintFrames(Isolate* isolate,
696 StringStream* accumulator,
697 StackFrame::PrintMode mode) {
698 StackFrameIterator it(isolate);
699 for (int i = 0; !it.done(); it.Advance()) {
700 it.frame()->Print(accumulator, mode, i++);
705 void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) {
706 // The MentionedObjectCache is not GC-proof at the moment.
707 DisallowHeapAllocation no_gc;
708 DCHECK(accumulator->IsMentionedObjectCacheClear(this));
710 // Avoid printing anything if there are no frames.
711 if (c_entry_fp(thread_local_top()) == 0) return;
714 "\n==== JS stack trace =========================================\n\n");
715 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
716 if (mode == kPrintStackVerbose) {
718 "\n==== Details ================================================\n\n");
719 PrintFrames(this, accumulator, StackFrame::DETAILS);
720 accumulator->PrintMentionedObjectCache(this);
722 accumulator->Add("=====================\n\n");
726 void Isolate::SetFailedAccessCheckCallback(
727 v8::FailedAccessCheckCallback callback) {
728 thread_local_top()->failed_access_check_callback_ = callback;
732 static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
733 Handle<JSObject> receiver) {
734 Object* maybe_constructor = receiver->map()->GetConstructor();
735 if (!maybe_constructor->IsJSFunction()) return NULL;
736 JSFunction* constructor = JSFunction::cast(maybe_constructor);
737 if (!constructor->shared()->IsApiFunction()) return NULL;
740 constructor->shared()->get_api_func_data()->access_check_info();
741 if (data_obj == isolate->heap()->undefined_value()) return NULL;
743 return AccessCheckInfo::cast(data_obj);
747 void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) {
748 if (!thread_local_top()->failed_access_check_callback_) {
749 return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess));
752 DCHECK(receiver->IsAccessCheckNeeded());
755 // Get the data object from access check info.
756 HandleScope scope(this);
758 { DisallowHeapAllocation no_gc;
759 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
760 if (!access_check_info) {
761 AllowHeapAllocation doesnt_matter_anymore;
762 return ScheduleThrow(
763 *factory()->NewTypeError(MessageTemplate::kNoAccess));
765 data = handle(access_check_info->data(), this);
768 // Leaving JavaScript.
769 VMState<EXTERNAL> state(this);
770 thread_local_top()->failed_access_check_callback_(
771 v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data));
775 bool Isolate::IsInternallyUsedPropertyName(Handle<Object> name) {
776 if (name->IsSymbol()) {
777 return Handle<Symbol>::cast(name)->is_private();
779 return name.is_identical_to(factory()->hidden_string());
783 bool Isolate::IsInternallyUsedPropertyName(Object* name) {
784 if (name->IsSymbol()) {
785 return Symbol::cast(name)->is_private();
787 return name == heap()->hidden_string();
791 bool Isolate::MayAccess(Handle<JSObject> receiver) {
792 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
794 // Check for compatibility between the security tokens in the
795 // current lexical context and the accessed object.
799 DisallowHeapAllocation no_gc;
800 // During bootstrapping, callback functions are not enabled yet.
801 if (bootstrapper()->IsActive()) return true;
803 if (receiver->IsJSGlobalProxy()) {
804 Object* receiver_context =
805 JSGlobalProxy::cast(*receiver)->native_context();
806 if (!receiver_context->IsContext()) return false;
808 // Get the native context of current top context.
809 // avoid using Isolate::native_context() because it uses Handle.
810 Context* native_context = context()->global_object()->native_context();
811 if (receiver_context == native_context) return true;
813 if (Context::cast(receiver_context)->security_token() ==
814 native_context->security_token())
819 HandleScope scope(this);
821 v8::NamedSecurityCallback callback;
822 { DisallowHeapAllocation no_gc;
823 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
824 if (!access_check_info) return false;
825 Object* fun_obj = access_check_info->named_callback();
826 callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
827 if (!callback) return false;
828 data = handle(access_check_info->data(), this);
831 LOG(this, ApiSecurityCheck());
833 // Leaving JavaScript.
834 VMState<EXTERNAL> state(this);
835 Handle<Object> key = factory()->undefined_value();
836 return callback(v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(key),
837 v8::ACCESS_HAS, v8::Utils::ToLocal(data));
841 const char* const Isolate::kStackOverflowMessage =
842 "Uncaught RangeError: Maximum call stack size exceeded";
845 Object* Isolate::StackOverflow() {
846 HandleScope scope(this);
847 // At this point we cannot create an Error object using its javascript
848 // constructor. Instead, we copy the pre-constructed boilerplate and
849 // attach the stack trace as a hidden property.
850 Handle<String> key = factory()->stack_overflow_string();
851 Handle<Object> boilerplate =
852 Object::GetProperty(js_builtins_object(), key).ToHandleChecked();
853 if (boilerplate->IsUndefined()) {
854 return Throw(heap()->undefined_value(), nullptr);
856 Handle<JSObject> exception =
857 factory()->CopyJSObject(Handle<JSObject>::cast(boilerplate));
858 Throw(*exception, nullptr);
860 CaptureAndSetSimpleStackTrace(exception, factory()->undefined_value());
862 if (FLAG_verify_heap && FLAG_stress_compaction) {
863 heap()->CollectAllAvailableGarbage("trigger compaction");
865 #endif // VERIFY_HEAP
867 return heap()->exception();
871 Object* Isolate::TerminateExecution() {
872 return Throw(heap_.termination_exception(), nullptr);
876 void Isolate::CancelTerminateExecution() {
877 if (try_catch_handler()) {
878 try_catch_handler()->has_terminated_ = false;
880 if (has_pending_exception() &&
881 pending_exception() == heap_.termination_exception()) {
882 thread_local_top()->external_caught_exception_ = false;
883 clear_pending_exception();
885 if (has_scheduled_exception() &&
886 scheduled_exception() == heap_.termination_exception()) {
887 thread_local_top()->external_caught_exception_ = false;
888 clear_scheduled_exception();
893 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
894 ExecutionAccess access(this);
895 api_interrupts_queue_.push(InterruptEntry(callback, data));
896 stack_guard()->RequestApiInterrupt();
900 void Isolate::InvokeApiInterruptCallbacks() {
901 // Note: callback below should be called outside of execution access lock.
903 InterruptEntry entry;
905 ExecutionAccess access(this);
906 if (api_interrupts_queue_.empty()) return;
907 entry = api_interrupts_queue_.front();
908 api_interrupts_queue_.pop();
910 VMState<EXTERNAL> state(this);
911 HandleScope handle_scope(this);
912 entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
917 void ReportBootstrappingException(Handle<Object> exception,
918 MessageLocation* location) {
919 base::OS::PrintError("Exception thrown during bootstrapping\n");
920 if (location == NULL || location->script().is_null()) return;
921 // We are bootstrapping and caught an error where the location is set
922 // and we have a script for the location.
923 // In this case we could have an extension (or an internal error
924 // somewhere) and we print out the line number at which the error occured
925 // to the console for easier debugging.
927 location->script()->GetLineNumber(location->start_pos()) + 1;
928 if (exception->IsString() && location->script()->name()->IsString()) {
929 base::OS::PrintError(
930 "Extension or internal compilation error: %s in %s at line %d.\n",
931 String::cast(*exception)->ToCString().get(),
932 String::cast(location->script()->name())->ToCString().get(),
934 } else if (location->script()->name()->IsString()) {
935 base::OS::PrintError(
936 "Extension or internal compilation error in %s at line %d.\n",
937 String::cast(location->script()->name())->ToCString().get(),
939 } else if (exception->IsString()) {
940 base::OS::PrintError("Extension or internal compilation error: %s.\n",
941 String::cast(*exception)->ToCString().get());
943 base::OS::PrintError("Extension or internal compilation error.\n");
946 // Since comments and empty lines have been stripped from the source of
947 // builtins, print the actual source here so that line numbers match.
948 if (location->script()->source()->IsString()) {
949 Handle<String> src(String::cast(location->script()->source()));
950 PrintF("Failing script:");
951 int len = src->length();
953 PrintF(" <not available>\n");
957 PrintF("%5d: ", line_number);
958 for (int i = 0; i < len; i++) {
959 uint16_t character = src->Get(i);
960 PrintF("%c", character);
961 if (character == '\n' && i < len - 2) {
962 PrintF("%5d: ", ++line_number);
972 Object* Isolate::Throw(Object* exception, MessageLocation* location) {
973 DCHECK(!has_pending_exception());
975 HandleScope scope(this);
976 Handle<Object> exception_handle(exception, this);
978 // Determine whether a message needs to be created for the given exception
979 // depending on the following criteria:
980 // 1) External v8::TryCatch missing: Always create a message because any
981 // JavaScript handler for a finally-block might re-throw to top-level.
982 // 2) External v8::TryCatch exists: Only create a message if the handler
983 // captures messages or is verbose (which reports despite the catch).
984 // 3) ReThrow from v8::TryCatch: The message from a previous throw still
985 // exists and we preserve it instead of creating a new message.
986 bool requires_message = try_catch_handler() == nullptr ||
987 try_catch_handler()->is_verbose_ ||
988 try_catch_handler()->capture_message_;
989 bool rethrowing_message = thread_local_top()->rethrowing_message_;
991 thread_local_top()->rethrowing_message_ = false;
993 // Notify debugger of exception.
994 if (is_catchable_by_javascript(exception)) {
995 debug()->OnThrow(exception_handle);
998 // Generate the message if required.
999 if (requires_message && !rethrowing_message) {
1000 MessageLocation potential_computed_location;
1001 if (location == NULL) {
1002 // If no location was specified we use a computed one instead.
1003 ComputeLocation(&potential_computed_location);
1004 location = &potential_computed_location;
1007 if (bootstrapper()->IsActive()) {
1008 // It's not safe to try to make message objects or collect stack traces
1009 // while the bootstrapper is active since the infrastructure may not have
1010 // been properly initialized.
1011 ReportBootstrappingException(exception_handle, location);
1013 Handle<Object> message_obj = CreateMessage(exception_handle, location);
1014 thread_local_top()->pending_message_obj_ = *message_obj;
1016 // For any exception not caught by JavaScript, even when an external
1017 // handler is present:
1018 // If the abort-on-uncaught-exception flag is specified, and if the
1019 // embedder didn't specify a custom uncaught exception callback,
1020 // or if the custom callback determined that V8 should abort, then
1022 if (FLAG_abort_on_uncaught_exception &&
1023 PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT &&
1024 (!abort_on_uncaught_exception_callback_ ||
1025 abort_on_uncaught_exception_callback_(
1026 reinterpret_cast<v8::Isolate*>(this)))) {
1027 // Prevent endless recursion.
1028 FLAG_abort_on_uncaught_exception = false;
1029 // This flag is intended for use by JavaScript developers, so
1030 // print a user-friendly stack trace (not an internal one).
1031 PrintF(stderr, "%s\n\nFROM\n",
1032 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1033 PrintCurrentStackTrace(stderr);
1039 // Set the exception being thrown.
1040 set_pending_exception(*exception_handle);
1041 return heap()->exception();
1045 Object* Isolate::ReThrow(Object* exception) {
1046 DCHECK(!has_pending_exception());
1048 // Set the exception being re-thrown.
1049 set_pending_exception(exception);
1050 return heap()->exception();
1054 Object* Isolate::UnwindAndFindHandler() {
1055 Object* exception = pending_exception();
1057 Code* code = nullptr;
1058 Context* context = nullptr;
1059 intptr_t offset = 0;
1060 Address handler_sp = nullptr;
1061 Address handler_fp = nullptr;
1063 // Special handling of termination exceptions, uncatchable by JavaScript code,
1064 // we unwind the handlers until the top ENTRY handler is found.
1065 bool catchable_by_js = is_catchable_by_javascript(exception);
1067 // Compute handler and stack unwinding information by performing a full walk
1068 // over the stack and dispatching according to the frame type.
1069 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1070 StackFrame* frame = iter.frame();
1072 // For JSEntryStub frames we always have a handler.
1073 if (frame->is_entry() || frame->is_entry_construct()) {
1074 StackHandler* handler = frame->top_handler();
1076 // Restore the next handler.
1077 thread_local_top()->handler_ = handler->next()->address();
1079 // Gather information from the handler.
1080 code = frame->LookupCode();
1081 handler_sp = handler->address() + StackHandlerConstants::kSize;
1082 offset = Smi::cast(code->handler_table()->get(0))->value();
1086 // For optimized frames we perform a lookup in the handler table.
1087 if (frame->is_optimized() && catchable_by_js) {
1088 OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
1089 int stack_slots = 0; // Will contain stack slot count of frame.
1090 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, NULL);
1092 // Compute the stack pointer from the frame pointer. This ensures that
1093 // argument slots on the stack are dropped as returning would.
1094 Address return_sp = frame->fp() -
1095 StandardFrameConstants::kFixedFrameSizeFromFp -
1096 stack_slots * kPointerSize;
1098 // Gather information from the frame.
1099 code = frame->LookupCode();
1100 handler_sp = return_sp;
1101 handler_fp = frame->fp();
1106 // For JavaScript frames we perform a range lookup in the handler table.
1107 if (frame->is_java_script() && catchable_by_js) {
1108 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
1109 int stack_slots = 0; // Will contain operand stack depth of handler.
1110 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, NULL);
1112 // Compute the stack pointer from the frame pointer. This ensures that
1113 // operand stack slots are dropped for nested statements. Also restore
1114 // correct context for the handler which is pushed within the try-block.
1115 Address return_sp = frame->fp() -
1116 StandardFrameConstants::kFixedFrameSizeFromFp -
1117 stack_slots * kPointerSize;
1118 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1119 context = Context::cast(Memory::Object_at(return_sp - kPointerSize));
1121 // Gather information from the frame.
1122 code = frame->LookupCode();
1123 handler_sp = return_sp;
1124 handler_fp = frame->fp();
1129 RemoveMaterializedObjectsOnUnwind(frame);
1132 // Handler must exist.
1133 CHECK(code != nullptr);
1135 // Store information to be consumed by the CEntryStub.
1136 thread_local_top()->pending_handler_context_ = context;
1137 thread_local_top()->pending_handler_code_ = code;
1138 thread_local_top()->pending_handler_offset_ = offset;
1139 thread_local_top()->pending_handler_fp_ = handler_fp;
1140 thread_local_top()->pending_handler_sp_ = handler_sp;
1142 // Return and clear pending exception.
1143 clear_pending_exception();
1148 Isolate::CatchType Isolate::PredictExceptionCatcher() {
1149 Address external_handler = thread_local_top()->try_catch_handler_address();
1150 Address entry_handler = Isolate::handler(thread_local_top());
1151 if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL;
1153 // Search for an exception handler by performing a full walk over the stack.
1154 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1155 StackFrame* frame = iter.frame();
1157 // For JSEntryStub frames we update the JS_ENTRY handler.
1158 if (frame->is_entry() || frame->is_entry_construct()) {
1159 entry_handler = frame->top_handler()->next()->address();
1162 // For JavaScript frames we perform a lookup in the handler table.
1163 if (frame->is_java_script()) {
1164 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
1165 int stack_slots = 0; // The computed stack slot count is not used.
1166 HandlerTable::CatchPrediction prediction;
1167 if (js_frame->LookupExceptionHandlerInTable(&stack_slots, &prediction) >
1169 // We are conservative with our prediction: try-finally is considered
1170 // to always rethrow, to meet the expectation of the debugger.
1171 if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT;
1175 // The exception has been externally caught if and only if there is an
1176 // external handler which is on top of the top-most JS_ENTRY handler.
1177 if (external_handler != nullptr && !try_catch_handler()->is_verbose_) {
1178 if (entry_handler == nullptr || entry_handler > external_handler) {
1179 return CAUGHT_BY_EXTERNAL;
1184 // Handler not found.
1189 void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) {
1190 if (frame->is_optimized()) {
1191 bool removed = materialized_object_store_->Remove(frame->fp());
1193 // If there were any materialized objects, the code should be
1194 // marked for deopt.
1195 DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization());
1200 Object* Isolate::ThrowIllegalOperation() {
1201 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
1202 return Throw(heap()->illegal_access_string());
1206 void Isolate::ScheduleThrow(Object* exception) {
1207 // When scheduling a throw we first throw the exception to get the
1208 // error reporting if it is uncaught before rescheduling it.
1210 PropagatePendingExceptionToExternalTryCatch();
1211 if (has_pending_exception()) {
1212 thread_local_top()->scheduled_exception_ = pending_exception();
1213 thread_local_top()->external_caught_exception_ = false;
1214 clear_pending_exception();
1219 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1220 DCHECK(handler == try_catch_handler());
1221 DCHECK(handler->HasCaught());
1222 DCHECK(handler->rethrow_);
1223 DCHECK(handler->capture_message_);
1224 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
1225 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
1226 thread_local_top()->pending_message_obj_ = message;
1230 void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1231 DCHECK(has_scheduled_exception());
1232 if (scheduled_exception() == handler->exception_) {
1233 DCHECK(scheduled_exception() != heap()->termination_exception());
1234 clear_scheduled_exception();
1239 Object* Isolate::PromoteScheduledException() {
1240 Object* thrown = scheduled_exception();
1241 clear_scheduled_exception();
1242 // Re-throw the exception to avoid getting repeated error reporting.
1243 return ReThrow(thrown);
1247 void Isolate::PrintCurrentStackTrace(FILE* out) {
1248 StackTraceFrameIterator it(this);
1249 while (!it.done()) {
1250 HandleScope scope(this);
1251 // Find code position if recorded in relocation info.
1252 JavaScriptFrame* frame = it.frame();
1253 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1254 Handle<Object> pos_obj(Smi::FromInt(pos), this);
1255 // Fetch function and receiver.
1256 Handle<JSFunction> fun(frame->function());
1257 Handle<Object> recv(frame->receiver(), this);
1258 // Advance to the next JavaScript frame and determine if the
1259 // current frame is the top-level frame.
1261 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
1262 // Generate and print stack trace line.
1263 Handle<String> line =
1264 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1265 if (line->length() > 0) {
1273 void Isolate::ComputeLocation(MessageLocation* target) {
1274 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1275 StackTraceFrameIterator it(this);
1277 JavaScriptFrame* frame = it.frame();
1278 JSFunction* fun = frame->function();
1279 Object* script = fun->shared()->script();
1280 if (script->IsScript() &&
1281 !(Script::cast(script)->source()->IsUndefined())) {
1282 Handle<Script> casted_script(Script::cast(script));
1283 // Compute the location from the function and the relocation info of the
1284 // baseline code. For optimized code this will use the deoptimization
1285 // information to get canonical location information.
1286 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
1287 it.frame()->Summarize(&frames);
1288 FrameSummary& summary = frames.last();
1289 int pos = summary.code()->SourcePosition(summary.pc());
1290 *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1296 bool Isolate::ComputeLocationFromException(MessageLocation* target,
1297 Handle<Object> exception) {
1298 if (!exception->IsJSObject()) return false;
1300 Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1301 Handle<Object> start_pos = JSReceiver::GetDataProperty(
1302 Handle<JSObject>::cast(exception), start_pos_symbol);
1303 if (!start_pos->IsSmi()) return false;
1304 int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1306 Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1307 Handle<Object> end_pos = JSReceiver::GetDataProperty(
1308 Handle<JSObject>::cast(exception), end_pos_symbol);
1309 if (!end_pos->IsSmi()) return false;
1310 int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1312 Handle<Name> script_symbol = factory()->error_script_symbol();
1313 Handle<Object> script = JSReceiver::GetDataProperty(
1314 Handle<JSObject>::cast(exception), script_symbol);
1315 if (!script->IsScript()) return false;
1317 Handle<Script> cast_script(Script::cast(*script));
1318 *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1323 bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1324 Handle<Object> exception) {
1325 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1327 if (!exception->IsJSObject()) return false;
1328 Handle<Name> key = factory()->stack_trace_symbol();
1329 Handle<Object> property =
1330 JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key);
1331 if (!property->IsJSArray()) return false;
1332 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1334 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1335 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1337 for (int i = 1; i < elements_limit; i += 4) {
1338 Handle<JSFunction> fun =
1339 handle(JSFunction::cast(elements->get(i + 1)), this);
1340 if (!fun->IsSubjectToDebugging()) continue;
1342 Object* script = fun->shared()->script();
1343 if (script->IsScript() &&
1344 !(Script::cast(script)->source()->IsUndefined())) {
1345 int pos = PositionFromStackTrace(elements, i);
1346 Handle<Script> casted_script(Script::cast(script));
1347 *target = MessageLocation(casted_script, pos, pos + 1);
1355 // Traverse prototype chain to find out whether the object is derived from
1356 // the Error object.
1357 bool Isolate::IsErrorObject(Handle<Object> obj) {
1358 if (!obj->IsJSObject()) return false;
1360 Handle<String> error_key =
1361 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("$Error"));
1362 Handle<Object> error_constructor = Object::GetProperty(
1363 js_builtins_object(), error_key).ToHandleChecked();
1365 DisallowHeapAllocation no_gc;
1366 for (PrototypeIterator iter(this, *obj, PrototypeIterator::START_AT_RECEIVER);
1367 !iter.IsAtEnd(); iter.Advance()) {
1368 if (iter.GetCurrent()->IsJSProxy()) return false;
1369 if (JSObject::cast(iter.GetCurrent())->map()->GetConstructor() ==
1370 *error_constructor) {
1378 Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1379 MessageLocation* location) {
1380 Handle<JSArray> stack_trace_object;
1381 MessageLocation potential_computed_location;
1382 if (capture_stack_trace_for_uncaught_exceptions_) {
1383 if (IsErrorObject(exception)) {
1384 // We fetch the stack trace that corresponds to this error object.
1385 // If the lookup fails, the exception is probably not a valid Error
1386 // object. In that case, we fall through and capture the stack trace
1387 // at this throw site.
1388 stack_trace_object =
1389 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1391 if (stack_trace_object.is_null()) {
1392 // Not an error object, we capture stack and location at throw site.
1393 stack_trace_object = CaptureCurrentStackTrace(
1394 stack_trace_for_uncaught_exceptions_frame_limit_,
1395 stack_trace_for_uncaught_exceptions_options_);
1399 if (!ComputeLocationFromException(&potential_computed_location,
1401 if (!ComputeLocationFromStackTrace(&potential_computed_location,
1403 ComputeLocation(&potential_computed_location);
1406 location = &potential_computed_location;
1409 return MessageHandler::MakeMessageObject(
1410 this, MessageTemplate::kUncaughtException, location, exception,
1411 stack_trace_object);
1415 bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) {
1416 DCHECK_NE(heap()->the_hole_value(), exception);
1418 // For uncatchable exceptions, the JavaScript handler cannot be on top.
1419 if (!is_catchable_by_javascript(exception)) return false;
1421 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1422 Address entry_handler = Isolate::handler(thread_local_top());
1423 if (entry_handler == nullptr) return false;
1425 // Get the address of the external handler so we can compare the address to
1426 // determine which one is closer to the top of the stack.
1427 Address external_handler = thread_local_top()->try_catch_handler_address();
1428 if (external_handler == nullptr) return true;
1430 // The exception has been externally caught if and only if there is an
1431 // external handler which is on top of the top-most JS_ENTRY handler.
1433 // Note, that finally clauses would re-throw an exception unless it's aborted
1434 // by jumps in control flow (like return, break, etc.) and we'll have another
1435 // chance to set proper v8::TryCatch later.
1436 return (entry_handler < external_handler);
1440 bool Isolate::IsExternalHandlerOnTop(Object* exception) {
1441 DCHECK_NE(heap()->the_hole_value(), exception);
1443 // Get the address of the external handler so we can compare the address to
1444 // determine which one is closer to the top of the stack.
1445 Address external_handler = thread_local_top()->try_catch_handler_address();
1446 if (external_handler == nullptr) return false;
1448 // For uncatchable exceptions, the external handler is always on top.
1449 if (!is_catchable_by_javascript(exception)) return true;
1451 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1452 Address entry_handler = Isolate::handler(thread_local_top());
1453 if (entry_handler == nullptr) return true;
1455 // The exception has been externally caught if and only if there is an
1456 // external handler which is on top of the top-most JS_ENTRY handler.
1458 // Note, that finally clauses would re-throw an exception unless it's aborted
1459 // by jumps in control flow (like return, break, etc.) and we'll have another
1460 // chance to set proper v8::TryCatch later.
1461 return (entry_handler > external_handler);
1465 void Isolate::ReportPendingMessages() {
1466 Object* exception = pending_exception();
1468 // Try to propagate the exception to an external v8::TryCatch handler. If
1469 // propagation was unsuccessful, then we will get another chance at reporting
1470 // the pending message if the exception is re-thrown.
1471 bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch();
1472 if (!has_been_propagated) return;
1474 // Clear the pending message object early to avoid endless recursion.
1475 Object* message_obj = thread_local_top_.pending_message_obj_;
1476 clear_pending_message();
1478 // For uncatchable exceptions we do nothing. If needed, the exception and the
1479 // message have already been propagated to v8::TryCatch.
1480 if (!is_catchable_by_javascript(exception)) return;
1482 // Determine whether the message needs to be reported to all message handlers
1483 // depending on whether and external v8::TryCatch or an internal JavaScript
1484 // handler is on top.
1485 bool should_report_exception;
1486 if (IsExternalHandlerOnTop(exception)) {
1487 // Only report the exception if the external handler is verbose.
1488 should_report_exception = try_catch_handler()->is_verbose_;
1490 // Report the exception if it isn't caught by JavaScript code.
1491 should_report_exception = !IsJavaScriptHandlerOnTop(exception);
1494 // Actually report the pending message to all message handlers.
1495 if (!message_obj->IsTheHole() && should_report_exception) {
1496 HandleScope scope(this);
1497 Handle<JSMessageObject> message(JSMessageObject::cast(message_obj));
1498 Handle<JSValue> script_wrapper(JSValue::cast(message->script()));
1499 Handle<Script> script(Script::cast(script_wrapper->value()));
1500 int start_pos = message->start_position();
1501 int end_pos = message->end_position();
1502 MessageLocation location(script, start_pos, end_pos);
1503 MessageHandler::ReportMessage(this, &location, message);
1508 MessageLocation Isolate::GetMessageLocation() {
1509 DCHECK(has_pending_exception());
1511 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1512 !thread_local_top_.pending_message_obj_->IsTheHole()) {
1513 Handle<JSMessageObject> message_obj(
1514 JSMessageObject::cast(thread_local_top_.pending_message_obj_));
1515 Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script()));
1516 Handle<Script> script(Script::cast(script_wrapper->value()));
1517 int start_pos = message_obj->start_position();
1518 int end_pos = message_obj->end_position();
1519 return MessageLocation(script, start_pos, end_pos);
1522 return MessageLocation();
1526 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1527 DCHECK(has_pending_exception());
1528 PropagatePendingExceptionToExternalTryCatch();
1530 bool is_termination_exception =
1531 pending_exception() == heap_.termination_exception();
1533 // Do not reschedule the exception if this is the bottom call.
1534 bool clear_exception = is_bottom_call;
1536 if (is_termination_exception) {
1537 if (is_bottom_call) {
1538 thread_local_top()->external_caught_exception_ = false;
1539 clear_pending_exception();
1542 } else if (thread_local_top()->external_caught_exception_) {
1543 // If the exception is externally caught, clear it if there are no
1544 // JavaScript frames on the way to the C++ frame that has the
1545 // external handler.
1546 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1547 Address external_handler_address =
1548 thread_local_top()->try_catch_handler_address();
1549 JavaScriptFrameIterator it(this);
1550 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1551 clear_exception = true;
1555 // Clear the exception if needed.
1556 if (clear_exception) {
1557 thread_local_top()->external_caught_exception_ = false;
1558 clear_pending_exception();
1562 // Reschedule the exception.
1563 thread_local_top()->scheduled_exception_ = pending_exception();
1564 clear_pending_exception();
1569 void Isolate::PushPromise(Handle<JSObject> promise,
1570 Handle<JSFunction> function) {
1571 ThreadLocalTop* tltop = thread_local_top();
1572 PromiseOnStack* prev = tltop->promise_on_stack_;
1573 Handle<JSObject> global_promise =
1574 Handle<JSObject>::cast(global_handles()->Create(*promise));
1575 Handle<JSFunction> global_function =
1576 Handle<JSFunction>::cast(global_handles()->Create(*function));
1577 tltop->promise_on_stack_ =
1578 new PromiseOnStack(global_function, global_promise, prev);
1582 void Isolate::PopPromise() {
1583 ThreadLocalTop* tltop = thread_local_top();
1584 if (tltop->promise_on_stack_ == NULL) return;
1585 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
1586 Handle<Object> global_function = tltop->promise_on_stack_->function();
1587 Handle<Object> global_promise = tltop->promise_on_stack_->promise();
1588 delete tltop->promise_on_stack_;
1589 tltop->promise_on_stack_ = prev;
1590 global_handles()->Destroy(global_function.location());
1591 global_handles()->Destroy(global_promise.location());
1595 Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1596 Handle<Object> undefined = factory()->undefined_value();
1597 ThreadLocalTop* tltop = thread_local_top();
1598 if (tltop->promise_on_stack_ == NULL) return undefined;
1599 Handle<JSFunction> promise_function = tltop->promise_on_stack_->function();
1600 // Find the top-most try-catch or try-finally handler.
1601 if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined;
1602 for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
1603 JavaScriptFrame* frame = it.frame();
1604 int stack_slots = 0; // The computed stack slot count is not used.
1605 if (frame->LookupExceptionHandlerInTable(&stack_slots, NULL) > 0) {
1606 // Throwing inside a Promise only leads to a reject if not caught by an
1607 // inner try-catch or try-finally.
1608 if (frame->function() == *promise_function) {
1609 return tltop->promise_on_stack_->promise();
1618 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1621 StackTrace::StackTraceOptions options) {
1622 capture_stack_trace_for_uncaught_exceptions_ = capture;
1623 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1624 stack_trace_for_uncaught_exceptions_options_ = options;
1628 void Isolate::SetAbortOnUncaughtExceptionCallback(
1629 v8::Isolate::AbortOnUncaughtExceptionCallback callback) {
1630 abort_on_uncaught_exception_callback_ = callback;
1634 Handle<Context> Isolate::native_context() {
1635 return handle(context()->native_context());
1639 Handle<Context> Isolate::GetCallingNativeContext() {
1640 JavaScriptFrameIterator it(this);
1641 if (debug_->in_debug_scope()) {
1642 while (!it.done()) {
1643 JavaScriptFrame* frame = it.frame();
1644 Context* context = Context::cast(frame->context());
1645 if (context->native_context() == *debug_->debug_context()) {
1652 if (it.done()) return Handle<Context>::null();
1653 JavaScriptFrame* frame = it.frame();
1654 Context* context = Context::cast(frame->context());
1655 return Handle<Context>(context->native_context());
1659 char* Isolate::ArchiveThread(char* to) {
1660 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1661 sizeof(ThreadLocalTop));
1662 InitializeThreadLocal();
1663 clear_pending_exception();
1664 clear_pending_message();
1665 clear_scheduled_exception();
1666 return to + sizeof(ThreadLocalTop);
1670 char* Isolate::RestoreThread(char* from) {
1671 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1672 sizeof(ThreadLocalTop));
1673 // This might be just paranoia, but it seems to be needed in case a
1674 // thread_local_top_ is restored on a separate OS thread.
1675 #ifdef USE_SIMULATOR
1676 thread_local_top()->simulator_ = Simulator::current(this);
1678 DCHECK(context() == NULL || context()->IsContext());
1679 return from + sizeof(ThreadLocalTop);
1683 Isolate::ThreadDataTable::ThreadDataTable()
1688 Isolate::ThreadDataTable::~ThreadDataTable() {
1689 // TODO(svenpanne) The assertion below would fire if an embedder does not
1690 // cleanly dispose all Isolates before disposing v8, so we are conservative
1691 // and leave it out for now.
1692 // DCHECK_NULL(list_);
1696 Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1697 #if defined(USE_SIMULATOR)
1703 Isolate::PerIsolateThreadData*
1704 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1705 ThreadId thread_id) {
1706 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1707 if (data->Matches(isolate, thread_id)) return data;
1713 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1714 if (list_ != NULL) list_->prev_ = data;
1715 data->next_ = list_;
1720 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1721 if (list_ == data) list_ = data->next_;
1722 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1723 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1728 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1729 PerIsolateThreadData* data = list_;
1730 while (data != NULL) {
1731 PerIsolateThreadData* next = data->next_;
1732 if (data->isolate() == isolate) Remove(data);
1739 #define TRACE_ISOLATE(tag) \
1741 if (FLAG_trace_isolates) { \
1742 PrintF("Isolate %p (id %d)" #tag "\n", \
1743 reinterpret_cast<void*>(this), id()); \
1747 #define TRACE_ISOLATE(tag)
1751 Isolate::Isolate(bool enable_serializer)
1754 stack_trace_nesting_level_(0),
1755 incomplete_message_(NULL),
1756 bootstrapper_(NULL),
1757 runtime_profiler_(NULL),
1758 compilation_cache_(NULL),
1764 code_aging_helper_(NULL),
1765 deoptimizer_data_(NULL),
1766 materialized_object_store_(NULL),
1767 capture_stack_trace_for_uncaught_exceptions_(false),
1768 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1769 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1770 memory_allocator_(NULL),
1771 keyed_lookup_cache_(NULL),
1772 context_slot_cache_(NULL),
1773 descriptor_lookup_cache_(NULL),
1774 handle_scope_implementer_(NULL),
1775 unicode_cache_(NULL),
1776 inner_pointer_to_code_cache_(NULL),
1777 global_handles_(NULL),
1778 eternal_handles_(NULL),
1779 thread_manager_(NULL),
1780 has_installed_extensions_(false),
1781 string_tracker_(NULL),
1782 regexp_stack_(NULL),
1784 call_descriptor_data_(NULL),
1785 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1786 // be fixed once the default isolate cleanup is done.
1787 random_number_generator_(NULL),
1788 store_buffer_hash_set_1_address_(NULL),
1789 store_buffer_hash_set_2_address_(NULL),
1790 serializer_enabled_(enable_serializer),
1791 has_fatal_error_(false),
1792 initialized_from_snapshot_(false),
1793 cpu_profiler_(NULL),
1794 heap_profiler_(NULL),
1795 function_entry_hook_(NULL),
1796 deferred_handles_head_(NULL),
1797 optimizing_compile_dispatcher_(NULL),
1798 stress_deopt_count_(0),
1799 next_optimization_id_(0),
1801 next_unique_sfi_id_(0),
1803 use_counter_callback_(NULL),
1804 basic_block_profiler_(NULL),
1805 abort_on_uncaught_exception_callback_(NULL) {
1807 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1808 CHECK(thread_data_table_);
1810 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1811 TRACE_ISOLATE(constructor);
1813 memset(isolate_addresses_, 0,
1814 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1816 heap_.isolate_ = this;
1817 stack_guard_.isolate_ = this;
1819 // ThreadManager is initialized early to support locking an isolate
1820 // before it is entered.
1821 thread_manager_ = new ThreadManager();
1822 thread_manager_->isolate_ = this;
1825 // heap_histograms_ initializes itself.
1826 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1829 handle_scope_data_.Initialize();
1831 #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1832 name##_ = (initial_value);
1833 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1834 #undef ISOLATE_INIT_EXECUTE
1836 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1837 memset(name##_, 0, sizeof(type) * length);
1838 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1839 #undef ISOLATE_INIT_ARRAY_EXECUTE
1841 InitializeLoggingAndCounters();
1842 debug_ = new Debug(this);
1846 void Isolate::TearDown() {
1847 TRACE_ISOLATE(tear_down);
1849 // Temporarily set this isolate as current so that various parts of
1850 // the isolate can access it in their destructors without having a
1851 // direct pointer. We don't use Enter/Exit here to avoid
1852 // initializing the thread data.
1853 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1854 Isolate* saved_isolate = UncheckedCurrent();
1855 SetIsolateThreadLocals(this, NULL);
1860 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1861 thread_data_table_->RemoveAllThreads(this);
1866 // Restore the previous current isolate.
1867 SetIsolateThreadLocals(saved_isolate, saved_data);
1871 void Isolate::GlobalTearDown() {
1872 delete thread_data_table_;
1873 thread_data_table_ = NULL;
1877 void Isolate::ClearSerializerData() {
1878 delete external_reference_table_;
1879 external_reference_table_ = NULL;
1880 delete external_reference_map_;
1881 external_reference_map_ = NULL;
1882 delete root_index_map_;
1883 root_index_map_ = NULL;
1887 void Isolate::Deinit() {
1888 TRACE_ISOLATE(deinit);
1892 FreeThreadResources();
1894 if (concurrent_recompilation_enabled()) {
1895 optimizing_compile_dispatcher_->Stop();
1896 delete optimizing_compile_dispatcher_;
1897 optimizing_compile_dispatcher_ = NULL;
1900 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1901 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1904 DumpAndResetCompilationStats();
1906 if (FLAG_print_deopt_stress) {
1907 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1910 if (cpu_profiler_) {
1911 cpu_profiler_->DeleteAllProfiles();
1914 // We must stop the logger before we tear down other components.
1915 Sampler* sampler = logger_->sampler();
1916 if (sampler && sampler->IsActive()) sampler->Stop();
1918 delete deoptimizer_data_;
1919 deoptimizer_data_ = NULL;
1920 builtins_.TearDown();
1921 bootstrapper_->TearDown();
1923 if (runtime_profiler_ != NULL) {
1924 delete runtime_profiler_;
1925 runtime_profiler_ = NULL;
1928 delete basic_block_profiler_;
1929 basic_block_profiler_ = NULL;
1932 logger_->TearDown();
1934 delete heap_profiler_;
1935 heap_profiler_ = NULL;
1936 delete cpu_profiler_;
1937 cpu_profiler_ = NULL;
1939 ClearSerializerData();
1943 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1944 PerIsolateThreadData* data) {
1945 base::Thread::SetThreadLocal(isolate_key_, isolate);
1946 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1950 Isolate::~Isolate() {
1951 TRACE_ISOLATE(destructor);
1953 // Has to be called while counters_ are still alive
1954 runtime_zone_.DeleteKeptSegment();
1956 // The entry stack must be empty when we get here.
1957 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1959 delete entry_stack_;
1960 entry_stack_ = NULL;
1962 delete unicode_cache_;
1963 unicode_cache_ = NULL;
1968 delete[] call_descriptor_data_;
1969 call_descriptor_data_ = NULL;
1971 delete regexp_stack_;
1972 regexp_stack_ = NULL;
1974 delete descriptor_lookup_cache_;
1975 descriptor_lookup_cache_ = NULL;
1976 delete context_slot_cache_;
1977 context_slot_cache_ = NULL;
1978 delete keyed_lookup_cache_;
1979 keyed_lookup_cache_ = NULL;
1983 delete code_aging_helper_;
1984 code_aging_helper_ = NULL;
1985 delete stats_table_;
1986 stats_table_ = NULL;
1988 delete materialized_object_store_;
1989 materialized_object_store_ = NULL;
1997 delete handle_scope_implementer_;
1998 handle_scope_implementer_ = NULL;
2000 delete code_tracer();
2001 set_code_tracer(NULL);
2003 delete compilation_cache_;
2004 compilation_cache_ = NULL;
2005 delete bootstrapper_;
2006 bootstrapper_ = NULL;
2007 delete inner_pointer_to_code_cache_;
2008 inner_pointer_to_code_cache_ = NULL;
2010 delete thread_manager_;
2011 thread_manager_ = NULL;
2013 delete string_tracker_;
2014 string_tracker_ = NULL;
2016 delete memory_allocator_;
2017 memory_allocator_ = NULL;
2020 delete global_handles_;
2021 global_handles_ = NULL;
2022 delete eternal_handles_;
2023 eternal_handles_ = NULL;
2025 delete string_stream_debug_object_cache_;
2026 string_stream_debug_object_cache_ = NULL;
2028 delete random_number_generator_;
2029 random_number_generator_ = NULL;
2035 Simulator::TearDown(simulator_i_cache_, simulator_redirection_);
2036 simulator_i_cache_ = nullptr;
2037 simulator_redirection_ = nullptr;
2042 void Isolate::InitializeThreadLocal() {
2043 thread_local_top_.isolate_ = this;
2044 thread_local_top_.Initialize();
2048 bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
2049 Object* exception = pending_exception();
2051 if (IsJavaScriptHandlerOnTop(exception)) {
2052 thread_local_top_.external_caught_exception_ = false;
2056 if (!IsExternalHandlerOnTop(exception)) {
2057 thread_local_top_.external_caught_exception_ = false;
2061 thread_local_top_.external_caught_exception_ = true;
2062 if (!is_catchable_by_javascript(exception)) {
2063 try_catch_handler()->can_continue_ = false;
2064 try_catch_handler()->has_terminated_ = true;
2065 try_catch_handler()->exception_ = heap()->null_value();
2067 v8::TryCatch* handler = try_catch_handler();
2068 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2069 thread_local_top_.pending_message_obj_->IsTheHole());
2070 handler->can_continue_ = true;
2071 handler->has_terminated_ = false;
2072 handler->exception_ = pending_exception();
2073 // Propagate to the external try-catch only if we got an actual message.
2074 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
2076 handler->message_obj_ = thread_local_top_.pending_message_obj_;
2082 void Isolate::InitializeLoggingAndCounters() {
2083 if (logger_ == NULL) {
2084 logger_ = new Logger(this);
2086 if (counters_ == NULL) {
2087 counters_ = new Counters(this);
2092 bool Isolate::Init(Deserializer* des) {
2093 TRACE_ISOLATE(init);
2095 stress_deopt_count_ = FLAG_deopt_every_n_times;
2097 has_fatal_error_ = false;
2099 if (function_entry_hook() != NULL) {
2100 // When function entry hooking is in effect, we have to create the code
2101 // stubs from scratch to get entry hooks, rather than loading the previously
2102 // generated stubs from disk.
2103 // If this assert fires, the initialization path has regressed.
2104 DCHECK(des == NULL);
2107 // The initialization process does not handle memory exhaustion.
2108 DisallowAllocationFailure disallow_allocation_failure(this);
2110 memory_allocator_ = new MemoryAllocator(this);
2111 code_range_ = new CodeRange(this);
2113 // Safe after setting Heap::isolate_, and initializing StackGuard
2114 heap_.SetStackLimits();
2116 #define ASSIGN_ELEMENT(CamelName, hacker_name) \
2117 isolate_addresses_[Isolate::k##CamelName##Address] = \
2118 reinterpret_cast<Address>(hacker_name##_address());
2119 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
2120 #undef ASSIGN_ELEMENT
2122 string_tracker_ = new StringTracker();
2123 string_tracker_->isolate_ = this;
2124 compilation_cache_ = new CompilationCache(this);
2125 keyed_lookup_cache_ = new KeyedLookupCache();
2126 context_slot_cache_ = new ContextSlotCache();
2127 descriptor_lookup_cache_ = new DescriptorLookupCache();
2128 unicode_cache_ = new UnicodeCache();
2129 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
2130 global_handles_ = new GlobalHandles(this);
2131 eternal_handles_ = new EternalHandles();
2132 bootstrapper_ = new Bootstrapper(this);
2133 handle_scope_implementer_ = new HandleScopeImplementer(this);
2134 stub_cache_ = new StubCache(this);
2135 materialized_object_store_ = new MaterializedObjectStore(this);
2136 regexp_stack_ = new RegExpStack();
2137 regexp_stack_->isolate_ = this;
2138 date_cache_ = new DateCache();
2139 call_descriptor_data_ =
2140 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2141 cpu_profiler_ = new CpuProfiler(this);
2142 heap_profiler_ = new HeapProfiler(heap());
2144 // Enable logging before setting up the heap
2145 logger_->SetUp(this);
2147 // Initialize other runtime facilities
2148 #if defined(USE_SIMULATOR)
2149 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
2150 V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC
2151 Simulator::Initialize(this);
2155 code_aging_helper_ = new CodeAgingHelper();
2158 // Ensure that the thread has a valid stack guard. The v8::Locker object
2159 // will ensure this too, but we don't have to use lockers if we are only
2160 // using one thread.
2161 ExecutionAccess lock(this);
2162 stack_guard_.InitThread(lock);
2165 // SetUp the object heap.
2166 DCHECK(!heap_.HasBeenSetUp());
2167 if (!heap_.SetUp()) {
2168 V8::FatalProcessOutOfMemory("heap setup");
2172 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2174 const bool create_heap_objects = (des == NULL);
2175 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2176 V8::FatalProcessOutOfMemory("heap object creation");
2180 if (create_heap_objects) {
2181 // Terminate the cache array with the sentinel so we can iterate.
2182 partial_snapshot_cache_.Add(heap_.undefined_value());
2185 InitializeThreadLocal();
2187 bootstrapper_->Initialize(create_heap_objects);
2188 builtins_.SetUp(this, create_heap_objects);
2190 if (FLAG_log_internal_timer_events) {
2191 set_event_logger(Logger::DefaultEventLoggerSentinel);
2194 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2195 PrintF("Concurrent recompilation has been disabled for tracing.\n");
2196 } else if (OptimizingCompileDispatcher::Enabled()) {
2197 optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
2200 // Initialize runtime profiler before deserialization, because collections may
2201 // occur, clearing/updating ICs.
2202 runtime_profiler_ = new RuntimeProfiler(this);
2204 // If we are deserializing, read the state into the now-empty heap.
2205 if (!create_heap_objects) {
2206 des->Deserialize(this);
2208 stub_cache_->Initialize();
2210 // Finish initialization of ThreadLocal after deserialization is done.
2211 clear_pending_exception();
2212 clear_pending_message();
2213 clear_scheduled_exception();
2215 // Deserializing may put strange things in the root array's copy of the
2217 heap_.SetStackLimits();
2219 // Quiet the heap NaN if needed on target platform.
2220 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
2222 if (FLAG_trace_turbo) {
2223 // Create an empty file.
2224 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2227 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2228 Internals::kIsolateEmbedderDataOffset);
2229 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2230 Internals::kIsolateRootsOffset);
2231 CHECK_EQ(static_cast<int>(
2232 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2233 Internals::kAmountOfExternalAllocatedMemoryOffset);
2234 CHECK_EQ(static_cast<int>(OFFSET_OF(
2236 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2237 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2239 time_millis_at_init_ = base::OS::TimeCurrentMillis();
2241 heap_.NotifyDeserializationComplete();
2243 if (!create_heap_objects) {
2244 // Now that the heap is consistent, it's OK to generate the code for the
2245 // deopt entry table that might have been referred to by optimized code in
2247 HandleScope scope(this);
2248 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2251 kDeoptTableSerializeEntryCount - 1);
2254 if (!serializer_enabled()) {
2255 // Ensure that all stubs which need to be generated ahead of time, but
2256 // cannot be serialized into the snapshot have been generated.
2257 HandleScope scope(this);
2258 CodeStub::GenerateFPStubs(this);
2259 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2260 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2263 initialized_from_snapshot_ = (des != NULL);
2265 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2271 // Initialized lazily to allow early
2272 // v8::V8::SetAddHistogramSampleFunction calls.
2273 StatsTable* Isolate::stats_table() {
2274 if (stats_table_ == NULL) {
2275 stats_table_ = new StatsTable;
2277 return stats_table_;
2281 void Isolate::Enter() {
2282 Isolate* current_isolate = NULL;
2283 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2284 if (current_data != NULL) {
2285 current_isolate = current_data->isolate_;
2286 DCHECK(current_isolate != NULL);
2287 if (current_isolate == this) {
2288 DCHECK(Current() == this);
2289 DCHECK(entry_stack_ != NULL);
2290 DCHECK(entry_stack_->previous_thread_data == NULL ||
2291 entry_stack_->previous_thread_data->thread_id().Equals(
2292 ThreadId::Current()));
2293 // Same thread re-enters the isolate, no need to re-init anything.
2294 entry_stack_->entry_count++;
2299 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2300 DCHECK(data != NULL);
2301 DCHECK(data->isolate_ == this);
2303 EntryStackItem* item = new EntryStackItem(current_data,
2306 entry_stack_ = item;
2308 SetIsolateThreadLocals(this, data);
2310 // In case it's the first time some thread enters the isolate.
2311 set_thread_id(data->thread_id());
2315 void Isolate::Exit() {
2316 DCHECK(entry_stack_ != NULL);
2317 DCHECK(entry_stack_->previous_thread_data == NULL ||
2318 entry_stack_->previous_thread_data->thread_id().Equals(
2319 ThreadId::Current()));
2321 if (--entry_stack_->entry_count > 0) return;
2323 DCHECK(CurrentPerIsolateThreadData() != NULL);
2324 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
2327 EntryStackItem* item = entry_stack_;
2328 entry_stack_ = item->previous_item;
2330 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2331 Isolate* previous_isolate = item->previous_isolate;
2335 // Reinit the current thread for the isolate it was running before this one.
2336 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2340 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2341 deferred->next_ = deferred_handles_head_;
2342 if (deferred_handles_head_ != NULL) {
2343 deferred_handles_head_->previous_ = deferred;
2345 deferred_handles_head_ = deferred;
2349 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2351 // In debug mode assert that the linked list is well-formed.
2352 DeferredHandles* deferred_iterator = deferred;
2353 while (deferred_iterator->previous_ != NULL) {
2354 deferred_iterator = deferred_iterator->previous_;
2356 DCHECK(deferred_handles_head_ == deferred_iterator);
2358 if (deferred_handles_head_ == deferred) {
2359 deferred_handles_head_ = deferred_handles_head_->next_;
2361 if (deferred->next_ != NULL) {
2362 deferred->next_->previous_ = deferred->previous_;
2364 if (deferred->previous_ != NULL) {
2365 deferred->previous_->next_ = deferred->next_;
2370 void Isolate::DumpAndResetCompilationStats() {
2371 if (turbo_statistics() != nullptr) {
2372 OFStream os(stdout);
2373 os << *turbo_statistics() << std::endl;
2375 if (hstatistics() != nullptr) hstatistics()->Print();
2376 delete turbo_statistics_;
2377 turbo_statistics_ = nullptr;
2378 delete hstatistics_;
2379 hstatistics_ = nullptr;
2383 HStatistics* Isolate::GetHStatistics() {
2384 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2385 return hstatistics();
2389 CompilationStatistics* Isolate::GetTurboStatistics() {
2390 if (turbo_statistics() == NULL)
2391 set_turbo_statistics(new CompilationStatistics());
2392 return turbo_statistics();
2396 HTracer* Isolate::GetHTracer() {
2397 if (htracer() == NULL) set_htracer(new HTracer(id()));
2402 CodeTracer* Isolate::GetCodeTracer() {
2403 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2404 return code_tracer();
2408 Map* Isolate::get_initial_js_array_map(ElementsKind kind, Strength strength) {
2409 Context* native_context = context()->native_context();
2410 Object* maybe_map_array = is_strong(strength)
2411 ? native_context->js_array_strong_maps()
2412 : native_context->js_array_maps();
2413 if (!maybe_map_array->IsUndefined()) {
2414 Object* maybe_transitioned_map =
2415 FixedArray::cast(maybe_map_array)->get(kind);
2416 if (!maybe_transitioned_map->IsUndefined()) {
2417 return Map::cast(maybe_transitioned_map);
2424 bool Isolate::use_crankshaft() const {
2425 return FLAG_crankshaft &&
2426 !serializer_enabled_ &&
2427 CpuFeatures::SupportsCrankshaft();
2431 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2432 PropertyCell* no_elements_cell = heap()->array_protector();
2433 bool cell_reports_intact =
2434 no_elements_cell->value()->IsSmi() &&
2435 Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid;
2438 Map* root_array_map =
2439 get_initial_js_array_map(GetInitialFastElementsKind());
2440 Context* native_context = context()->native_context();
2441 JSObject* initial_array_proto = JSObject::cast(
2442 native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX));
2443 JSObject* initial_object_proto = JSObject::cast(
2444 native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX));
2446 if (root_array_map == NULL || initial_array_proto == initial_object_proto) {
2447 // We are in the bootstrapping process, and the entire check sequence
2448 // shouldn't be performed.
2449 return cell_reports_intact;
2452 // Check that the array prototype hasn't been altered WRT empty elements.
2453 if (root_array_map->prototype() != initial_array_proto) {
2454 DCHECK_EQ(false, cell_reports_intact);
2455 return cell_reports_intact;
2458 if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2459 DCHECK_EQ(false, cell_reports_intact);
2460 return cell_reports_intact;
2463 // Check that the object prototype hasn't been altered WRT empty elements.
2464 PrototypeIterator iter(this, initial_array_proto);
2465 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
2466 DCHECK_EQ(false, cell_reports_intact);
2467 return cell_reports_intact;
2469 if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2470 DCHECK_EQ(false, cell_reports_intact);
2471 return cell_reports_intact;
2475 if (!iter.IsAtEnd()) {
2476 DCHECK_EQ(false, cell_reports_intact);
2477 return cell_reports_intact;
2482 return cell_reports_intact;
2486 void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) {
2487 if (IsFastArrayConstructorPrototypeChainIntact() &&
2488 object->map()->is_prototype_map()) {
2489 Object* context = heap()->native_contexts_list();
2490 while (!context->IsUndefined()) {
2491 Context* current_context = Context::cast(context);
2492 if (current_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX) ==
2494 current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2496 PropertyCell::SetValueWithInvalidation(
2497 factory()->array_protector(),
2498 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2501 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2507 bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) {
2508 if (array->map()->is_prototype_map()) {
2509 Object* context = heap()->native_contexts_list();
2510 while (!context->IsUndefined()) {
2511 Context* current_context = Context::cast(context);
2512 if (current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2516 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2523 CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2524 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2525 return &call_descriptor_data_[index];
2529 base::RandomNumberGenerator* Isolate::random_number_generator() {
2530 if (random_number_generator_ == NULL) {
2531 if (FLAG_random_seed != 0) {
2532 random_number_generator_ =
2533 new base::RandomNumberGenerator(FLAG_random_seed);
2535 random_number_generator_ = new base::RandomNumberGenerator();
2538 return random_number_generator_;
2542 Object* Isolate::FindCodeObject(Address a) {
2543 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2548 #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2549 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2550 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2551 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2552 #undef ISOLATE_FIELD_OFFSET
2556 Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry,
2557 Handle<Map> map, const char* cname) {
2558 Handle<String> name = factory()->InternalizeUtf8String(cname);
2559 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2560 JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0,
2561 "SetupSymbolRegistry");
2562 JSObject::AddProperty(registry, name, obj, NONE);
2567 Handle<JSObject> Isolate::GetSymbolRegistry() {
2568 if (heap()->symbol_registry()->IsSmi()) {
2569 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2570 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2571 heap()->set_symbol_registry(*registry);
2573 SetUpSubregistry(registry, map, "for");
2574 SetUpSubregistry(registry, map, "for_api");
2575 SetUpSubregistry(registry, map, "keyFor");
2576 SetUpSubregistry(registry, map, "private_api");
2577 heap()->AddPrivateGlobalSymbols(
2578 SetUpSubregistry(registry, map, "private_intern"));
2580 return Handle<JSObject>::cast(factory()->symbol_registry());
2584 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2585 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2586 if (callback == call_completed_callbacks_.at(i)) return;
2588 call_completed_callbacks_.Add(callback);
2592 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2593 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2594 if (callback == call_completed_callbacks_.at(i)) {
2595 call_completed_callbacks_.Remove(i);
2601 void Isolate::FireCallCompletedCallback() {
2602 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2603 bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2604 if (!has_call_completed_callbacks && !run_microtasks) return;
2606 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2607 if (run_microtasks) RunMicrotasks();
2608 // Fire callbacks. Increase call depth to prevent recursive callbacks.
2609 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2610 reinterpret_cast<v8::Isolate*>(this));
2611 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2612 call_completed_callbacks_.at(i)();
2617 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2618 promise_reject_callback_ = callback;
2622 void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2623 Handle<Object> value,
2624 v8::PromiseRejectEvent event) {
2625 if (promise_reject_callback_ == NULL) return;
2626 Handle<JSArray> stack_trace;
2627 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2628 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2630 promise_reject_callback_(v8::PromiseRejectMessage(
2631 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2632 v8::Utils::StackTraceToLocal(stack_trace)));
2636 void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2637 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2638 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2639 int num_tasks = pending_microtask_count();
2640 DCHECK(num_tasks <= queue->length());
2641 if (num_tasks == 0) {
2642 queue = factory()->NewFixedArray(8);
2643 heap()->set_microtask_queue(*queue);
2644 } else if (num_tasks == queue->length()) {
2645 queue = FixedArray::CopySize(queue, num_tasks * 2);
2646 heap()->set_microtask_queue(*queue);
2648 DCHECK(queue->get(num_tasks)->IsUndefined());
2649 queue->set(num_tasks, *microtask);
2650 set_pending_microtask_count(num_tasks + 1);
2654 void Isolate::RunMicrotasks() {
2655 // %RunMicrotasks may be called in mjsunit tests, which violates
2656 // this assertion, hence the check for --allow-natives-syntax.
2657 // TODO(adamk): However, this also fails some layout tests.
2659 // DCHECK(FLAG_allow_natives_syntax ||
2660 // handle_scope_implementer()->CallDepthIsZero());
2662 // Increase call depth to prevent recursive callbacks.
2663 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2664 reinterpret_cast<v8::Isolate*>(this));
2666 while (pending_microtask_count() > 0) {
2667 HandleScope scope(this);
2668 int num_tasks = pending_microtask_count();
2669 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2670 DCHECK(num_tasks <= queue->length());
2671 set_pending_microtask_count(0);
2672 heap()->set_microtask_queue(heap()->empty_fixed_array());
2674 for (int i = 0; i < num_tasks; i++) {
2675 HandleScope scope(this);
2676 Handle<Object> microtask(queue->get(i), this);
2677 if (microtask->IsJSFunction()) {
2678 Handle<JSFunction> microtask_function =
2679 Handle<JSFunction>::cast(microtask);
2680 SaveContext save(this);
2681 set_context(microtask_function->context()->native_context());
2682 MaybeHandle<Object> maybe_exception;
2683 MaybeHandle<Object> result =
2684 Execution::TryCall(microtask_function, factory()->undefined_value(),
2685 0, NULL, &maybe_exception);
2686 // If execution is terminating, just bail out.
2687 Handle<Object> exception;
2688 if (result.is_null() && maybe_exception.is_null()) {
2689 // Clear out any remaining callbacks in the queue.
2690 heap()->set_microtask_queue(heap()->empty_fixed_array());
2691 set_pending_microtask_count(0);
2695 Handle<CallHandlerInfo> callback_info =
2696 Handle<CallHandlerInfo>::cast(microtask);
2697 v8::MicrotaskCallback callback =
2698 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2699 void* data = v8::ToCData<void*>(callback_info->data());
2707 void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2708 DCHECK(!use_counter_callback_);
2709 use_counter_callback_ = callback;
2713 void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
2714 // The counter callback may cause the embedder to call into V8, which is not
2715 // generally possible during GC.
2716 if (heap_.gc_state() == Heap::NOT_IN_GC) {
2717 if (use_counter_callback_) {
2718 HandleScope handle_scope(this);
2719 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2722 heap_.IncrementDeferredCount(feature);
2727 BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2728 if (basic_block_profiler_ == NULL) {
2729 basic_block_profiler_ = new BasicBlockProfiler();
2731 return basic_block_profiler_;
2735 std::string Isolate::GetTurboCfgFileName() {
2736 if (FLAG_trace_turbo_cfg_file == NULL) {
2737 std::ostringstream os;
2738 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2741 return FLAG_trace_turbo_cfg_file;
2746 // Heap::detached_contexts tracks detached contexts as pairs
2747 // (number of GC since the context was detached, the context).
2748 void Isolate::AddDetachedContext(Handle<Context> context) {
2749 HandleScope scope(this);
2750 Handle<WeakCell> cell = factory()->NewWeakCell(context);
2751 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2752 int length = detached_contexts->length();
2753 detached_contexts = FixedArray::CopySize(detached_contexts, length + 2);
2754 detached_contexts->set(length, Smi::FromInt(0));
2755 detached_contexts->set(length + 1, *cell);
2756 heap()->set_detached_contexts(*detached_contexts);
2760 void Isolate::CheckDetachedContextsAfterGC() {
2761 HandleScope scope(this);
2762 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2763 int length = detached_contexts->length();
2764 if (length == 0) return;
2766 for (int i = 0; i < length; i += 2) {
2767 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2768 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2769 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2770 if (!cell->cleared()) {
2771 detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2772 detached_contexts->set(new_length + 1, cell);
2775 counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
2777 if (FLAG_trace_detached_contexts) {
2778 PrintF("%d detached contexts are collected out of %d\n",
2779 length - new_length, length);
2780 for (int i = 0; i < new_length; i += 2) {
2781 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2782 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2783 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2784 if (mark_sweeps > 3) {
2785 PrintF("detached context 0x%p\n survived %d GCs (leak?)\n",
2786 static_cast<void*>(cell->value()), mark_sweeps);
2790 if (new_length == 0) {
2791 heap()->set_detached_contexts(heap()->empty_fixed_array());
2792 } else if (new_length < length) {
2793 heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
2794 *detached_contexts, length - new_length);
2799 bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const {
2800 StackGuard* stack_guard = isolate_->stack_guard();
2801 #ifdef USE_SIMULATOR
2802 // The simulator uses a separate JS stack.
2803 Address jssp_address = Simulator::current(isolate_)->get_sp();
2804 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
2805 if (jssp - gap < stack_guard->real_jslimit()) return true;
2806 #endif // USE_SIMULATOR
2807 return GetCurrentStackPosition() - gap < stack_guard->real_climit();
2811 SaveContext::SaveContext(Isolate* isolate)
2812 : isolate_(isolate), prev_(isolate->save_context()) {
2813 if (isolate->context() != NULL) {
2814 context_ = Handle<Context>(isolate->context());
2816 isolate->set_save_context(this);
2818 c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
2822 bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2823 // First check whether the previous scope intercepts.
2824 if (prev_ && prev_->Intercept(flag)) return true;
2825 // Then check whether this scope intercepts.
2826 if ((flag & intercept_mask_)) {
2827 intercepted_flags_ |= flag;
2833 } // namespace internal