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/isolate-inl.h"
29 #include "src/lithium-allocator.h"
31 #include "src/messages.h"
32 #include "src/prototype.h"
33 #include "src/regexp-stack.h"
34 #include "src/runtime-profiler.h"
35 #include "src/sampler.h"
36 #include "src/scopeinfo.h"
37 #include "src/serialize.h"
38 #include "src/simulator.h"
39 #include "src/version.h"
40 #include "src/vm-state-inl.h"
46 base::Atomic32 ThreadId::highest_thread_id_ = 0;
48 int ThreadId::AllocateThreadId() {
49 int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
54 int ThreadId::GetCurrentThreadId() {
55 int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
57 thread_id = AllocateThreadId();
58 base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
64 ThreadLocalTop::ThreadLocalTop() {
69 void ThreadLocalTop::InitializeInternal() {
77 external_callback_scope_ = NULL;
78 current_vm_state_ = EXTERNAL;
79 try_catch_handler_ = NULL;
81 thread_id_ = ThreadId::Invalid();
82 external_caught_exception_ = false;
83 failed_access_check_callback_ = NULL;
86 promise_on_stack_ = NULL;
88 // These members are re-initialized later after deserialization
90 pending_exception_ = NULL;
91 has_pending_message_ = false;
92 rethrowing_message_ = false;
93 pending_message_obj_ = NULL;
94 pending_message_script_ = NULL;
95 scheduled_exception_ = NULL;
99 void ThreadLocalTop::Initialize() {
100 InitializeInternal();
102 simulator_ = Simulator::current(isolate_);
104 thread_id_ = ThreadId::Current();
108 void ThreadLocalTop::Free() {
109 // Match unmatched PopPromise calls.
110 while (promise_on_stack_) isolate_->PopPromise();
114 base::Thread::LocalStorageKey Isolate::isolate_key_;
115 base::Thread::LocalStorageKey Isolate::thread_id_key_;
116 base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
117 base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER;
118 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
119 base::Atomic32 Isolate::isolate_counter_ = 0;
121 base::Atomic32 Isolate::isolate_key_created_ = 0;
124 Isolate::PerIsolateThreadData*
125 Isolate::FindOrAllocatePerThreadDataForThisThread() {
126 ThreadId thread_id = ThreadId::Current();
127 PerIsolateThreadData* per_thread = NULL;
129 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
130 per_thread = thread_data_table_->Lookup(this, thread_id);
131 if (per_thread == NULL) {
132 per_thread = new PerIsolateThreadData(this, thread_id);
133 thread_data_table_->Insert(per_thread);
135 DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
141 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
142 ThreadId thread_id = ThreadId::Current();
143 return FindPerThreadDataForThread(thread_id);
147 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
148 ThreadId thread_id) {
149 PerIsolateThreadData* per_thread = NULL;
151 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
152 per_thread = thread_data_table_->Lookup(this, thread_id);
158 void Isolate::InitializeOncePerProcess() {
159 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
160 CHECK(thread_data_table_ == NULL);
161 isolate_key_ = base::Thread::CreateThreadLocalKey();
163 base::NoBarrier_Store(&isolate_key_created_, 1);
165 thread_id_key_ = base::Thread::CreateThreadLocalKey();
166 per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
167 thread_data_table_ = new Isolate::ThreadDataTable();
171 Address Isolate::get_address_from_id(Isolate::AddressId id) {
172 return isolate_addresses_[id];
176 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
177 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
179 return thread_storage + sizeof(ThreadLocalTop);
183 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
184 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
185 v->VisitThread(this, thread);
189 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
190 // Visit the roots from the top for a given thread.
191 v->VisitPointer(&thread->pending_exception_);
192 v->VisitPointer(&(thread->pending_message_obj_));
193 v->VisitPointer(bit_cast<Object**>(&(thread->pending_message_script_)));
194 v->VisitPointer(bit_cast<Object**>(&(thread->context_)));
195 v->VisitPointer(&thread->scheduled_exception_);
197 for (v8::TryCatch* block = thread->try_catch_handler();
199 block = block->next_) {
200 v->VisitPointer(bit_cast<Object**>(&(block->exception_)));
201 v->VisitPointer(bit_cast<Object**>(&(block->message_obj_)));
202 v->VisitPointer(bit_cast<Object**>(&(block->message_script_)));
205 // Iterate over pointers on native execution stack.
206 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
207 it.frame()->Iterate(v);
212 void Isolate::Iterate(ObjectVisitor* v) {
213 ThreadLocalTop* current_t = thread_local_top();
214 Iterate(v, current_t);
218 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
219 for (DeferredHandles* deferred = deferred_handles_head_;
221 deferred = deferred->next_) {
222 deferred->Iterate(visitor);
228 bool Isolate::IsDeferredHandle(Object** handle) {
229 // Each DeferredHandles instance keeps the handles to one job in the
230 // concurrent recompilation queue, containing a list of blocks. Each block
231 // contains kHandleBlockSize handles except for the first block, which may
232 // not be fully filled.
233 // We iterate through all the blocks to see whether the argument handle
234 // belongs to one of the blocks. If so, it is deferred.
235 for (DeferredHandles* deferred = deferred_handles_head_;
237 deferred = deferred->next_) {
238 List<Object**>* blocks = &deferred->blocks_;
239 for (int i = 0; i < blocks->length(); i++) {
240 Object** block_limit = (i == 0) ? deferred->first_block_limit_
241 : blocks->at(i) + kHandleBlockSize;
242 if (blocks->at(i) <= handle && handle < block_limit) return true;
250 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
251 thread_local_top()->set_try_catch_handler(that);
255 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
256 DCHECK(thread_local_top()->try_catch_handler() == that);
257 thread_local_top()->set_try_catch_handler(that->next_);
258 thread_local_top()->catcher_ = NULL;
262 Handle<String> Isolate::StackTraceString() {
263 if (stack_trace_nesting_level_ == 0) {
264 stack_trace_nesting_level_++;
265 HeapStringAllocator allocator;
266 StringStream::ClearMentionedObjectCache(this);
267 StringStream accumulator(&allocator);
268 incomplete_message_ = &accumulator;
269 PrintStack(&accumulator);
270 Handle<String> stack_trace = accumulator.ToString(this);
271 incomplete_message_ = NULL;
272 stack_trace_nesting_level_ = 0;
274 } else if (stack_trace_nesting_level_ == 1) {
275 stack_trace_nesting_level_++;
276 base::OS::PrintError(
277 "\n\nAttempt to print stack while printing stack (double fault)\n");
278 base::OS::PrintError(
279 "If you are lucky you may find a partial stack dump on stdout.\n\n");
280 incomplete_message_->OutputToStdOut();
281 return factory()->empty_string();
285 return factory()->empty_string();
290 void Isolate::PushStackTraceAndDie(unsigned int magic,
293 unsigned int magic2) {
294 const int kMaxStackTraceSize = 8192;
295 Handle<String> trace = StackTraceString();
296 uint8_t buffer[kMaxStackTraceSize];
297 int length = Min(kMaxStackTraceSize - 1, trace->length());
298 String::WriteToFlat(*trace, buffer, 0, length);
299 buffer[length] = '\0';
300 // TODO(dcarney): convert buffer to utf8?
301 base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2,
302 static_cast<void*>(object), static_cast<void*>(map),
303 reinterpret_cast<char*>(buffer));
308 // Determines whether the given stack frame should be displayed in
309 // a stack trace. The caller is the error constructor that asked
310 // for the stack trace to be collected. The first time a construct
311 // call to this function is encountered it is skipped. The seen_caller
312 // in/out parameter is used to remember if the caller has been seen
314 static bool IsVisibleInStackTrace(JSFunction* fun,
318 if ((fun == caller) && !(*seen_caller)) {
322 // Skip all frames until we've seen the caller.
323 if (!(*seen_caller)) return false;
324 // Also, skip non-visible built-in functions and any call with the builtins
325 // object as receiver, so as to not reveal either the builtins object or
326 // an internal function.
327 // The --builtins-in-stack-traces command line flag allows including
328 // internal call sites in the stack trace for debugging purposes.
329 if (!FLAG_builtins_in_stack_traces) {
330 if (receiver->IsJSBuiltinsObject()) return false;
331 if (fun->IsBuiltin()) {
332 return fun->shared()->native();
333 } else if (fun->IsFromNativeScript() || fun->IsFromExtensionScript()) {
341 Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
342 Handle<Object> caller) {
343 // Get stack trace limit.
344 Handle<Object> error = Object::GetProperty(
345 this, js_builtins_object(), "$Error").ToHandleChecked();
346 if (!error->IsJSObject()) return factory()->undefined_value();
348 Handle<String> stackTraceLimit =
349 factory()->InternalizeUtf8String("stackTraceLimit");
350 DCHECK(!stackTraceLimit.is_null());
351 Handle<Object> stack_trace_limit =
352 JSObject::GetDataProperty(Handle<JSObject>::cast(error),
354 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
355 int limit = FastD2IChecked(stack_trace_limit->Number());
356 limit = Max(limit, 0); // Ensure that limit is not negative.
358 int initial_size = Min(limit, 10);
359 Handle<FixedArray> elements =
360 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
362 // If the caller parameter is a function we skip frames until we're
363 // under it before starting to collect.
364 bool seen_caller = !caller->IsJSFunction();
365 // First element is reserved to store the number of sloppy frames.
368 int sloppy_frames = 0;
369 bool encountered_strict_function = false;
370 for (JavaScriptFrameIterator iter(this);
371 !iter.done() && frames_seen < limit;
373 JavaScriptFrame* frame = iter.frame();
374 // Set initial size to the maximum inlining level + 1 for the outermost
376 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
377 frame->Summarize(&frames);
378 for (int i = frames.length() - 1; i >= 0; i--) {
379 Handle<JSFunction> fun = frames[i].function();
380 Handle<Object> recv = frames[i].receiver();
381 // Filter out internal frames that we do not want to show.
382 if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) continue;
383 // Filter out frames from other security contexts.
384 if (!this->context()->HasSameSecurityTokenAs(fun->context())) continue;
385 if (cursor + 4 > elements->length()) {
386 int new_capacity = JSObject::NewElementsCapacity(elements->length());
387 Handle<FixedArray> new_elements =
388 factory()->NewFixedArrayWithHoles(new_capacity);
389 for (int i = 0; i < cursor; i++) {
390 new_elements->set(i, elements->get(i));
392 elements = new_elements;
394 DCHECK(cursor + 4 <= elements->length());
396 Handle<Code> code = frames[i].code();
397 Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
398 // The stack trace API should not expose receivers and function
399 // objects on frames deeper than the top-most one with a strict
400 // mode function. The number of sloppy frames is stored as
401 // first element in the result array.
402 if (!encountered_strict_function) {
403 if (is_strict(fun->shared()->language_mode())) {
404 encountered_strict_function = true;
409 elements->set(cursor++, *recv);
410 elements->set(cursor++, *fun);
411 elements->set(cursor++, *code);
412 elements->set(cursor++, *offset);
416 elements->set(0, Smi::FromInt(sloppy_frames));
417 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
418 result->set_length(Smi::FromInt(cursor));
423 void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
424 if (capture_stack_trace_for_uncaught_exceptions_) {
425 // Capture stack trace for a detailed exception message.
426 Handle<Name> key = factory()->detailed_stack_trace_symbol();
427 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
428 stack_trace_for_uncaught_exceptions_frame_limit_,
429 stack_trace_for_uncaught_exceptions_options_);
430 JSObject::SetProperty(error_object, key, stack_trace, STRICT).Assert();
435 void Isolate::CaptureAndSetSimpleStackTrace(Handle<JSObject> error_object,
436 Handle<Object> caller) {
437 // Capture stack trace for simple stack trace string formatting.
438 Handle<Name> key = factory()->stack_trace_symbol();
439 Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
440 JSObject::SetProperty(error_object, key, stack_trace, STRICT).Assert();
444 Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
445 Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
446 Handle<Object> stack_trace =
447 JSObject::GetDataProperty(error_object, key_detailed);
448 if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
450 if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
452 // Try to get details from simple stack trace.
453 Handle<JSArray> detailed_stack_trace =
454 GetDetailedFromSimpleStackTrace(error_object);
455 if (!detailed_stack_trace.is_null()) {
456 // Save the detailed stack since the simple one might be withdrawn later.
457 JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
460 return detailed_stack_trace;
464 class CaptureStackTraceHelper {
466 CaptureStackTraceHelper(Isolate* isolate,
467 StackTrace::StackTraceOptions options)
468 : isolate_(isolate) {
469 if (options & StackTrace::kColumnOffset) {
471 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
473 if (options & StackTrace::kLineNumber) {
475 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
477 if (options & StackTrace::kScriptId) {
479 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
481 if (options & StackTrace::kScriptName) {
483 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
485 if (options & StackTrace::kScriptNameOrSourceURL) {
486 script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
487 STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
489 if (options & StackTrace::kFunctionName) {
490 function_key_ = factory()->InternalizeOneByteString(
491 STATIC_CHAR_VECTOR("functionName"));
493 if (options & StackTrace::kIsEval) {
495 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
497 if (options & StackTrace::kIsConstructor) {
498 constructor_key_ = factory()->InternalizeOneByteString(
499 STATIC_CHAR_VECTOR("isConstructor"));
503 Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun,
504 Handle<Code> code, Address pc,
505 bool is_constructor) {
506 Handle<JSObject> stack_frame =
507 factory()->NewJSObject(isolate_->object_function());
509 Handle<Script> script(Script::cast(fun->shared()->script()));
511 if (!line_key_.is_null()) {
512 int script_line_offset = script->line_offset()->value();
513 int position = code->SourcePosition(pc);
514 int line_number = Script::GetLineNumber(script, position);
515 // line_number is already shifted by the script_line_offset.
516 int relative_line_number = line_number - script_line_offset;
517 if (!column_key_.is_null() && relative_line_number >= 0) {
518 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
519 int start = (relative_line_number == 0) ? 0 :
520 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
521 int column_offset = position - start;
522 if (relative_line_number == 0) {
523 // For the case where the code is on the same line as the script
525 column_offset += script->column_offset()->value();
527 JSObject::AddProperty(stack_frame, column_key_,
528 handle(Smi::FromInt(column_offset + 1), isolate_),
531 JSObject::AddProperty(stack_frame, line_key_,
532 handle(Smi::FromInt(line_number + 1), isolate_),
536 if (!script_id_key_.is_null()) {
537 JSObject::AddProperty(stack_frame, script_id_key_,
538 handle(script->id(), isolate_), NONE);
541 if (!script_name_key_.is_null()) {
542 JSObject::AddProperty(stack_frame, script_name_key_,
543 handle(script->name(), isolate_), NONE);
546 if (!script_name_or_source_url_key_.is_null()) {
547 Handle<Object> result = Script::GetNameOrSourceURL(script);
548 JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
552 if (!function_key_.is_null()) {
553 Handle<Object> fun_name(fun->shared()->DebugName(), isolate_);
554 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
557 if (!eval_key_.is_null()) {
558 Handle<Object> is_eval = factory()->ToBoolean(
559 script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
560 JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
563 if (!constructor_key_.is_null()) {
564 Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
565 JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
573 inline Factory* factory() { return isolate_->factory(); }
576 Handle<String> column_key_;
577 Handle<String> line_key_;
578 Handle<String> script_id_key_;
579 Handle<String> script_name_key_;
580 Handle<String> script_name_or_source_url_key_;
581 Handle<String> function_key_;
582 Handle<String> eval_key_;
583 Handle<String> constructor_key_;
587 Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
588 Handle<JSObject> error_object) {
589 Handle<Name> key = factory()->stack_trace_symbol();
590 Handle<Object> property = JSObject::GetDataProperty(error_object, key);
591 if (!property->IsJSArray()) return Handle<JSArray>();
592 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
594 CaptureStackTraceHelper helper(this,
595 stack_trace_for_uncaught_exceptions_options_);
598 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
599 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
601 int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
602 if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
604 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
605 for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
606 Handle<Object> recv = handle(elements->get(i), this);
607 Handle<JSFunction> fun =
608 handle(JSFunction::cast(elements->get(i + 1)), this);
609 Handle<Code> code = handle(Code::cast(elements->get(i + 2)), this);
610 Handle<Smi> offset = handle(Smi::cast(elements->get(i + 3)), this);
611 Address pc = code->address() + offset->value();
612 bool is_constructor =
613 recv->IsJSObject() &&
614 Handle<JSObject>::cast(recv)->map()->constructor() == *fun;
616 Handle<JSObject> stack_frame =
617 helper.NewStackFrameObject(fun, code, pc, is_constructor);
619 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
623 stack_trace->set_length(Smi::FromInt(frames_seen));
628 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
629 int frame_limit, StackTrace::StackTraceOptions options) {
630 CaptureStackTraceHelper helper(this, options);
632 // Ensure no negative values.
633 int limit = Max(frame_limit, 0);
634 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
636 StackTraceFrameIterator it(this);
638 while (!it.done() && (frames_seen < limit)) {
639 JavaScriptFrame* frame = it.frame();
640 // Set initial size to the maximum inlining level + 1 for the outermost
642 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
643 frame->Summarize(&frames);
644 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
645 Handle<JSFunction> fun = frames[i].function();
646 // Filter frames from other security contexts.
647 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
648 !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
650 Handle<JSObject> stack_frame = helper.NewStackFrameObject(
651 fun, frames[i].code(), frames[i].pc(), frames[i].is_constructor());
653 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
659 stack_trace->set_length(Smi::FromInt(frames_seen));
664 void Isolate::PrintStack(FILE* out) {
665 if (stack_trace_nesting_level_ == 0) {
666 stack_trace_nesting_level_++;
667 StringStream::ClearMentionedObjectCache(this);
668 HeapStringAllocator allocator;
669 StringStream accumulator(&allocator);
670 incomplete_message_ = &accumulator;
671 PrintStack(&accumulator);
672 accumulator.OutputToFile(out);
673 InitializeLoggingAndCounters();
674 accumulator.Log(this);
675 incomplete_message_ = NULL;
676 stack_trace_nesting_level_ = 0;
677 } else if (stack_trace_nesting_level_ == 1) {
678 stack_trace_nesting_level_++;
679 base::OS::PrintError(
680 "\n\nAttempt to print stack while printing stack (double fault)\n");
681 base::OS::PrintError(
682 "If you are lucky you may find a partial stack dump on stdout.\n\n");
683 incomplete_message_->OutputToFile(out);
688 static void PrintFrames(Isolate* isolate,
689 StringStream* accumulator,
690 StackFrame::PrintMode mode) {
691 StackFrameIterator it(isolate);
692 for (int i = 0; !it.done(); it.Advance()) {
693 it.frame()->Print(accumulator, mode, i++);
698 void Isolate::PrintStack(StringStream* accumulator) {
699 // The MentionedObjectCache is not GC-proof at the moment.
700 DisallowHeapAllocation no_gc;
701 DCHECK(StringStream::IsMentionedObjectCacheClear(this));
703 // Avoid printing anything if there are no frames.
704 if (c_entry_fp(thread_local_top()) == 0) return;
707 "\n==== JS stack trace =========================================\n\n");
708 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
711 "\n==== Details ================================================\n\n");
712 PrintFrames(this, accumulator, StackFrame::DETAILS);
714 accumulator->PrintMentionedObjectCache(this);
715 accumulator->Add("=====================\n\n");
719 void Isolate::SetFailedAccessCheckCallback(
720 v8::FailedAccessCheckCallback callback) {
721 thread_local_top()->failed_access_check_callback_ = callback;
725 static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
726 Handle<JSObject> receiver) {
727 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
728 if (!constructor->shared()->IsApiFunction()) return NULL;
731 constructor->shared()->get_api_func_data()->access_check_info();
732 if (data_obj == isolate->heap()->undefined_value()) return NULL;
734 return AccessCheckInfo::cast(data_obj);
738 void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver,
739 v8::AccessType type) {
740 if (!thread_local_top()->failed_access_check_callback_) {
741 Handle<String> message = factory()->InternalizeUtf8String("no access");
742 Handle<Object> error;
743 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
744 this, error, factory()->NewTypeError(message), /* void */);
745 ScheduleThrow(*error);
749 DCHECK(receiver->IsAccessCheckNeeded());
752 // Get the data object from access check info.
753 HandleScope scope(this);
755 { DisallowHeapAllocation no_gc;
756 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
757 if (!access_check_info) return;
758 data = handle(access_check_info->data(), this);
761 // Leaving JavaScript.
762 VMState<EXTERNAL> state(this);
763 thread_local_top()->failed_access_check_callback_(
764 v8::Utils::ToLocal(receiver),
766 v8::Utils::ToLocal(data));
770 enum MayAccessDecision {
775 static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
776 Handle<JSObject> receiver,
777 v8::AccessType type) {
778 DisallowHeapAllocation no_gc;
779 // During bootstrapping, callback functions are not enabled yet.
780 if (isolate->bootstrapper()->IsActive()) return YES;
782 if (receiver->IsJSGlobalProxy()) {
783 Object* receiver_context = JSGlobalProxy::cast(*receiver)->native_context();
784 if (!receiver_context->IsContext()) return NO;
786 // Get the native context of current top context.
787 // avoid using Isolate::native_context() because it uses Handle.
788 Context* native_context =
789 isolate->context()->global_object()->native_context();
790 if (receiver_context == native_context) return YES;
792 if (Context::cast(receiver_context)->security_token() ==
793 native_context->security_token())
801 bool Isolate::IsInternallyUsedPropertyName(Handle<Object> name) {
802 return name.is_identical_to(factory()->hidden_string()) ||
803 name.is_identical_to(factory()->prototype_users_symbol());
807 bool Isolate::IsInternallyUsedPropertyName(Object* name) {
808 return name == heap()->hidden_string() ||
809 name == heap()->prototype_users_symbol();
813 bool Isolate::MayNamedAccess(Handle<JSObject> receiver,
815 v8::AccessType type) {
816 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
818 // Skip checks for internally used properties. Note, we do not
819 // require existence of a context in this case.
820 if (IsInternallyUsedPropertyName(key)) return true;
822 // Check for compatibility between the security tokens in the
823 // current lexical context and the accessed object.
826 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
827 if (decision != UNKNOWN) return decision == YES;
829 HandleScope scope(this);
831 v8::NamedSecurityCallback callback;
832 { DisallowHeapAllocation no_gc;
833 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
834 if (!access_check_info) return false;
835 Object* fun_obj = access_check_info->named_callback();
836 callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
837 if (!callback) return false;
838 data = handle(access_check_info->data(), this);
841 LOG(this, ApiNamedSecurityCheck(*key));
843 // Leaving JavaScript.
844 VMState<EXTERNAL> state(this);
845 return callback(v8::Utils::ToLocal(receiver),
846 v8::Utils::ToLocal(key),
848 v8::Utils::ToLocal(data));
852 bool Isolate::MayIndexedAccess(Handle<JSObject> receiver,
854 v8::AccessType type) {
855 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
856 // Check for compatibility between the security tokens in the
857 // current lexical context and the accessed object.
860 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
861 if (decision != UNKNOWN) return decision == YES;
863 HandleScope scope(this);
865 v8::IndexedSecurityCallback callback;
866 { DisallowHeapAllocation no_gc;
867 // Get named access check callback
868 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
869 if (!access_check_info) return false;
870 Object* fun_obj = access_check_info->indexed_callback();
871 callback = v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
872 if (!callback) return false;
873 data = handle(access_check_info->data(), this);
876 LOG(this, ApiIndexedSecurityCheck(index));
878 // Leaving JavaScript.
879 VMState<EXTERNAL> state(this);
881 v8::Utils::ToLocal(receiver), index, type, v8::Utils::ToLocal(data));
885 const char* const Isolate::kStackOverflowMessage =
886 "Uncaught RangeError: Maximum call stack size exceeded";
889 Object* Isolate::StackOverflow() {
890 HandleScope scope(this);
891 // At this point we cannot create an Error object using its javascript
892 // constructor. Instead, we copy the pre-constructed boilerplate and
893 // attach the stack trace as a hidden property.
894 Handle<String> key = factory()->stack_overflow_string();
895 Handle<JSObject> boilerplate = Handle<JSObject>::cast(
896 Object::GetProperty(js_builtins_object(), key).ToHandleChecked());
897 Handle<JSObject> exception = factory()->CopyJSObject(boilerplate);
898 DoThrow(*exception, NULL);
900 CaptureAndSetSimpleStackTrace(exception, factory()->undefined_value());
901 return heap()->exception();
905 Object* Isolate::TerminateExecution() {
906 DoThrow(heap_.termination_exception(), NULL);
907 return heap()->exception();
911 void Isolate::CancelTerminateExecution() {
912 if (try_catch_handler()) {
913 try_catch_handler()->has_terminated_ = false;
915 if (has_pending_exception() &&
916 pending_exception() == heap_.termination_exception()) {
917 thread_local_top()->external_caught_exception_ = false;
918 clear_pending_exception();
920 if (has_scheduled_exception() &&
921 scheduled_exception() == heap_.termination_exception()) {
922 thread_local_top()->external_caught_exception_ = false;
923 clear_scheduled_exception();
928 void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
929 ExecutionAccess access(this);
930 api_interrupts_queue_.push(InterruptEntry(callback, data));
931 stack_guard()->RequestApiInterrupt();
935 void Isolate::InvokeApiInterruptCallbacks() {
936 // Note: callback below should be called outside of execution access lock.
938 InterruptEntry entry;
940 ExecutionAccess access(this);
941 if (api_interrupts_queue_.empty()) return;
942 entry = api_interrupts_queue_.front();
943 api_interrupts_queue_.pop();
945 VMState<EXTERNAL> state(this);
946 HandleScope handle_scope(this);
947 entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
952 Object* Isolate::Throw(Object* exception, MessageLocation* location) {
953 DoThrow(exception, location);
954 return heap()->exception();
958 Object* Isolate::ReThrow(Object* exception) {
959 bool can_be_caught_externally = false;
960 bool catchable_by_javascript = is_catchable_by_javascript(exception);
961 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
963 thread_local_top()->catcher_ = can_be_caught_externally ?
964 try_catch_handler() : NULL;
966 // Set the exception being re-thrown.
967 set_pending_exception(exception);
968 return heap()->exception();
972 Object* Isolate::ThrowIllegalOperation() {
973 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
974 return Throw(heap_.illegal_access_string());
978 void Isolate::ScheduleThrow(Object* exception) {
979 // When scheduling a throw we first throw the exception to get the
980 // error reporting if it is uncaught before rescheduling it.
982 PropagatePendingExceptionToExternalTryCatch();
983 if (has_pending_exception()) {
984 thread_local_top()->scheduled_exception_ = pending_exception();
985 thread_local_top()->external_caught_exception_ = false;
986 clear_pending_exception();
991 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
992 DCHECK(handler == try_catch_handler());
993 DCHECK(handler->HasCaught());
994 DCHECK(handler->rethrow_);
995 DCHECK(handler->capture_message_);
996 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
997 Object* script = reinterpret_cast<Object*>(handler->message_script_);
998 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
999 DCHECK(script->IsScript() || script->IsTheHole());
1000 thread_local_top()->pending_message_obj_ = message;
1001 thread_local_top()->pending_message_script_ = script;
1002 thread_local_top()->pending_message_start_pos_ = handler->message_start_pos_;
1003 thread_local_top()->pending_message_end_pos_ = handler->message_end_pos_;
1007 void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1008 DCHECK(has_scheduled_exception());
1009 if (scheduled_exception() == handler->exception_) {
1010 DCHECK(scheduled_exception() != heap()->termination_exception());
1011 clear_scheduled_exception();
1016 Object* Isolate::PromoteScheduledException() {
1017 Object* thrown = scheduled_exception();
1018 clear_scheduled_exception();
1019 // Re-throw the exception to avoid getting repeated error reporting.
1020 return ReThrow(thrown);
1024 void Isolate::PrintCurrentStackTrace(FILE* out) {
1025 StackTraceFrameIterator it(this);
1026 while (!it.done()) {
1027 HandleScope scope(this);
1028 // Find code position if recorded in relocation info.
1029 JavaScriptFrame* frame = it.frame();
1030 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1031 Handle<Object> pos_obj(Smi::FromInt(pos), this);
1032 // Fetch function and receiver.
1033 Handle<JSFunction> fun(frame->function());
1034 Handle<Object> recv(frame->receiver(), this);
1035 // Advance to the next JavaScript frame and determine if the
1036 // current frame is the top-level frame.
1038 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
1039 // Generate and print stack trace line.
1040 Handle<String> line =
1041 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1042 if (line->length() > 0) {
1050 void Isolate::ComputeLocation(MessageLocation* target) {
1051 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1052 StackTraceFrameIterator it(this);
1054 JavaScriptFrame* frame = it.frame();
1055 JSFunction* fun = frame->function();
1056 Object* script = fun->shared()->script();
1057 if (script->IsScript() &&
1058 !(Script::cast(script)->source()->IsUndefined())) {
1059 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1060 // Compute the location from the function and the reloc info.
1061 Handle<Script> casted_script(Script::cast(script));
1062 *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1068 bool Isolate::ComputeLocationFromException(MessageLocation* target,
1069 Handle<Object> exception) {
1070 if (!exception->IsJSObject()) return false;
1072 Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1073 Handle<Object> start_pos = JSObject::GetDataProperty(
1074 Handle<JSObject>::cast(exception), start_pos_symbol);
1075 if (!start_pos->IsSmi()) return false;
1076 int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1078 Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1079 Handle<Object> end_pos = JSObject::GetDataProperty(
1080 Handle<JSObject>::cast(exception), end_pos_symbol);
1081 if (!end_pos->IsSmi()) return false;
1082 int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1084 Handle<Name> script_symbol = factory()->error_script_symbol();
1085 Handle<Object> script = JSObject::GetDataProperty(
1086 Handle<JSObject>::cast(exception), script_symbol);
1087 if (!script->IsScript()) return false;
1089 Handle<Script> cast_script(Script::cast(*script));
1090 *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1095 bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1096 Handle<Object> exception) {
1097 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1099 if (!exception->IsJSObject()) return false;
1100 Handle<Name> key = factory()->stack_trace_symbol();
1101 Handle<Object> property =
1102 JSObject::GetDataProperty(Handle<JSObject>::cast(exception), key);
1103 if (!property->IsJSArray()) return false;
1104 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1106 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1107 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1109 for (int i = 1; i < elements_limit; i += 4) {
1110 Handle<JSFunction> fun =
1111 handle(JSFunction::cast(elements->get(i + 1)), this);
1112 if (fun->IsFromNativeScript()) continue;
1113 Handle<Code> code = handle(Code::cast(elements->get(i + 2)), this);
1114 Handle<Smi> offset = handle(Smi::cast(elements->get(i + 3)), this);
1115 Address pc = code->address() + offset->value();
1117 Object* script = fun->shared()->script();
1118 if (script->IsScript() &&
1119 !(Script::cast(script)->source()->IsUndefined())) {
1120 int pos = code->SourcePosition(pc);
1121 Handle<Script> casted_script(Script::cast(script));
1122 *target = MessageLocation(casted_script, pos, pos + 1);
1130 bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1131 bool catchable_by_javascript) {
1132 // Find the top-most try-catch handler.
1133 StackHandler* handler =
1134 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1135 while (handler != NULL && !handler->is_catch()) {
1136 handler = handler->next();
1139 // Get the address of the external handler so we can compare the address to
1140 // determine which one is closer to the top of the stack.
1141 Address external_handler_address =
1142 thread_local_top()->try_catch_handler_address();
1144 // The exception has been externally caught if and only if there is
1145 // an external handler which is on top of the top-most try-catch
1147 *can_be_caught_externally = external_handler_address != NULL &&
1148 (handler == NULL || handler->address() > external_handler_address ||
1149 !catchable_by_javascript);
1151 if (*can_be_caught_externally) {
1152 // Only report the exception if the external handler is verbose.
1153 return try_catch_handler()->is_verbose_;
1155 // Report the exception if it isn't caught by JavaScript code.
1156 return handler == NULL;
1161 // Traverse prototype chain to find out whether the object is derived from
1162 // the Error object.
1163 bool Isolate::IsErrorObject(Handle<Object> obj) {
1164 if (!obj->IsJSObject()) return false;
1166 Handle<String> error_key =
1167 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("$Error"));
1168 Handle<Object> error_constructor = Object::GetProperty(
1169 js_builtins_object(), error_key).ToHandleChecked();
1171 DisallowHeapAllocation no_gc;
1172 for (PrototypeIterator iter(this, *obj, PrototypeIterator::START_AT_RECEIVER);
1173 !iter.IsAtEnd(); iter.Advance()) {
1174 if (iter.GetCurrent()->IsJSProxy()) return false;
1175 if (JSObject::cast(iter.GetCurrent())->map()->constructor() ==
1176 *error_constructor) {
1183 static int fatal_exception_depth = 0;
1186 Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1187 MessageLocation* location) {
1188 Handle<JSArray> stack_trace_object;
1189 MessageLocation potential_computed_location;
1190 if (capture_stack_trace_for_uncaught_exceptions_) {
1191 if (IsErrorObject(exception)) {
1192 // We fetch the stack trace that corresponds to this error object.
1193 // If the lookup fails, the exception is probably not a valid Error
1194 // object. In that case, we fall through and capture the stack trace
1195 // at this throw site.
1196 stack_trace_object =
1197 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1199 if (stack_trace_object.is_null()) {
1200 // Not an error object, we capture stack and location at throw site.
1201 stack_trace_object = CaptureCurrentStackTrace(
1202 stack_trace_for_uncaught_exceptions_frame_limit_,
1203 stack_trace_for_uncaught_exceptions_options_);
1207 if (!ComputeLocationFromException(&potential_computed_location,
1209 if (!ComputeLocationFromStackTrace(&potential_computed_location,
1211 ComputeLocation(&potential_computed_location);
1214 location = &potential_computed_location;
1217 // If the exception argument is a custom object, turn it into a string
1218 // before throwing as uncaught exception. Note that the pending
1219 // exception object to be set later must not be turned into a string.
1220 if (exception->IsJSObject() && !IsErrorObject(exception)) {
1221 MaybeHandle<Object> maybe_exception =
1222 Execution::ToDetailString(this, exception);
1223 if (!maybe_exception.ToHandle(&exception)) {
1225 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("exception"));
1228 return MessageHandler::MakeMessageObject(this, "uncaught_exception", location,
1229 HandleVector<Object>(&exception, 1),
1230 stack_trace_object);
1234 void ReportBootstrappingException(Handle<Object> exception,
1235 MessageLocation* location) {
1236 base::OS::PrintError("Exception thrown during bootstrapping\n");
1237 if (location == NULL || location->script().is_null()) return;
1238 // We are bootstrapping and caught an error where the location is set
1239 // and we have a script for the location.
1240 // In this case we could have an extension (or an internal error
1241 // somewhere) and we print out the line number at which the error occured
1242 // to the console for easier debugging.
1244 location->script()->GetLineNumber(location->start_pos()) + 1;
1245 if (exception->IsString() && location->script()->name()->IsString()) {
1246 base::OS::PrintError(
1247 "Extension or internal compilation error: %s in %s at line %d.\n",
1248 String::cast(*exception)->ToCString().get(),
1249 String::cast(location->script()->name())->ToCString().get(),
1251 } else if (location->script()->name()->IsString()) {
1252 base::OS::PrintError(
1253 "Extension or internal compilation error in %s at line %d.\n",
1254 String::cast(location->script()->name())->ToCString().get(),
1257 base::OS::PrintError("Extension or internal compilation error.\n");
1260 // Since comments and empty lines have been stripped from the source of
1261 // builtins, print the actual source here so that line numbers match.
1262 if (location->script()->source()->IsString()) {
1263 Handle<String> src(String::cast(location->script()->source()));
1264 PrintF("Failing script:\n");
1265 int len = src->length();
1266 int line_number = 1;
1267 PrintF("%5d: ", line_number);
1268 for (int i = 0; i < len; i++) {
1269 uint16_t character = src->Get(i);
1270 PrintF("%c", character);
1271 if (character == '\n' && i < len - 2) {
1272 PrintF("%5d: ", ++line_number);
1280 void Isolate::DoThrow(Object* exception, MessageLocation* location) {
1281 DCHECK(!has_pending_exception());
1283 HandleScope scope(this);
1284 Handle<Object> exception_handle(exception, this);
1286 // Determine reporting and whether the exception is caught externally.
1287 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1288 bool can_be_caught_externally = false;
1289 bool should_report_exception =
1290 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1291 bool report_exception = catchable_by_javascript && should_report_exception;
1292 bool try_catch_needs_message =
1293 can_be_caught_externally && try_catch_handler()->capture_message_;
1294 bool rethrowing_message = thread_local_top()->rethrowing_message_;
1296 thread_local_top()->rethrowing_message_ = false;
1298 // Notify debugger of exception.
1299 if (catchable_by_javascript) {
1300 debug()->OnThrow(exception_handle, report_exception);
1303 // Generate the message if required.
1304 if (!rethrowing_message && (report_exception || try_catch_needs_message)) {
1305 MessageLocation potential_computed_location;
1306 if (location == NULL) {
1307 // If no location was specified we use a computed one instead.
1308 ComputeLocation(&potential_computed_location);
1309 location = &potential_computed_location;
1312 if (bootstrapper()->IsActive()) {
1313 // It's not safe to try to make message objects or collect stack traces
1314 // while the bootstrapper is active since the infrastructure may not have
1315 // been properly initialized.
1316 ReportBootstrappingException(exception_handle, location);
1318 Handle<Object> message_obj = CreateMessage(exception_handle, location);
1320 thread_local_top()->pending_message_obj_ = *message_obj;
1321 thread_local_top()->pending_message_script_ = *location->script();
1322 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1323 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1325 // If the abort-on-uncaught-exception flag is specified, abort on any
1326 // exception not caught by JavaScript, even when an external handler is
1327 // present. This flag is intended for use by JavaScript developers, so
1328 // print a user-friendly stack trace (not an internal one).
1329 if (fatal_exception_depth == 0 && FLAG_abort_on_uncaught_exception &&
1330 (report_exception || can_be_caught_externally)) {
1331 fatal_exception_depth++;
1332 PrintF(stderr, "%s\n\nFROM\n",
1333 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1334 PrintCurrentStackTrace(stderr);
1340 // Save the message for reporting if the the exception remains uncaught.
1341 thread_local_top()->has_pending_message_ = report_exception;
1343 // Do not forget to clean catcher_ if currently thrown exception cannot
1344 // be caught. If necessary, ReThrow will update the catcher.
1345 thread_local_top()->catcher_ = can_be_caught_externally ?
1346 try_catch_handler() : NULL;
1348 set_pending_exception(*exception_handle);
1352 bool Isolate::HasExternalTryCatch() {
1353 DCHECK(has_pending_exception());
1355 return (thread_local_top()->catcher_ != NULL) &&
1356 (try_catch_handler() == thread_local_top()->catcher_);
1360 bool Isolate::IsFinallyOnTop() {
1361 // Get the address of the external handler so we can compare the address to
1362 // determine which one is closer to the top of the stack.
1363 Address external_handler_address =
1364 thread_local_top()->try_catch_handler_address();
1365 DCHECK(external_handler_address != NULL);
1367 // The exception has been externally caught if and only if there is
1368 // an external handler which is on top of the top-most try-finally
1370 // There should be no try-catch blocks as they would prohibit us from
1371 // finding external catcher in the first place (see catcher_ check above).
1373 // Note, that finally clause would rethrow an exception unless it's
1374 // aborted by jumps in control flow like return, break, etc. and we'll
1375 // have another chances to set proper v8::TryCatch.
1376 StackHandler* handler =
1377 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1378 while (handler != NULL && handler->address() < external_handler_address) {
1379 DCHECK(!handler->is_catch());
1380 if (handler->is_finally()) return true;
1382 handler = handler->next();
1389 void Isolate::ReportPendingMessages() {
1390 DCHECK(has_pending_exception());
1391 bool can_clear_message = PropagatePendingExceptionToExternalTryCatch();
1393 HandleScope scope(this);
1394 if (thread_local_top_.pending_exception_ == heap()->termination_exception()) {
1395 // Do nothing: if needed, the exception has been already propagated to
1398 if (thread_local_top_.has_pending_message_) {
1399 thread_local_top_.has_pending_message_ = false;
1400 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1401 HandleScope scope(this);
1402 Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1404 if (!thread_local_top_.pending_message_script_->IsTheHole()) {
1405 Handle<Script> script(
1406 Script::cast(thread_local_top_.pending_message_script_));
1407 int start_pos = thread_local_top_.pending_message_start_pos_;
1408 int end_pos = thread_local_top_.pending_message_end_pos_;
1409 MessageLocation location(script, start_pos, end_pos);
1410 MessageHandler::ReportMessage(this, &location, message_obj);
1412 MessageHandler::ReportMessage(this, NULL, message_obj);
1417 if (can_clear_message) clear_pending_message();
1421 MessageLocation Isolate::GetMessageLocation() {
1422 DCHECK(has_pending_exception());
1424 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1425 thread_local_top_.has_pending_message_ &&
1426 !thread_local_top_.pending_message_obj_->IsTheHole()) {
1427 Handle<Script> script(
1428 Script::cast(thread_local_top_.pending_message_script_));
1429 int start_pos = thread_local_top_.pending_message_start_pos_;
1430 int end_pos = thread_local_top_.pending_message_end_pos_;
1431 return MessageLocation(script, start_pos, end_pos);
1434 return MessageLocation();
1438 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1439 DCHECK(has_pending_exception());
1440 PropagatePendingExceptionToExternalTryCatch();
1442 bool is_termination_exception =
1443 pending_exception() == heap_.termination_exception();
1445 // Do not reschedule the exception if this is the bottom call.
1446 bool clear_exception = is_bottom_call;
1448 if (is_termination_exception) {
1449 if (is_bottom_call) {
1450 thread_local_top()->external_caught_exception_ = false;
1451 clear_pending_exception();
1454 } else if (thread_local_top()->external_caught_exception_) {
1455 // If the exception is externally caught, clear it if there are no
1456 // JavaScript frames on the way to the C++ frame that has the
1457 // external handler.
1458 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1459 Address external_handler_address =
1460 thread_local_top()->try_catch_handler_address();
1461 JavaScriptFrameIterator it(this);
1462 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1463 clear_exception = true;
1467 // Clear the exception if needed.
1468 if (clear_exception) {
1469 thread_local_top()->external_caught_exception_ = false;
1470 clear_pending_exception();
1474 // Reschedule the exception.
1475 thread_local_top()->scheduled_exception_ = pending_exception();
1476 clear_pending_exception();
1481 void Isolate::PushPromise(Handle<JSObject> promise) {
1482 ThreadLocalTop* tltop = thread_local_top();
1483 PromiseOnStack* prev = tltop->promise_on_stack_;
1484 StackHandler* handler = StackHandler::FromAddress(Isolate::handler(tltop));
1485 Handle<JSObject> global_handle =
1486 Handle<JSObject>::cast(global_handles()->Create(*promise));
1487 tltop->promise_on_stack_ = new PromiseOnStack(handler, global_handle, prev);
1491 void Isolate::PopPromise() {
1492 ThreadLocalTop* tltop = thread_local_top();
1493 if (tltop->promise_on_stack_ == NULL) return;
1494 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
1495 Handle<Object> global_handle = tltop->promise_on_stack_->promise();
1496 delete tltop->promise_on_stack_;
1497 tltop->promise_on_stack_ = prev;
1498 global_handles()->Destroy(global_handle.location());
1502 Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1503 Handle<Object> undefined = factory()->undefined_value();
1504 ThreadLocalTop* tltop = thread_local_top();
1505 if (tltop->promise_on_stack_ == NULL) return undefined;
1506 StackHandler* promise_try = tltop->promise_on_stack_->handler();
1507 // Find the top-most try-catch handler.
1508 StackHandler* handler = StackHandler::FromAddress(Isolate::handler(tltop));
1510 if (handler == promise_try) {
1511 return tltop->promise_on_stack_->promise();
1513 handler = handler->next();
1514 // Throwing inside a Promise can be intercepted by an inner try-catch, so
1515 // we stop at the first try-catch handler.
1516 } while (handler != NULL && !handler->is_catch());
1521 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1524 StackTrace::StackTraceOptions options) {
1525 capture_stack_trace_for_uncaught_exceptions_ = capture;
1526 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1527 stack_trace_for_uncaught_exceptions_options_ = options;
1531 Handle<Context> Isolate::native_context() {
1532 return handle(context()->native_context());
1536 Handle<Context> Isolate::GetCallingNativeContext() {
1537 JavaScriptFrameIterator it(this);
1538 if (debug_->in_debug_scope()) {
1539 while (!it.done()) {
1540 JavaScriptFrame* frame = it.frame();
1541 Context* context = Context::cast(frame->context());
1542 if (context->native_context() == *debug_->debug_context()) {
1549 if (it.done()) return Handle<Context>::null();
1550 JavaScriptFrame* frame = it.frame();
1551 Context* context = Context::cast(frame->context());
1552 return Handle<Context>(context->native_context());
1556 char* Isolate::ArchiveThread(char* to) {
1557 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1558 sizeof(ThreadLocalTop));
1559 InitializeThreadLocal();
1560 clear_pending_exception();
1561 clear_pending_message();
1562 clear_scheduled_exception();
1563 return to + sizeof(ThreadLocalTop);
1567 char* Isolate::RestoreThread(char* from) {
1568 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1569 sizeof(ThreadLocalTop));
1570 // This might be just paranoia, but it seems to be needed in case a
1571 // thread_local_top_ is restored on a separate OS thread.
1572 #ifdef USE_SIMULATOR
1573 thread_local_top()->simulator_ = Simulator::current(this);
1575 DCHECK(context() == NULL || context()->IsContext());
1576 return from + sizeof(ThreadLocalTop);
1580 Isolate::ThreadDataTable::ThreadDataTable()
1585 Isolate::ThreadDataTable::~ThreadDataTable() {
1586 // TODO(svenpanne) The assertion below would fire if an embedder does not
1587 // cleanly dispose all Isolates before disposing v8, so we are conservative
1588 // and leave it out for now.
1589 // DCHECK_NULL(list_);
1593 Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1594 #if defined(USE_SIMULATOR)
1600 Isolate::PerIsolateThreadData*
1601 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1602 ThreadId thread_id) {
1603 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1604 if (data->Matches(isolate, thread_id)) return data;
1610 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1611 if (list_ != NULL) list_->prev_ = data;
1612 data->next_ = list_;
1617 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1618 if (list_ == data) list_ = data->next_;
1619 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1620 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1625 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1626 PerIsolateThreadData* data = list_;
1627 while (data != NULL) {
1628 PerIsolateThreadData* next = data->next_;
1629 if (data->isolate() == isolate) Remove(data);
1636 #define TRACE_ISOLATE(tag) \
1638 if (FLAG_trace_isolates) { \
1639 PrintF("Isolate %p (id %d)" #tag "\n", \
1640 reinterpret_cast<void*>(this), id()); \
1644 #define TRACE_ISOLATE(tag)
1648 Isolate::Isolate(bool enable_serializer)
1651 stack_trace_nesting_level_(0),
1652 incomplete_message_(NULL),
1653 bootstrapper_(NULL),
1654 runtime_profiler_(NULL),
1655 compilation_cache_(NULL),
1661 code_aging_helper_(NULL),
1662 deoptimizer_data_(NULL),
1663 materialized_object_store_(NULL),
1664 capture_stack_trace_for_uncaught_exceptions_(false),
1665 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1666 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1667 memory_allocator_(NULL),
1668 keyed_lookup_cache_(NULL),
1669 context_slot_cache_(NULL),
1670 descriptor_lookup_cache_(NULL),
1671 handle_scope_implementer_(NULL),
1672 unicode_cache_(NULL),
1673 inner_pointer_to_code_cache_(NULL),
1674 global_handles_(NULL),
1675 eternal_handles_(NULL),
1676 thread_manager_(NULL),
1677 has_installed_extensions_(false),
1678 string_tracker_(NULL),
1679 regexp_stack_(NULL),
1681 call_descriptor_data_(NULL),
1682 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1683 // be fixed once the default isolate cleanup is done.
1684 random_number_generator_(NULL),
1685 store_buffer_hash_set_1_address_(NULL),
1686 store_buffer_hash_set_2_address_(NULL),
1687 serializer_enabled_(enable_serializer),
1688 has_fatal_error_(false),
1689 initialized_from_snapshot_(false),
1690 cpu_profiler_(NULL),
1691 heap_profiler_(NULL),
1692 function_entry_hook_(NULL),
1693 deferred_handles_head_(NULL),
1694 optimizing_compiler_thread_(NULL),
1695 stress_deopt_count_(0),
1696 next_optimization_id_(0),
1698 next_unique_sfi_id_(0),
1700 use_counter_callback_(NULL),
1701 basic_block_profiler_(NULL) {
1703 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1704 CHECK(thread_data_table_);
1706 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1707 TRACE_ISOLATE(constructor);
1709 memset(isolate_addresses_, 0,
1710 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1712 heap_.isolate_ = this;
1713 stack_guard_.isolate_ = this;
1715 // ThreadManager is initialized early to support locking an isolate
1716 // before it is entered.
1717 thread_manager_ = new ThreadManager();
1718 thread_manager_->isolate_ = this;
1721 // heap_histograms_ initializes itself.
1722 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1725 handle_scope_data_.Initialize();
1727 #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1728 name##_ = (initial_value);
1729 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1730 #undef ISOLATE_INIT_EXECUTE
1732 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1733 memset(name##_, 0, sizeof(type) * length);
1734 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1735 #undef ISOLATE_INIT_ARRAY_EXECUTE
1737 InitializeLoggingAndCounters();
1738 debug_ = new Debug(this);
1742 void Isolate::TearDown() {
1743 TRACE_ISOLATE(tear_down);
1745 // Temporarily set this isolate as current so that various parts of
1746 // the isolate can access it in their destructors without having a
1747 // direct pointer. We don't use Enter/Exit here to avoid
1748 // initializing the thread data.
1749 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1750 Isolate* saved_isolate = UncheckedCurrent();
1751 SetIsolateThreadLocals(this, NULL);
1756 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1757 thread_data_table_->RemoveAllThreads(this);
1760 if (serialize_partial_snapshot_cache_ != NULL) {
1761 delete[] serialize_partial_snapshot_cache_;
1762 serialize_partial_snapshot_cache_ = NULL;
1767 // Restore the previous current isolate.
1768 SetIsolateThreadLocals(saved_isolate, saved_data);
1772 void Isolate::GlobalTearDown() {
1773 delete thread_data_table_;
1774 thread_data_table_ = NULL;
1778 void Isolate::Deinit() {
1779 TRACE_ISOLATE(deinit);
1783 FreeThreadResources();
1785 if (concurrent_recompilation_enabled()) {
1786 optimizing_compiler_thread_->Stop();
1787 delete optimizing_compiler_thread_;
1788 optimizing_compiler_thread_ = NULL;
1791 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1792 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1795 DumpAndResetCompilationStats();
1797 if (FLAG_print_deopt_stress) {
1798 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1801 // We must stop the logger before we tear down other components.
1802 Sampler* sampler = logger_->sampler();
1803 if (sampler && sampler->IsActive()) sampler->Stop();
1805 delete deoptimizer_data_;
1806 deoptimizer_data_ = NULL;
1807 builtins_.TearDown();
1808 bootstrapper_->TearDown();
1810 if (runtime_profiler_ != NULL) {
1811 delete runtime_profiler_;
1812 runtime_profiler_ = NULL;
1815 delete basic_block_profiler_;
1816 basic_block_profiler_ = NULL;
1819 logger_->TearDown();
1821 delete heap_profiler_;
1822 heap_profiler_ = NULL;
1823 delete cpu_profiler_;
1824 cpu_profiler_ = NULL;
1828 void Isolate::PushToPartialSnapshotCache(Object* obj) {
1829 int length = serialize_partial_snapshot_cache_length();
1830 int capacity = serialize_partial_snapshot_cache_capacity();
1832 if (length >= capacity) {
1833 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1834 Object** new_array = new Object*[new_capacity];
1835 for (int i = 0; i < length; i++) {
1836 new_array[i] = serialize_partial_snapshot_cache()[i];
1838 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1839 set_serialize_partial_snapshot_cache(new_array);
1840 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1843 serialize_partial_snapshot_cache()[length] = obj;
1844 set_serialize_partial_snapshot_cache_length(length + 1);
1848 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1849 PerIsolateThreadData* data) {
1850 base::Thread::SetThreadLocal(isolate_key_, isolate);
1851 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1855 Isolate::~Isolate() {
1856 TRACE_ISOLATE(destructor);
1858 // Has to be called while counters_ are still alive
1859 runtime_zone_.DeleteKeptSegment();
1861 // The entry stack must be empty when we get here.
1862 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1864 delete entry_stack_;
1865 entry_stack_ = NULL;
1867 delete unicode_cache_;
1868 unicode_cache_ = NULL;
1873 delete[] call_descriptor_data_;
1874 call_descriptor_data_ = NULL;
1876 delete regexp_stack_;
1877 regexp_stack_ = NULL;
1879 delete descriptor_lookup_cache_;
1880 descriptor_lookup_cache_ = NULL;
1881 delete context_slot_cache_;
1882 context_slot_cache_ = NULL;
1883 delete keyed_lookup_cache_;
1884 keyed_lookup_cache_ = NULL;
1888 delete code_aging_helper_;
1889 code_aging_helper_ = NULL;
1890 delete stats_table_;
1891 stats_table_ = NULL;
1893 delete materialized_object_store_;
1894 materialized_object_store_ = NULL;
1902 delete handle_scope_implementer_;
1903 handle_scope_implementer_ = NULL;
1905 delete code_tracer();
1906 set_code_tracer(NULL);
1908 delete compilation_cache_;
1909 compilation_cache_ = NULL;
1910 delete bootstrapper_;
1911 bootstrapper_ = NULL;
1912 delete inner_pointer_to_code_cache_;
1913 inner_pointer_to_code_cache_ = NULL;
1915 delete thread_manager_;
1916 thread_manager_ = NULL;
1918 delete string_tracker_;
1919 string_tracker_ = NULL;
1921 delete memory_allocator_;
1922 memory_allocator_ = NULL;
1925 delete global_handles_;
1926 global_handles_ = NULL;
1927 delete eternal_handles_;
1928 eternal_handles_ = NULL;
1930 delete string_stream_debug_object_cache_;
1931 string_stream_debug_object_cache_ = NULL;
1933 delete external_reference_table_;
1934 external_reference_table_ = NULL;
1936 delete random_number_generator_;
1937 random_number_generator_ = NULL;
1944 void Isolate::InitializeThreadLocal() {
1945 thread_local_top_.isolate_ = this;
1946 thread_local_top_.Initialize();
1950 bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
1951 DCHECK(has_pending_exception());
1953 bool has_external_try_catch = HasExternalTryCatch();
1954 if (!has_external_try_catch) {
1955 thread_local_top_.external_caught_exception_ = false;
1959 bool catchable_by_js = is_catchable_by_javascript(pending_exception());
1960 if (catchable_by_js && IsFinallyOnTop()) {
1961 thread_local_top_.external_caught_exception_ = false;
1965 thread_local_top_.external_caught_exception_ = true;
1966 if (thread_local_top_.pending_exception_ == heap()->termination_exception()) {
1967 try_catch_handler()->can_continue_ = false;
1968 try_catch_handler()->has_terminated_ = true;
1969 try_catch_handler()->exception_ = heap()->null_value();
1971 v8::TryCatch* handler = try_catch_handler();
1972 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
1973 thread_local_top_.pending_message_obj_->IsTheHole());
1974 DCHECK(thread_local_top_.pending_message_script_->IsScript() ||
1975 thread_local_top_.pending_message_script_->IsTheHole());
1976 handler->can_continue_ = true;
1977 handler->has_terminated_ = false;
1978 handler->exception_ = pending_exception();
1979 // Propagate to the external try-catch only if we got an actual message.
1980 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
1982 handler->message_obj_ = thread_local_top_.pending_message_obj_;
1983 handler->message_script_ = thread_local_top_.pending_message_script_;
1984 handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
1985 handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
1991 void Isolate::InitializeLoggingAndCounters() {
1992 if (logger_ == NULL) {
1993 logger_ = new Logger(this);
1995 if (counters_ == NULL) {
1996 counters_ = new Counters(this);
2001 bool Isolate::Init(Deserializer* des) {
2002 TRACE_ISOLATE(init);
2004 stress_deopt_count_ = FLAG_deopt_every_n_times;
2006 has_fatal_error_ = false;
2008 if (function_entry_hook() != NULL) {
2009 // When function entry hooking is in effect, we have to create the code
2010 // stubs from scratch to get entry hooks, rather than loading the previously
2011 // generated stubs from disk.
2012 // If this assert fires, the initialization path has regressed.
2013 DCHECK(des == NULL);
2016 // The initialization process does not handle memory exhaustion.
2017 DisallowAllocationFailure disallow_allocation_failure(this);
2019 memory_allocator_ = new MemoryAllocator(this);
2020 code_range_ = new CodeRange(this);
2022 // Safe after setting Heap::isolate_, and initializing StackGuard
2023 heap_.SetStackLimits();
2025 #define ASSIGN_ELEMENT(CamelName, hacker_name) \
2026 isolate_addresses_[Isolate::k##CamelName##Address] = \
2027 reinterpret_cast<Address>(hacker_name##_address());
2028 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
2029 #undef ASSIGN_ELEMENT
2031 string_tracker_ = new StringTracker();
2032 string_tracker_->isolate_ = this;
2033 compilation_cache_ = new CompilationCache(this);
2034 keyed_lookup_cache_ = new KeyedLookupCache();
2035 context_slot_cache_ = new ContextSlotCache();
2036 descriptor_lookup_cache_ = new DescriptorLookupCache();
2037 unicode_cache_ = new UnicodeCache();
2038 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
2039 global_handles_ = new GlobalHandles(this);
2040 eternal_handles_ = new EternalHandles();
2041 bootstrapper_ = new Bootstrapper(this);
2042 handle_scope_implementer_ = new HandleScopeImplementer(this);
2043 stub_cache_ = new StubCache(this);
2044 materialized_object_store_ = new MaterializedObjectStore(this);
2045 regexp_stack_ = new RegExpStack();
2046 regexp_stack_->isolate_ = this;
2047 date_cache_ = new DateCache();
2048 call_descriptor_data_ =
2049 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2050 cpu_profiler_ = new CpuProfiler(this);
2051 heap_profiler_ = new HeapProfiler(heap());
2053 // Enable logging before setting up the heap
2054 logger_->SetUp(this);
2056 // Initialize other runtime facilities
2057 #if defined(USE_SIMULATOR)
2058 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
2059 V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC
2060 Simulator::Initialize(this);
2064 code_aging_helper_ = new CodeAgingHelper();
2067 // Ensure that the thread has a valid stack guard. The v8::Locker object
2068 // will ensure this too, but we don't have to use lockers if we are only
2069 // using one thread.
2070 ExecutionAccess lock(this);
2071 stack_guard_.InitThread(lock);
2074 // SetUp the object heap.
2075 DCHECK(!heap_.HasBeenSetUp());
2076 if (!heap_.SetUp()) {
2077 V8::FatalProcessOutOfMemory("heap setup");
2081 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2083 const bool create_heap_objects = (des == NULL);
2084 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2085 V8::FatalProcessOutOfMemory("heap object creation");
2089 if (create_heap_objects) {
2090 // Terminate the cache array with the sentinel so we can iterate.
2091 PushToPartialSnapshotCache(heap_.undefined_value());
2094 InitializeThreadLocal();
2096 bootstrapper_->Initialize(create_heap_objects);
2097 builtins_.SetUp(this, create_heap_objects);
2099 if (FLAG_log_internal_timer_events) {
2100 set_event_logger(Logger::DefaultEventLoggerSentinel);
2103 // Set default value if not yet set.
2104 // TODO(yangguo): move this to ResourceConstraints::ConfigureDefaults
2105 // once ResourceConstraints becomes an argument to the Isolate constructor.
2106 if (max_available_threads_ < 1) {
2107 // Choose the default between 1 and 4.
2108 max_available_threads_ =
2109 Max(Min(base::SysInfo::NumberOfProcessors(), 4), 1);
2112 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2113 PrintF("Concurrent recompilation has been disabled for tracing.\n");
2114 } else if (OptimizingCompilerThread::Enabled(max_available_threads_)) {
2115 optimizing_compiler_thread_ = new OptimizingCompilerThread(this);
2116 optimizing_compiler_thread_->Start();
2119 // Initialize runtime profiler before deserialization, because collections may
2120 // occur, clearing/updating ICs.
2121 runtime_profiler_ = new RuntimeProfiler(this);
2123 // If we are deserializing, read the state into the now-empty heap.
2124 if (!create_heap_objects) {
2125 des->Deserialize(this);
2127 stub_cache_->Initialize();
2129 // Finish initialization of ThreadLocal after deserialization is done.
2130 clear_pending_exception();
2131 clear_pending_message();
2132 clear_scheduled_exception();
2134 // Deserializing may put strange things in the root array's copy of the
2136 heap_.SetStackLimits();
2138 // Quiet the heap NaN if needed on target platform.
2139 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
2141 if (FLAG_trace_turbo) {
2142 // Create an empty file.
2143 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2146 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2147 Internals::kIsolateEmbedderDataOffset);
2148 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2149 Internals::kIsolateRootsOffset);
2150 CHECK_EQ(static_cast<int>(
2151 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2152 Internals::kAmountOfExternalAllocatedMemoryOffset);
2153 CHECK_EQ(static_cast<int>(OFFSET_OF(
2155 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2156 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2158 time_millis_at_init_ = base::OS::TimeCurrentMillis();
2160 heap_.NotifyDeserializationComplete();
2162 if (!create_heap_objects) {
2163 // Now that the heap is consistent, it's OK to generate the code for the
2164 // deopt entry table that might have been referred to by optimized code in
2166 HandleScope scope(this);
2167 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2170 kDeoptTableSerializeEntryCount - 1);
2173 if (!serializer_enabled()) {
2174 // Ensure that all stubs which need to be generated ahead of time, but
2175 // cannot be serialized into the snapshot have been generated.
2176 HandleScope scope(this);
2177 CodeStub::GenerateFPStubs(this);
2178 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2179 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2182 initialized_from_snapshot_ = (des != NULL);
2184 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2190 // Initialized lazily to allow early
2191 // v8::V8::SetAddHistogramSampleFunction calls.
2192 StatsTable* Isolate::stats_table() {
2193 if (stats_table_ == NULL) {
2194 stats_table_ = new StatsTable;
2196 return stats_table_;
2200 void Isolate::Enter() {
2201 Isolate* current_isolate = NULL;
2202 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2203 if (current_data != NULL) {
2204 current_isolate = current_data->isolate_;
2205 DCHECK(current_isolate != NULL);
2206 if (current_isolate == this) {
2207 DCHECK(Current() == this);
2208 DCHECK(entry_stack_ != NULL);
2209 DCHECK(entry_stack_->previous_thread_data == NULL ||
2210 entry_stack_->previous_thread_data->thread_id().Equals(
2211 ThreadId::Current()));
2212 // Same thread re-enters the isolate, no need to re-init anything.
2213 entry_stack_->entry_count++;
2218 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2219 DCHECK(data != NULL);
2220 DCHECK(data->isolate_ == this);
2222 EntryStackItem* item = new EntryStackItem(current_data,
2225 entry_stack_ = item;
2227 SetIsolateThreadLocals(this, data);
2229 // In case it's the first time some thread enters the isolate.
2230 set_thread_id(data->thread_id());
2234 void Isolate::Exit() {
2235 DCHECK(entry_stack_ != NULL);
2236 DCHECK(entry_stack_->previous_thread_data == NULL ||
2237 entry_stack_->previous_thread_data->thread_id().Equals(
2238 ThreadId::Current()));
2240 if (--entry_stack_->entry_count > 0) return;
2242 DCHECK(CurrentPerIsolateThreadData() != NULL);
2243 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
2246 EntryStackItem* item = entry_stack_;
2247 entry_stack_ = item->previous_item;
2249 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2250 Isolate* previous_isolate = item->previous_isolate;
2254 // Reinit the current thread for the isolate it was running before this one.
2255 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2259 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2260 deferred->next_ = deferred_handles_head_;
2261 if (deferred_handles_head_ != NULL) {
2262 deferred_handles_head_->previous_ = deferred;
2264 deferred_handles_head_ = deferred;
2268 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2270 // In debug mode assert that the linked list is well-formed.
2271 DeferredHandles* deferred_iterator = deferred;
2272 while (deferred_iterator->previous_ != NULL) {
2273 deferred_iterator = deferred_iterator->previous_;
2275 DCHECK(deferred_handles_head_ == deferred_iterator);
2277 if (deferred_handles_head_ == deferred) {
2278 deferred_handles_head_ = deferred_handles_head_->next_;
2280 if (deferred->next_ != NULL) {
2281 deferred->next_->previous_ = deferred->previous_;
2283 if (deferred->previous_ != NULL) {
2284 deferred->previous_->next_ = deferred->next_;
2289 void Isolate::DumpAndResetCompilationStats() {
2290 if (turbo_statistics() != nullptr) {
2291 OFStream os(stdout);
2292 os << *turbo_statistics() << std::endl;
2294 if (hstatistics() != nullptr) hstatistics()->Print();
2295 delete turbo_statistics_;
2296 turbo_statistics_ = nullptr;
2297 delete hstatistics_;
2298 hstatistics_ = nullptr;
2302 HStatistics* Isolate::GetHStatistics() {
2303 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2304 return hstatistics();
2308 CompilationStatistics* Isolate::GetTurboStatistics() {
2309 if (turbo_statistics() == NULL)
2310 set_turbo_statistics(new CompilationStatistics());
2311 return turbo_statistics();
2315 HTracer* Isolate::GetHTracer() {
2316 if (htracer() == NULL) set_htracer(new HTracer(id()));
2321 CodeTracer* Isolate::GetCodeTracer() {
2322 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2323 return code_tracer();
2327 Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2328 Context* native_context = context()->native_context();
2329 Object* maybe_map_array = native_context->js_array_maps();
2330 if (!maybe_map_array->IsUndefined()) {
2331 Object* maybe_transitioned_map =
2332 FixedArray::cast(maybe_map_array)->get(kind);
2333 if (!maybe_transitioned_map->IsUndefined()) {
2334 return Map::cast(maybe_transitioned_map);
2341 bool Isolate::use_crankshaft() const {
2342 return FLAG_crankshaft &&
2343 !serializer_enabled_ &&
2344 CpuFeatures::SupportsCrankshaft();
2348 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2349 Map* root_array_map =
2350 get_initial_js_array_map(GetInitialFastElementsKind());
2351 DCHECK(root_array_map != NULL);
2352 JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2354 // Check that the array prototype hasn't been altered WRT empty elements.
2355 if (root_array_map->prototype() != initial_array_proto) return false;
2356 if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2360 // Check that the object prototype hasn't been altered WRT empty elements.
2361 JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2362 PrototypeIterator iter(this, initial_array_proto);
2363 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
2366 if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2371 return iter.IsAtEnd();
2375 CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2376 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2377 return &call_descriptor_data_[index];
2381 Object* Isolate::FindCodeObject(Address a) {
2382 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2387 #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2388 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2389 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2390 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2391 #undef ISOLATE_FIELD_OFFSET
2395 Handle<JSObject> Isolate::GetSymbolRegistry() {
2396 if (heap()->symbol_registry()->IsSmi()) {
2397 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2398 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2399 heap()->set_symbol_registry(*registry);
2401 static const char* nested[] = {"for", "for_api", "keyFor", "private_api",
2403 for (unsigned i = 0; i < arraysize(nested); ++i) {
2404 Handle<String> name = factory()->InternalizeUtf8String(nested[i]);
2405 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2406 JSObject::NormalizeProperties(obj, KEEP_INOBJECT_PROPERTIES, 8,
2407 "SetupSymbolRegistry");
2408 JSObject::SetProperty(registry, name, obj, STRICT).Assert();
2411 return Handle<JSObject>::cast(factory()->symbol_registry());
2415 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2416 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2417 if (callback == call_completed_callbacks_.at(i)) return;
2419 call_completed_callbacks_.Add(callback);
2423 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2424 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2425 if (callback == call_completed_callbacks_.at(i)) {
2426 call_completed_callbacks_.Remove(i);
2432 void Isolate::FireCallCompletedCallback() {
2433 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2434 bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2435 if (!has_call_completed_callbacks && !run_microtasks) return;
2437 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2438 if (run_microtasks) RunMicrotasks();
2439 // Fire callbacks. Increase call depth to prevent recursive callbacks.
2440 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2441 reinterpret_cast<v8::Isolate*>(this));
2442 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2443 call_completed_callbacks_.at(i)();
2448 void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2449 promise_reject_callback_ = callback;
2453 void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2454 Handle<Object> value,
2455 v8::PromiseRejectEvent event) {
2456 if (promise_reject_callback_ == NULL) return;
2457 Handle<JSArray> stack_trace;
2458 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2459 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2461 promise_reject_callback_(v8::PromiseRejectMessage(
2462 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2463 v8::Utils::StackTraceToLocal(stack_trace)));
2467 void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2468 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2469 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2470 int num_tasks = pending_microtask_count();
2471 DCHECK(num_tasks <= queue->length());
2472 if (num_tasks == 0) {
2473 queue = factory()->NewFixedArray(8);
2474 heap()->set_microtask_queue(*queue);
2475 } else if (num_tasks == queue->length()) {
2476 queue = FixedArray::CopySize(queue, num_tasks * 2);
2477 heap()->set_microtask_queue(*queue);
2479 DCHECK(queue->get(num_tasks)->IsUndefined());
2480 queue->set(num_tasks, *microtask);
2481 set_pending_microtask_count(num_tasks + 1);
2485 void Isolate::RunMicrotasks() {
2486 // %RunMicrotasks may be called in mjsunit tests, which violates
2487 // this assertion, hence the check for --allow-natives-syntax.
2488 // TODO(adamk): However, this also fails some layout tests.
2490 // DCHECK(FLAG_allow_natives_syntax ||
2491 // handle_scope_implementer()->CallDepthIsZero());
2493 // Increase call depth to prevent recursive callbacks.
2494 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2495 reinterpret_cast<v8::Isolate*>(this));
2497 while (pending_microtask_count() > 0) {
2498 HandleScope scope(this);
2499 int num_tasks = pending_microtask_count();
2500 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2501 DCHECK(num_tasks <= queue->length());
2502 set_pending_microtask_count(0);
2503 heap()->set_microtask_queue(heap()->empty_fixed_array());
2505 for (int i = 0; i < num_tasks; i++) {
2506 HandleScope scope(this);
2507 Handle<Object> microtask(queue->get(i), this);
2508 if (microtask->IsJSFunction()) {
2509 Handle<JSFunction> microtask_function =
2510 Handle<JSFunction>::cast(microtask);
2511 SaveContext save(this);
2512 set_context(microtask_function->context()->native_context());
2513 MaybeHandle<Object> maybe_exception;
2514 MaybeHandle<Object> result =
2515 Execution::TryCall(microtask_function, factory()->undefined_value(),
2516 0, NULL, &maybe_exception);
2517 // If execution is terminating, just bail out.
2518 Handle<Object> exception;
2519 if (result.is_null() && maybe_exception.is_null()) {
2520 // Clear out any remaining callbacks in the queue.
2521 heap()->set_microtask_queue(heap()->empty_fixed_array());
2522 set_pending_microtask_count(0);
2526 Handle<CallHandlerInfo> callback_info =
2527 Handle<CallHandlerInfo>::cast(microtask);
2528 v8::MicrotaskCallback callback =
2529 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2530 void* data = v8::ToCData<void*>(callback_info->data());
2538 void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2539 DCHECK(!use_counter_callback_);
2540 use_counter_callback_ = callback;
2544 void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
2545 if (use_counter_callback_) {
2546 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2551 BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2552 if (basic_block_profiler_ == NULL) {
2553 basic_block_profiler_ = new BasicBlockProfiler();
2555 return basic_block_profiler_;
2559 std::string Isolate::GetTurboCfgFileName() {
2560 if (FLAG_trace_turbo_cfg_file == NULL) {
2561 std::ostringstream os;
2562 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2565 return FLAG_trace_turbo_cfg_file;
2570 // Heap::detached_contexts tracks detached contexts as pairs
2571 // (number of GC since the context was detached, the context).
2572 void Isolate::AddDetachedContext(Handle<Context> context) {
2573 HandleScope scope(this);
2574 Handle<WeakCell> cell = factory()->NewWeakCell(context);
2575 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2576 int length = detached_contexts->length();
2577 detached_contexts = FixedArray::CopySize(detached_contexts, length + 2);
2578 detached_contexts->set(length, Smi::FromInt(0));
2579 detached_contexts->set(length + 1, *cell);
2580 heap()->set_detached_contexts(*detached_contexts);
2584 void Isolate::CheckDetachedContextsAfterGC() {
2585 HandleScope scope(this);
2586 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2587 int length = detached_contexts->length();
2588 if (length == 0) return;
2590 for (int i = 0; i < length; i += 2) {
2591 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2592 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2593 if (!cell->cleared()) {
2594 detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2595 detached_contexts->set(new_length + 1, cell);
2598 counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
2600 if (FLAG_trace_detached_contexts) {
2601 PrintF("%d detached contexts are collected out of %d\n",
2602 length - new_length, length);
2603 for (int i = 0; i < new_length; i += 2) {
2604 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2605 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2606 if (mark_sweeps > 3) {
2607 PrintF("detached context 0x%p\n survived %d GCs (leak?)\n",
2608 static_cast<void*>(cell->value()), mark_sweeps);
2612 if (new_length == 0) {
2613 heap()->set_detached_contexts(heap()->empty_fixed_array());
2614 } else if (new_length < length) {
2615 heap()->RightTrimFixedArray<Heap::FROM_GC>(*detached_contexts,
2616 length - new_length);
2621 bool StackLimitCheck::JsHasOverflowed() const {
2622 StackGuard* stack_guard = isolate_->stack_guard();
2623 #ifdef USE_SIMULATOR
2624 // The simulator uses a separate JS stack.
2625 Address jssp_address = Simulator::current(isolate_)->get_sp();
2626 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
2627 if (jssp < stack_guard->real_jslimit()) return true;
2628 #endif // USE_SIMULATOR
2629 return GetCurrentStackPosition() < stack_guard->real_climit();
2633 bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2634 // First check whether the previous scope intercepts.
2635 if (prev_ && prev_->Intercept(flag)) return true;
2636 // Then check whether this scope intercepts.
2637 if ((flag & intercept_mask_)) {
2638 intercepted_flags_ |= flag;
2644 } } // namespace v8::internal