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.
10 #include "src/base/platform/platform.h"
11 #include "src/base/utils/random-number-generator.h"
12 #include "src/bootstrapper.h"
13 #include "src/codegen.h"
14 #include "src/compilation-cache.h"
15 #include "src/cpu-profiler.h"
16 #include "src/debug.h"
17 #include "src/deoptimizer.h"
18 #include "src/heap/spaces.h"
19 #include "src/heap/sweeper-thread.h"
20 #include "src/heap-profiler.h"
21 #include "src/hydrogen.h"
22 #include "src/isolate-inl.h"
23 #include "src/lithium-allocator.h"
25 #include "src/messages.h"
26 #include "src/prototype.h"
27 #include "src/regexp-stack.h"
28 #include "src/runtime-profiler.h"
29 #include "src/sampler.h"
30 #include "src/scopeinfo.h"
31 #include "src/serialize.h"
32 #include "src/simulator.h"
33 #include "src/stub-cache.h"
34 #include "src/version.h"
35 #include "src/vm-state-inl.h"
41 base::Atomic32 ThreadId::highest_thread_id_ = 0;
43 int ThreadId::AllocateThreadId() {
44 int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
49 int ThreadId::GetCurrentThreadId() {
50 Isolate::EnsureInitialized();
51 int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
53 thread_id = AllocateThreadId();
54 base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
60 ThreadLocalTop::ThreadLocalTop() {
65 void ThreadLocalTop::InitializeInternal() {
72 external_callback_scope_ = NULL;
73 current_vm_state_ = EXTERNAL;
74 try_catch_handler_ = NULL;
76 thread_id_ = ThreadId::Invalid();
77 external_caught_exception_ = false;
78 failed_access_check_callback_ = NULL;
81 top_lookup_result_ = NULL;
83 // These members are re-initialized later after deserialization
85 pending_exception_ = NULL;
86 has_pending_message_ = false;
87 rethrowing_message_ = false;
88 pending_message_obj_ = NULL;
89 pending_message_script_ = NULL;
90 scheduled_exception_ = NULL;
94 void ThreadLocalTop::Initialize() {
97 simulator_ = Simulator::current(isolate_);
99 thread_id_ = ThreadId::Current();
103 base::Thread::LocalStorageKey Isolate::isolate_key_;
104 base::Thread::LocalStorageKey Isolate::thread_id_key_;
105 base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
107 base::Thread::LocalStorageKey PerThreadAssertScopeBase::thread_local_key;
109 base::LazyMutex Isolate::process_wide_mutex_ = LAZY_MUTEX_INITIALIZER;
110 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
111 base::Atomic32 Isolate::isolate_counter_ = 0;
113 Isolate::PerIsolateThreadData*
114 Isolate::FindOrAllocatePerThreadDataForThisThread() {
116 ThreadId thread_id = ThreadId::Current();
117 PerIsolateThreadData* per_thread = NULL;
119 base::LockGuard<base::Mutex> lock_guard(process_wide_mutex_.Pointer());
120 per_thread = thread_data_table_->Lookup(this, thread_id);
121 if (per_thread == NULL) {
122 per_thread = new PerIsolateThreadData(this, thread_id);
123 thread_data_table_->Insert(per_thread);
125 DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
131 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
132 ThreadId thread_id = ThreadId::Current();
133 return FindPerThreadDataForThread(thread_id);
137 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
138 ThreadId thread_id) {
140 PerIsolateThreadData* per_thread = NULL;
142 base::LockGuard<base::Mutex> lock_guard(process_wide_mutex_.Pointer());
143 per_thread = thread_data_table_->Lookup(this, thread_id);
149 void Isolate::EnsureInitialized() {
150 base::LockGuard<base::Mutex> lock_guard(process_wide_mutex_.Pointer());
151 if (thread_data_table_ == NULL) {
152 isolate_key_ = base::Thread::CreateThreadLocalKey();
153 thread_id_key_ = base::Thread::CreateThreadLocalKey();
154 per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
156 PerThreadAssertScopeBase::thread_local_key =
157 base::Thread::CreateThreadLocalKey();
159 thread_data_table_ = new Isolate::ThreadDataTable();
164 Address Isolate::get_address_from_id(Isolate::AddressId id) {
165 return isolate_addresses_[id];
169 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
170 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
172 return thread_storage + sizeof(ThreadLocalTop);
176 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
177 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
178 v->VisitThread(this, thread);
182 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
183 // Visit the roots from the top for a given thread.
184 v->VisitPointer(&thread->pending_exception_);
185 v->VisitPointer(&(thread->pending_message_obj_));
186 v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
187 v->VisitPointer(BitCast<Object**>(&(thread->context_)));
188 v->VisitPointer(&thread->scheduled_exception_);
190 for (v8::TryCatch* block = thread->try_catch_handler();
192 block = block->next_) {
193 v->VisitPointer(BitCast<Object**>(&(block->exception_)));
194 v->VisitPointer(BitCast<Object**>(&(block->message_obj_)));
195 v->VisitPointer(BitCast<Object**>(&(block->message_script_)));
198 // Iterate over pointers on native execution stack.
199 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
200 it.frame()->Iterate(v);
203 // Iterate pointers in live lookup results.
204 thread->top_lookup_result_->Iterate(v);
208 void Isolate::Iterate(ObjectVisitor* v) {
209 ThreadLocalTop* current_t = thread_local_top();
210 Iterate(v, current_t);
214 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
215 for (DeferredHandles* deferred = deferred_handles_head_;
217 deferred = deferred->next_) {
218 deferred->Iterate(visitor);
224 bool Isolate::IsDeferredHandle(Object** handle) {
225 // Each DeferredHandles instance keeps the handles to one job in the
226 // concurrent recompilation queue, containing a list of blocks. Each block
227 // contains kHandleBlockSize handles except for the first block, which may
228 // not be fully filled.
229 // We iterate through all the blocks to see whether the argument handle
230 // belongs to one of the blocks. If so, it is deferred.
231 for (DeferredHandles* deferred = deferred_handles_head_;
233 deferred = deferred->next_) {
234 List<Object**>* blocks = &deferred->blocks_;
235 for (int i = 0; i < blocks->length(); i++) {
236 Object** block_limit = (i == 0) ? deferred->first_block_limit_
237 : blocks->at(i) + kHandleBlockSize;
238 if (blocks->at(i) <= handle && handle < block_limit) return true;
246 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
247 thread_local_top()->set_try_catch_handler(that);
251 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
252 DCHECK(thread_local_top()->try_catch_handler() == that);
253 thread_local_top()->set_try_catch_handler(that->next_);
254 thread_local_top()->catcher_ = NULL;
258 Handle<String> Isolate::StackTraceString() {
259 if (stack_trace_nesting_level_ == 0) {
260 stack_trace_nesting_level_++;
261 HeapStringAllocator allocator;
262 StringStream::ClearMentionedObjectCache(this);
263 StringStream accumulator(&allocator);
264 incomplete_message_ = &accumulator;
265 PrintStack(&accumulator);
266 Handle<String> stack_trace = accumulator.ToString(this);
267 incomplete_message_ = NULL;
268 stack_trace_nesting_level_ = 0;
270 } else if (stack_trace_nesting_level_ == 1) {
271 stack_trace_nesting_level_++;
272 base::OS::PrintError(
273 "\n\nAttempt to print stack while printing stack (double fault)\n");
274 base::OS::PrintError(
275 "If you are lucky you may find a partial stack dump on stdout.\n\n");
276 incomplete_message_->OutputToStdOut();
277 return factory()->empty_string();
281 return factory()->empty_string();
286 void Isolate::PushStackTraceAndDie(unsigned int magic,
289 unsigned int magic2) {
290 const int kMaxStackTraceSize = 8192;
291 Handle<String> trace = StackTraceString();
292 uint8_t buffer[kMaxStackTraceSize];
293 int length = Min(kMaxStackTraceSize - 1, trace->length());
294 String::WriteToFlat(*trace, buffer, 0, length);
295 buffer[length] = '\0';
296 // TODO(dcarney): convert buffer to utf8?
297 base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2,
298 static_cast<void*>(object), static_cast<void*>(map),
299 reinterpret_cast<char*>(buffer));
304 // Determines whether the given stack frame should be displayed in
305 // a stack trace. The caller is the error constructor that asked
306 // for the stack trace to be collected. The first time a construct
307 // call to this function is encountered it is skipped. The seen_caller
308 // in/out parameter is used to remember if the caller has been seen
310 static bool IsVisibleInStackTrace(JSFunction* fun,
314 if ((fun == caller) && !(*seen_caller)) {
318 // Skip all frames until we've seen the caller.
319 if (!(*seen_caller)) return false;
320 // Also, skip non-visible built-in functions and any call with the builtins
321 // object as receiver, so as to not reveal either the builtins object or
322 // an internal function.
323 // The --builtins-in-stack-traces command line flag allows including
324 // internal call sites in the stack trace for debugging purposes.
325 if (!FLAG_builtins_in_stack_traces) {
326 if (receiver->IsJSBuiltinsObject()) return false;
327 if (fun->IsBuiltin()) {
328 return fun->shared()->native();
329 } else if (fun->IsFromNativeScript() || fun->IsFromExtensionScript()) {
337 Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
338 Handle<Object> caller) {
339 // Get stack trace limit.
340 Handle<Object> error = Object::GetProperty(
341 this, js_builtins_object(), "$Error").ToHandleChecked();
342 if (!error->IsJSObject()) return factory()->undefined_value();
344 Handle<String> stackTraceLimit =
345 factory()->InternalizeUtf8String("stackTraceLimit");
346 DCHECK(!stackTraceLimit.is_null());
347 Handle<Object> stack_trace_limit =
348 JSObject::GetDataProperty(Handle<JSObject>::cast(error),
350 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
351 int limit = FastD2IChecked(stack_trace_limit->Number());
352 limit = Max(limit, 0); // Ensure that limit is not negative.
354 int initial_size = Min(limit, 10);
355 Handle<FixedArray> elements =
356 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
358 // If the caller parameter is a function we skip frames until we're
359 // under it before starting to collect.
360 bool seen_caller = !caller->IsJSFunction();
361 // First element is reserved to store the number of sloppy frames.
364 int sloppy_frames = 0;
365 bool encountered_strict_function = false;
366 for (JavaScriptFrameIterator iter(this);
367 !iter.done() && frames_seen < limit;
369 JavaScriptFrame* frame = iter.frame();
370 // Set initial size to the maximum inlining level + 1 for the outermost
372 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
373 frame->Summarize(&frames);
374 for (int i = frames.length() - 1; i >= 0; i--) {
375 Handle<JSFunction> fun = frames[i].function();
376 Handle<Object> recv = frames[i].receiver();
377 // Filter out internal frames that we do not want to show.
378 if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) continue;
379 // Filter out frames from other security contexts.
380 if (!this->context()->HasSameSecurityTokenAs(fun->context())) continue;
381 if (cursor + 4 > elements->length()) {
382 int new_capacity = JSObject::NewElementsCapacity(elements->length());
383 Handle<FixedArray> new_elements =
384 factory()->NewFixedArrayWithHoles(new_capacity);
385 for (int i = 0; i < cursor; i++) {
386 new_elements->set(i, elements->get(i));
388 elements = new_elements;
390 DCHECK(cursor + 4 <= elements->length());
393 Handle<Code> code = frames[i].code();
394 Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
395 // The stack trace API should not expose receivers and function
396 // objects on frames deeper than the top-most one with a strict
397 // mode function. The number of sloppy frames is stored as
398 // first element in the result array.
399 if (!encountered_strict_function) {
400 if (fun->shared()->strict_mode() == STRICT) {
401 encountered_strict_function = true;
406 elements->set(cursor++, *recv);
407 elements->set(cursor++, *fun);
408 elements->set(cursor++, *code);
409 elements->set(cursor++, *offset);
413 elements->set(0, Smi::FromInt(sloppy_frames));
414 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
415 result->set_length(Smi::FromInt(cursor));
420 void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
421 if (capture_stack_trace_for_uncaught_exceptions_) {
422 // Capture stack trace for a detailed exception message.
423 Handle<Name> key = factory()->detailed_stack_trace_symbol();
424 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
425 stack_trace_for_uncaught_exceptions_frame_limit_,
426 stack_trace_for_uncaught_exceptions_options_);
427 JSObject::SetProperty(error_object, key, stack_trace, STRICT).Assert();
432 void Isolate::CaptureAndSetSimpleStackTrace(Handle<JSObject> error_object,
433 Handle<Object> caller) {
434 // Capture stack trace for simple stack trace string formatting.
435 Handle<Name> key = factory()->stack_trace_symbol();
436 Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
437 JSObject::SetProperty(error_object, key, stack_trace, STRICT).Assert();
441 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
442 int frame_limit, StackTrace::StackTraceOptions options) {
443 // Ensure no negative values.
444 int limit = Max(frame_limit, 0);
445 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
447 Handle<String> column_key =
448 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("column"));
449 Handle<String> line_key =
450 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("lineNumber"));
451 Handle<String> script_id_key =
452 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptId"));
453 Handle<String> script_name_key =
454 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptName"));
455 Handle<String> script_name_or_source_url_key =
456 factory()->InternalizeOneByteString(
457 STATIC_ASCII_VECTOR("scriptNameOrSourceURL"));
458 Handle<String> function_key =
459 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("functionName"));
460 Handle<String> eval_key =
461 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isEval"));
462 Handle<String> constructor_key =
463 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isConstructor"));
465 StackTraceFrameIterator it(this);
467 while (!it.done() && (frames_seen < limit)) {
468 JavaScriptFrame* frame = it.frame();
469 // Set initial size to the maximum inlining level + 1 for the outermost
471 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
472 frame->Summarize(&frames);
473 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
474 Handle<JSFunction> fun = frames[i].function();
475 // Filter frames from other security contexts.
476 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
477 !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
479 // Create a JSObject to hold the information for the StackFrame.
480 Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
482 Handle<Script> script(Script::cast(fun->shared()->script()));
484 if (options & StackTrace::kLineNumber) {
485 int script_line_offset = script->line_offset()->value();
486 int position = frames[i].code()->SourcePosition(frames[i].pc());
487 int line_number = Script::GetLineNumber(script, position);
488 // line_number is already shifted by the script_line_offset.
489 int relative_line_number = line_number - script_line_offset;
490 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
491 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
492 int start = (relative_line_number == 0) ? 0 :
493 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
494 int column_offset = position - start;
495 if (relative_line_number == 0) {
496 // For the case where the code is on the same line as the script
498 column_offset += script->column_offset()->value();
500 JSObject::AddProperty(
501 stack_frame, column_key,
502 handle(Smi::FromInt(column_offset + 1), this), NONE);
504 JSObject::AddProperty(
505 stack_frame, line_key,
506 handle(Smi::FromInt(line_number + 1), this), NONE);
509 if (options & StackTrace::kScriptId) {
510 JSObject::AddProperty(
511 stack_frame, script_id_key, handle(script->id(), this), NONE);
514 if (options & StackTrace::kScriptName) {
515 JSObject::AddProperty(
516 stack_frame, script_name_key, handle(script->name(), this), NONE);
519 if (options & StackTrace::kScriptNameOrSourceURL) {
520 Handle<Object> result = Script::GetNameOrSourceURL(script);
521 JSObject::AddProperty(
522 stack_frame, script_name_or_source_url_key, result, NONE);
525 if (options & StackTrace::kFunctionName) {
526 Handle<Object> fun_name(fun->shared()->DebugName(), this);
527 JSObject::AddProperty(stack_frame, function_key, fun_name, NONE);
530 if (options & StackTrace::kIsEval) {
531 Handle<Object> is_eval =
532 script->compilation_type() == Script::COMPILATION_TYPE_EVAL ?
533 factory()->true_value() : factory()->false_value();
534 JSObject::AddProperty(stack_frame, eval_key, is_eval, NONE);
537 if (options & StackTrace::kIsConstructor) {
538 Handle<Object> is_constructor = (frames[i].is_constructor()) ?
539 factory()->true_value() : factory()->false_value();
540 JSObject::AddProperty(
541 stack_frame, constructor_key, is_constructor, NONE);
544 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
550 stack_trace->set_length(Smi::FromInt(frames_seen));
555 void Isolate::PrintStack(FILE* out) {
556 if (stack_trace_nesting_level_ == 0) {
557 stack_trace_nesting_level_++;
558 StringStream::ClearMentionedObjectCache(this);
559 HeapStringAllocator allocator;
560 StringStream accumulator(&allocator);
561 incomplete_message_ = &accumulator;
562 PrintStack(&accumulator);
563 accumulator.OutputToFile(out);
564 InitializeLoggingAndCounters();
565 accumulator.Log(this);
566 incomplete_message_ = NULL;
567 stack_trace_nesting_level_ = 0;
568 } else if (stack_trace_nesting_level_ == 1) {
569 stack_trace_nesting_level_++;
570 base::OS::PrintError(
571 "\n\nAttempt to print stack while printing stack (double fault)\n");
572 base::OS::PrintError(
573 "If you are lucky you may find a partial stack dump on stdout.\n\n");
574 incomplete_message_->OutputToFile(out);
579 static void PrintFrames(Isolate* isolate,
580 StringStream* accumulator,
581 StackFrame::PrintMode mode) {
582 StackFrameIterator it(isolate);
583 for (int i = 0; !it.done(); it.Advance()) {
584 it.frame()->Print(accumulator, mode, i++);
589 void Isolate::PrintStack(StringStream* accumulator) {
590 if (!IsInitialized()) {
592 "\n==== JS stack trace is not available =======================\n\n");
594 "\n==== Isolate for the thread is not initialized =============\n\n");
597 // The MentionedObjectCache is not GC-proof at the moment.
598 DisallowHeapAllocation no_gc;
599 DCHECK(StringStream::IsMentionedObjectCacheClear(this));
601 // Avoid printing anything if there are no frames.
602 if (c_entry_fp(thread_local_top()) == 0) return;
605 "\n==== JS stack trace =========================================\n\n");
606 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
609 "\n==== Details ================================================\n\n");
610 PrintFrames(this, accumulator, StackFrame::DETAILS);
612 accumulator->PrintMentionedObjectCache(this);
613 accumulator->Add("=====================\n\n");
617 void Isolate::SetFailedAccessCheckCallback(
618 v8::FailedAccessCheckCallback callback) {
619 thread_local_top()->failed_access_check_callback_ = callback;
623 static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
624 Handle<JSObject> receiver) {
625 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
626 if (!constructor->shared()->IsApiFunction()) return NULL;
629 constructor->shared()->get_api_func_data()->access_check_info();
630 if (data_obj == isolate->heap()->undefined_value()) return NULL;
632 return AccessCheckInfo::cast(data_obj);
636 void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver,
637 v8::AccessType type) {
638 if (!thread_local_top()->failed_access_check_callback_) {
639 Handle<String> message = factory()->InternalizeUtf8String("no access");
640 ScheduleThrow(*factory()->NewTypeError(message));
644 DCHECK(receiver->IsAccessCheckNeeded());
647 // Get the data object from access check info.
648 HandleScope scope(this);
650 { DisallowHeapAllocation no_gc;
651 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
652 if (!access_check_info) return;
653 data = handle(access_check_info->data(), this);
656 // Leaving JavaScript.
657 VMState<EXTERNAL> state(this);
658 thread_local_top()->failed_access_check_callback_(
659 v8::Utils::ToLocal(receiver),
661 v8::Utils::ToLocal(data));
665 enum MayAccessDecision {
670 static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
671 Handle<JSObject> receiver,
672 v8::AccessType type) {
673 DisallowHeapAllocation no_gc;
674 // During bootstrapping, callback functions are not enabled yet.
675 if (isolate->bootstrapper()->IsActive()) return YES;
677 if (receiver->IsJSGlobalProxy()) {
678 Object* receiver_context = JSGlobalProxy::cast(*receiver)->native_context();
679 if (!receiver_context->IsContext()) return NO;
681 // Get the native context of current top context.
682 // avoid using Isolate::native_context() because it uses Handle.
683 Context* native_context =
684 isolate->context()->global_object()->native_context();
685 if (receiver_context == native_context) return YES;
687 if (Context::cast(receiver_context)->security_token() ==
688 native_context->security_token())
696 bool Isolate::MayNamedAccess(Handle<JSObject> receiver,
698 v8::AccessType type) {
699 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
701 // Skip checks for hidden properties access. Note, we do not
702 // require existence of a context in this case.
703 if (key.is_identical_to(factory()->hidden_string())) return true;
705 // Check for compatibility between the security tokens in the
706 // current lexical context and the accessed object.
709 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
710 if (decision != UNKNOWN) return decision == YES;
712 HandleScope scope(this);
714 v8::NamedSecurityCallback callback;
715 { DisallowHeapAllocation no_gc;
716 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
717 if (!access_check_info) return false;
718 Object* fun_obj = access_check_info->named_callback();
719 callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
720 if (!callback) return false;
721 data = handle(access_check_info->data(), this);
724 LOG(this, ApiNamedSecurityCheck(*key));
726 // Leaving JavaScript.
727 VMState<EXTERNAL> state(this);
728 return callback(v8::Utils::ToLocal(receiver),
729 v8::Utils::ToLocal(key),
731 v8::Utils::ToLocal(data));
735 bool Isolate::MayIndexedAccess(Handle<JSObject> receiver,
737 v8::AccessType type) {
738 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
739 // Check for compatibility between the security tokens in the
740 // current lexical context and the accessed object.
743 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
744 if (decision != UNKNOWN) return decision == YES;
746 HandleScope scope(this);
748 v8::IndexedSecurityCallback callback;
749 { DisallowHeapAllocation no_gc;
750 // Get named access check callback
751 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
752 if (!access_check_info) return false;
753 Object* fun_obj = access_check_info->indexed_callback();
754 callback = v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
755 if (!callback) return false;
756 data = handle(access_check_info->data(), this);
759 LOG(this, ApiIndexedSecurityCheck(index));
761 // Leaving JavaScript.
762 VMState<EXTERNAL> state(this);
764 v8::Utils::ToLocal(receiver), index, type, v8::Utils::ToLocal(data));
768 const char* const Isolate::kStackOverflowMessage =
769 "Uncaught RangeError: Maximum call stack size exceeded";
772 Object* Isolate::StackOverflow() {
773 HandleScope scope(this);
774 // At this point we cannot create an Error object using its javascript
775 // constructor. Instead, we copy the pre-constructed boilerplate and
776 // attach the stack trace as a hidden property.
777 Handle<String> key = factory()->stack_overflow_string();
778 Handle<JSObject> boilerplate = Handle<JSObject>::cast(
779 Object::GetProperty(js_builtins_object(), key).ToHandleChecked());
780 Handle<JSObject> exception = factory()->CopyJSObject(boilerplate);
781 DoThrow(*exception, NULL);
783 CaptureAndSetSimpleStackTrace(exception, factory()->undefined_value());
784 return heap()->exception();
788 Object* Isolate::TerminateExecution() {
789 DoThrow(heap_.termination_exception(), NULL);
790 return heap()->exception();
794 void Isolate::CancelTerminateExecution() {
795 if (try_catch_handler()) {
796 try_catch_handler()->has_terminated_ = false;
798 if (has_pending_exception() &&
799 pending_exception() == heap_.termination_exception()) {
800 thread_local_top()->external_caught_exception_ = false;
801 clear_pending_exception();
803 if (has_scheduled_exception() &&
804 scheduled_exception() == heap_.termination_exception()) {
805 thread_local_top()->external_caught_exception_ = false;
806 clear_scheduled_exception();
811 void Isolate::InvokeApiInterruptCallback() {
812 // Note: callback below should be called outside of execution access lock.
813 InterruptCallback callback = NULL;
816 ExecutionAccess access(this);
817 callback = api_interrupt_callback_;
818 data = api_interrupt_callback_data_;
819 api_interrupt_callback_ = NULL;
820 api_interrupt_callback_data_ = NULL;
823 if (callback != NULL) {
824 VMState<EXTERNAL> state(this);
825 HandleScope handle_scope(this);
826 callback(reinterpret_cast<v8::Isolate*>(this), data);
831 Object* Isolate::Throw(Object* exception, MessageLocation* location) {
832 DoThrow(exception, location);
833 return heap()->exception();
837 Object* Isolate::ReThrow(Object* exception) {
838 bool can_be_caught_externally = false;
839 bool catchable_by_javascript = is_catchable_by_javascript(exception);
840 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
842 thread_local_top()->catcher_ = can_be_caught_externally ?
843 try_catch_handler() : NULL;
845 // Set the exception being re-thrown.
846 set_pending_exception(exception);
847 return heap()->exception();
851 Object* Isolate::ThrowIllegalOperation() {
852 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
853 return Throw(heap_.illegal_access_string());
857 Object* Isolate::ThrowInvalidStringLength() {
858 return Throw(*factory()->NewRangeError(
859 "invalid_string_length", HandleVector<Object>(NULL, 0)));
863 void Isolate::ScheduleThrow(Object* exception) {
864 // When scheduling a throw we first throw the exception to get the
865 // error reporting if it is uncaught before rescheduling it.
867 PropagatePendingExceptionToExternalTryCatch();
868 if (has_pending_exception()) {
869 thread_local_top()->scheduled_exception_ = pending_exception();
870 thread_local_top()->external_caught_exception_ = false;
871 clear_pending_exception();
876 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
877 DCHECK(handler == try_catch_handler());
878 DCHECK(handler->HasCaught());
879 DCHECK(handler->rethrow_);
880 DCHECK(handler->capture_message_);
881 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
882 Object* script = reinterpret_cast<Object*>(handler->message_script_);
883 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
884 DCHECK(script->IsScript() || script->IsTheHole());
885 thread_local_top()->pending_message_obj_ = message;
886 thread_local_top()->pending_message_script_ = script;
887 thread_local_top()->pending_message_start_pos_ = handler->message_start_pos_;
888 thread_local_top()->pending_message_end_pos_ = handler->message_end_pos_;
892 void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
893 DCHECK(has_scheduled_exception());
894 if (scheduled_exception() == handler->exception_) {
895 DCHECK(scheduled_exception() != heap()->termination_exception());
896 clear_scheduled_exception();
901 Object* Isolate::PromoteScheduledException() {
902 Object* thrown = scheduled_exception();
903 clear_scheduled_exception();
904 // Re-throw the exception to avoid getting repeated error reporting.
905 return ReThrow(thrown);
909 void Isolate::PrintCurrentStackTrace(FILE* out) {
910 StackTraceFrameIterator it(this);
912 HandleScope scope(this);
913 // Find code position if recorded in relocation info.
914 JavaScriptFrame* frame = it.frame();
915 int pos = frame->LookupCode()->SourcePosition(frame->pc());
916 Handle<Object> pos_obj(Smi::FromInt(pos), this);
917 // Fetch function and receiver.
918 Handle<JSFunction> fun(frame->function());
919 Handle<Object> recv(frame->receiver(), this);
920 // Advance to the next JavaScript frame and determine if the
921 // current frame is the top-level frame.
923 Handle<Object> is_top_level = it.done()
924 ? factory()->true_value()
925 : factory()->false_value();
926 // Generate and print stack trace line.
927 Handle<String> line =
928 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
929 if (line->length() > 0) {
937 void Isolate::ComputeLocation(MessageLocation* target) {
938 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
939 StackTraceFrameIterator it(this);
941 JavaScriptFrame* frame = it.frame();
942 JSFunction* fun = frame->function();
943 Object* script = fun->shared()->script();
944 if (script->IsScript() &&
945 !(Script::cast(script)->source()->IsUndefined())) {
946 int pos = frame->LookupCode()->SourcePosition(frame->pc());
947 // Compute the location from the function and the reloc info.
948 Handle<Script> casted_script(Script::cast(script));
949 *target = MessageLocation(casted_script, pos, pos + 1);
955 bool Isolate::ShouldReportException(bool* can_be_caught_externally,
956 bool catchable_by_javascript) {
957 // Find the top-most try-catch handler.
958 StackHandler* handler =
959 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
960 while (handler != NULL && !handler->is_catch()) {
961 handler = handler->next();
964 // Get the address of the external handler so we can compare the address to
965 // determine which one is closer to the top of the stack.
966 Address external_handler_address =
967 thread_local_top()->try_catch_handler_address();
969 // The exception has been externally caught if and only if there is
970 // an external handler which is on top of the top-most try-catch
972 *can_be_caught_externally = external_handler_address != NULL &&
973 (handler == NULL || handler->address() > external_handler_address ||
974 !catchable_by_javascript);
976 if (*can_be_caught_externally) {
977 // Only report the exception if the external handler is verbose.
978 return try_catch_handler()->is_verbose_;
980 // Report the exception if it isn't caught by JavaScript code.
981 return handler == NULL;
986 bool Isolate::IsErrorObject(Handle<Object> obj) {
987 if (!obj->IsJSObject()) return false;
989 Handle<String> error_key =
990 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("$Error"));
991 Handle<Object> error_constructor = Object::GetProperty(
992 js_builtins_object(), error_key).ToHandleChecked();
994 DisallowHeapAllocation no_gc;
995 for (PrototypeIterator iter(this, *obj, PrototypeIterator::START_AT_RECEIVER);
996 !iter.IsAtEnd(); iter.Advance()) {
997 if (iter.GetCurrent()->IsJSProxy()) return false;
998 if (JSObject::cast(iter.GetCurrent())->map()->constructor() ==
999 *error_constructor) {
1006 static int fatal_exception_depth = 0;
1008 void Isolate::DoThrow(Object* exception, MessageLocation* location) {
1009 DCHECK(!has_pending_exception());
1011 HandleScope scope(this);
1012 Handle<Object> exception_handle(exception, this);
1014 // Determine reporting and whether the exception is caught externally.
1015 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1016 bool can_be_caught_externally = false;
1017 bool should_report_exception =
1018 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1019 bool report_exception = catchable_by_javascript && should_report_exception;
1020 bool try_catch_needs_message =
1021 can_be_caught_externally && try_catch_handler()->capture_message_ &&
1022 !thread_local_top()->rethrowing_message_;
1023 bool bootstrapping = bootstrapper()->IsActive();
1025 thread_local_top()->rethrowing_message_ = false;
1027 // Notify debugger of exception.
1028 if (catchable_by_javascript) {
1029 debug()->OnThrow(exception_handle, report_exception);
1032 // Generate the message if required.
1033 if (report_exception || try_catch_needs_message) {
1034 MessageLocation potential_computed_location;
1035 if (location == NULL) {
1036 // If no location was specified we use a computed one instead.
1037 ComputeLocation(&potential_computed_location);
1038 location = &potential_computed_location;
1040 // It's not safe to try to make message objects or collect stack traces
1041 // while the bootstrapper is active since the infrastructure may not have
1042 // been properly initialized.
1043 if (!bootstrapping) {
1044 Handle<JSArray> stack_trace_object;
1045 if (capture_stack_trace_for_uncaught_exceptions_) {
1046 if (IsErrorObject(exception_handle)) {
1047 // We fetch the stack trace that corresponds to this error object.
1048 Handle<Name> key = factory()->detailed_stack_trace_symbol();
1049 // Look up as own property. If the lookup fails, the exception is
1050 // probably not a valid Error object. In that case, we fall through
1051 // and capture the stack trace at this throw site.
1052 LookupIterator lookup(
1053 exception_handle, key, LookupIterator::CHECK_OWN_REAL);
1054 Handle<Object> stack_trace_property;
1055 if (Object::GetProperty(&lookup).ToHandle(&stack_trace_property) &&
1056 stack_trace_property->IsJSArray()) {
1057 stack_trace_object = Handle<JSArray>::cast(stack_trace_property);
1060 if (stack_trace_object.is_null()) {
1061 // Not an error object, we capture at throw site.
1062 stack_trace_object = CaptureCurrentStackTrace(
1063 stack_trace_for_uncaught_exceptions_frame_limit_,
1064 stack_trace_for_uncaught_exceptions_options_);
1068 Handle<Object> exception_arg = exception_handle;
1069 // If the exception argument is a custom object, turn it into a string
1070 // before throwing as uncaught exception. Note that the pending
1071 // exception object to be set later must not be turned into a string.
1072 if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
1073 MaybeHandle<Object> maybe_exception =
1074 Execution::ToDetailString(this, exception_arg);
1075 if (!maybe_exception.ToHandle(&exception_arg)) {
1076 exception_arg = factory()->InternalizeOneByteString(
1077 STATIC_ASCII_VECTOR("exception"));
1080 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1082 "uncaught_exception",
1084 HandleVector<Object>(&exception_arg, 1),
1085 stack_trace_object);
1086 thread_local_top()->pending_message_obj_ = *message_obj;
1087 if (location != NULL) {
1088 thread_local_top()->pending_message_script_ = *location->script();
1089 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1090 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1093 // If the abort-on-uncaught-exception flag is specified, abort on any
1094 // exception not caught by JavaScript, even when an external handler is
1095 // present. This flag is intended for use by JavaScript developers, so
1096 // print a user-friendly stack trace (not an internal one).
1097 if (fatal_exception_depth == 0 &&
1098 FLAG_abort_on_uncaught_exception &&
1099 (report_exception || can_be_caught_externally)) {
1100 fatal_exception_depth++;
1103 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1104 PrintCurrentStackTrace(stderr);
1107 } else if (location != NULL && !location->script().is_null()) {
1108 // We are bootstrapping and caught an error where the location is set
1109 // and we have a script for the location.
1110 // In this case we could have an extension (or an internal error
1111 // somewhere) and we print out the line number at which the error occured
1112 // to the console for easier debugging.
1114 location->script()->GetLineNumber(location->start_pos()) + 1;
1115 if (exception->IsString() && location->script()->name()->IsString()) {
1116 base::OS::PrintError(
1117 "Extension or internal compilation error: %s in %s at line %d.\n",
1118 String::cast(exception)->ToCString().get(),
1119 String::cast(location->script()->name())->ToCString().get(),
1121 } else if (location->script()->name()->IsString()) {
1122 base::OS::PrintError(
1123 "Extension or internal compilation error in %s at line %d.\n",
1124 String::cast(location->script()->name())->ToCString().get(),
1127 base::OS::PrintError("Extension or internal compilation error.\n");
1130 // Since comments and empty lines have been stripped from the source of
1131 // builtins, print the actual source here so that line numbers match.
1132 if (location->script()->source()->IsString()) {
1133 Handle<String> src(String::cast(location->script()->source()));
1134 PrintF("Failing script:\n");
1135 int len = src->length();
1136 int line_number = 1;
1137 PrintF("%5d: ", line_number);
1138 for (int i = 0; i < len; i++) {
1139 uint16_t character = src->Get(i);
1140 PrintF("%c", character);
1141 if (character == '\n' && i < len - 2) {
1142 PrintF("%5d: ", ++line_number);
1150 // Save the message for reporting if the the exception remains uncaught.
1151 thread_local_top()->has_pending_message_ = report_exception;
1153 // Do not forget to clean catcher_ if currently thrown exception cannot
1154 // be caught. If necessary, ReThrow will update the catcher.
1155 thread_local_top()->catcher_ = can_be_caught_externally ?
1156 try_catch_handler() : NULL;
1158 set_pending_exception(*exception_handle);
1162 bool Isolate::HasExternalTryCatch() {
1163 DCHECK(has_pending_exception());
1165 return (thread_local_top()->catcher_ != NULL) &&
1166 (try_catch_handler() == thread_local_top()->catcher_);
1170 bool Isolate::IsFinallyOnTop() {
1171 // Get the address of the external handler so we can compare the address to
1172 // determine which one is closer to the top of the stack.
1173 Address external_handler_address =
1174 thread_local_top()->try_catch_handler_address();
1175 DCHECK(external_handler_address != NULL);
1177 // The exception has been externally caught if and only if there is
1178 // an external handler which is on top of the top-most try-finally
1180 // There should be no try-catch blocks as they would prohibit us from
1181 // finding external catcher in the first place (see catcher_ check above).
1183 // Note, that finally clause would rethrow an exception unless it's
1184 // aborted by jumps in control flow like return, break, etc. and we'll
1185 // have another chances to set proper v8::TryCatch.
1186 StackHandler* handler =
1187 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1188 while (handler != NULL && handler->address() < external_handler_address) {
1189 DCHECK(!handler->is_catch());
1190 if (handler->is_finally()) return true;
1192 handler = handler->next();
1199 void Isolate::ReportPendingMessages() {
1200 DCHECK(has_pending_exception());
1201 bool can_clear_message = PropagatePendingExceptionToExternalTryCatch();
1203 HandleScope scope(this);
1204 if (thread_local_top_.pending_exception_ == heap()->termination_exception()) {
1205 // Do nothing: if needed, the exception has been already propagated to
1208 if (thread_local_top_.has_pending_message_) {
1209 thread_local_top_.has_pending_message_ = false;
1210 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1211 HandleScope scope(this);
1212 Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1214 if (!thread_local_top_.pending_message_script_->IsTheHole()) {
1215 Handle<Script> script(
1216 Script::cast(thread_local_top_.pending_message_script_));
1217 int start_pos = thread_local_top_.pending_message_start_pos_;
1218 int end_pos = thread_local_top_.pending_message_end_pos_;
1219 MessageLocation location(script, start_pos, end_pos);
1220 MessageHandler::ReportMessage(this, &location, message_obj);
1222 MessageHandler::ReportMessage(this, NULL, message_obj);
1227 if (can_clear_message) clear_pending_message();
1231 MessageLocation Isolate::GetMessageLocation() {
1232 DCHECK(has_pending_exception());
1234 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1235 thread_local_top_.has_pending_message_ &&
1236 !thread_local_top_.pending_message_obj_->IsTheHole() &&
1237 !thread_local_top_.pending_message_obj_->IsTheHole()) {
1238 Handle<Script> script(
1239 Script::cast(thread_local_top_.pending_message_script_));
1240 int start_pos = thread_local_top_.pending_message_start_pos_;
1241 int end_pos = thread_local_top_.pending_message_end_pos_;
1242 return MessageLocation(script, start_pos, end_pos);
1245 return MessageLocation();
1249 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1250 DCHECK(has_pending_exception());
1251 PropagatePendingExceptionToExternalTryCatch();
1253 bool is_termination_exception =
1254 pending_exception() == heap_.termination_exception();
1256 // Do not reschedule the exception if this is the bottom call.
1257 bool clear_exception = is_bottom_call;
1259 if (is_termination_exception) {
1260 if (is_bottom_call) {
1261 thread_local_top()->external_caught_exception_ = false;
1262 clear_pending_exception();
1265 } else if (thread_local_top()->external_caught_exception_) {
1266 // If the exception is externally caught, clear it if there are no
1267 // JavaScript frames on the way to the C++ frame that has the
1268 // external handler.
1269 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1270 Address external_handler_address =
1271 thread_local_top()->try_catch_handler_address();
1272 JavaScriptFrameIterator it(this);
1273 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1274 clear_exception = true;
1278 // Clear the exception if needed.
1279 if (clear_exception) {
1280 thread_local_top()->external_caught_exception_ = false;
1281 clear_pending_exception();
1285 // Reschedule the exception.
1286 thread_local_top()->scheduled_exception_ = pending_exception();
1287 clear_pending_exception();
1292 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1295 StackTrace::StackTraceOptions options) {
1296 capture_stack_trace_for_uncaught_exceptions_ = capture;
1297 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1298 stack_trace_for_uncaught_exceptions_options_ = options;
1302 Handle<Context> Isolate::native_context() {
1303 return handle(context()->native_context());
1307 Handle<Context> Isolate::global_context() {
1308 return handle(context()->global_object()->global_context());
1312 Handle<Context> Isolate::GetCallingNativeContext() {
1313 JavaScriptFrameIterator it(this);
1314 if (debug_->in_debug_scope()) {
1315 while (!it.done()) {
1316 JavaScriptFrame* frame = it.frame();
1317 Context* context = Context::cast(frame->context());
1318 if (context->native_context() == *debug_->debug_context()) {
1325 if (it.done()) return Handle<Context>::null();
1326 JavaScriptFrame* frame = it.frame();
1327 Context* context = Context::cast(frame->context());
1328 return Handle<Context>(context->native_context());
1332 char* Isolate::ArchiveThread(char* to) {
1333 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1334 sizeof(ThreadLocalTop));
1335 InitializeThreadLocal();
1336 clear_pending_exception();
1337 clear_pending_message();
1338 clear_scheduled_exception();
1339 return to + sizeof(ThreadLocalTop);
1343 char* Isolate::RestoreThread(char* from) {
1344 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1345 sizeof(ThreadLocalTop));
1346 // This might be just paranoia, but it seems to be needed in case a
1347 // thread_local_top_ is restored on a separate OS thread.
1348 #ifdef USE_SIMULATOR
1349 thread_local_top()->simulator_ = Simulator::current(this);
1351 DCHECK(context() == NULL || context()->IsContext());
1352 return from + sizeof(ThreadLocalTop);
1356 Isolate::ThreadDataTable::ThreadDataTable()
1361 Isolate::ThreadDataTable::~ThreadDataTable() {
1362 // TODO(svenpanne) The assertion below would fire if an embedder does not
1363 // cleanly dispose all Isolates before disposing v8, so we are conservative
1364 // and leave it out for now.
1365 // DCHECK_EQ(NULL, list_);
1369 Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1370 #if defined(USE_SIMULATOR)
1376 Isolate::PerIsolateThreadData*
1377 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1378 ThreadId thread_id) {
1379 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1380 if (data->Matches(isolate, thread_id)) return data;
1386 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1387 if (list_ != NULL) list_->prev_ = data;
1388 data->next_ = list_;
1393 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1394 if (list_ == data) list_ = data->next_;
1395 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1396 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1401 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1402 PerIsolateThreadData* data = list_;
1403 while (data != NULL) {
1404 PerIsolateThreadData* next = data->next_;
1405 if (data->isolate() == isolate) Remove(data);
1412 #define TRACE_ISOLATE(tag) \
1414 if (FLAG_trace_isolates) { \
1415 PrintF("Isolate %p (id %d)" #tag "\n", \
1416 reinterpret_cast<void*>(this), id()); \
1420 #define TRACE_ISOLATE(tag)
1426 state_(UNINITIALIZED),
1428 stack_trace_nesting_level_(0),
1429 incomplete_message_(NULL),
1430 bootstrapper_(NULL),
1431 runtime_profiler_(NULL),
1432 compilation_cache_(NULL),
1438 code_aging_helper_(NULL),
1439 deoptimizer_data_(NULL),
1440 materialized_object_store_(NULL),
1441 capture_stack_trace_for_uncaught_exceptions_(false),
1442 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1443 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1444 memory_allocator_(NULL),
1445 keyed_lookup_cache_(NULL),
1446 context_slot_cache_(NULL),
1447 descriptor_lookup_cache_(NULL),
1448 handle_scope_implementer_(NULL),
1449 unicode_cache_(NULL),
1450 runtime_zone_(this),
1451 inner_pointer_to_code_cache_(NULL),
1452 write_iterator_(NULL),
1453 global_handles_(NULL),
1454 eternal_handles_(NULL),
1455 thread_manager_(NULL),
1456 has_installed_extensions_(false),
1457 string_tracker_(NULL),
1458 regexp_stack_(NULL),
1460 code_stub_interface_descriptors_(NULL),
1461 call_descriptors_(NULL),
1462 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1463 // be fixed once the default isolate cleanup is done.
1464 random_number_generator_(NULL),
1465 serializer_enabled_(false),
1466 has_fatal_error_(false),
1467 initialized_from_snapshot_(false),
1468 cpu_profiler_(NULL),
1469 heap_profiler_(NULL),
1470 function_entry_hook_(NULL),
1471 deferred_handles_head_(NULL),
1472 optimizing_compiler_thread_(NULL),
1473 sweeper_thread_(NULL),
1474 num_sweeper_threads_(0),
1475 stress_deopt_count_(0),
1476 next_optimization_id_(0),
1477 use_counter_callback_(NULL) {
1478 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1479 TRACE_ISOLATE(constructor);
1481 memset(isolate_addresses_, 0,
1482 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1484 heap_.isolate_ = this;
1485 stack_guard_.isolate_ = this;
1487 // ThreadManager is initialized early to support locking an isolate
1488 // before it is entered.
1489 thread_manager_ = new ThreadManager();
1490 thread_manager_->isolate_ = this;
1493 // heap_histograms_ initializes itself.
1494 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1497 handle_scope_data_.Initialize();
1499 #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1500 name##_ = (initial_value);
1501 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1502 #undef ISOLATE_INIT_EXECUTE
1504 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1505 memset(name##_, 0, sizeof(type) * length);
1506 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1507 #undef ISOLATE_INIT_ARRAY_EXECUTE
1509 InitializeLoggingAndCounters();
1510 debug_ = new Debug(this);
1514 void Isolate::TearDown() {
1515 TRACE_ISOLATE(tear_down);
1517 // Temporarily set this isolate as current so that various parts of
1518 // the isolate can access it in their destructors without having a
1519 // direct pointer. We don't use Enter/Exit here to avoid
1520 // initializing the thread data.
1521 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1522 Isolate* saved_isolate = UncheckedCurrent();
1523 SetIsolateThreadLocals(this, NULL);
1528 base::LockGuard<base::Mutex> lock_guard(process_wide_mutex_.Pointer());
1529 thread_data_table_->RemoveAllThreads(this);
1532 if (serialize_partial_snapshot_cache_ != NULL) {
1533 delete[] serialize_partial_snapshot_cache_;
1534 serialize_partial_snapshot_cache_ = NULL;
1539 // Restore the previous current isolate.
1540 SetIsolateThreadLocals(saved_isolate, saved_data);
1544 void Isolate::GlobalTearDown() {
1545 delete thread_data_table_;
1549 void Isolate::Deinit() {
1550 if (state_ == INITIALIZED) {
1551 TRACE_ISOLATE(deinit);
1555 if (concurrent_recompilation_enabled()) {
1556 optimizing_compiler_thread_->Stop();
1557 delete optimizing_compiler_thread_;
1558 optimizing_compiler_thread_ = NULL;
1561 for (int i = 0; i < num_sweeper_threads_; i++) {
1562 sweeper_thread_[i]->Stop();
1563 delete sweeper_thread_[i];
1564 sweeper_thread_[i] = NULL;
1566 delete[] sweeper_thread_;
1567 sweeper_thread_ = NULL;
1569 if (FLAG_job_based_sweeping &&
1570 heap_.mark_compact_collector()->sweeping_in_progress()) {
1571 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1574 if (FLAG_turbo_stats) GetTStatistics()->Print("TurboFan");
1575 if (FLAG_hydrogen_stats) GetHStatistics()->Print("Hydrogen");
1577 if (FLAG_print_deopt_stress) {
1578 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1581 // We must stop the logger before we tear down other components.
1582 Sampler* sampler = logger_->sampler();
1583 if (sampler && sampler->IsActive()) sampler->Stop();
1585 delete deoptimizer_data_;
1586 deoptimizer_data_ = NULL;
1587 builtins_.TearDown();
1588 bootstrapper_->TearDown();
1590 if (runtime_profiler_ != NULL) {
1591 delete runtime_profiler_;
1592 runtime_profiler_ = NULL;
1595 logger_->TearDown();
1597 delete heap_profiler_;
1598 heap_profiler_ = NULL;
1599 delete cpu_profiler_;
1600 cpu_profiler_ = NULL;
1602 // The default isolate is re-initializable due to legacy API.
1603 state_ = UNINITIALIZED;
1608 void Isolate::PushToPartialSnapshotCache(Object* obj) {
1609 int length = serialize_partial_snapshot_cache_length();
1610 int capacity = serialize_partial_snapshot_cache_capacity();
1612 if (length >= capacity) {
1613 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1614 Object** new_array = new Object*[new_capacity];
1615 for (int i = 0; i < length; i++) {
1616 new_array[i] = serialize_partial_snapshot_cache()[i];
1618 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1619 set_serialize_partial_snapshot_cache(new_array);
1620 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1623 serialize_partial_snapshot_cache()[length] = obj;
1624 set_serialize_partial_snapshot_cache_length(length + 1);
1628 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1629 PerIsolateThreadData* data) {
1630 EnsureInitialized();
1631 base::Thread::SetThreadLocal(isolate_key_, isolate);
1632 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1636 Isolate::~Isolate() {
1637 TRACE_ISOLATE(destructor);
1639 // Has to be called while counters_ are still alive
1640 runtime_zone_.DeleteKeptSegment();
1642 // The entry stack must be empty when we get here.
1643 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1645 delete entry_stack_;
1646 entry_stack_ = NULL;
1648 delete unicode_cache_;
1649 unicode_cache_ = NULL;
1654 delete[] code_stub_interface_descriptors_;
1655 code_stub_interface_descriptors_ = NULL;
1657 delete[] call_descriptors_;
1658 call_descriptors_ = NULL;
1660 delete regexp_stack_;
1661 regexp_stack_ = NULL;
1663 delete descriptor_lookup_cache_;
1664 descriptor_lookup_cache_ = NULL;
1665 delete context_slot_cache_;
1666 context_slot_cache_ = NULL;
1667 delete keyed_lookup_cache_;
1668 keyed_lookup_cache_ = NULL;
1672 delete code_aging_helper_;
1673 code_aging_helper_ = NULL;
1674 delete stats_table_;
1675 stats_table_ = NULL;
1677 delete materialized_object_store_;
1678 materialized_object_store_ = NULL;
1686 delete handle_scope_implementer_;
1687 handle_scope_implementer_ = NULL;
1689 delete compilation_cache_;
1690 compilation_cache_ = NULL;
1691 delete bootstrapper_;
1692 bootstrapper_ = NULL;
1693 delete inner_pointer_to_code_cache_;
1694 inner_pointer_to_code_cache_ = NULL;
1695 delete write_iterator_;
1696 write_iterator_ = NULL;
1698 delete thread_manager_;
1699 thread_manager_ = NULL;
1701 delete string_tracker_;
1702 string_tracker_ = NULL;
1704 delete memory_allocator_;
1705 memory_allocator_ = NULL;
1708 delete global_handles_;
1709 global_handles_ = NULL;
1710 delete eternal_handles_;
1711 eternal_handles_ = NULL;
1713 delete string_stream_debug_object_cache_;
1714 string_stream_debug_object_cache_ = NULL;
1716 delete external_reference_table_;
1717 external_reference_table_ = NULL;
1719 delete random_number_generator_;
1720 random_number_generator_ = NULL;
1727 void Isolate::InitializeThreadLocal() {
1728 thread_local_top_.isolate_ = this;
1729 thread_local_top_.Initialize();
1733 bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
1734 DCHECK(has_pending_exception());
1736 bool has_external_try_catch = HasExternalTryCatch();
1737 if (!has_external_try_catch) {
1738 thread_local_top_.external_caught_exception_ = false;
1742 bool catchable_by_js = is_catchable_by_javascript(pending_exception());
1743 if (catchable_by_js && IsFinallyOnTop()) {
1744 thread_local_top_.external_caught_exception_ = false;
1748 thread_local_top_.external_caught_exception_ = true;
1749 if (thread_local_top_.pending_exception_ == heap()->termination_exception()) {
1750 try_catch_handler()->can_continue_ = false;
1751 try_catch_handler()->has_terminated_ = true;
1752 try_catch_handler()->exception_ = heap()->null_value();
1754 v8::TryCatch* handler = try_catch_handler();
1755 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
1756 thread_local_top_.pending_message_obj_->IsTheHole());
1757 DCHECK(thread_local_top_.pending_message_script_->IsScript() ||
1758 thread_local_top_.pending_message_script_->IsTheHole());
1759 handler->can_continue_ = true;
1760 handler->has_terminated_ = false;
1761 handler->exception_ = pending_exception();
1762 // Propagate to the external try-catch only if we got an actual message.
1763 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
1765 handler->message_obj_ = thread_local_top_.pending_message_obj_;
1766 handler->message_script_ = thread_local_top_.pending_message_script_;
1767 handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
1768 handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
1774 void Isolate::InitializeLoggingAndCounters() {
1775 if (logger_ == NULL) {
1776 logger_ = new Logger(this);
1778 if (counters_ == NULL) {
1779 counters_ = new Counters(this);
1784 bool Isolate::Init(Deserializer* des) {
1785 DCHECK(state_ != INITIALIZED);
1786 TRACE_ISOLATE(init);
1788 stress_deopt_count_ = FLAG_deopt_every_n_times;
1790 has_fatal_error_ = false;
1792 if (function_entry_hook() != NULL) {
1793 // When function entry hooking is in effect, we have to create the code
1794 // stubs from scratch to get entry hooks, rather than loading the previously
1795 // generated stubs from disk.
1796 // If this assert fires, the initialization path has regressed.
1797 DCHECK(des == NULL);
1800 // The initialization process does not handle memory exhaustion.
1801 DisallowAllocationFailure disallow_allocation_failure(this);
1803 memory_allocator_ = new MemoryAllocator(this);
1804 code_range_ = new CodeRange(this);
1806 // Safe after setting Heap::isolate_, and initializing StackGuard
1807 heap_.SetStackLimits();
1809 #define ASSIGN_ELEMENT(CamelName, hacker_name) \
1810 isolate_addresses_[Isolate::k##CamelName##Address] = \
1811 reinterpret_cast<Address>(hacker_name##_address());
1812 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
1813 #undef ASSIGN_ELEMENT
1815 string_tracker_ = new StringTracker();
1816 string_tracker_->isolate_ = this;
1817 compilation_cache_ = new CompilationCache(this);
1818 keyed_lookup_cache_ = new KeyedLookupCache();
1819 context_slot_cache_ = new ContextSlotCache();
1820 descriptor_lookup_cache_ = new DescriptorLookupCache();
1821 unicode_cache_ = new UnicodeCache();
1822 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
1823 write_iterator_ = new ConsStringIteratorOp();
1824 global_handles_ = new GlobalHandles(this);
1825 eternal_handles_ = new EternalHandles();
1826 bootstrapper_ = new Bootstrapper(this);
1827 handle_scope_implementer_ = new HandleScopeImplementer(this);
1828 stub_cache_ = new StubCache(this);
1829 materialized_object_store_ = new MaterializedObjectStore(this);
1830 regexp_stack_ = new RegExpStack();
1831 regexp_stack_->isolate_ = this;
1832 date_cache_ = new DateCache();
1833 code_stub_interface_descriptors_ =
1834 new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
1836 new CallInterfaceDescriptor[NUMBER_OF_CALL_DESCRIPTORS];
1837 cpu_profiler_ = new CpuProfiler(this);
1838 heap_profiler_ = new HeapProfiler(heap());
1840 // Enable logging before setting up the heap
1841 logger_->SetUp(this);
1843 // Initialize other runtime facilities
1844 #if defined(USE_SIMULATOR)
1845 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || \
1846 V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64
1847 Simulator::Initialize(this);
1851 code_aging_helper_ = new CodeAgingHelper();
1854 // Ensure that the thread has a valid stack guard. The v8::Locker object
1855 // will ensure this too, but we don't have to use lockers if we are only
1856 // using one thread.
1857 ExecutionAccess lock(this);
1858 stack_guard_.InitThread(lock);
1861 // SetUp the object heap.
1862 DCHECK(!heap_.HasBeenSetUp());
1863 if (!heap_.SetUp()) {
1864 V8::FatalProcessOutOfMemory("heap setup");
1868 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
1870 const bool create_heap_objects = (des == NULL);
1871 if (create_heap_objects && !heap_.CreateHeapObjects()) {
1872 V8::FatalProcessOutOfMemory("heap object creation");
1876 if (create_heap_objects) {
1877 // Terminate the cache array with the sentinel so we can iterate.
1878 PushToPartialSnapshotCache(heap_.undefined_value());
1881 InitializeThreadLocal();
1883 bootstrapper_->Initialize(create_heap_objects);
1884 builtins_.SetUp(this, create_heap_objects);
1886 if (FLAG_log_internal_timer_events) {
1887 set_event_logger(Logger::DefaultTimerEventsLogger);
1889 set_event_logger(Logger::EmptyTimerEventsLogger);
1892 // Set default value if not yet set.
1893 // TODO(yangguo): move this to ResourceConstraints::ConfigureDefaults
1894 // once ResourceConstraints becomes an argument to the Isolate constructor.
1895 if (max_available_threads_ < 1) {
1896 // Choose the default between 1 and 4.
1897 max_available_threads_ =
1898 Max(Min(base::OS::NumberOfProcessorsOnline(), 4), 1);
1901 if (!FLAG_job_based_sweeping) {
1902 num_sweeper_threads_ =
1903 SweeperThread::NumberOfThreads(max_available_threads_);
1906 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
1907 PrintF("Concurrent recompilation has been disabled for tracing.\n");
1908 } else if (OptimizingCompilerThread::Enabled(max_available_threads_)) {
1909 optimizing_compiler_thread_ = new OptimizingCompilerThread(this);
1910 optimizing_compiler_thread_->Start();
1913 if (num_sweeper_threads_ > 0) {
1914 sweeper_thread_ = new SweeperThread*[num_sweeper_threads_];
1915 for (int i = 0; i < num_sweeper_threads_; i++) {
1916 sweeper_thread_[i] = new SweeperThread(this);
1917 sweeper_thread_[i]->Start();
1921 // If we are deserializing, read the state into the now-empty heap.
1922 if (!create_heap_objects) {
1923 des->Deserialize(this);
1925 stub_cache_->Initialize();
1927 // Finish initialization of ThreadLocal after deserialization is done.
1928 clear_pending_exception();
1929 clear_pending_message();
1930 clear_scheduled_exception();
1932 // Deserializing may put strange things in the root array's copy of the
1934 heap_.SetStackLimits();
1936 // Quiet the heap NaN if needed on target platform.
1937 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
1939 runtime_profiler_ = new RuntimeProfiler(this);
1941 // If we are deserializing, log non-function code objects and compiled
1942 // functions found in the snapshot.
1943 if (!create_heap_objects &&
1946 FLAG_perf_jit_prof ||
1947 FLAG_perf_basic_prof ||
1948 logger_->is_logging_code_events())) {
1949 HandleScope scope(this);
1950 LOG(this, LogCodeObjects());
1951 LOG(this, LogCompiledFunctions());
1954 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
1955 Internals::kIsolateEmbedderDataOffset);
1956 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
1957 Internals::kIsolateRootsOffset);
1958 CHECK_EQ(static_cast<int>(
1959 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
1960 Internals::kAmountOfExternalAllocatedMemoryOffset);
1961 CHECK_EQ(static_cast<int>(OFFSET_OF(
1963 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
1964 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
1966 state_ = INITIALIZED;
1967 time_millis_at_init_ = base::OS::TimeCurrentMillis();
1969 if (!create_heap_objects) {
1970 // Now that the heap is consistent, it's OK to generate the code for the
1971 // deopt entry table that might have been referred to by optimized code in
1973 HandleScope scope(this);
1974 Deoptimizer::EnsureCodeForDeoptimizationEntry(
1977 kDeoptTableSerializeEntryCount - 1);
1980 if (!serializer_enabled()) {
1981 // Ensure that all stubs which need to be generated ahead of time, but
1982 // cannot be serialized into the snapshot have been generated.
1983 HandleScope scope(this);
1984 CodeStub::GenerateFPStubs(this);
1985 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
1986 StubFailureTrampolineStub::GenerateAheadOfTime(this);
1987 // Ensure interface descriptors are initialized even when stubs have been
1988 // deserialized out of the snapshot without using the graph builder.
1989 FastCloneShallowArrayStub::InstallDescriptors(this);
1990 BinaryOpICStub::InstallDescriptors(this);
1991 BinaryOpWithAllocationSiteStub::InstallDescriptors(this);
1992 CompareNilICStub::InstallDescriptors(this);
1993 ToBooleanStub::InstallDescriptors(this);
1994 ToNumberStub::InstallDescriptors(this);
1995 ArrayConstructorStubBase::InstallDescriptors(this);
1996 InternalArrayConstructorStubBase::InstallDescriptors(this);
1997 FastNewClosureStub::InstallDescriptors(this);
1998 FastNewContextStub::InstallDescriptors(this);
1999 NumberToStringStub::InstallDescriptors(this);
2000 StringAddStub::InstallDescriptors(this);
2001 RegExpConstructResultStub::InstallDescriptors(this);
2002 KeyedLoadGenericStub::InstallDescriptors(this);
2003 StoreFieldStub::InstallDescriptors(this);
2006 CallDescriptors::InitializeForIsolate(this);
2008 initialized_from_snapshot_ = (des != NULL);
2014 // Initialized lazily to allow early
2015 // v8::V8::SetAddHistogramSampleFunction calls.
2016 StatsTable* Isolate::stats_table() {
2017 if (stats_table_ == NULL) {
2018 stats_table_ = new StatsTable;
2020 return stats_table_;
2024 void Isolate::Enter() {
2025 Isolate* current_isolate = NULL;
2026 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2027 if (current_data != NULL) {
2028 current_isolate = current_data->isolate_;
2029 DCHECK(current_isolate != NULL);
2030 if (current_isolate == this) {
2031 DCHECK(Current() == this);
2032 DCHECK(entry_stack_ != NULL);
2033 DCHECK(entry_stack_->previous_thread_data == NULL ||
2034 entry_stack_->previous_thread_data->thread_id().Equals(
2035 ThreadId::Current()));
2036 // Same thread re-enters the isolate, no need to re-init anything.
2037 entry_stack_->entry_count++;
2042 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2043 DCHECK(data != NULL);
2044 DCHECK(data->isolate_ == this);
2046 EntryStackItem* item = new EntryStackItem(current_data,
2049 entry_stack_ = item;
2051 SetIsolateThreadLocals(this, data);
2053 // In case it's the first time some thread enters the isolate.
2054 set_thread_id(data->thread_id());
2058 void Isolate::Exit() {
2059 DCHECK(entry_stack_ != NULL);
2060 DCHECK(entry_stack_->previous_thread_data == NULL ||
2061 entry_stack_->previous_thread_data->thread_id().Equals(
2062 ThreadId::Current()));
2064 if (--entry_stack_->entry_count > 0) return;
2066 DCHECK(CurrentPerIsolateThreadData() != NULL);
2067 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
2070 EntryStackItem* item = entry_stack_;
2071 entry_stack_ = item->previous_item;
2073 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2074 Isolate* previous_isolate = item->previous_isolate;
2078 // Reinit the current thread for the isolate it was running before this one.
2079 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2083 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2084 deferred->next_ = deferred_handles_head_;
2085 if (deferred_handles_head_ != NULL) {
2086 deferred_handles_head_->previous_ = deferred;
2088 deferred_handles_head_ = deferred;
2092 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2094 // In debug mode assert that the linked list is well-formed.
2095 DeferredHandles* deferred_iterator = deferred;
2096 while (deferred_iterator->previous_ != NULL) {
2097 deferred_iterator = deferred_iterator->previous_;
2099 DCHECK(deferred_handles_head_ == deferred_iterator);
2101 if (deferred_handles_head_ == deferred) {
2102 deferred_handles_head_ = deferred_handles_head_->next_;
2104 if (deferred->next_ != NULL) {
2105 deferred->next_->previous_ = deferred->previous_;
2107 if (deferred->previous_ != NULL) {
2108 deferred->previous_->next_ = deferred->next_;
2113 HStatistics* Isolate::GetHStatistics() {
2114 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2115 return hstatistics();
2119 HStatistics* Isolate::GetTStatistics() {
2120 if (tstatistics() == NULL) set_tstatistics(new HStatistics());
2121 return tstatistics();
2125 HTracer* Isolate::GetHTracer() {
2126 if (htracer() == NULL) set_htracer(new HTracer(id()));
2131 CodeTracer* Isolate::GetCodeTracer() {
2132 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2133 return code_tracer();
2137 Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2138 Context* native_context = context()->native_context();
2139 Object* maybe_map_array = native_context->js_array_maps();
2140 if (!maybe_map_array->IsUndefined()) {
2141 Object* maybe_transitioned_map =
2142 FixedArray::cast(maybe_map_array)->get(kind);
2143 if (!maybe_transitioned_map->IsUndefined()) {
2144 return Map::cast(maybe_transitioned_map);
2151 bool Isolate::use_crankshaft() const {
2152 return FLAG_crankshaft &&
2153 !serializer_enabled_ &&
2154 CpuFeatures::SupportsCrankshaft();
2158 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2159 Map* root_array_map =
2160 get_initial_js_array_map(GetInitialFastElementsKind());
2161 DCHECK(root_array_map != NULL);
2162 JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2164 // Check that the array prototype hasn't been altered WRT empty elements.
2165 if (root_array_map->prototype() != initial_array_proto) return false;
2166 if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2170 // Check that the object prototype hasn't been altered WRT empty elements.
2171 JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2172 PrototypeIterator iter(this, initial_array_proto);
2173 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
2176 if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2181 return iter.IsAtEnd();
2185 CodeStubInterfaceDescriptor*
2186 Isolate::code_stub_interface_descriptor(int index) {
2187 return code_stub_interface_descriptors_ + index;
2191 CallInterfaceDescriptor*
2192 Isolate::call_descriptor(CallDescriptorKey index) {
2193 DCHECK(0 <= index && index < NUMBER_OF_CALL_DESCRIPTORS);
2194 return &call_descriptors_[index];
2198 Object* Isolate::FindCodeObject(Address a) {
2199 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2204 #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2205 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2206 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2207 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2208 #undef ISOLATE_FIELD_OFFSET
2212 Handle<JSObject> Isolate::GetSymbolRegistry() {
2213 if (heap()->symbol_registry()->IsUndefined()) {
2214 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2215 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2216 heap()->set_symbol_registry(*registry);
2218 static const char* nested[] = {
2219 "for", "for_api", "for_intern", "keyFor", "private_api", "private_intern"
2221 for (unsigned i = 0; i < ARRAY_SIZE(nested); ++i) {
2222 Handle<String> name = factory()->InternalizeUtf8String(nested[i]);
2223 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2224 JSObject::NormalizeProperties(obj, KEEP_INOBJECT_PROPERTIES, 8);
2225 JSObject::SetProperty(registry, name, obj, STRICT).Assert();
2228 return Handle<JSObject>::cast(factory()->symbol_registry());
2232 void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2233 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2234 if (callback == call_completed_callbacks_.at(i)) return;
2236 call_completed_callbacks_.Add(callback);
2240 void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2241 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2242 if (callback == call_completed_callbacks_.at(i)) {
2243 call_completed_callbacks_.Remove(i);
2249 void Isolate::FireCallCompletedCallback() {
2250 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2251 bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2252 if (!has_call_completed_callbacks && !run_microtasks) return;
2254 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2255 if (run_microtasks) RunMicrotasks();
2256 // Fire callbacks. Increase call depth to prevent recursive callbacks.
2257 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2258 reinterpret_cast<v8::Isolate*>(this));
2259 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2260 call_completed_callbacks_.at(i)();
2265 void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2266 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2267 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2268 int num_tasks = pending_microtask_count();
2269 DCHECK(num_tasks <= queue->length());
2270 if (num_tasks == 0) {
2271 queue = factory()->NewFixedArray(8);
2272 heap()->set_microtask_queue(*queue);
2273 } else if (num_tasks == queue->length()) {
2274 queue = FixedArray::CopySize(queue, num_tasks * 2);
2275 heap()->set_microtask_queue(*queue);
2277 DCHECK(queue->get(num_tasks)->IsUndefined());
2278 queue->set(num_tasks, *microtask);
2279 set_pending_microtask_count(num_tasks + 1);
2283 void Isolate::RunMicrotasks() {
2284 // %RunMicrotasks may be called in mjsunit tests, which violates
2285 // this assertion, hence the check for --allow-natives-syntax.
2286 // TODO(adamk): However, this also fails some layout tests.
2288 // DCHECK(FLAG_allow_natives_syntax ||
2289 // handle_scope_implementer()->CallDepthIsZero());
2291 // Increase call depth to prevent recursive callbacks.
2292 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2293 reinterpret_cast<v8::Isolate*>(this));
2295 while (pending_microtask_count() > 0) {
2296 HandleScope scope(this);
2297 int num_tasks = pending_microtask_count();
2298 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2299 DCHECK(num_tasks <= queue->length());
2300 set_pending_microtask_count(0);
2301 heap()->set_microtask_queue(heap()->empty_fixed_array());
2303 for (int i = 0; i < num_tasks; i++) {
2304 HandleScope scope(this);
2305 Handle<Object> microtask(queue->get(i), this);
2306 if (microtask->IsJSFunction()) {
2307 Handle<JSFunction> microtask_function =
2308 Handle<JSFunction>::cast(microtask);
2309 SaveContext save(this);
2310 set_context(microtask_function->context()->native_context());
2311 Handle<Object> exception;
2312 MaybeHandle<Object> result = Execution::TryCall(
2313 microtask_function, factory()->undefined_value(),
2314 0, NULL, &exception);
2315 // If execution is terminating, just bail out.
2316 if (result.is_null() &&
2317 !exception.is_null() &&
2318 *exception == heap()->termination_exception()) {
2319 // Clear out any remaining callbacks in the queue.
2320 heap()->set_microtask_queue(heap()->empty_fixed_array());
2321 set_pending_microtask_count(0);
2325 Handle<CallHandlerInfo> callback_info =
2326 Handle<CallHandlerInfo>::cast(microtask);
2327 v8::MicrotaskCallback callback =
2328 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2329 void* data = v8::ToCData<void*>(callback_info->data());
2337 void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2338 DCHECK(!use_counter_callback_);
2339 use_counter_callback_ = callback;
2343 void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
2344 if (use_counter_callback_) {
2345 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2350 bool StackLimitCheck::JsHasOverflowed() const {
2351 StackGuard* stack_guard = isolate_->stack_guard();
2352 #ifdef USE_SIMULATOR
2353 // The simulator uses a separate JS stack.
2354 Address jssp_address = Simulator::current(isolate_)->get_sp();
2355 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
2356 if (jssp < stack_guard->real_jslimit()) return true;
2357 #endif // USE_SIMULATOR
2358 return GetCurrentStackPosition() < stack_guard->real_climit();
2362 bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2363 // First check whether the previous scope intercepts.
2364 if (prev_ && prev_->Intercept(flag)) return true;
2365 // Then check whether this scope intercepts.
2366 if ((flag & intercept_mask_)) {
2367 intercepted_flags_ |= flag;
2373 } } // namespace v8::internal