1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "allocation-inl.h"
34 #include "bootstrapper.h"
36 #include "compilation-cache.h"
37 #include "cpu-profiler.h"
39 #include "deoptimizer.h"
40 #include "heap-profiler.h"
43 #include "lithium-allocator.h"
45 #include "marking-thread.h"
48 #include "regexp-stack.h"
49 #include "runtime-profiler.h"
51 #include "scopeinfo.h"
52 #include "serialize.h"
53 #include "simulator.h"
55 #include "stub-cache.h"
56 #include "sweeper-thread.h"
58 #include "vm-state-inl.h"
64 Atomic32 ThreadId::highest_thread_id_ = 0;
66 int ThreadId::AllocateThreadId() {
67 int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
72 int ThreadId::GetCurrentThreadId() {
73 int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
75 thread_id = AllocateThreadId();
76 Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
82 ThreadLocalTop::ThreadLocalTop() {
84 // This flag may be set using v8::V8::IgnoreOutOfMemoryException()
85 // before an isolate is initialized. The initialize methods below do
86 // not touch it to preserve its value.
87 ignore_out_of_memory_ = false;
91 void ThreadLocalTop::InitializeInternal() {
98 external_callback_scope_ = NULL;
99 current_vm_state_ = EXTERNAL;
100 try_catch_handler_address_ = NULL;
102 thread_id_ = ThreadId::Invalid();
103 external_caught_exception_ = false;
104 failed_access_check_callback_ = NULL;
105 save_context_ = NULL;
107 top_lookup_result_ = NULL;
109 // These members are re-initialized later after deserialization
111 pending_exception_ = NULL;
112 has_pending_message_ = false;
113 rethrowing_message_ = false;
114 pending_message_obj_ = NULL;
115 pending_message_script_ = NULL;
116 scheduled_exception_ = NULL;
120 void ThreadLocalTop::Initialize() {
121 InitializeInternal();
123 #if V8_TARGET_ARCH_ARM
124 simulator_ = Simulator::current(isolate_);
125 #elif V8_TARGET_ARCH_MIPS
126 simulator_ = Simulator::current(isolate_);
129 thread_id_ = ThreadId::Current();
133 v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
134 return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
138 int SystemThreadManager::NumberOfParallelSystemThreads(
139 ParallelSystemComponent type) {
140 int number_of_threads = Min(OS::NumberOfCores(), kMaxThreads);
141 ASSERT(number_of_threads > 0);
142 if (number_of_threads == 1) {
145 if (type == PARALLEL_SWEEPING) {
146 return number_of_threads;
147 } else if (type == CONCURRENT_SWEEPING) {
148 return number_of_threads - 1;
149 } else if (type == PARALLEL_MARKING) {
150 return number_of_threads;
156 // Create a dummy thread that will wait forever on a semaphore. The only
157 // purpose for this thread is to have some stack area to save essential data
158 // into for use by a stacks only core dump (aka minidump).
159 class PreallocatedMemoryThread: public Thread {
162 if (data_ready_semaphore_ != NULL) {
163 // Initial access is guarded until the data has been published.
164 data_ready_semaphore_->Wait();
165 delete data_ready_semaphore_;
166 data_ready_semaphore_ = NULL;
172 if (data_ready_semaphore_ != NULL) {
173 // Initial access is guarded until the data has been published.
174 data_ready_semaphore_->Wait();
175 delete data_ready_semaphore_;
176 data_ready_semaphore_ = NULL;
181 // Stop the PreallocatedMemoryThread and release its resources.
183 keep_running_ = false;
184 wait_for_ever_semaphore_->Signal();
186 // Wait for the thread to terminate.
189 if (data_ready_semaphore_ != NULL) {
190 delete data_ready_semaphore_;
191 data_ready_semaphore_ = NULL;
194 delete wait_for_ever_semaphore_;
195 wait_for_ever_semaphore_ = NULL;
199 // When the thread starts running it will allocate a fixed number of bytes
200 // on the stack and publish the location of this memory for others to use.
202 EmbeddedVector<char, 15 * 1024> local_buffer;
204 // Initialize the buffer with a known good value.
205 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
206 local_buffer.length());
208 // Publish the local buffer and signal its availability.
209 data_ = local_buffer.start();
210 length_ = local_buffer.length();
211 data_ready_semaphore_->Signal();
213 while (keep_running_) {
214 // This thread will wait here until the end of time.
215 wait_for_ever_semaphore_->Wait();
218 // Make sure we access the buffer after the wait to remove all possibility
219 // of it being optimized away.
220 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
221 local_buffer.length());
226 PreallocatedMemoryThread()
227 : Thread("v8:PreallocMem"),
229 wait_for_ever_semaphore_(OS::CreateSemaphore(0)),
230 data_ready_semaphore_(OS::CreateSemaphore(0)),
235 // Used to make sure that the thread keeps looping even for spurious wakeups.
238 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
239 Semaphore* wait_for_ever_semaphore_;
240 // Semaphore to signal that the data has been initialized.
241 Semaphore* data_ready_semaphore_;
243 // Location and size of the preallocated memory block.
247 friend class Isolate;
249 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
253 void Isolate::PreallocatedMemoryThreadStart() {
254 if (preallocated_memory_thread_ != NULL) return;
255 preallocated_memory_thread_ = new PreallocatedMemoryThread();
256 preallocated_memory_thread_->Start();
260 void Isolate::PreallocatedMemoryThreadStop() {
261 if (preallocated_memory_thread_ == NULL) return;
262 preallocated_memory_thread_->StopThread();
263 // Done with the thread entirely.
264 delete preallocated_memory_thread_;
265 preallocated_memory_thread_ = NULL;
269 void Isolate::PreallocatedStorageInit(size_t size) {
270 ASSERT(free_list_.next_ == &free_list_);
271 ASSERT(free_list_.previous_ == &free_list_);
272 PreallocatedStorage* free_chunk =
273 reinterpret_cast<PreallocatedStorage*>(new char[size]);
274 free_list_.next_ = free_list_.previous_ = free_chunk;
275 free_chunk->next_ = free_chunk->previous_ = &free_list_;
276 free_chunk->size_ = size - sizeof(PreallocatedStorage);
277 preallocated_storage_preallocated_ = true;
281 void* Isolate::PreallocatedStorageNew(size_t size) {
282 if (!preallocated_storage_preallocated_) {
283 return FreeStoreAllocationPolicy().New(size);
285 ASSERT(free_list_.next_ != &free_list_);
286 ASSERT(free_list_.previous_ != &free_list_);
288 size = (size + kPointerSize - 1) & ~(kPointerSize - 1);
289 // Search for exact fit.
290 for (PreallocatedStorage* storage = free_list_.next_;
291 storage != &free_list_;
292 storage = storage->next_) {
293 if (storage->size_ == size) {
295 storage->LinkTo(&in_use_list_);
296 return reinterpret_cast<void*>(storage + 1);
299 // Search for first fit.
300 for (PreallocatedStorage* storage = free_list_.next_;
301 storage != &free_list_;
302 storage = storage->next_) {
303 if (storage->size_ >= size + sizeof(PreallocatedStorage)) {
305 storage->LinkTo(&in_use_list_);
306 PreallocatedStorage* left_over =
307 reinterpret_cast<PreallocatedStorage*>(
308 reinterpret_cast<char*>(storage + 1) + size);
309 left_over->size_ = storage->size_ - size - sizeof(PreallocatedStorage);
310 ASSERT(size + left_over->size_ + sizeof(PreallocatedStorage) ==
312 storage->size_ = size;
313 left_over->LinkTo(&free_list_);
314 return reinterpret_cast<void*>(storage + 1);
317 // Allocation failure.
323 // We don't attempt to coalesce.
324 void Isolate::PreallocatedStorageDelete(void* p) {
328 if (!preallocated_storage_preallocated_) {
329 FreeStoreAllocationPolicy::Delete(p);
332 PreallocatedStorage* storage = reinterpret_cast<PreallocatedStorage*>(p) - 1;
333 ASSERT(storage->next_->previous_ == storage);
334 ASSERT(storage->previous_->next_ == storage);
336 storage->LinkTo(&free_list_);
339 Isolate* Isolate::default_isolate_ = NULL;
340 Thread::LocalStorageKey Isolate::isolate_key_;
341 Thread::LocalStorageKey Isolate::thread_id_key_;
342 Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
344 Thread::LocalStorageKey PerThreadAssertScopeBase::thread_local_key;
346 Mutex* Isolate::process_wide_mutex_ = OS::CreateMutex();
347 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
348 Atomic32 Isolate::isolate_counter_ = 0;
350 Isolate::PerIsolateThreadData* Isolate::AllocatePerIsolateThreadData(
351 ThreadId thread_id) {
352 ASSERT(!thread_id.Equals(ThreadId::Invalid()));
353 PerIsolateThreadData* per_thread = new PerIsolateThreadData(this, thread_id);
355 ScopedLock lock(process_wide_mutex_);
356 ASSERT(thread_data_table_->Lookup(this, thread_id) == NULL);
357 thread_data_table_->Insert(per_thread);
358 ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
364 Isolate::PerIsolateThreadData*
365 Isolate::FindOrAllocatePerThreadDataForThisThread() {
366 ThreadId thread_id = ThreadId::Current();
367 PerIsolateThreadData* per_thread = NULL;
369 ScopedLock lock(process_wide_mutex_);
370 per_thread = thread_data_table_->Lookup(this, thread_id);
371 if (per_thread == NULL) {
372 per_thread = AllocatePerIsolateThreadData(thread_id);
379 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
380 ThreadId thread_id = ThreadId::Current();
381 return FindPerThreadDataForThread(thread_id);
385 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
386 ThreadId thread_id) {
387 PerIsolateThreadData* per_thread = NULL;
389 ScopedLock lock(process_wide_mutex_);
390 per_thread = thread_data_table_->Lookup(this, thread_id);
396 void Isolate::EnsureDefaultIsolate() {
397 ScopedLock lock(process_wide_mutex_);
398 if (default_isolate_ == NULL) {
399 isolate_key_ = Thread::CreateThreadLocalKey();
400 thread_id_key_ = Thread::CreateThreadLocalKey();
401 per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
403 PerThreadAssertScopeBase::thread_local_key = Thread::CreateThreadLocalKey();
405 thread_data_table_ = new Isolate::ThreadDataTable();
406 default_isolate_ = new Isolate();
408 // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
409 // because a non-null thread data may be already set.
410 if (Thread::GetThreadLocal(isolate_key_) == NULL) {
411 Thread::SetThreadLocal(isolate_key_, default_isolate_);
415 struct StaticInitializer {
416 StaticInitializer() {
417 Isolate::EnsureDefaultIsolate();
419 } static_initializer;
421 #ifdef ENABLE_DEBUGGER_SUPPORT
422 Debugger* Isolate::GetDefaultIsolateDebugger() {
423 EnsureDefaultIsolate();
424 return default_isolate_->debugger();
429 StackGuard* Isolate::GetDefaultIsolateStackGuard() {
430 EnsureDefaultIsolate();
431 return default_isolate_->stack_guard();
435 void Isolate::EnterDefaultIsolate() {
436 EnsureDefaultIsolate();
437 ASSERT(default_isolate_ != NULL);
439 PerIsolateThreadData* data = CurrentPerIsolateThreadData();
440 // If not yet in default isolate - enter it.
441 if (data == NULL || data->isolate() != default_isolate_) {
442 default_isolate_->Enter();
447 v8::Isolate* Isolate::GetDefaultIsolateForLocking() {
448 EnsureDefaultIsolate();
449 return reinterpret_cast<v8::Isolate*>(default_isolate_);
453 Address Isolate::get_address_from_id(Isolate::AddressId id) {
454 return isolate_addresses_[id];
458 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
459 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
461 return thread_storage + sizeof(ThreadLocalTop);
465 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
466 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
467 v->VisitThread(this, thread);
471 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
472 // Visit the roots from the top for a given thread.
474 // The pending exception can sometimes be a failure. We can't show
475 // that to the GC, which only understands objects.
476 if (thread->pending_exception_->ToObject(&pending)) {
477 v->VisitPointer(&pending);
478 thread->pending_exception_ = pending; // In case GC updated it.
480 v->VisitPointer(&(thread->pending_message_obj_));
481 v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
482 v->VisitPointer(BitCast<Object**>(&(thread->context_)));
484 if (thread->scheduled_exception_->ToObject(&scheduled)) {
485 v->VisitPointer(&scheduled);
486 thread->scheduled_exception_ = scheduled;
489 for (v8::TryCatch* block = thread->TryCatchHandler();
491 block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
492 v->VisitPointer(BitCast<Object**>(&(block->exception_)));
493 v->VisitPointer(BitCast<Object**>(&(block->message_obj_)));
494 v->VisitPointer(BitCast<Object**>(&(block->message_script_)));
497 // Iterate over pointers on native execution stack.
498 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
499 it.frame()->Iterate(v);
502 // Iterate pointers in live lookup results.
503 thread->top_lookup_result_->Iterate(v);
507 void Isolate::Iterate(ObjectVisitor* v) {
508 ThreadLocalTop* current_t = thread_local_top();
509 Iterate(v, current_t);
513 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
514 for (DeferredHandles* deferred = deferred_handles_head_;
516 deferred = deferred->next_) {
517 deferred->Iterate(visitor);
523 bool Isolate::IsDeferredHandle(Object** handle) {
524 // Each DeferredHandles instance keeps the handles to one job in the
525 // parallel recompilation queue, containing a list of blocks. Each block
526 // contains kHandleBlockSize handles except for the first block, which may
527 // not be fully filled.
528 // We iterate through all the blocks to see whether the argument handle
529 // belongs to one of the blocks. If so, it is deferred.
530 for (DeferredHandles* deferred = deferred_handles_head_;
532 deferred = deferred->next_) {
533 List<Object**>* blocks = &deferred->blocks_;
534 for (int i = 0; i < blocks->length(); i++) {
535 Object** block_limit = (i == 0) ? deferred->first_block_limit_
536 : blocks->at(i) + kHandleBlockSize;
537 if (blocks->at(i) <= handle && handle < block_limit) return true;
545 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
546 // The ARM simulator has a separate JS stack. We therefore register
547 // the C++ try catch handler with the simulator and get back an
548 // address that can be used for comparisons with addresses into the
549 // JS stack. When running without the simulator, the address
550 // returned will be the address of the C++ try catch handler itself.
551 Address address = reinterpret_cast<Address>(
552 SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
553 thread_local_top()->set_try_catch_handler_address(address);
557 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
558 ASSERT(thread_local_top()->TryCatchHandler() == that);
559 thread_local_top()->set_try_catch_handler_address(
560 reinterpret_cast<Address>(that->next_));
561 thread_local_top()->catcher_ = NULL;
562 SimulatorStack::UnregisterCTryCatch();
566 Handle<String> Isolate::StackTraceString() {
567 if (stack_trace_nesting_level_ == 0) {
568 stack_trace_nesting_level_++;
569 HeapStringAllocator allocator;
570 StringStream::ClearMentionedObjectCache();
571 StringStream accumulator(&allocator);
572 incomplete_message_ = &accumulator;
573 PrintStack(&accumulator);
574 Handle<String> stack_trace = accumulator.ToString();
575 incomplete_message_ = NULL;
576 stack_trace_nesting_level_ = 0;
578 } else if (stack_trace_nesting_level_ == 1) {
579 stack_trace_nesting_level_++;
581 "\n\nAttempt to print stack while printing stack (double fault)\n");
583 "If you are lucky you may find a partial stack dump on stdout.\n\n");
584 incomplete_message_->OutputToStdOut();
585 return factory()->empty_string();
589 return factory()->empty_string();
594 void Isolate::PushStackTraceAndDie(unsigned int magic,
597 unsigned int magic2) {
598 const int kMaxStackTraceSize = 8192;
599 Handle<String> trace = StackTraceString();
600 uint8_t buffer[kMaxStackTraceSize];
601 int length = Min(kMaxStackTraceSize - 1, trace->length());
602 String::WriteToFlat(*trace, buffer, 0, length);
603 buffer[length] = '\0';
604 // TODO(dcarney): convert buffer to utf8?
605 OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n",
607 static_cast<void*>(object), static_cast<void*>(map),
608 reinterpret_cast<char*>(buffer));
613 // Determines whether the given stack frame should be displayed in
614 // a stack trace. The caller is the error constructor that asked
615 // for the stack trace to be collected. The first time a construct
616 // call to this function is encountered it is skipped. The seen_caller
617 // in/out parameter is used to remember if the caller has been seen
619 static bool IsVisibleInStackTrace(StackFrame* raw_frame,
622 // Only display JS frames.
623 if (!raw_frame->is_java_script()) return false;
624 JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
625 JSFunction* fun = frame->function();
626 if ((fun == caller) && !(*seen_caller)) {
630 // Skip all frames until we've seen the caller.
631 if (!(*seen_caller)) return false;
632 // Also, skip non-visible built-in functions and any call with the builtins
633 // object as receiver, so as to not reveal either the builtins object or
634 // an internal function.
635 // The --builtins-in-stack-traces command line flag allows including
636 // internal call sites in the stack trace for debugging purposes.
637 if (!FLAG_builtins_in_stack_traces) {
638 if (frame->receiver()->IsJSBuiltinsObject() ||
639 (fun->IsBuiltin() && !fun->shared()->native())) {
647 Handle<JSArray> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
648 Handle<Object> caller,
650 limit = Max(limit, 0); // Ensure that limit is not negative.
651 int initial_size = Min(limit, 10);
652 Handle<FixedArray> elements =
653 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
655 // If the caller parameter is a function we skip frames until we're
656 // under it before starting to collect.
657 bool seen_caller = !caller->IsJSFunction();
658 // First element is reserved to store the number of non-strict frames.
661 int non_strict_frames = 0;
662 bool encountered_strict_function = false;
663 for (StackFrameIterator iter(this);
664 !iter.done() && frames_seen < limit;
666 StackFrame* raw_frame = iter.frame();
667 if (IsVisibleInStackTrace(raw_frame, *caller, &seen_caller)) {
669 JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
670 // Set initial size to the maximum inlining level + 1 for the outermost
672 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
673 frame->Summarize(&frames);
674 for (int i = frames.length() - 1; i >= 0; i--) {
675 if (cursor + 4 > elements->length()) {
676 int new_capacity = JSObject::NewElementsCapacity(elements->length());
677 Handle<FixedArray> new_elements =
678 factory()->NewFixedArrayWithHoles(new_capacity);
679 for (int i = 0; i < cursor; i++) {
680 new_elements->set(i, elements->get(i));
682 elements = new_elements;
684 ASSERT(cursor + 4 <= elements->length());
686 Handle<Object> recv = frames[i].receiver();
687 Handle<JSFunction> fun = frames[i].function();
688 Handle<Code> code = frames[i].code();
689 Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
690 // The stack trace API should not expose receivers and function
691 // objects on frames deeper than the top-most one with a strict
692 // mode function. The number of non-strict frames is stored as
693 // first element in the result array.
694 if (!encountered_strict_function) {
695 if (!fun->shared()->is_classic_mode()) {
696 encountered_strict_function = true;
701 elements->set(cursor++, *recv);
702 elements->set(cursor++, *fun);
703 elements->set(cursor++, *code);
704 elements->set(cursor++, *offset);
708 elements->set(0, Smi::FromInt(non_strict_frames));
709 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
710 result->set_length(Smi::FromInt(cursor));
715 void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
716 if (capture_stack_trace_for_uncaught_exceptions_) {
717 // Capture stack trace for a detailed exception message.
718 Handle<String> key = factory()->hidden_stack_trace_string();
719 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
720 stack_trace_for_uncaught_exceptions_frame_limit_,
721 stack_trace_for_uncaught_exceptions_options_);
722 JSObject::SetHiddenProperty(error_object, key, stack_trace);
727 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
728 int frame_limit, StackTrace::StackTraceOptions options) {
729 // Ensure no negative values.
730 int limit = Max(frame_limit, 0);
731 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
733 Handle<String> column_key =
734 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("column"));
735 Handle<String> line_key =
736 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("lineNumber"));
737 Handle<String> script_key =
738 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptName"));
739 Handle<String> script_name_or_source_url_key =
740 factory()->InternalizeOneByteString(
741 STATIC_ASCII_VECTOR("scriptNameOrSourceURL"));
742 Handle<String> function_key =
743 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("functionName"));
744 Handle<String> eval_key =
745 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isEval"));
746 Handle<String> constructor_key =
747 factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isConstructor"));
749 StackTraceFrameIterator it(this);
751 while (!it.done() && (frames_seen < limit)) {
752 JavaScriptFrame* frame = it.frame();
753 // Set initial size to the maximum inlining level + 1 for the outermost
755 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
756 frame->Summarize(&frames);
757 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
758 // Create a JSObject to hold the information for the StackFrame.
759 Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
761 Handle<JSFunction> fun = frames[i].function();
762 Handle<Script> script(Script::cast(fun->shared()->script()));
764 if (options & StackTrace::kLineNumber) {
765 int script_line_offset = script->line_offset()->value();
766 int position = frames[i].code()->SourcePosition(frames[i].pc());
767 int line_number = GetScriptLineNumber(script, position);
768 // line_number is already shifted by the script_line_offset.
769 int relative_line_number = line_number - script_line_offset;
770 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
771 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
772 int start = (relative_line_number == 0) ? 0 :
773 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
774 int column_offset = position - start;
775 if (relative_line_number == 0) {
776 // For the case where the code is on the same line as the script
778 column_offset += script->column_offset()->value();
780 CHECK_NOT_EMPTY_HANDLE(
782 JSObject::SetLocalPropertyIgnoreAttributes(
783 stack_frame, column_key,
784 Handle<Smi>(Smi::FromInt(column_offset + 1), this), NONE));
786 CHECK_NOT_EMPTY_HANDLE(
788 JSObject::SetLocalPropertyIgnoreAttributes(
789 stack_frame, line_key,
790 Handle<Smi>(Smi::FromInt(line_number + 1), this), NONE));
793 if (options & StackTrace::kScriptName) {
794 Handle<Object> script_name(script->name(), this);
795 CHECK_NOT_EMPTY_HANDLE(this,
796 JSObject::SetLocalPropertyIgnoreAttributes(
797 stack_frame, script_key, script_name, NONE));
800 if (options & StackTrace::kScriptNameOrSourceURL) {
801 Handle<Object> result = GetScriptNameOrSourceURL(script);
802 CHECK_NOT_EMPTY_HANDLE(this,
803 JSObject::SetLocalPropertyIgnoreAttributes(
804 stack_frame, script_name_or_source_url_key,
808 if (options & StackTrace::kFunctionName) {
809 Handle<Object> fun_name(fun->shared()->name(), this);
810 if (!fun_name->BooleanValue()) {
811 fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
813 CHECK_NOT_EMPTY_HANDLE(this,
814 JSObject::SetLocalPropertyIgnoreAttributes(
815 stack_frame, function_key, fun_name, NONE));
818 if (options & StackTrace::kIsEval) {
819 int type = Smi::cast(script->compilation_type())->value();
820 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
821 factory()->true_value() : factory()->false_value();
822 CHECK_NOT_EMPTY_HANDLE(this,
823 JSObject::SetLocalPropertyIgnoreAttributes(
824 stack_frame, eval_key, is_eval, NONE));
827 if (options & StackTrace::kIsConstructor) {
828 Handle<Object> is_constructor = (frames[i].is_constructor()) ?
829 factory()->true_value() : factory()->false_value();
830 CHECK_NOT_EMPTY_HANDLE(this,
831 JSObject::SetLocalPropertyIgnoreAttributes(
832 stack_frame, constructor_key,
833 is_constructor, NONE));
836 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
842 stack_trace->set_length(Smi::FromInt(frames_seen));
847 void Isolate::PrintStack(FILE* out) {
848 if (stack_trace_nesting_level_ == 0) {
849 stack_trace_nesting_level_++;
851 StringAllocator* allocator;
852 if (preallocated_message_space_ == NULL) {
853 allocator = new HeapStringAllocator();
855 allocator = preallocated_message_space_;
858 StringStream::ClearMentionedObjectCache();
859 StringStream accumulator(allocator);
860 incomplete_message_ = &accumulator;
861 PrintStack(&accumulator);
862 accumulator.OutputToFile(out);
863 InitializeLoggingAndCounters();
865 incomplete_message_ = NULL;
866 stack_trace_nesting_level_ = 0;
867 if (preallocated_message_space_ == NULL) {
868 // Remove the HeapStringAllocator created above.
871 } else if (stack_trace_nesting_level_ == 1) {
872 stack_trace_nesting_level_++;
874 "\n\nAttempt to print stack while printing stack (double fault)\n");
876 "If you are lucky you may find a partial stack dump on stdout.\n\n");
877 incomplete_message_->OutputToFile(out);
882 static void PrintFrames(Isolate* isolate,
883 StringStream* accumulator,
884 StackFrame::PrintMode mode) {
885 StackFrameIterator it(isolate);
886 for (int i = 0; !it.done(); it.Advance()) {
887 it.frame()->Print(accumulator, mode, i++);
892 void Isolate::PrintStack(StringStream* accumulator) {
893 if (!IsInitialized()) {
895 "\n==== JS stack trace is not available =======================\n\n");
897 "\n==== Isolate for the thread is not initialized =============\n\n");
900 // The MentionedObjectCache is not GC-proof at the moment.
901 DisallowHeapAllocation no_gc;
902 ASSERT(StringStream::IsMentionedObjectCacheClear());
904 // Avoid printing anything if there are no frames.
905 if (c_entry_fp(thread_local_top()) == 0) return;
908 "\n==== JS stack trace =========================================\n\n");
909 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
912 "\n==== Details ================================================\n\n");
913 PrintFrames(this, accumulator, StackFrame::DETAILS);
915 accumulator->PrintMentionedObjectCache();
916 accumulator->Add("=====================\n\n");
920 void Isolate::SetFailedAccessCheckCallback(
921 v8::FailedAccessCheckCallback callback) {
922 thread_local_top()->failed_access_check_callback_ = callback;
926 void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
927 if (!thread_local_top()->failed_access_check_callback_) return;
929 ASSERT(receiver->IsAccessCheckNeeded());
932 // Get the data object from access check info.
933 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
934 if (!constructor->shared()->IsApiFunction()) return;
936 constructor->shared()->get_api_func_data()->access_check_info();
937 if (data_obj == heap_.undefined_value()) return;
939 HandleScope scope(this);
940 Handle<JSObject> receiver_handle(receiver);
941 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
942 { VMState<EXTERNAL> state(this);
943 thread_local_top()->failed_access_check_callback_(
944 v8::Utils::ToLocal(receiver_handle),
946 v8::Utils::ToLocal(data));
951 enum MayAccessDecision {
956 static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
958 v8::AccessType type) {
959 // During bootstrapping, callback functions are not enabled yet.
960 if (isolate->bootstrapper()->IsActive()) return YES;
962 if (receiver->IsJSGlobalProxy()) {
963 Object* receiver_context = JSGlobalProxy::cast(receiver)->native_context();
964 if (!receiver_context->IsContext()) return NO;
966 // Get the native context of current top context.
967 // avoid using Isolate::native_context() because it uses Handle.
968 Context* native_context =
969 isolate->context()->global_object()->native_context();
970 if (receiver_context == native_context) return YES;
972 if (Context::cast(receiver_context)->security_token() ==
973 native_context->security_token())
981 bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
982 v8::AccessType type) {
983 ASSERT(receiver->IsAccessCheckNeeded());
985 // The callers of this method are not expecting a GC.
986 DisallowHeapAllocation no_gc;
988 // Skip checks for hidden properties access. Note, we do not
989 // require existence of a context in this case.
990 if (key == heap_.hidden_string()) return true;
992 // Check for compatibility between the security tokens in the
993 // current lexical context and the accessed object.
996 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
997 if (decision != UNKNOWN) return decision == YES;
999 // Get named access check callback
1000 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
1001 if (!constructor->shared()->IsApiFunction()) return false;
1004 constructor->shared()->get_api_func_data()->access_check_info();
1005 if (data_obj == heap_.undefined_value()) return false;
1007 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
1008 v8::NamedSecurityCallback callback =
1009 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
1011 if (!callback) return false;
1013 HandleScope scope(this);
1014 Handle<JSObject> receiver_handle(receiver, this);
1015 Handle<Object> key_handle(key, this);
1016 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
1017 LOG(this, ApiNamedSecurityCheck(key));
1018 bool result = false;
1020 // Leaving JavaScript.
1021 VMState<EXTERNAL> state(this);
1022 result = callback(v8::Utils::ToLocal(receiver_handle),
1023 v8::Utils::ToLocal(key_handle),
1025 v8::Utils::ToLocal(data));
1031 bool Isolate::MayIndexedAccess(JSObject* receiver,
1033 v8::AccessType type) {
1034 ASSERT(receiver->IsAccessCheckNeeded());
1035 // Check for compatibility between the security tokens in the
1036 // current lexical context and the accessed object.
1039 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
1040 if (decision != UNKNOWN) return decision == YES;
1042 // Get indexed access check callback
1043 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
1044 if (!constructor->shared()->IsApiFunction()) return false;
1047 constructor->shared()->get_api_func_data()->access_check_info();
1048 if (data_obj == heap_.undefined_value()) return false;
1050 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
1051 v8::IndexedSecurityCallback callback =
1052 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
1054 if (!callback) return false;
1056 HandleScope scope(this);
1057 Handle<JSObject> receiver_handle(receiver, this);
1058 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
1059 LOG(this, ApiIndexedSecurityCheck(index));
1060 bool result = false;
1062 // Leaving JavaScript.
1063 VMState<EXTERNAL> state(this);
1064 result = callback(v8::Utils::ToLocal(receiver_handle),
1067 v8::Utils::ToLocal(data));
1073 const char* const Isolate::kStackOverflowMessage =
1074 "Uncaught RangeError: Maximum call stack size exceeded";
1077 Failure* Isolate::StackOverflow() {
1078 HandleScope scope(this);
1079 // At this point we cannot create an Error object using its javascript
1080 // constructor. Instead, we copy the pre-constructed boilerplate and
1081 // attach the stack trace as a hidden property.
1082 Handle<String> key = factory()->stack_overflow_string();
1083 Handle<JSObject> boilerplate =
1084 Handle<JSObject>::cast(GetProperty(this, js_builtins_object(), key));
1085 Handle<JSObject> exception = Copy(boilerplate);
1086 DoThrow(*exception, NULL);
1088 // Get stack trace limit.
1089 Handle<Object> error = GetProperty(js_builtins_object(), "$Error");
1090 if (!error->IsJSObject()) return Failure::Exception();
1091 Handle<Object> stack_trace_limit =
1092 GetProperty(Handle<JSObject>::cast(error), "stackTraceLimit");
1093 if (!stack_trace_limit->IsNumber()) return Failure::Exception();
1094 double dlimit = stack_trace_limit->Number();
1095 int limit = std::isnan(dlimit) ? 0 : static_cast<int>(dlimit);
1097 Handle<JSArray> stack_trace = CaptureSimpleStackTrace(
1098 exception, factory()->undefined_value(), limit);
1099 JSObject::SetHiddenProperty(exception,
1100 factory()->hidden_stack_trace_string(),
1102 return Failure::Exception();
1106 Failure* Isolate::TerminateExecution() {
1107 DoThrow(heap_.termination_exception(), NULL);
1108 return Failure::Exception();
1112 void Isolate::CancelTerminateExecution() {
1113 if (try_catch_handler()) {
1114 try_catch_handler()->has_terminated_ = false;
1116 if (has_pending_exception() &&
1117 pending_exception() == heap_.termination_exception()) {
1118 thread_local_top()->external_caught_exception_ = false;
1119 clear_pending_exception();
1121 if (has_scheduled_exception() &&
1122 scheduled_exception() == heap_.termination_exception()) {
1123 thread_local_top()->external_caught_exception_ = false;
1124 clear_scheduled_exception();
1129 Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
1130 DoThrow(exception, location);
1131 return Failure::Exception();
1135 Failure* Isolate::ReThrow(MaybeObject* exception) {
1136 bool can_be_caught_externally = false;
1137 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1138 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1140 thread_local_top()->catcher_ = can_be_caught_externally ?
1141 try_catch_handler() : NULL;
1143 // Set the exception being re-thrown.
1144 set_pending_exception(exception);
1145 if (exception->IsFailure()) return exception->ToFailureUnchecked();
1146 return Failure::Exception();
1150 Failure* Isolate::ThrowIllegalOperation() {
1151 return Throw(heap_.illegal_access_string());
1155 void Isolate::ScheduleThrow(Object* exception) {
1156 // When scheduling a throw we first throw the exception to get the
1157 // error reporting if it is uncaught before rescheduling it.
1159 PropagatePendingExceptionToExternalTryCatch();
1160 if (has_pending_exception()) {
1161 thread_local_top()->scheduled_exception_ = pending_exception();
1162 thread_local_top()->external_caught_exception_ = false;
1163 clear_pending_exception();
1168 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1169 ASSERT(handler == try_catch_handler());
1170 ASSERT(handler->HasCaught());
1171 ASSERT(handler->rethrow_);
1172 ASSERT(handler->capture_message_);
1173 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
1174 Object* script = reinterpret_cast<Object*>(handler->message_script_);
1175 ASSERT(message->IsJSMessageObject() || message->IsTheHole());
1176 ASSERT(script->IsScript() || script->IsTheHole());
1177 thread_local_top()->pending_message_obj_ = message;
1178 thread_local_top()->pending_message_script_ = script;
1179 thread_local_top()->pending_message_start_pos_ = handler->message_start_pos_;
1180 thread_local_top()->pending_message_end_pos_ = handler->message_end_pos_;
1184 Failure* Isolate::PromoteScheduledException() {
1185 MaybeObject* thrown = scheduled_exception();
1186 clear_scheduled_exception();
1187 // Re-throw the exception to avoid getting repeated error reporting.
1188 return ReThrow(thrown);
1192 void Isolate::PrintCurrentStackTrace(FILE* out) {
1193 StackTraceFrameIterator it(this);
1194 while (!it.done()) {
1195 HandleScope scope(this);
1196 // Find code position if recorded in relocation info.
1197 JavaScriptFrame* frame = it.frame();
1198 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1199 Handle<Object> pos_obj(Smi::FromInt(pos), this);
1200 // Fetch function and receiver.
1201 Handle<JSFunction> fun(frame->function());
1202 Handle<Object> recv(frame->receiver(), this);
1203 // Advance to the next JavaScript frame and determine if the
1204 // current frame is the top-level frame.
1206 Handle<Object> is_top_level = it.done()
1207 ? factory()->true_value()
1208 : factory()->false_value();
1209 // Generate and print stack trace line.
1210 Handle<String> line =
1211 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1212 if (line->length() > 0) {
1220 void Isolate::ComputeLocation(MessageLocation* target) {
1221 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1222 StackTraceFrameIterator it(this);
1224 JavaScriptFrame* frame = it.frame();
1225 JSFunction* fun = frame->function();
1226 Object* script = fun->shared()->script();
1227 if (script->IsScript() &&
1228 !(Script::cast(script)->source()->IsUndefined())) {
1229 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1230 // Compute the location from the function and the reloc info.
1231 Handle<Script> casted_script(Script::cast(script));
1232 *target = MessageLocation(casted_script, pos, pos + 1);
1238 bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1239 bool catchable_by_javascript) {
1240 // Find the top-most try-catch handler.
1241 StackHandler* handler =
1242 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1243 while (handler != NULL && !handler->is_catch()) {
1244 handler = handler->next();
1247 // Get the address of the external handler so we can compare the address to
1248 // determine which one is closer to the top of the stack.
1249 Address external_handler_address =
1250 thread_local_top()->try_catch_handler_address();
1252 // The exception has been externally caught if and only if there is
1253 // an external handler which is on top of the top-most try-catch
1255 *can_be_caught_externally = external_handler_address != NULL &&
1256 (handler == NULL || handler->address() > external_handler_address ||
1257 !catchable_by_javascript);
1259 if (*can_be_caught_externally) {
1260 // Only report the exception if the external handler is verbose.
1261 return try_catch_handler()->is_verbose_;
1263 // Report the exception if it isn't caught by JavaScript code.
1264 return handler == NULL;
1269 bool Isolate::IsErrorObject(Handle<Object> obj) {
1270 if (!obj->IsJSObject()) return false;
1273 *(factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("$Error")));
1274 Object* error_constructor =
1275 js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1277 for (Object* prototype = *obj; !prototype->IsNull();
1278 prototype = prototype->GetPrototype(this)) {
1279 if (!prototype->IsJSObject()) return false;
1280 if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1287 static int fatal_exception_depth = 0;
1289 void Isolate::DoThrow(Object* exception, MessageLocation* location) {
1290 ASSERT(!has_pending_exception());
1292 HandleScope scope(this);
1293 Handle<Object> exception_handle(exception, this);
1295 // Determine reporting and whether the exception is caught externally.
1296 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1297 bool can_be_caught_externally = false;
1298 bool should_report_exception =
1299 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1300 bool report_exception = catchable_by_javascript && should_report_exception;
1301 bool try_catch_needs_message =
1302 can_be_caught_externally && try_catch_handler()->capture_message_ &&
1303 !thread_local_top()->rethrowing_message_;
1304 bool bootstrapping = bootstrapper()->IsActive();
1306 thread_local_top()->rethrowing_message_ = false;
1308 #ifdef ENABLE_DEBUGGER_SUPPORT
1309 // Notify debugger of exception.
1310 if (catchable_by_javascript) {
1311 debugger_->OnException(exception_handle, report_exception);
1315 // Generate the message if required.
1316 if (report_exception || try_catch_needs_message) {
1317 MessageLocation potential_computed_location;
1318 if (location == NULL) {
1319 // If no location was specified we use a computed one instead.
1320 ComputeLocation(&potential_computed_location);
1321 location = &potential_computed_location;
1323 // It's not safe to try to make message objects or collect stack traces
1324 // while the bootstrapper is active since the infrastructure may not have
1325 // been properly initialized.
1326 if (!bootstrapping) {
1327 Handle<String> stack_trace;
1328 if (FLAG_trace_exception) stack_trace = StackTraceString();
1329 Handle<JSArray> stack_trace_object;
1330 if (capture_stack_trace_for_uncaught_exceptions_) {
1331 if (IsErrorObject(exception_handle)) {
1332 // We fetch the stack trace that corresponds to this error object.
1333 String* key = heap()->hidden_stack_trace_string();
1334 Object* stack_property =
1335 JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1336 // Property lookup may have failed. In this case it's probably not
1337 // a valid Error object.
1338 if (stack_property->IsJSArray()) {
1339 stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1342 if (stack_trace_object.is_null()) {
1343 // Not an error object, we capture at throw site.
1344 stack_trace_object = CaptureCurrentStackTrace(
1345 stack_trace_for_uncaught_exceptions_frame_limit_,
1346 stack_trace_for_uncaught_exceptions_options_);
1350 Handle<Object> exception_arg = exception_handle;
1351 // If the exception argument is a custom object, turn it into a string
1352 // before throwing as uncaught exception. Note that the pending
1353 // exception object to be set later must not be turned into a string.
1354 if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
1355 bool failed = false;
1356 exception_arg = Execution::ToDetailString(exception_arg, &failed);
1358 exception_arg = factory()->InternalizeOneByteString(
1359 STATIC_ASCII_VECTOR("exception"));
1362 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1364 "uncaught_exception",
1366 HandleVector<Object>(&exception_arg, 1),
1368 stack_trace_object);
1369 thread_local_top()->pending_message_obj_ = *message_obj;
1370 if (location != NULL) {
1371 thread_local_top()->pending_message_script_ = *location->script();
1372 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1373 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1376 // If the abort-on-uncaught-exception flag is specified, abort on any
1377 // exception not caught by JavaScript, even when an external handler is
1378 // present. This flag is intended for use by JavaScript developers, so
1379 // print a user-friendly stack trace (not an internal one).
1380 if (fatal_exception_depth == 0 &&
1381 FLAG_abort_on_uncaught_exception &&
1382 (report_exception || can_be_caught_externally)) {
1383 fatal_exception_depth++;
1386 *MessageHandler::GetLocalizedMessage(this, message_obj));
1387 PrintCurrentStackTrace(stderr);
1390 } else if (location != NULL && !location->script().is_null()) {
1391 // We are bootstrapping and caught an error where the location is set
1392 // and we have a script for the location.
1393 // In this case we could have an extension (or an internal error
1394 // somewhere) and we print out the line number at which the error occured
1395 // to the console for easier debugging.
1396 int line_number = GetScriptLineNumberSafe(location->script(),
1397 location->start_pos());
1398 if (exception->IsString()) {
1400 "Extension or internal compilation error: %s in %s at line %d.\n",
1401 *String::cast(exception)->ToCString(),
1402 *String::cast(location->script()->name())->ToCString(),
1406 "Extension or internal compilation error in %s at line %d.\n",
1407 *String::cast(location->script()->name())->ToCString(),
1413 // Save the message for reporting if the the exception remains uncaught.
1414 thread_local_top()->has_pending_message_ = report_exception;
1416 // Do not forget to clean catcher_ if currently thrown exception cannot
1417 // be caught. If necessary, ReThrow will update the catcher.
1418 thread_local_top()->catcher_ = can_be_caught_externally ?
1419 try_catch_handler() : NULL;
1421 set_pending_exception(*exception_handle);
1425 bool Isolate::IsExternallyCaught() {
1426 ASSERT(has_pending_exception());
1428 if ((thread_local_top()->catcher_ == NULL) ||
1429 (try_catch_handler() != thread_local_top()->catcher_)) {
1430 // When throwing the exception, we found no v8::TryCatch
1431 // which should care about this exception.
1435 if (!is_catchable_by_javascript(pending_exception())) {
1439 // Get the address of the external handler so we can compare the address to
1440 // determine which one is closer to the top of the stack.
1441 Address external_handler_address =
1442 thread_local_top()->try_catch_handler_address();
1443 ASSERT(external_handler_address != NULL);
1445 // The exception has been externally caught if and only if there is
1446 // an external handler which is on top of the top-most try-finally
1448 // There should be no try-catch blocks as they would prohibit us from
1449 // finding external catcher in the first place (see catcher_ check above).
1451 // Note, that finally clause would rethrow an exception unless it's
1452 // aborted by jumps in control flow like return, break, etc. and we'll
1453 // have another chances to set proper v8::TryCatch.
1454 StackHandler* handler =
1455 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1456 while (handler != NULL && handler->address() < external_handler_address) {
1457 ASSERT(!handler->is_catch());
1458 if (handler->is_finally()) return false;
1460 handler = handler->next();
1467 void Isolate::ReportPendingMessages() {
1468 ASSERT(has_pending_exception());
1469 PropagatePendingExceptionToExternalTryCatch();
1471 // If the pending exception is OutOfMemoryException set out_of_memory in
1472 // the native context. Note: We have to mark the native context here
1473 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1475 HandleScope scope(this);
1476 if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
1477 context()->mark_out_of_memory();
1478 } else if (thread_local_top_.pending_exception_ ==
1479 heap()->termination_exception()) {
1480 // Do nothing: if needed, the exception has been already propagated to
1483 if (thread_local_top_.has_pending_message_) {
1484 thread_local_top_.has_pending_message_ = false;
1485 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1486 HandleScope scope(this);
1487 Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1489 if (!thread_local_top_.pending_message_script_->IsTheHole()) {
1490 Handle<Script> script(
1491 Script::cast(thread_local_top_.pending_message_script_));
1492 int start_pos = thread_local_top_.pending_message_start_pos_;
1493 int end_pos = thread_local_top_.pending_message_end_pos_;
1494 MessageLocation location(script, start_pos, end_pos);
1495 MessageHandler::ReportMessage(this, &location, message_obj);
1497 MessageHandler::ReportMessage(this, NULL, message_obj);
1502 clear_pending_message();
1506 MessageLocation Isolate::GetMessageLocation() {
1507 ASSERT(has_pending_exception());
1509 if (!thread_local_top_.pending_exception_->IsOutOfMemory() &&
1510 thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1511 thread_local_top_.has_pending_message_ &&
1512 !thread_local_top_.pending_message_obj_->IsTheHole() &&
1513 !thread_local_top_.pending_message_obj_->IsTheHole()) {
1514 Handle<Script> script(
1515 Script::cast(thread_local_top_.pending_message_script_));
1516 int start_pos = thread_local_top_.pending_message_start_pos_;
1517 int end_pos = thread_local_top_.pending_message_end_pos_;
1518 return MessageLocation(script, start_pos, end_pos);
1521 return MessageLocation();
1525 void Isolate::TraceException(bool flag) {
1526 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1530 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1531 ASSERT(has_pending_exception());
1532 PropagatePendingExceptionToExternalTryCatch();
1534 // Always reschedule out of memory exceptions.
1535 if (!is_out_of_memory()) {
1536 bool is_termination_exception =
1537 pending_exception() == heap_.termination_exception();
1539 // Do not reschedule the exception if this is the bottom call.
1540 bool clear_exception = is_bottom_call;
1542 if (is_termination_exception) {
1543 if (is_bottom_call) {
1544 thread_local_top()->external_caught_exception_ = false;
1545 clear_pending_exception();
1548 } else if (thread_local_top()->external_caught_exception_) {
1549 // If the exception is externally caught, clear it if there are no
1550 // JavaScript frames on the way to the C++ frame that has the
1551 // external handler.
1552 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1553 Address external_handler_address =
1554 thread_local_top()->try_catch_handler_address();
1555 JavaScriptFrameIterator it(this);
1556 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1557 clear_exception = true;
1561 // Clear the exception if needed.
1562 if (clear_exception) {
1563 thread_local_top()->external_caught_exception_ = false;
1564 clear_pending_exception();
1569 // Reschedule the exception.
1570 thread_local_top()->scheduled_exception_ = pending_exception();
1571 clear_pending_exception();
1576 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1579 StackTrace::StackTraceOptions options) {
1580 capture_stack_trace_for_uncaught_exceptions_ = capture;
1581 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1582 stack_trace_for_uncaught_exceptions_options_ = options;
1586 bool Isolate::is_out_of_memory() {
1587 if (has_pending_exception()) {
1588 MaybeObject* e = pending_exception();
1589 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1593 if (has_scheduled_exception()) {
1594 MaybeObject* e = scheduled_exception();
1595 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1603 Handle<Context> Isolate::native_context() {
1604 return Handle<Context>(context()->global_object()->native_context());
1608 Handle<Context> Isolate::global_context() {
1609 return Handle<Context>(context()->global_object()->global_context());
1613 Handle<Context> Isolate::GetCallingNativeContext() {
1614 JavaScriptFrameIterator it(this);
1615 #ifdef ENABLE_DEBUGGER_SUPPORT
1616 if (debug_->InDebugger()) {
1617 while (!it.done()) {
1618 JavaScriptFrame* frame = it.frame();
1619 Context* context = Context::cast(frame->context());
1620 if (context->native_context() == *debug_->debug_context()) {
1627 #endif // ENABLE_DEBUGGER_SUPPORT
1628 if (it.done()) return Handle<Context>::null();
1629 JavaScriptFrame* frame = it.frame();
1630 Context* context = Context::cast(frame->context());
1631 return Handle<Context>(context->native_context());
1635 char* Isolate::ArchiveThread(char* to) {
1636 OS::MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1637 sizeof(ThreadLocalTop));
1638 InitializeThreadLocal();
1639 clear_pending_exception();
1640 clear_pending_message();
1641 clear_scheduled_exception();
1642 return to + sizeof(ThreadLocalTop);
1646 char* Isolate::RestoreThread(char* from) {
1647 OS::MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1648 sizeof(ThreadLocalTop));
1649 // This might be just paranoia, but it seems to be needed in case a
1650 // thread_local_top_ is restored on a separate OS thread.
1651 #ifdef USE_SIMULATOR
1652 #if V8_TARGET_ARCH_ARM
1653 thread_local_top()->simulator_ = Simulator::current(this);
1654 #elif V8_TARGET_ARCH_MIPS
1655 thread_local_top()->simulator_ = Simulator::current(this);
1658 ASSERT(context() == NULL || context()->IsContext());
1659 return from + sizeof(ThreadLocalTop);
1663 Isolate::ThreadDataTable::ThreadDataTable()
1668 Isolate::ThreadDataTable::~ThreadDataTable() {
1669 // TODO(svenpanne) The assertion below would fire if an embedder does not
1670 // cleanly dispose all Isolates before disposing v8, so we are conservative
1671 // and leave it out for now.
1672 // ASSERT_EQ(NULL, list_);
1676 Isolate::PerIsolateThreadData*
1677 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1678 ThreadId thread_id) {
1679 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1680 if (data->Matches(isolate, thread_id)) return data;
1686 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1687 if (list_ != NULL) list_->prev_ = data;
1688 data->next_ = list_;
1693 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1694 if (list_ == data) list_ = data->next_;
1695 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1696 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1701 void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1702 ThreadId thread_id) {
1703 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1710 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1711 PerIsolateThreadData* data = list_;
1712 while (data != NULL) {
1713 PerIsolateThreadData* next = data->next_;
1714 if (data->isolate() == isolate) Remove(data);
1721 #define TRACE_ISOLATE(tag) \
1723 if (FLAG_trace_isolates) { \
1724 PrintF("Isolate %p (id %d)" #tag "\n", \
1725 reinterpret_cast<void*>(this), id()); \
1729 #define TRACE_ISOLATE(tag)
1734 : state_(UNINITIALIZED),
1735 embedder_data_(NULL),
1737 stack_trace_nesting_level_(0),
1738 incomplete_message_(NULL),
1739 preallocated_memory_thread_(NULL),
1740 preallocated_message_space_(NULL),
1741 bootstrapper_(NULL),
1742 runtime_profiler_(NULL),
1743 compilation_cache_(NULL),
1746 // Must be initialized early to allow v8::SetResourceConstraints calls.
1747 break_access_(OS::CreateMutex()),
1748 debugger_initialized_(false),
1749 // Must be initialized early to allow v8::Debug calls.
1750 debugger_access_(OS::CreateMutex()),
1754 deoptimizer_data_(NULL),
1755 capture_stack_trace_for_uncaught_exceptions_(false),
1756 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1757 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1758 transcendental_cache_(NULL),
1759 memory_allocator_(NULL),
1760 keyed_lookup_cache_(NULL),
1761 context_slot_cache_(NULL),
1762 descriptor_lookup_cache_(NULL),
1763 handle_scope_implementer_(NULL),
1764 unicode_cache_(NULL),
1765 runtime_zone_(this),
1768 preallocated_storage_preallocated_(false),
1769 inner_pointer_to_code_cache_(NULL),
1770 write_iterator_(NULL),
1771 global_handles_(NULL),
1772 context_switcher_(NULL),
1773 thread_manager_(NULL),
1774 fp_stubs_generated_(false),
1775 has_installed_extensions_(false),
1776 string_tracker_(NULL),
1777 regexp_stack_(NULL),
1779 code_stub_interface_descriptors_(NULL),
1780 initialized_from_snapshot_(false),
1781 cpu_profiler_(NULL),
1782 heap_profiler_(NULL),
1783 function_entry_hook_(NULL),
1784 deferred_handles_head_(NULL),
1785 optimizing_compiler_thread_(this),
1786 marking_thread_(NULL),
1787 sweeper_thread_(NULL),
1788 callback_table_(NULL),
1789 stress_deopt_count_(0) {
1790 id_ = NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1791 TRACE_ISOLATE(constructor);
1793 memset(isolate_addresses_, 0,
1794 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1796 heap_.isolate_ = this;
1797 stack_guard_.isolate_ = this;
1799 // ThreadManager is initialized early to support locking an isolate
1800 // before it is entered.
1801 thread_manager_ = new ThreadManager();
1802 thread_manager_->isolate_ = this;
1804 #if V8_TARGET_ARCH_ARM && !defined(__arm__) || \
1805 V8_TARGET_ARCH_MIPS && !defined(__mips__)
1806 simulator_initialized_ = false;
1807 simulator_i_cache_ = NULL;
1808 simulator_redirection_ = NULL;
1812 // heap_histograms_ initializes itself.
1813 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1814 memset(code_kind_statistics_, 0,
1815 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
1818 #ifdef ENABLE_DEBUGGER_SUPPORT
1823 handle_scope_data_.Initialize();
1825 #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1826 name##_ = (initial_value);
1827 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1828 #undef ISOLATE_INIT_EXECUTE
1830 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1831 memset(name##_, 0, sizeof(type) * length);
1832 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1833 #undef ISOLATE_INIT_ARRAY_EXECUTE
1837 void Isolate::TearDown() {
1838 TRACE_ISOLATE(tear_down);
1840 // Temporarily set this isolate as current so that various parts of
1841 // the isolate can access it in their destructors without having a
1842 // direct pointer. We don't use Enter/Exit here to avoid
1843 // initializing the thread data.
1844 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1845 Isolate* saved_isolate = UncheckedCurrent();
1846 SetIsolateThreadLocals(this, NULL);
1850 { ScopedLock lock(process_wide_mutex_);
1851 thread_data_table_->RemoveAllThreads(this);
1854 if (serialize_partial_snapshot_cache_ != NULL) {
1855 delete[] serialize_partial_snapshot_cache_;
1856 serialize_partial_snapshot_cache_ = NULL;
1859 if (!IsDefaultIsolate()) {
1863 // Restore the previous current isolate.
1864 SetIsolateThreadLocals(saved_isolate, saved_data);
1868 void Isolate::GlobalTearDown() {
1869 delete thread_data_table_;
1873 void Isolate::Deinit() {
1874 if (state_ == INITIALIZED) {
1875 TRACE_ISOLATE(deinit);
1877 #ifdef ENABLE_DEBUGGER_SUPPORT
1878 debugger()->UnloadDebugger();
1881 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Stop();
1883 if (FLAG_sweeper_threads > 0) {
1884 for (int i = 0; i < FLAG_sweeper_threads; i++) {
1885 sweeper_thread_[i]->Stop();
1886 delete sweeper_thread_[i];
1888 delete[] sweeper_thread_;
1891 if (FLAG_marking_threads > 0) {
1892 for (int i = 0; i < FLAG_marking_threads; i++) {
1893 marking_thread_[i]->Stop();
1894 delete marking_thread_[i];
1896 delete[] marking_thread_;
1899 if (FLAG_hydrogen_stats) GetHStatistics()->Print();
1901 if (FLAG_print_deopt_stress) {
1902 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1905 // We must stop the logger before we tear down other components.
1906 Sampler* sampler = logger_->sampler();
1907 if (sampler && sampler->IsActive()) sampler->Stop();
1909 delete deoptimizer_data_;
1910 deoptimizer_data_ = NULL;
1911 if (FLAG_preemption) {
1912 v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
1913 v8::Locker::StopPreemption();
1915 builtins_.TearDown();
1916 bootstrapper_->TearDown();
1918 // Remove the external reference to the preallocated stack memory.
1919 delete preallocated_message_space_;
1920 preallocated_message_space_ = NULL;
1921 PreallocatedMemoryThreadStop();
1923 if (runtime_profiler_ != NULL) {
1924 runtime_profiler_->TearDown();
1925 delete runtime_profiler_;
1926 runtime_profiler_ = NULL;
1929 logger_->TearDown();
1931 delete heap_profiler_;
1932 heap_profiler_ = NULL;
1933 delete cpu_profiler_;
1934 cpu_profiler_ = NULL;
1936 // The default isolate is re-initializable due to legacy API.
1937 state_ = UNINITIALIZED;
1942 void Isolate::PushToPartialSnapshotCache(Object* obj) {
1943 int length = serialize_partial_snapshot_cache_length();
1944 int capacity = serialize_partial_snapshot_cache_capacity();
1946 if (length >= capacity) {
1947 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1948 Object** new_array = new Object*[new_capacity];
1949 for (int i = 0; i < length; i++) {
1950 new_array[i] = serialize_partial_snapshot_cache()[i];
1952 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1953 set_serialize_partial_snapshot_cache(new_array);
1954 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1957 serialize_partial_snapshot_cache()[length] = obj;
1958 set_serialize_partial_snapshot_cache_length(length + 1);
1962 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1963 PerIsolateThreadData* data) {
1964 Thread::SetThreadLocal(isolate_key_, isolate);
1965 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1969 Isolate::~Isolate() {
1970 TRACE_ISOLATE(destructor);
1972 // Has to be called while counters_ are still alive
1973 runtime_zone_.DeleteKeptSegment();
1975 // The entry stack must be empty when we get here,
1976 // except for the default isolate, where it can
1977 // still contain up to one entry stack item
1978 ASSERT(entry_stack_ == NULL || this == default_isolate_);
1979 ASSERT(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1981 delete entry_stack_;
1982 entry_stack_ = NULL;
1984 delete[] assembler_spare_buffer_;
1985 assembler_spare_buffer_ = NULL;
1987 delete unicode_cache_;
1988 unicode_cache_ = NULL;
1993 delete[] code_stub_interface_descriptors_;
1994 code_stub_interface_descriptors_ = NULL;
1996 delete regexp_stack_;
1997 regexp_stack_ = NULL;
1999 delete descriptor_lookup_cache_;
2000 descriptor_lookup_cache_ = NULL;
2001 delete context_slot_cache_;
2002 context_slot_cache_ = NULL;
2003 delete keyed_lookup_cache_;
2004 keyed_lookup_cache_ = NULL;
2006 delete transcendental_cache_;
2007 transcendental_cache_ = NULL;
2010 delete stats_table_;
2011 stats_table_ = NULL;
2019 delete handle_scope_implementer_;
2020 handle_scope_implementer_ = NULL;
2021 delete break_access_;
2022 break_access_ = NULL;
2023 delete debugger_access_;
2024 debugger_access_ = NULL;
2026 delete compilation_cache_;
2027 compilation_cache_ = NULL;
2028 delete bootstrapper_;
2029 bootstrapper_ = NULL;
2030 delete inner_pointer_to_code_cache_;
2031 inner_pointer_to_code_cache_ = NULL;
2032 delete write_iterator_;
2033 write_iterator_ = NULL;
2035 delete context_switcher_;
2036 context_switcher_ = NULL;
2037 delete thread_manager_;
2038 thread_manager_ = NULL;
2040 delete string_tracker_;
2041 string_tracker_ = NULL;
2043 delete memory_allocator_;
2044 memory_allocator_ = NULL;
2047 delete global_handles_;
2048 global_handles_ = NULL;
2050 delete string_stream_debug_object_cache_;
2051 string_stream_debug_object_cache_ = NULL;
2053 delete external_reference_table_;
2054 external_reference_table_ = NULL;
2056 delete callback_table_;
2057 callback_table_ = NULL;
2059 #ifdef ENABLE_DEBUGGER_SUPPORT
2068 void Isolate::InitializeThreadLocal() {
2069 thread_local_top_.isolate_ = this;
2070 thread_local_top_.Initialize();
2074 void Isolate::PropagatePendingExceptionToExternalTryCatch() {
2075 ASSERT(has_pending_exception());
2077 bool external_caught = IsExternallyCaught();
2078 thread_local_top_.external_caught_exception_ = external_caught;
2080 if (!external_caught) return;
2082 if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
2083 // Do not propagate OOM exception: we should kill VM asap.
2084 } else if (thread_local_top_.pending_exception_ ==
2085 heap()->termination_exception()) {
2086 try_catch_handler()->can_continue_ = false;
2087 try_catch_handler()->has_terminated_ = true;
2088 try_catch_handler()->exception_ = heap()->null_value();
2090 v8::TryCatch* handler = try_catch_handler();
2091 // At this point all non-object (failure) exceptions have
2092 // been dealt with so this shouldn't fail.
2093 ASSERT(!pending_exception()->IsFailure());
2094 ASSERT(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2095 thread_local_top_.pending_message_obj_->IsTheHole());
2096 ASSERT(thread_local_top_.pending_message_script_->IsScript() ||
2097 thread_local_top_.pending_message_script_->IsTheHole());
2098 handler->can_continue_ = true;
2099 handler->has_terminated_ = false;
2100 handler->exception_ = pending_exception();
2101 // Propagate to the external try-catch only if we got an actual message.
2102 if (thread_local_top_.pending_message_obj_->IsTheHole()) return;
2104 handler->message_obj_ = thread_local_top_.pending_message_obj_;
2105 handler->message_script_ = thread_local_top_.pending_message_script_;
2106 handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
2107 handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
2112 void Isolate::InitializeLoggingAndCounters() {
2113 if (logger_ == NULL) {
2114 logger_ = new Logger(this);
2116 if (counters_ == NULL) {
2117 counters_ = new Counters(this);
2122 void Isolate::InitializeDebugger() {
2123 #ifdef ENABLE_DEBUGGER_SUPPORT
2124 ScopedLock lock(debugger_access_);
2125 if (NoBarrier_Load(&debugger_initialized_)) return;
2126 InitializeLoggingAndCounters();
2127 debug_ = new Debug(this);
2128 debugger_ = new Debugger(this);
2129 Release_Store(&debugger_initialized_, true);
2134 bool Isolate::Init(Deserializer* des) {
2135 ASSERT(state_ != INITIALIZED);
2136 ASSERT(Isolate::Current() == this);
2137 TRACE_ISOLATE(init);
2139 stress_deopt_count_ = FLAG_deopt_every_n_times;
2141 if (function_entry_hook() != NULL) {
2142 // When function entry hooking is in effect, we have to create the code
2143 // stubs from scratch to get entry hooks, rather than loading the previously
2144 // generated stubs from disk.
2145 // If this assert fires, the initialization path has regressed.
2146 ASSERT(des == NULL);
2149 // The initialization process does not handle memory exhaustion.
2150 DisallowAllocationFailure disallow_allocation_failure;
2152 InitializeLoggingAndCounters();
2154 InitializeDebugger();
2156 memory_allocator_ = new MemoryAllocator(this);
2157 code_range_ = new CodeRange(this);
2159 // Safe after setting Heap::isolate_, initializing StackGuard and
2160 // ensuring that Isolate::Current() == this.
2161 heap_.SetStackLimits();
2163 #define ASSIGN_ELEMENT(CamelName, hacker_name) \
2164 isolate_addresses_[Isolate::k##CamelName##Address] = \
2165 reinterpret_cast<Address>(hacker_name##_address());
2166 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
2167 #undef ASSIGN_ELEMENT
2169 string_tracker_ = new StringTracker();
2170 string_tracker_->isolate_ = this;
2171 compilation_cache_ = new CompilationCache(this);
2172 transcendental_cache_ = new TranscendentalCache();
2173 keyed_lookup_cache_ = new KeyedLookupCache();
2174 context_slot_cache_ = new ContextSlotCache();
2175 descriptor_lookup_cache_ = new DescriptorLookupCache();
2176 unicode_cache_ = new UnicodeCache();
2177 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
2178 write_iterator_ = new ConsStringIteratorOp();
2179 global_handles_ = new GlobalHandles(this);
2180 bootstrapper_ = new Bootstrapper(this);
2181 handle_scope_implementer_ = new HandleScopeImplementer(this);
2182 stub_cache_ = new StubCache(this);
2183 regexp_stack_ = new RegExpStack();
2184 regexp_stack_->isolate_ = this;
2185 date_cache_ = new DateCache();
2186 code_stub_interface_descriptors_ =
2187 new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
2188 cpu_profiler_ = new CpuProfiler(this);
2189 heap_profiler_ = new HeapProfiler(heap());
2191 // Enable logging before setting up the heap
2192 logger_->SetUp(this);
2194 // Initialize other runtime facilities
2195 #if defined(USE_SIMULATOR)
2196 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_MIPS
2197 Simulator::Initialize(this);
2202 // Ensure that the thread has a valid stack guard. The v8::Locker object
2203 // will ensure this too, but we don't have to use lockers if we are only
2204 // using one thread.
2205 ExecutionAccess lock(this);
2206 stack_guard_.InitThread(lock);
2209 // SetUp the object heap.
2210 ASSERT(!heap_.HasBeenSetUp());
2211 if (!heap_.SetUp()) {
2212 V8::FatalProcessOutOfMemory("heap setup");
2216 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2218 const bool create_heap_objects = (des == NULL);
2219 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2220 V8::FatalProcessOutOfMemory("heap object creation");
2224 if (create_heap_objects) {
2225 // Terminate the cache array with the sentinel so we can iterate.
2226 PushToPartialSnapshotCache(heap_.undefined_value());
2229 InitializeThreadLocal();
2231 bootstrapper_->Initialize(create_heap_objects);
2232 builtins_.SetUp(create_heap_objects);
2234 // Only preallocate on the first initialization.
2235 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
2236 // Start the thread which will set aside some memory.
2237 PreallocatedMemoryThreadStart();
2238 preallocated_message_space_ =
2239 new NoAllocationStringAllocator(
2240 preallocated_memory_thread_->data(),
2241 preallocated_memory_thread_->length());
2242 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
2245 if (FLAG_preemption) {
2246 v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
2247 v8::Locker::StartPreemption(100);
2250 #ifdef ENABLE_DEBUGGER_SUPPORT
2251 debug_->SetUp(create_heap_objects);
2254 // If we are deserializing, read the state into the now-empty heap.
2255 if (!create_heap_objects) {
2258 stub_cache_->Initialize();
2260 // Finish initialization of ThreadLocal after deserialization is done.
2261 clear_pending_exception();
2262 clear_pending_message();
2263 clear_scheduled_exception();
2265 // Deserializing may put strange things in the root array's copy of the
2267 heap_.SetStackLimits();
2269 // Quiet the heap NaN if needed on target platform.
2270 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
2272 runtime_profiler_ = new RuntimeProfiler(this);
2273 runtime_profiler_->SetUp();
2275 // If we are deserializing, log non-function code objects and compiled
2276 // functions found in the snapshot.
2277 if (!create_heap_objects &&
2278 (FLAG_log_code || FLAG_ll_prof || logger_->is_logging_code_events())) {
2279 HandleScope scope(this);
2280 LOG(this, LogCodeObjects());
2281 LOG(this, LogCompiledFunctions());
2284 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2285 Internals::kIsolateEmbedderDataOffset);
2286 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2287 Internals::kIsolateRootsOffset);
2289 state_ = INITIALIZED;
2290 time_millis_at_init_ = OS::TimeCurrentMillis();
2292 if (!create_heap_objects) {
2293 // Now that the heap is consistent, it's OK to generate the code for the
2294 // deopt entry table that might have been referred to by optimized code in
2296 HandleScope scope(this);
2297 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2300 kDeoptTableSerializeEntryCount - 1);
2303 if (!Serializer::enabled()) {
2304 // Ensure that all stubs which need to be generated ahead of time, but
2305 // cannot be serialized into the snapshot have been generated.
2306 HandleScope scope(this);
2307 CodeStub::GenerateFPStubs(this);
2308 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2309 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2310 // TODO(mstarzinger): The following is an ugly hack to make sure the
2311 // interface descriptor is initialized even when stubs have been
2312 // deserialized out of the snapshot without the graph builder.
2313 FastCloneShallowArrayStub stub(FastCloneShallowArrayStub::CLONE_ELEMENTS,
2314 DONT_TRACK_ALLOCATION_SITE, 0);
2315 stub.InitializeInterfaceDescriptor(
2316 this, code_stub_interface_descriptor(CodeStub::FastCloneShallowArray));
2317 CompareNilICStub::InitializeForIsolate(this);
2318 ToBooleanStub::InitializeForIsolate(this);
2319 ArrayConstructorStubBase::InstallDescriptors(this);
2320 InternalArrayConstructorStubBase::InstallDescriptors(this);
2323 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Start();
2325 if (FLAG_marking_threads > 0) {
2326 marking_thread_ = new MarkingThread*[FLAG_marking_threads];
2327 for (int i = 0; i < FLAG_marking_threads; i++) {
2328 marking_thread_[i] = new MarkingThread(this);
2329 marking_thread_[i]->Start();
2333 if (FLAG_sweeper_threads > 0) {
2334 sweeper_thread_ = new SweeperThread*[FLAG_sweeper_threads];
2335 for (int i = 0; i < FLAG_sweeper_threads; i++) {
2336 sweeper_thread_[i] = new SweeperThread(this);
2337 sweeper_thread_[i]->Start();
2341 initialized_from_snapshot_ = (des != NULL);
2347 // Initialized lazily to allow early
2348 // v8::V8::SetAddHistogramSampleFunction calls.
2349 StatsTable* Isolate::stats_table() {
2350 if (stats_table_ == NULL) {
2351 stats_table_ = new StatsTable;
2353 return stats_table_;
2357 void Isolate::Enter() {
2358 Isolate* current_isolate = NULL;
2359 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2360 if (current_data != NULL) {
2361 current_isolate = current_data->isolate_;
2362 ASSERT(current_isolate != NULL);
2363 if (current_isolate == this) {
2364 ASSERT(Current() == this);
2365 ASSERT(entry_stack_ != NULL);
2366 ASSERT(entry_stack_->previous_thread_data == NULL ||
2367 entry_stack_->previous_thread_data->thread_id().Equals(
2368 ThreadId::Current()));
2369 // Same thread re-enters the isolate, no need to re-init anything.
2370 entry_stack_->entry_count++;
2375 // Threads can have default isolate set into TLS as Current but not yet have
2376 // PerIsolateThreadData for it, as it requires more advanced phase of the
2377 // initialization. For example, a thread might be the one that system used for
2378 // static initializers - in this case the default isolate is set in TLS but
2379 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2380 // there, use the isolate set in TLS.
2381 if (current_isolate == NULL) {
2382 current_isolate = Isolate::UncheckedCurrent();
2385 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2386 ASSERT(data != NULL);
2387 ASSERT(data->isolate_ == this);
2389 EntryStackItem* item = new EntryStackItem(current_data,
2392 entry_stack_ = item;
2394 SetIsolateThreadLocals(this, data);
2396 // In case it's the first time some thread enters the isolate.
2397 set_thread_id(data->thread_id());
2401 void Isolate::Exit() {
2402 ASSERT(entry_stack_ != NULL);
2403 ASSERT(entry_stack_->previous_thread_data == NULL ||
2404 entry_stack_->previous_thread_data->thread_id().Equals(
2405 ThreadId::Current()));
2407 if (--entry_stack_->entry_count > 0) return;
2409 ASSERT(CurrentPerIsolateThreadData() != NULL);
2410 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2413 EntryStackItem* item = entry_stack_;
2414 entry_stack_ = item->previous_item;
2416 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2417 Isolate* previous_isolate = item->previous_isolate;
2421 // Reinit the current thread for the isolate it was running before this one.
2422 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2426 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2427 deferred->next_ = deferred_handles_head_;
2428 if (deferred_handles_head_ != NULL) {
2429 deferred_handles_head_->previous_ = deferred;
2431 deferred_handles_head_ = deferred;
2435 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2437 // In debug mode assert that the linked list is well-formed.
2438 DeferredHandles* deferred_iterator = deferred;
2439 while (deferred_iterator->previous_ != NULL) {
2440 deferred_iterator = deferred_iterator->previous_;
2442 ASSERT(deferred_handles_head_ == deferred_iterator);
2444 if (deferred_handles_head_ == deferred) {
2445 deferred_handles_head_ = deferred_handles_head_->next_;
2447 if (deferred->next_ != NULL) {
2448 deferred->next_->previous_ = deferred->previous_;
2450 if (deferred->previous_ != NULL) {
2451 deferred->previous_->next_ = deferred->next_;
2456 HStatistics* Isolate::GetHStatistics() {
2457 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2458 return hstatistics();
2462 HTracer* Isolate::GetHTracer() {
2463 if (htracer() == NULL) set_htracer(new HTracer(id()));
2468 Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2469 Context* native_context = context()->native_context();
2470 Object* maybe_map_array = native_context->js_array_maps();
2471 if (!maybe_map_array->IsUndefined()) {
2472 Object* maybe_transitioned_map =
2473 FixedArray::cast(maybe_map_array)->get(kind);
2474 if (!maybe_transitioned_map->IsUndefined()) {
2475 return Map::cast(maybe_transitioned_map);
2482 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2483 Map* root_array_map =
2484 get_initial_js_array_map(GetInitialFastElementsKind());
2485 ASSERT(root_array_map != NULL);
2486 JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2488 // Check that the array prototype hasn't been altered WRT empty elements.
2489 if (root_array_map->prototype() != initial_array_proto) return false;
2490 if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2494 // Check that the object prototype hasn't been altered WRT empty elements.
2495 JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2496 Object* root_array_map_proto = initial_array_proto->GetPrototype();
2497 if (root_array_map_proto != initial_object_proto) return false;
2498 if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2502 return initial_object_proto->GetPrototype()->IsNull();
2506 CodeStubInterfaceDescriptor*
2507 Isolate::code_stub_interface_descriptor(int index) {
2508 return code_stub_interface_descriptors_ + index;
2512 Object* Isolate::FindCodeObject(Address a) {
2513 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2518 #define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2519 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2520 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2521 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2522 #undef ISOLATE_FIELD_OFFSET
2525 } } // namespace v8::internal