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 // If the abort-on-uncaught-exception flag is specified, abort on any
1017 // exception not caught by JavaScript, even when an external handler is
1018 // present. This flag is intended for use by JavaScript developers, so
1019 // print a user-friendly stack trace (not an internal one).
1020 if (FLAG_abort_on_uncaught_exception &&
1021 PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) {
1022 FLAG_abort_on_uncaught_exception = false; // Prevent endless recursion.
1023 PrintF(stderr, "%s\n\nFROM\n",
1024 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1025 PrintCurrentStackTrace(stderr);
1031 // Set the exception being thrown.
1032 set_pending_exception(*exception_handle);
1033 return heap()->exception();
1037 Object* Isolate::ReThrow(Object* exception) {
1038 DCHECK(!has_pending_exception());
1040 // Set the exception being re-thrown.
1041 set_pending_exception(exception);
1042 return heap()->exception();
1046 Object* Isolate::UnwindAndFindHandler() {
1047 Object* exception = pending_exception();
1049 Code* code = nullptr;
1050 Context* context = nullptr;
1051 intptr_t offset = 0;
1052 Address handler_sp = nullptr;
1053 Address handler_fp = nullptr;
1055 // Special handling of termination exceptions, uncatchable by JavaScript code,
1056 // we unwind the handlers until the top ENTRY handler is found.
1057 bool catchable_by_js = is_catchable_by_javascript(exception);
1059 // Compute handler and stack unwinding information by performing a full walk
1060 // over the stack and dispatching according to the frame type.
1061 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1062 StackFrame* frame = iter.frame();
1064 // For JSEntryStub frames we always have a handler.
1065 if (frame->is_entry() || frame->is_entry_construct()) {
1066 StackHandler* handler = frame->top_handler();
1068 // Restore the next handler.
1069 thread_local_top()->handler_ = handler->next()->address();
1071 // Gather information from the handler.
1072 code = frame->LookupCode();
1073 handler_sp = handler->address() + StackHandlerConstants::kSize;
1074 offset = Smi::cast(code->handler_table()->get(0))->value();
1078 // For optimized frames we perform a lookup in the handler table.
1079 if (frame->is_optimized() && catchable_by_js) {
1080 OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
1081 int stack_slots = 0; // Will contain stack slot count of frame.
1082 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, NULL);
1084 // Compute the stack pointer from the frame pointer. This ensures that
1085 // argument slots on the stack are dropped as returning would.
1086 Address return_sp = frame->fp() -
1087 StandardFrameConstants::kFixedFrameSizeFromFp -
1088 stack_slots * kPointerSize;
1090 // Gather information from the frame.
1091 code = frame->LookupCode();
1092 handler_sp = return_sp;
1093 handler_fp = frame->fp();
1098 // For JavaScript frames we perform a range lookup in the handler table.
1099 if (frame->is_java_script() && catchable_by_js) {
1100 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
1101 int stack_slots = 0; // Will contain operand stack depth of handler.
1102 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, NULL);
1104 // Compute the stack pointer from the frame pointer. This ensures that
1105 // operand stack slots are dropped for nested statements. Also restore
1106 // correct context for the handler which is pushed within the try-block.
1107 Address return_sp = frame->fp() -
1108 StandardFrameConstants::kFixedFrameSizeFromFp -
1109 stack_slots * kPointerSize;
1110 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1111 context = Context::cast(Memory::Object_at(return_sp - kPointerSize));
1113 // Gather information from the frame.
1114 code = frame->LookupCode();
1115 handler_sp = return_sp;
1116 handler_fp = frame->fp();
1121 RemoveMaterializedObjectsOnUnwind(frame);
1124 // Handler must exist.
1125 CHECK(code != nullptr);
1127 // Store information to be consumed by the CEntryStub.
1128 thread_local_top()->pending_handler_context_ = context;
1129 thread_local_top()->pending_handler_code_ = code;
1130 thread_local_top()->pending_handler_offset_ = offset;
1131 thread_local_top()->pending_handler_fp_ = handler_fp;
1132 thread_local_top()->pending_handler_sp_ = handler_sp;
1134 // Return and clear pending exception.
1135 clear_pending_exception();
1140 Isolate::CatchType Isolate::PredictExceptionCatcher() {
1141 Address external_handler = thread_local_top()->try_catch_handler_address();
1142 Address entry_handler = Isolate::handler(thread_local_top());
1143 if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL;
1145 // Search for an exception handler by performing a full walk over the stack.
1146 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1147 StackFrame* frame = iter.frame();
1149 // For JSEntryStub frames we update the JS_ENTRY handler.
1150 if (frame->is_entry() || frame->is_entry_construct()) {
1151 entry_handler = frame->top_handler()->next()->address();
1154 // For JavaScript frames we perform a lookup in the handler table.
1155 if (frame->is_java_script()) {
1156 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
1157 int stack_slots = 0; // The computed stack slot count is not used.
1158 HandlerTable::CatchPrediction prediction;
1159 if (js_frame->LookupExceptionHandlerInTable(&stack_slots, &prediction) >
1161 // We are conservative with our prediction: try-finally is considered
1162 // to always rethrow, to meet the expectation of the debugger.
1163 if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT;
1167 // The exception has been externally caught if and only if there is an
1168 // external handler which is on top of the top-most JS_ENTRY handler.
1169 if (external_handler != nullptr && !try_catch_handler()->is_verbose_) {
1170 if (entry_handler == nullptr || entry_handler > external_handler) {
1171 return CAUGHT_BY_EXTERNAL;
1176 // Handler not found.
1181 void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) {
1182 if (frame->is_optimized()) {
1183 bool removed = materialized_object_store_->Remove(frame->fp());
1185 // If there were any materialized objects, the code should be
1186 // marked for deopt.
1187 DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization());
1192 Object* Isolate::ThrowIllegalOperation() {
1193 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
1194 return Throw(heap()->illegal_access_string());
1198 void Isolate::ScheduleThrow(Object* exception) {
1199 // When scheduling a throw we first throw the exception to get the
1200 // error reporting if it is uncaught before rescheduling it.
1202 PropagatePendingExceptionToExternalTryCatch();
1203 if (has_pending_exception()) {
1204 thread_local_top()->scheduled_exception_ = pending_exception();
1205 thread_local_top()->external_caught_exception_ = false;
1206 clear_pending_exception();
1211 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1212 DCHECK(handler == try_catch_handler());
1213 DCHECK(handler->HasCaught());
1214 DCHECK(handler->rethrow_);
1215 DCHECK(handler->capture_message_);
1216 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
1217 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
1218 thread_local_top()->pending_message_obj_ = message;
1222 void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1223 DCHECK(has_scheduled_exception());
1224 if (scheduled_exception() == handler->exception_) {
1225 DCHECK(scheduled_exception() != heap()->termination_exception());
1226 clear_scheduled_exception();
1231 Object* Isolate::PromoteScheduledException() {
1232 Object* thrown = scheduled_exception();
1233 clear_scheduled_exception();
1234 // Re-throw the exception to avoid getting repeated error reporting.
1235 return ReThrow(thrown);
1239 void Isolate::PrintCurrentStackTrace(FILE* out) {
1240 StackTraceFrameIterator it(this);
1241 while (!it.done()) {
1242 HandleScope scope(this);
1243 // Find code position if recorded in relocation info.
1244 JavaScriptFrame* frame = it.frame();
1245 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1246 Handle<Object> pos_obj(Smi::FromInt(pos), this);
1247 // Fetch function and receiver.
1248 Handle<JSFunction> fun(frame->function());
1249 Handle<Object> recv(frame->receiver(), this);
1250 // Advance to the next JavaScript frame and determine if the
1251 // current frame is the top-level frame.
1253 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
1254 // Generate and print stack trace line.
1255 Handle<String> line =
1256 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1257 if (line->length() > 0) {
1265 void Isolate::ComputeLocation(MessageLocation* target) {
1266 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1267 StackTraceFrameIterator it(this);
1269 JavaScriptFrame* frame = it.frame();
1270 JSFunction* fun = frame->function();
1271 Object* script = fun->shared()->script();
1272 if (script->IsScript() &&
1273 !(Script::cast(script)->source()->IsUndefined())) {
1274 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1275 // Compute the location from the function and the reloc info.
1276 Handle<Script> casted_script(Script::cast(script));
1277 *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1283 bool Isolate::ComputeLocationFromException(MessageLocation* target,
1284 Handle<Object> exception) {
1285 if (!exception->IsJSObject()) return false;
1287 Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1288 Handle<Object> start_pos = JSReceiver::GetDataProperty(
1289 Handle<JSObject>::cast(exception), start_pos_symbol);
1290 if (!start_pos->IsSmi()) return false;
1291 int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1293 Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1294 Handle<Object> end_pos = JSReceiver::GetDataProperty(
1295 Handle<JSObject>::cast(exception), end_pos_symbol);
1296 if (!end_pos->IsSmi()) return false;
1297 int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1299 Handle<Name> script_symbol = factory()->error_script_symbol();
1300 Handle<Object> script = JSReceiver::GetDataProperty(
1301 Handle<JSObject>::cast(exception), script_symbol);
1302 if (!script->IsScript()) return false;
1304 Handle<Script> cast_script(Script::cast(*script));
1305 *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1310 bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1311 Handle<Object> exception) {
1312 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1314 if (!exception->IsJSObject()) return false;
1315 Handle<Name> key = factory()->stack_trace_symbol();
1316 Handle<Object> property =
1317 JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key);
1318 if (!property->IsJSArray()) return false;
1319 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1321 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1322 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1324 for (int i = 1; i < elements_limit; i += 4) {
1325 Handle<JSFunction> fun =
1326 handle(JSFunction::cast(elements->get(i + 1)), this);
1327 if (!fun->IsSubjectToDebugging()) continue;
1329 Object* script = fun->shared()->script();
1330 if (script->IsScript() &&
1331 !(Script::cast(script)->source()->IsUndefined())) {
1332 int pos = PositionFromStackTrace(elements, i);
1333 Handle<Script> casted_script(Script::cast(script));
1334 *target = MessageLocation(casted_script, pos, pos + 1);
1342 // Traverse prototype chain to find out whether the object is derived from
1343 // the Error object.
1344 bool Isolate::IsErrorObject(Handle<Object> obj) {
1345 if (!obj->IsJSObject()) return false;
1347 Handle<String> error_key =
1348 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("$Error"));
1349 Handle<Object> error_constructor = Object::GetProperty(
1350 js_builtins_object(), error_key).ToHandleChecked();
1352 DisallowHeapAllocation no_gc;
1353 for (PrototypeIterator iter(this, *obj, PrototypeIterator::START_AT_RECEIVER);
1354 !iter.IsAtEnd(); iter.Advance()) {
1355 if (iter.GetCurrent()->IsJSProxy()) return false;
1356 if (JSObject::cast(iter.GetCurrent())->map()->GetConstructor() ==
1357 *error_constructor) {
1365 Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1366 MessageLocation* location) {
1367 Handle<JSArray> stack_trace_object;
1368 MessageLocation potential_computed_location;
1369 if (capture_stack_trace_for_uncaught_exceptions_) {
1370 if (IsErrorObject(exception)) {
1371 // We fetch the stack trace that corresponds to this error object.
1372 // If the lookup fails, the exception is probably not a valid Error
1373 // object. In that case, we fall through and capture the stack trace
1374 // at this throw site.
1375 stack_trace_object =
1376 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1378 if (stack_trace_object.is_null()) {
1379 // Not an error object, we capture stack and location at throw site.
1380 stack_trace_object = CaptureCurrentStackTrace(
1381 stack_trace_for_uncaught_exceptions_frame_limit_,
1382 stack_trace_for_uncaught_exceptions_options_);
1386 if (!ComputeLocationFromException(&potential_computed_location,
1388 if (!ComputeLocationFromStackTrace(&potential_computed_location,
1390 ComputeLocation(&potential_computed_location);
1393 location = &potential_computed_location;
1396 return MessageHandler::MakeMessageObject(
1397 this, MessageTemplate::kUncaughtException, location, exception,
1398 stack_trace_object);
1402 bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) {
1403 DCHECK_NE(heap()->the_hole_value(), exception);
1405 // For uncatchable exceptions, the JavaScript handler cannot be on top.
1406 if (!is_catchable_by_javascript(exception)) return false;
1408 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1409 Address entry_handler = Isolate::handler(thread_local_top());
1410 if (entry_handler == nullptr) return false;
1412 // Get the address of the external handler so we can compare the address to
1413 // determine which one is closer to the top of the stack.
1414 Address external_handler = thread_local_top()->try_catch_handler_address();
1415 if (external_handler == nullptr) return true;
1417 // The exception has been externally caught if and only if there is an
1418 // external handler which is on top of the top-most JS_ENTRY handler.
1420 // Note, that finally clauses would re-throw an exception unless it's aborted
1421 // by jumps in control flow (like return, break, etc.) and we'll have another
1422 // chance to set proper v8::TryCatch later.
1423 return (entry_handler < external_handler);
1427 bool Isolate::IsExternalHandlerOnTop(Object* exception) {
1428 DCHECK_NE(heap()->the_hole_value(), exception);
1430 // Get the address of the external handler so we can compare the address to
1431 // determine which one is closer to the top of the stack.
1432 Address external_handler = thread_local_top()->try_catch_handler_address();
1433 if (external_handler == nullptr) return false;
1435 // For uncatchable exceptions, the external handler is always on top.
1436 if (!is_catchable_by_javascript(exception)) return true;
1438 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1439 Address entry_handler = Isolate::handler(thread_local_top());
1440 if (entry_handler == nullptr) return true;
1442 // The exception has been externally caught if and only if there is an
1443 // external handler which is on top of the top-most JS_ENTRY handler.
1445 // Note, that finally clauses would re-throw an exception unless it's aborted
1446 // by jumps in control flow (like return, break, etc.) and we'll have another
1447 // chance to set proper v8::TryCatch later.
1448 return (entry_handler > external_handler);
1452 void Isolate::ReportPendingMessages() {
1453 Object* exception = pending_exception();
1455 // Try to propagate the exception to an external v8::TryCatch handler. If
1456 // propagation was unsuccessful, then we will get another chance at reporting
1457 // the pending message if the exception is re-thrown.
1458 bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch();
1459 if (!has_been_propagated) return;
1461 // Clear the pending message object early to avoid endless recursion.
1462 Object* message_obj = thread_local_top_.pending_message_obj_;
1463 clear_pending_message();
1465 // For uncatchable exceptions we do nothing. If needed, the exception and the
1466 // message have already been propagated to v8::TryCatch.
1467 if (!is_catchable_by_javascript(exception)) return;
1469 // Determine whether the message needs to be reported to all message handlers
1470 // depending on whether and external v8::TryCatch or an internal JavaScript
1471 // handler is on top.
1472 bool should_report_exception;
1473 if (IsExternalHandlerOnTop(exception)) {
1474 // Only report the exception if the external handler is verbose.
1475 should_report_exception = try_catch_handler()->is_verbose_;
1477 // Report the exception if it isn't caught by JavaScript code.
1478 should_report_exception = !IsJavaScriptHandlerOnTop(exception);
1481 // Actually report the pending message to all message handlers.
1482 if (!message_obj->IsTheHole() && should_report_exception) {
1483 HandleScope scope(this);
1484 Handle<JSMessageObject> message(JSMessageObject::cast(message_obj));
1485 Handle<JSValue> script_wrapper(JSValue::cast(message->script()));
1486 Handle<Script> script(Script::cast(script_wrapper->value()));
1487 int start_pos = message->start_position();
1488 int end_pos = message->end_position();
1489 MessageLocation location(script, start_pos, end_pos);
1490 MessageHandler::ReportMessage(this, &location, message);
1495 MessageLocation Isolate::GetMessageLocation() {
1496 DCHECK(has_pending_exception());
1498 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1499 !thread_local_top_.pending_message_obj_->IsTheHole()) {
1500 Handle<JSMessageObject> message_obj(
1501 JSMessageObject::cast(thread_local_top_.pending_message_obj_));
1502 Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script()));
1503 Handle<Script> script(Script::cast(script_wrapper->value()));
1504 int start_pos = message_obj->start_position();
1505 int end_pos = message_obj->end_position();
1506 return MessageLocation(script, start_pos, end_pos);
1509 return MessageLocation();
1513 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1514 DCHECK(has_pending_exception());
1515 PropagatePendingExceptionToExternalTryCatch();
1517 bool is_termination_exception =
1518 pending_exception() == heap_.termination_exception();
1520 // Do not reschedule the exception if this is the bottom call.
1521 bool clear_exception = is_bottom_call;
1523 if (is_termination_exception) {
1524 if (is_bottom_call) {
1525 thread_local_top()->external_caught_exception_ = false;
1526 clear_pending_exception();
1529 } else if (thread_local_top()->external_caught_exception_) {
1530 // If the exception is externally caught, clear it if there are no
1531 // JavaScript frames on the way to the C++ frame that has the
1532 // external handler.
1533 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1534 Address external_handler_address =
1535 thread_local_top()->try_catch_handler_address();
1536 JavaScriptFrameIterator it(this);
1537 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1538 clear_exception = true;
1542 // Clear the exception if needed.
1543 if (clear_exception) {
1544 thread_local_top()->external_caught_exception_ = false;
1545 clear_pending_exception();
1549 // Reschedule the exception.
1550 thread_local_top()->scheduled_exception_ = pending_exception();
1551 clear_pending_exception();
1556 void Isolate::PushPromise(Handle<JSObject> promise,
1557 Handle<JSFunction> function) {
1558 ThreadLocalTop* tltop = thread_local_top();
1559 PromiseOnStack* prev = tltop->promise_on_stack_;
1560 Handle<JSObject> global_promise =
1561 Handle<JSObject>::cast(global_handles()->Create(*promise));
1562 Handle<JSFunction> global_function =
1563 Handle<JSFunction>::cast(global_handles()->Create(*function));
1564 tltop->promise_on_stack_ =
1565 new PromiseOnStack(global_function, global_promise, prev);
1569 void Isolate::PopPromise() {
1570 ThreadLocalTop* tltop = thread_local_top();
1571 if (tltop->promise_on_stack_ == NULL) return;
1572 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
1573 Handle<Object> global_function = tltop->promise_on_stack_->function();
1574 Handle<Object> global_promise = tltop->promise_on_stack_->promise();
1575 delete tltop->promise_on_stack_;
1576 tltop->promise_on_stack_ = prev;
1577 global_handles()->Destroy(global_function.location());
1578 global_handles()->Destroy(global_promise.location());
1582 Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1583 Handle<Object> undefined = factory()->undefined_value();
1584 ThreadLocalTop* tltop = thread_local_top();
1585 if (tltop->promise_on_stack_ == NULL) return undefined;
1586 Handle<JSFunction> promise_function = tltop->promise_on_stack_->function();
1587 // Find the top-most try-catch or try-finally handler.
1588 if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined;
1589 for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
1590 JavaScriptFrame* frame = it.frame();
1591 int stack_slots = 0; // The computed stack slot count is not used.
1592 if (frame->LookupExceptionHandlerInTable(&stack_slots, NULL) > 0) {
1593 // Throwing inside a Promise only leads to a reject if not caught by an
1594 // inner try-catch or try-finally.
1595 if (frame->function() == *promise_function) {
1596 return tltop->promise_on_stack_->promise();
1605 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1608 StackTrace::StackTraceOptions options) {
1609 capture_stack_trace_for_uncaught_exceptions_ = capture;
1610 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1611 stack_trace_for_uncaught_exceptions_options_ = options;
1615 Handle<Context> Isolate::native_context() {
1616 return handle(context()->native_context());
1620 Handle<Context> Isolate::GetCallingNativeContext() {
1621 JavaScriptFrameIterator it(this);
1622 if (debug_->in_debug_scope()) {
1623 while (!it.done()) {
1624 JavaScriptFrame* frame = it.frame();
1625 Context* context = Context::cast(frame->context());
1626 if (context->native_context() == *debug_->debug_context()) {
1633 if (it.done()) return Handle<Context>::null();
1634 JavaScriptFrame* frame = it.frame();
1635 Context* context = Context::cast(frame->context());
1636 return Handle<Context>(context->native_context());
1640 char* Isolate::ArchiveThread(char* to) {
1641 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1642 sizeof(ThreadLocalTop));
1643 InitializeThreadLocal();
1644 clear_pending_exception();
1645 clear_pending_message();
1646 clear_scheduled_exception();
1647 return to + sizeof(ThreadLocalTop);
1651 char* Isolate::RestoreThread(char* from) {
1652 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1653 sizeof(ThreadLocalTop));
1654 // This might be just paranoia, but it seems to be needed in case a
1655 // thread_local_top_ is restored on a separate OS thread.
1656 #ifdef USE_SIMULATOR
1657 thread_local_top()->simulator_ = Simulator::current(this);
1659 DCHECK(context() == NULL || context()->IsContext());
1660 return from + sizeof(ThreadLocalTop);
1664 Isolate::ThreadDataTable::ThreadDataTable()
1669 Isolate::ThreadDataTable::~ThreadDataTable() {
1670 // TODO(svenpanne) The assertion below would fire if an embedder does not
1671 // cleanly dispose all Isolates before disposing v8, so we are conservative
1672 // and leave it out for now.
1673 // DCHECK_NULL(list_);
1677 Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1678 #if defined(USE_SIMULATOR)
1684 Isolate::PerIsolateThreadData*
1685 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1686 ThreadId thread_id) {
1687 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1688 if (data->Matches(isolate, thread_id)) return data;
1694 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1695 if (list_ != NULL) list_->prev_ = data;
1696 data->next_ = list_;
1701 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1702 if (list_ == data) list_ = data->next_;
1703 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1704 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1709 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1710 PerIsolateThreadData* data = list_;
1711 while (data != NULL) {
1712 PerIsolateThreadData* next = data->next_;
1713 if (data->isolate() == isolate) Remove(data);
1720 #define TRACE_ISOLATE(tag) \
1722 if (FLAG_trace_isolates) { \
1723 PrintF("Isolate %p (id %d)" #tag "\n", \
1724 reinterpret_cast<void*>(this), id()); \
1728 #define TRACE_ISOLATE(tag)
1732 Isolate::Isolate(bool enable_serializer)
1735 stack_trace_nesting_level_(0),
1736 incomplete_message_(NULL),
1737 bootstrapper_(NULL),
1738 runtime_profiler_(NULL),
1739 compilation_cache_(NULL),
1745 code_aging_helper_(NULL),
1746 deoptimizer_data_(NULL),
1747 materialized_object_store_(NULL),
1748 capture_stack_trace_for_uncaught_exceptions_(false),
1749 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1750 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1751 memory_allocator_(NULL),
1752 keyed_lookup_cache_(NULL),
1753 context_slot_cache_(NULL),
1754 descriptor_lookup_cache_(NULL),
1755 handle_scope_implementer_(NULL),
1756 unicode_cache_(NULL),
1757 inner_pointer_to_code_cache_(NULL),
1758 global_handles_(NULL),
1759 eternal_handles_(NULL),
1760 thread_manager_(NULL),
1761 has_installed_extensions_(false),
1762 string_tracker_(NULL),
1763 regexp_stack_(NULL),
1765 call_descriptor_data_(NULL),
1766 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1767 // be fixed once the default isolate cleanup is done.
1768 random_number_generator_(NULL),
1769 store_buffer_hash_set_1_address_(NULL),
1770 store_buffer_hash_set_2_address_(NULL),
1771 serializer_enabled_(enable_serializer),
1772 has_fatal_error_(false),
1773 initialized_from_snapshot_(false),
1774 cpu_profiler_(NULL),
1775 heap_profiler_(NULL),
1776 function_entry_hook_(NULL),
1777 deferred_handles_head_(NULL),
1778 optimizing_compile_dispatcher_(NULL),
1779 stress_deopt_count_(0),
1780 next_optimization_id_(0),
1782 next_unique_sfi_id_(0),
1784 use_counter_callback_(NULL),
1785 basic_block_profiler_(NULL) {
1787 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1788 CHECK(thread_data_table_);
1790 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1791 TRACE_ISOLATE(constructor);
1793 memset(isolate_addresses_, 0,
1794 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1796 heap_.isolate_ = this;
1797 stack_guard_.isolate_ = this;
1799 // ThreadManager is initialized early to support locking an isolate
1800 // before it is entered.
1801 thread_manager_ = new ThreadManager();
1802 thread_manager_->isolate_ = this;
1805 // heap_histograms_ initializes itself.
1806 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1809 handle_scope_data_.Initialize();
1811 #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1812 name##_ = (initial_value);
1813 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1814 #undef ISOLATE_INIT_EXECUTE
1816 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1817 memset(name##_, 0, sizeof(type) * length);
1818 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1819 #undef ISOLATE_INIT_ARRAY_EXECUTE
1821 InitializeLoggingAndCounters();
1822 debug_ = new Debug(this);
1826 void Isolate::TearDown() {
1827 TRACE_ISOLATE(tear_down);
1829 // Temporarily set this isolate as current so that various parts of
1830 // the isolate can access it in their destructors without having a
1831 // direct pointer. We don't use Enter/Exit here to avoid
1832 // initializing the thread data.
1833 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1834 Isolate* saved_isolate = UncheckedCurrent();
1835 SetIsolateThreadLocals(this, NULL);
1840 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1841 thread_data_table_->RemoveAllThreads(this);
1846 // Restore the previous current isolate.
1847 SetIsolateThreadLocals(saved_isolate, saved_data);
1851 void Isolate::GlobalTearDown() {
1852 delete thread_data_table_;
1853 thread_data_table_ = NULL;
1857 void Isolate::ClearSerializerData() {
1858 delete external_reference_table_;
1859 external_reference_table_ = NULL;
1860 delete external_reference_map_;
1861 external_reference_map_ = NULL;
1862 delete root_index_map_;
1863 root_index_map_ = NULL;
1867 void Isolate::Deinit() {
1868 TRACE_ISOLATE(deinit);
1872 FreeThreadResources();
1874 if (concurrent_recompilation_enabled()) {
1875 optimizing_compile_dispatcher_->Stop();
1876 delete optimizing_compile_dispatcher_;
1877 optimizing_compile_dispatcher_ = NULL;
1880 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1881 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1884 DumpAndResetCompilationStats();
1886 if (FLAG_print_deopt_stress) {
1887 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1890 // We must stop the logger before we tear down other components.
1891 Sampler* sampler = logger_->sampler();
1892 if (sampler && sampler->IsActive()) sampler->Stop();
1894 delete deoptimizer_data_;
1895 deoptimizer_data_ = NULL;
1896 builtins_.TearDown();
1897 bootstrapper_->TearDown();
1899 if (runtime_profiler_ != NULL) {
1900 delete runtime_profiler_;
1901 runtime_profiler_ = NULL;
1904 delete basic_block_profiler_;
1905 basic_block_profiler_ = NULL;
1908 logger_->TearDown();
1910 delete heap_profiler_;
1911 heap_profiler_ = NULL;
1912 delete cpu_profiler_;
1913 cpu_profiler_ = NULL;
1915 ClearSerializerData();
1919 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1920 PerIsolateThreadData* data) {
1921 base::Thread::SetThreadLocal(isolate_key_, isolate);
1922 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1926 Isolate::~Isolate() {
1927 TRACE_ISOLATE(destructor);
1929 // Has to be called while counters_ are still alive
1930 runtime_zone_.DeleteKeptSegment();
1932 // The entry stack must be empty when we get here.
1933 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1935 delete entry_stack_;
1936 entry_stack_ = NULL;
1938 delete unicode_cache_;
1939 unicode_cache_ = NULL;
1944 delete[] call_descriptor_data_;
1945 call_descriptor_data_ = NULL;
1947 delete regexp_stack_;
1948 regexp_stack_ = NULL;
1950 delete descriptor_lookup_cache_;
1951 descriptor_lookup_cache_ = NULL;
1952 delete context_slot_cache_;
1953 context_slot_cache_ = NULL;
1954 delete keyed_lookup_cache_;
1955 keyed_lookup_cache_ = NULL;
1959 delete code_aging_helper_;
1960 code_aging_helper_ = NULL;
1961 delete stats_table_;
1962 stats_table_ = NULL;
1964 delete materialized_object_store_;
1965 materialized_object_store_ = NULL;
1973 delete handle_scope_implementer_;
1974 handle_scope_implementer_ = NULL;
1976 delete code_tracer();
1977 set_code_tracer(NULL);
1979 delete compilation_cache_;
1980 compilation_cache_ = NULL;
1981 delete bootstrapper_;
1982 bootstrapper_ = NULL;
1983 delete inner_pointer_to_code_cache_;
1984 inner_pointer_to_code_cache_ = NULL;
1986 delete thread_manager_;
1987 thread_manager_ = NULL;
1989 delete string_tracker_;
1990 string_tracker_ = NULL;
1992 delete memory_allocator_;
1993 memory_allocator_ = NULL;
1996 delete global_handles_;
1997 global_handles_ = NULL;
1998 delete eternal_handles_;
1999 eternal_handles_ = NULL;
2001 delete string_stream_debug_object_cache_;
2002 string_stream_debug_object_cache_ = NULL;
2004 delete random_number_generator_;
2005 random_number_generator_ = NULL;
2011 Simulator::TearDown(simulator_i_cache_, simulator_redirection_);
2012 simulator_i_cache_ = nullptr;
2013 simulator_redirection_ = nullptr;
2018 void Isolate::InitializeThreadLocal() {
2019 thread_local_top_.isolate_ = this;
2020 thread_local_top_.Initialize();
2024 bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
2025 Object* exception = pending_exception();
2027 if (IsJavaScriptHandlerOnTop(exception)) {
2028 thread_local_top_.external_caught_exception_ = false;
2032 if (!IsExternalHandlerOnTop(exception)) {
2033 thread_local_top_.external_caught_exception_ = false;
2037 thread_local_top_.external_caught_exception_ = true;
2038 if (!is_catchable_by_javascript(exception)) {
2039 try_catch_handler()->can_continue_ = false;
2040 try_catch_handler()->has_terminated_ = true;
2041 try_catch_handler()->exception_ = heap()->null_value();
2043 v8::TryCatch* handler = try_catch_handler();
2044 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2045 thread_local_top_.pending_message_obj_->IsTheHole());
2046 handler->can_continue_ = true;
2047 handler->has_terminated_ = false;
2048 handler->exception_ = pending_exception();
2049 // Propagate to the external try-catch only if we got an actual message.
2050 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
2052 handler->message_obj_ = thread_local_top_.pending_message_obj_;
2058 void Isolate::InitializeLoggingAndCounters() {
2059 if (logger_ == NULL) {
2060 logger_ = new Logger(this);
2062 if (counters_ == NULL) {
2063 counters_ = new Counters(this);
2068 bool Isolate::Init(Deserializer* des) {
2069 TRACE_ISOLATE(init);
2071 stress_deopt_count_ = FLAG_deopt_every_n_times;
2073 has_fatal_error_ = false;
2075 if (function_entry_hook() != NULL) {
2076 // When function entry hooking is in effect, we have to create the code
2077 // stubs from scratch to get entry hooks, rather than loading the previously
2078 // generated stubs from disk.
2079 // If this assert fires, the initialization path has regressed.
2080 DCHECK(des == NULL);
2083 // The initialization process does not handle memory exhaustion.
2084 DisallowAllocationFailure disallow_allocation_failure(this);
2086 memory_allocator_ = new MemoryAllocator(this);
2087 code_range_ = new CodeRange(this);
2089 // Safe after setting Heap::isolate_, and initializing StackGuard
2090 heap_.SetStackLimits();
2092 #define ASSIGN_ELEMENT(CamelName, hacker_name) \
2093 isolate_addresses_[Isolate::k##CamelName##Address] = \
2094 reinterpret_cast<Address>(hacker_name##_address());
2095 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
2096 #undef ASSIGN_ELEMENT
2098 string_tracker_ = new StringTracker();
2099 string_tracker_->isolate_ = this;
2100 compilation_cache_ = new CompilationCache(this);
2101 keyed_lookup_cache_ = new KeyedLookupCache();
2102 context_slot_cache_ = new ContextSlotCache();
2103 descriptor_lookup_cache_ = new DescriptorLookupCache();
2104 unicode_cache_ = new UnicodeCache();
2105 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
2106 global_handles_ = new GlobalHandles(this);
2107 eternal_handles_ = new EternalHandles();
2108 bootstrapper_ = new Bootstrapper(this);
2109 handle_scope_implementer_ = new HandleScopeImplementer(this);
2110 stub_cache_ = new StubCache(this);
2111 materialized_object_store_ = new MaterializedObjectStore(this);
2112 regexp_stack_ = new RegExpStack();
2113 regexp_stack_->isolate_ = this;
2114 date_cache_ = new DateCache();
2115 call_descriptor_data_ =
2116 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2117 cpu_profiler_ = new CpuProfiler(this);
2118 heap_profiler_ = new HeapProfiler(heap());
2120 // Enable logging before setting up the heap
2121 logger_->SetUp(this);
2123 // Initialize other runtime facilities
2124 #if defined(USE_SIMULATOR)
2125 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
2126 V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC
2127 Simulator::Initialize(this);
2131 code_aging_helper_ = new CodeAgingHelper();
2134 // Ensure that the thread has a valid stack guard. The v8::Locker object
2135 // will ensure this too, but we don't have to use lockers if we are only
2136 // using one thread.
2137 ExecutionAccess lock(this);
2138 stack_guard_.InitThread(lock);
2141 // SetUp the object heap.
2142 DCHECK(!heap_.HasBeenSetUp());
2143 if (!heap_.SetUp()) {
2144 V8::FatalProcessOutOfMemory("heap setup");
2148 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2150 const bool create_heap_objects = (des == NULL);
2151 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2152 V8::FatalProcessOutOfMemory("heap object creation");
2156 if (create_heap_objects) {
2157 // Terminate the cache array with the sentinel so we can iterate.
2158 partial_snapshot_cache_.Add(heap_.undefined_value());
2161 InitializeThreadLocal();
2163 bootstrapper_->Initialize(create_heap_objects);
2164 builtins_.SetUp(this, create_heap_objects);
2166 if (FLAG_log_internal_timer_events) {
2167 set_event_logger(Logger::DefaultEventLoggerSentinel);
2170 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2171 PrintF("Concurrent recompilation has been disabled for tracing.\n");
2172 } else if (OptimizingCompileDispatcher::Enabled()) {
2173 optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
2176 // Initialize runtime profiler before deserialization, because collections may
2177 // occur, clearing/updating ICs.
2178 runtime_profiler_ = new RuntimeProfiler(this);
2180 // If we are deserializing, read the state into the now-empty heap.
2181 if (!create_heap_objects) {
2182 des->Deserialize(this);
2184 stub_cache_->Initialize();
2186 // Finish initialization of ThreadLocal after deserialization is done.
2187 clear_pending_exception();
2188 clear_pending_message();
2189 clear_scheduled_exception();
2191 // Deserializing may put strange things in the root array's copy of the
2193 heap_.SetStackLimits();
2195 // Quiet the heap NaN if needed on target platform.
2196 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
2198 if (FLAG_trace_turbo) {
2199 // Create an empty file.
2200 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2203 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2204 Internals::kIsolateEmbedderDataOffset);
2205 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2206 Internals::kIsolateRootsOffset);
2207 CHECK_EQ(static_cast<int>(
2208 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2209 Internals::kAmountOfExternalAllocatedMemoryOffset);
2210 CHECK_EQ(static_cast<int>(OFFSET_OF(
2212 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2213 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2215 time_millis_at_init_ = base::OS::TimeCurrentMillis();
2217 heap_.NotifyDeserializationComplete();
2219 if (!create_heap_objects) {
2220 // Now that the heap is consistent, it's OK to generate the code for the
2221 // deopt entry table that might have been referred to by optimized code in
2223 HandleScope scope(this);
2224 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2227 kDeoptTableSerializeEntryCount - 1);
2230 if (!serializer_enabled()) {
2231 // Ensure that all stubs which need to be generated ahead of time, but
2232 // cannot be serialized into the snapshot have been generated.
2233 HandleScope scope(this);
2234 CodeStub::GenerateFPStubs(this);
2235 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2236 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2239 initialized_from_snapshot_ = (des != NULL);
2241 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2247 // Initialized lazily to allow early
2248 // v8::V8::SetAddHistogramSampleFunction calls.
2249 StatsTable* Isolate::stats_table() {
2250 if (stats_table_ == NULL) {
2251 stats_table_ = new StatsTable;
2253 return stats_table_;
2257 void Isolate::Enter() {
2258 Isolate* current_isolate = NULL;
2259 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2260 if (current_data != NULL) {
2261 current_isolate = current_data->isolate_;
2262 DCHECK(current_isolate != NULL);
2263 if (current_isolate == this) {
2264 DCHECK(Current() == this);
2265 DCHECK(entry_stack_ != NULL);
2266 DCHECK(entry_stack_->previous_thread_data == NULL ||
2267 entry_stack_->previous_thread_data->thread_id().Equals(
2268 ThreadId::Current()));
2269 // Same thread re-enters the isolate, no need to re-init anything.
2270 entry_stack_->entry_count++;
2275 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2276 DCHECK(data != NULL);
2277 DCHECK(data->isolate_ == this);
2279 EntryStackItem* item = new EntryStackItem(current_data,
2282 entry_stack_ = item;
2284 SetIsolateThreadLocals(this, data);
2286 // In case it's the first time some thread enters the isolate.
2287 set_thread_id(data->thread_id());
2291 void Isolate::Exit() {
2292 DCHECK(entry_stack_ != NULL);
2293 DCHECK(entry_stack_->previous_thread_data == NULL ||
2294 entry_stack_->previous_thread_data->thread_id().Equals(
2295 ThreadId::Current()));
2297 if (--entry_stack_->entry_count > 0) return;
2299 DCHECK(CurrentPerIsolateThreadData() != NULL);
2300 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
2303 EntryStackItem* item = entry_stack_;
2304 entry_stack_ = item->previous_item;
2306 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2307 Isolate* previous_isolate = item->previous_isolate;
2311 // Reinit the current thread for the isolate it was running before this one.
2312 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2316 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2317 deferred->next_ = deferred_handles_head_;
2318 if (deferred_handles_head_ != NULL) {
2319 deferred_handles_head_->previous_ = deferred;
2321 deferred_handles_head_ = deferred;
2325 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2327 // In debug mode assert that the linked list is well-formed.
2328 DeferredHandles* deferred_iterator = deferred;
2329 while (deferred_iterator->previous_ != NULL) {
2330 deferred_iterator = deferred_iterator->previous_;
2332 DCHECK(deferred_handles_head_ == deferred_iterator);
2334 if (deferred_handles_head_ == deferred) {
2335 deferred_handles_head_ = deferred_handles_head_->next_;
2337 if (deferred->next_ != NULL) {
2338 deferred->next_->previous_ = deferred->previous_;
2340 if (deferred->previous_ != NULL) {
2341 deferred->previous_->next_ = deferred->next_;
2346 void Isolate::DumpAndResetCompilationStats() {
2347 if (turbo_statistics() != nullptr) {
2348 OFStream os(stdout);
2349 os << *turbo_statistics() << std::endl;
2351 if (hstatistics() != nullptr) hstatistics()->Print();
2352 delete turbo_statistics_;
2353 turbo_statistics_ = nullptr;
2354 delete hstatistics_;
2355 hstatistics_ = nullptr;
2359 HStatistics* Isolate::GetHStatistics() {
2360 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2361 return hstatistics();
2365 CompilationStatistics* Isolate::GetTurboStatistics() {
2366 if (turbo_statistics() == NULL)
2367 set_turbo_statistics(new CompilationStatistics());
2368 return turbo_statistics();
2372 HTracer* Isolate::GetHTracer() {
2373 if (htracer() == NULL) set_htracer(new HTracer(id()));
2378 CodeTracer* Isolate::GetCodeTracer() {
2379 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2380 return code_tracer();
2384 Map* Isolate::get_initial_js_array_map(ElementsKind kind, Strength strength) {
2385 Context* native_context = context()->native_context();
2386 Object* maybe_map_array = is_strong(strength)
2387 ? native_context->js_array_strong_maps()
2388 : native_context->js_array_maps();
2389 if (!maybe_map_array->IsUndefined()) {
2390 Object* maybe_transitioned_map =
2391 FixedArray::cast(maybe_map_array)->get(kind);
2392 if (!maybe_transitioned_map->IsUndefined()) {
2393 return Map::cast(maybe_transitioned_map);
2400 bool Isolate::use_crankshaft() const {
2401 return FLAG_crankshaft &&
2402 !serializer_enabled_ &&
2403 CpuFeatures::SupportsCrankshaft();
2407 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2408 PropertyCell* no_elements_cell = heap()->array_protector();
2409 bool cell_reports_intact =
2410 no_elements_cell->value()->IsSmi() &&
2411 Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid;
2414 Map* root_array_map =
2415 get_initial_js_array_map(GetInitialFastElementsKind());
2416 Context* native_context = context()->native_context();
2417 JSObject* initial_array_proto = JSObject::cast(
2418 native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX));
2419 JSObject* initial_object_proto = JSObject::cast(
2420 native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX));
2422 if (root_array_map == NULL || initial_array_proto == initial_object_proto) {
2423 // We are in the bootstrapping process, and the entire check sequence
2424 // shouldn't be performed.
2425 return cell_reports_intact;
2428 // Check that the array prototype hasn't been altered WRT empty elements.
2429 if (root_array_map->prototype() != initial_array_proto) {
2430 DCHECK_EQ(false, cell_reports_intact);
2431 return cell_reports_intact;
2434 if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2435 DCHECK_EQ(false, cell_reports_intact);
2436 return cell_reports_intact;
2439 // Check that the object prototype hasn't been altered WRT empty elements.
2440 PrototypeIterator iter(this, initial_array_proto);
2441 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
2442 DCHECK_EQ(false, cell_reports_intact);
2443 return cell_reports_intact;
2445 if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2446 DCHECK_EQ(false, cell_reports_intact);
2447 return cell_reports_intact;
2451 if (!iter.IsAtEnd()) {
2452 DCHECK_EQ(false, cell_reports_intact);
2453 return cell_reports_intact;
2458 return cell_reports_intact;
2462 void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) {
2463 if (IsFastArrayConstructorPrototypeChainIntact() &&
2464 object->map()->is_prototype_map()) {
2465 Object* context = heap()->native_contexts_list();
2466 while (!context->IsUndefined()) {
2467 Context* current_context = Context::cast(context);
2468 if (current_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX) ==
2470 current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2472 PropertyCell::SetValueWithInvalidation(
2473 factory()->array_protector(),
2474 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2477 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2483 bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) {
2484 if (array->map()->is_prototype_map()) {
2485 Object* context = heap()->native_contexts_list();
2486 while (!context->IsUndefined()) {
2487 Context* current_context = Context::cast(context);
2488 if (current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2492 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2499 CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2500 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2501 return &call_descriptor_data_[index];
2505 base::RandomNumberGenerator* Isolate::random_number_generator() {
2506 if (random_number_generator_ == NULL) {
2507 if (FLAG_random_seed != 0) {
2508 random_number_generator_ =
2509 new base::RandomNumberGenerator(FLAG_random_seed);
2511 random_number_generator_ = new base::RandomNumberGenerator();
2514 return random_number_generator_;
2518 Object* Isolate::FindCodeObject(Address a) {
2519 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2524 #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2525 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2526 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2527 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2528 #undef ISOLATE_FIELD_OFFSET
2532 Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry,
2533 Handle<Map> map, const char* cname) {
2534 Handle<String> name = factory()->InternalizeUtf8String(cname);
2535 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2536 JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0,
2537 "SetupSymbolRegistry");
2538 JSObject::AddProperty(registry, name, obj, NONE);
2543 Handle<JSObject> Isolate::GetSymbolRegistry() {
2544 if (heap()->symbol_registry()->IsSmi()) {
2545 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2546 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2547 heap()->set_symbol_registry(*registry);
2549 SetUpSubregistry(registry, map, "for");
2550 SetUpSubregistry(registry, map, "for_api");
2551 SetUpSubregistry(registry, map, "keyFor");
2552 SetUpSubregistry(registry, map, "private_api");
2553 heap()->AddPrivateGlobalSymbols(
2554 SetUpSubregistry(registry, map, "private_intern"));
2556 return Handle<JSObject>::cast(factory()->symbol_registry());
2560 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2561 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2562 if (callback == call_completed_callbacks_.at(i)) return;
2564 call_completed_callbacks_.Add(callback);
2568 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2569 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2570 if (callback == call_completed_callbacks_.at(i)) {
2571 call_completed_callbacks_.Remove(i);
2577 void Isolate::FireCallCompletedCallback() {
2578 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2579 bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2580 if (!has_call_completed_callbacks && !run_microtasks) return;
2582 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2583 if (run_microtasks) RunMicrotasks();
2584 // Fire callbacks. Increase call depth to prevent recursive callbacks.
2585 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2586 reinterpret_cast<v8::Isolate*>(this));
2587 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2588 call_completed_callbacks_.at(i)();
2593 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2594 promise_reject_callback_ = callback;
2598 void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2599 Handle<Object> value,
2600 v8::PromiseRejectEvent event) {
2601 if (promise_reject_callback_ == NULL) return;
2602 Handle<JSArray> stack_trace;
2603 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2604 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2606 promise_reject_callback_(v8::PromiseRejectMessage(
2607 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2608 v8::Utils::StackTraceToLocal(stack_trace)));
2612 void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2613 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2614 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2615 int num_tasks = pending_microtask_count();
2616 DCHECK(num_tasks <= queue->length());
2617 if (num_tasks == 0) {
2618 queue = factory()->NewFixedArray(8);
2619 heap()->set_microtask_queue(*queue);
2620 } else if (num_tasks == queue->length()) {
2621 queue = FixedArray::CopySize(queue, num_tasks * 2);
2622 heap()->set_microtask_queue(*queue);
2624 DCHECK(queue->get(num_tasks)->IsUndefined());
2625 queue->set(num_tasks, *microtask);
2626 set_pending_microtask_count(num_tasks + 1);
2630 void Isolate::RunMicrotasks() {
2631 // %RunMicrotasks may be called in mjsunit tests, which violates
2632 // this assertion, hence the check for --allow-natives-syntax.
2633 // TODO(adamk): However, this also fails some layout tests.
2635 // DCHECK(FLAG_allow_natives_syntax ||
2636 // handle_scope_implementer()->CallDepthIsZero());
2638 // Increase call depth to prevent recursive callbacks.
2639 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2640 reinterpret_cast<v8::Isolate*>(this));
2642 while (pending_microtask_count() > 0) {
2643 HandleScope scope(this);
2644 int num_tasks = pending_microtask_count();
2645 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2646 DCHECK(num_tasks <= queue->length());
2647 set_pending_microtask_count(0);
2648 heap()->set_microtask_queue(heap()->empty_fixed_array());
2650 for (int i = 0; i < num_tasks; i++) {
2651 HandleScope scope(this);
2652 Handle<Object> microtask(queue->get(i), this);
2653 if (microtask->IsJSFunction()) {
2654 Handle<JSFunction> microtask_function =
2655 Handle<JSFunction>::cast(microtask);
2656 SaveContext save(this);
2657 set_context(microtask_function->context()->native_context());
2658 MaybeHandle<Object> maybe_exception;
2659 MaybeHandle<Object> result =
2660 Execution::TryCall(microtask_function, factory()->undefined_value(),
2661 0, NULL, &maybe_exception);
2662 // If execution is terminating, just bail out.
2663 Handle<Object> exception;
2664 if (result.is_null() && maybe_exception.is_null()) {
2665 // Clear out any remaining callbacks in the queue.
2666 heap()->set_microtask_queue(heap()->empty_fixed_array());
2667 set_pending_microtask_count(0);
2671 Handle<CallHandlerInfo> callback_info =
2672 Handle<CallHandlerInfo>::cast(microtask);
2673 v8::MicrotaskCallback callback =
2674 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2675 void* data = v8::ToCData<void*>(callback_info->data());
2683 void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2684 DCHECK(!use_counter_callback_);
2685 use_counter_callback_ = callback;
2689 void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
2690 // The counter callback may cause the embedder to call into V8, which is not
2691 // generally possible during GC.
2692 if (heap_.gc_state() == Heap::NOT_IN_GC) {
2693 if (use_counter_callback_) {
2694 HandleScope handle_scope(this);
2695 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2698 heap_.IncrementDeferredCount(feature);
2703 BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2704 if (basic_block_profiler_ == NULL) {
2705 basic_block_profiler_ = new BasicBlockProfiler();
2707 return basic_block_profiler_;
2711 std::string Isolate::GetTurboCfgFileName() {
2712 if (FLAG_trace_turbo_cfg_file == NULL) {
2713 std::ostringstream os;
2714 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2717 return FLAG_trace_turbo_cfg_file;
2722 // Heap::detached_contexts tracks detached contexts as pairs
2723 // (number of GC since the context was detached, the context).
2724 void Isolate::AddDetachedContext(Handle<Context> context) {
2725 HandleScope scope(this);
2726 Handle<WeakCell> cell = factory()->NewWeakCell(context);
2727 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2728 int length = detached_contexts->length();
2729 detached_contexts = FixedArray::CopySize(detached_contexts, length + 2);
2730 detached_contexts->set(length, Smi::FromInt(0));
2731 detached_contexts->set(length + 1, *cell);
2732 heap()->set_detached_contexts(*detached_contexts);
2736 void Isolate::CheckDetachedContextsAfterGC() {
2737 HandleScope scope(this);
2738 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2739 int length = detached_contexts->length();
2740 if (length == 0) return;
2742 for (int i = 0; i < length; i += 2) {
2743 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2744 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2745 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2746 if (!cell->cleared()) {
2747 detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2748 detached_contexts->set(new_length + 1, cell);
2751 counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
2753 if (FLAG_trace_detached_contexts) {
2754 PrintF("%d detached contexts are collected out of %d\n",
2755 length - new_length, length);
2756 for (int i = 0; i < new_length; i += 2) {
2757 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2758 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2759 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2760 if (mark_sweeps > 3) {
2761 PrintF("detached context 0x%p\n survived %d GCs (leak?)\n",
2762 static_cast<void*>(cell->value()), mark_sweeps);
2766 if (new_length == 0) {
2767 heap()->set_detached_contexts(heap()->empty_fixed_array());
2768 } else if (new_length < length) {
2769 heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
2770 *detached_contexts, length - new_length);
2775 bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const {
2776 StackGuard* stack_guard = isolate_->stack_guard();
2777 #ifdef USE_SIMULATOR
2778 // The simulator uses a separate JS stack.
2779 Address jssp_address = Simulator::current(isolate_)->get_sp();
2780 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
2781 if (jssp - gap < stack_guard->real_jslimit()) return true;
2782 #endif // USE_SIMULATOR
2783 return GetCurrentStackPosition() - gap < stack_guard->real_climit();
2787 SaveContext::SaveContext(Isolate* isolate)
2788 : isolate_(isolate), prev_(isolate->save_context()) {
2789 if (isolate->context() != NULL) {
2790 context_ = Handle<Context>(isolate->context());
2792 isolate->set_save_context(this);
2794 c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
2798 bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2799 // First check whether the previous scope intercepts.
2800 if (prev_ && prev_->Intercept(flag)) return true;
2801 // Then check whether this scope intercepts.
2802 if ((flag & intercept_mask_)) {
2803 intercepted_flags_ |= flag;
2809 } // namespace internal