blob: 85ae32ac4ebeab0dcdc85cbfd3133798e6d35c67 [file] [log] [blame]
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001// Copyright 2012 the V8 project authors. All rights reserved.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
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.
15//
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.
27
28#include <stdlib.h>
29
30#include "v8.h"
31
32#include "ast.h"
33#include "bootstrapper.h"
34#include "codegen.h"
35#include "compilation-cache.h"
36#include "debug.h"
37#include "deoptimizer.h"
38#include "heap-profiler.h"
39#include "hydrogen.h"
40#include "isolate.h"
41#include "lithium-allocator.h"
42#include "log.h"
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000043#include "messages.h"
jkummerow@chromium.org1456e702012-03-30 08:38:13 +000044#include "platform.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000045#include "regexp-stack.h"
46#include "runtime-profiler.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000047#include "scopeinfo.h"
48#include "serialize.h"
49#include "simulator.h"
50#include "spaces.h"
51#include "stub-cache.h"
52#include "version.h"
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000053#include "vm-state-inl.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000054
55
56namespace v8 {
57namespace internal {
58
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000059Atomic32 ThreadId::highest_thread_id_ = 0;
60
61int ThreadId::AllocateThreadId() {
62 int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
63 return new_id;
64}
65
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000066
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000067int ThreadId::GetCurrentThreadId() {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000068 int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000069 if (thread_id == 0) {
70 thread_id = AllocateThreadId();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000071 Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000072 }
73 return thread_id;
74}
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000075
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000076
77ThreadLocalTop::ThreadLocalTop() {
78 InitializeInternal();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +000079 // This flag may be set using v8::V8::IgnoreOutOfMemoryException()
80 // before an isolate is initialized. The initialize methods below do
81 // not touch it to preserve its value.
82 ignore_out_of_memory_ = false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000083}
84
85
86void ThreadLocalTop::InitializeInternal() {
87 c_entry_fp_ = 0;
88 handler_ = 0;
89#ifdef USE_SIMULATOR
90 simulator_ = NULL;
91#endif
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000092 js_entry_sp_ = NULL;
93 external_callback_ = NULL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000094 current_vm_state_ = EXTERNAL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000095 try_catch_handler_address_ = NULL;
96 context_ = NULL;
97 thread_id_ = ThreadId::Invalid();
98 external_caught_exception_ = false;
99 failed_access_check_callback_ = NULL;
100 save_context_ = NULL;
101 catcher_ = NULL;
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +0000102 top_lookup_result_ = NULL;
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +0000103
104 // These members are re-initialized later after deserialization
105 // is complete.
106 pending_exception_ = NULL;
107 has_pending_message_ = false;
108 pending_message_obj_ = NULL;
109 pending_message_script_ = NULL;
110 scheduled_exception_ = NULL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000111}
112
113
114void ThreadLocalTop::Initialize() {
115 InitializeInternal();
116#ifdef USE_SIMULATOR
117#ifdef V8_TARGET_ARCH_ARM
118 simulator_ = Simulator::current(isolate_);
119#elif V8_TARGET_ARCH_MIPS
120 simulator_ = Simulator::current(isolate_);
121#endif
122#endif
123 thread_id_ = ThreadId::Current();
124}
125
126
127v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
128 return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
129}
130
131
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000132// Create a dummy thread that will wait forever on a semaphore. The only
133// purpose for this thread is to have some stack area to save essential data
134// into for use by a stacks only core dump (aka minidump).
135class PreallocatedMemoryThread: public Thread {
136 public:
137 char* data() {
138 if (data_ready_semaphore_ != NULL) {
139 // Initial access is guarded until the data has been published.
140 data_ready_semaphore_->Wait();
141 delete data_ready_semaphore_;
142 data_ready_semaphore_ = NULL;
143 }
144 return data_;
145 }
146
147 unsigned length() {
148 if (data_ready_semaphore_ != NULL) {
149 // Initial access is guarded until the data has been published.
150 data_ready_semaphore_->Wait();
151 delete data_ready_semaphore_;
152 data_ready_semaphore_ = NULL;
153 }
154 return length_;
155 }
156
157 // Stop the PreallocatedMemoryThread and release its resources.
158 void StopThread() {
159 keep_running_ = false;
160 wait_for_ever_semaphore_->Signal();
161
162 // Wait for the thread to terminate.
163 Join();
164
165 if (data_ready_semaphore_ != NULL) {
166 delete data_ready_semaphore_;
167 data_ready_semaphore_ = NULL;
168 }
169
170 delete wait_for_ever_semaphore_;
171 wait_for_ever_semaphore_ = NULL;
172 }
173
174 protected:
175 // When the thread starts running it will allocate a fixed number of bytes
176 // on the stack and publish the location of this memory for others to use.
177 void Run() {
178 EmbeddedVector<char, 15 * 1024> local_buffer;
179
180 // Initialize the buffer with a known good value.
181 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
182 local_buffer.length());
183
184 // Publish the local buffer and signal its availability.
185 data_ = local_buffer.start();
186 length_ = local_buffer.length();
187 data_ready_semaphore_->Signal();
188
189 while (keep_running_) {
190 // This thread will wait here until the end of time.
191 wait_for_ever_semaphore_->Wait();
192 }
193
194 // Make sure we access the buffer after the wait to remove all possibility
195 // of it being optimized away.
196 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
197 local_buffer.length());
198 }
199
200
201 private:
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000202 PreallocatedMemoryThread()
203 : Thread("v8:PreallocMem"),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000204 keep_running_(true),
205 wait_for_ever_semaphore_(OS::CreateSemaphore(0)),
206 data_ready_semaphore_(OS::CreateSemaphore(0)),
207 data_(NULL),
208 length_(0) {
209 }
210
211 // Used to make sure that the thread keeps looping even for spurious wakeups.
212 bool keep_running_;
213
214 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
215 Semaphore* wait_for_ever_semaphore_;
216 // Semaphore to signal that the data has been initialized.
217 Semaphore* data_ready_semaphore_;
218
219 // Location and size of the preallocated memory block.
220 char* data_;
221 unsigned length_;
222
223 friend class Isolate;
224
225 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
226};
227
228
229void Isolate::PreallocatedMemoryThreadStart() {
230 if (preallocated_memory_thread_ != NULL) return;
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000231 preallocated_memory_thread_ = new PreallocatedMemoryThread();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000232 preallocated_memory_thread_->Start();
233}
234
235
236void Isolate::PreallocatedMemoryThreadStop() {
237 if (preallocated_memory_thread_ == NULL) return;
238 preallocated_memory_thread_->StopThread();
239 // Done with the thread entirely.
240 delete preallocated_memory_thread_;
241 preallocated_memory_thread_ = NULL;
242}
243
244
lrn@chromium.org7516f052011-03-30 08:52:27 +0000245void Isolate::PreallocatedStorageInit(size_t size) {
246 ASSERT(free_list_.next_ == &free_list_);
247 ASSERT(free_list_.previous_ == &free_list_);
248 PreallocatedStorage* free_chunk =
249 reinterpret_cast<PreallocatedStorage*>(new char[size]);
250 free_list_.next_ = free_list_.previous_ = free_chunk;
251 free_chunk->next_ = free_chunk->previous_ = &free_list_;
252 free_chunk->size_ = size - sizeof(PreallocatedStorage);
253 preallocated_storage_preallocated_ = true;
254}
255
256
257void* Isolate::PreallocatedStorageNew(size_t size) {
258 if (!preallocated_storage_preallocated_) {
rossberg@chromium.org400388e2012-06-06 09:29:22 +0000259 return FreeStoreAllocationPolicy().New(size);
lrn@chromium.org7516f052011-03-30 08:52:27 +0000260 }
261 ASSERT(free_list_.next_ != &free_list_);
262 ASSERT(free_list_.previous_ != &free_list_);
263
264 size = (size + kPointerSize - 1) & ~(kPointerSize - 1);
265 // Search for exact fit.
266 for (PreallocatedStorage* storage = free_list_.next_;
267 storage != &free_list_;
268 storage = storage->next_) {
269 if (storage->size_ == size) {
270 storage->Unlink();
271 storage->LinkTo(&in_use_list_);
272 return reinterpret_cast<void*>(storage + 1);
273 }
274 }
275 // Search for first fit.
276 for (PreallocatedStorage* storage = free_list_.next_;
277 storage != &free_list_;
278 storage = storage->next_) {
279 if (storage->size_ >= size + sizeof(PreallocatedStorage)) {
280 storage->Unlink();
281 storage->LinkTo(&in_use_list_);
282 PreallocatedStorage* left_over =
283 reinterpret_cast<PreallocatedStorage*>(
284 reinterpret_cast<char*>(storage + 1) + size);
285 left_over->size_ = storage->size_ - size - sizeof(PreallocatedStorage);
286 ASSERT(size + left_over->size_ + sizeof(PreallocatedStorage) ==
287 storage->size_);
288 storage->size_ = size;
289 left_over->LinkTo(&free_list_);
290 return reinterpret_cast<void*>(storage + 1);
291 }
292 }
293 // Allocation failure.
294 ASSERT(false);
295 return NULL;
296}
297
298
299// We don't attempt to coalesce.
300void Isolate::PreallocatedStorageDelete(void* p) {
301 if (p == NULL) {
302 return;
303 }
304 if (!preallocated_storage_preallocated_) {
305 FreeStoreAllocationPolicy::Delete(p);
306 return;
307 }
308 PreallocatedStorage* storage = reinterpret_cast<PreallocatedStorage*>(p) - 1;
309 ASSERT(storage->next_->previous_ == storage);
310 ASSERT(storage->previous_->next_ == storage);
311 storage->Unlink();
312 storage->LinkTo(&free_list_);
313}
314
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000315Isolate* Isolate::default_isolate_ = NULL;
316Thread::LocalStorageKey Isolate::isolate_key_;
317Thread::LocalStorageKey Isolate::thread_id_key_;
318Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
319Mutex* Isolate::process_wide_mutex_ = OS::CreateMutex();
320Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
321
322
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000323Isolate::PerIsolateThreadData* Isolate::AllocatePerIsolateThreadData(
324 ThreadId thread_id) {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000325 ASSERT(!thread_id.Equals(ThreadId::Invalid()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000326 PerIsolateThreadData* per_thread = new PerIsolateThreadData(this, thread_id);
327 {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000328 ScopedLock lock(process_wide_mutex_);
329 ASSERT(thread_data_table_->Lookup(this, thread_id) == NULL);
330 thread_data_table_->Insert(per_thread);
331 ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000332 }
333 return per_thread;
334}
335
336
337Isolate::PerIsolateThreadData*
338 Isolate::FindOrAllocatePerThreadDataForThisThread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000339 ThreadId thread_id = ThreadId::Current();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000340 PerIsolateThreadData* per_thread = NULL;
341 {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000342 ScopedLock lock(process_wide_mutex_);
343 per_thread = thread_data_table_->Lookup(this, thread_id);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000344 if (per_thread == NULL) {
345 per_thread = AllocatePerIsolateThreadData(thread_id);
346 }
347 }
348 return per_thread;
349}
350
351
lrn@chromium.org1c092762011-05-09 09:42:16 +0000352Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
353 ThreadId thread_id = ThreadId::Current();
354 PerIsolateThreadData* per_thread = NULL;
355 {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000356 ScopedLock lock(process_wide_mutex_);
357 per_thread = thread_data_table_->Lookup(this, thread_id);
lrn@chromium.org1c092762011-05-09 09:42:16 +0000358 }
359 return per_thread;
360}
361
362
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000363void Isolate::EnsureDefaultIsolate() {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000364 ScopedLock lock(process_wide_mutex_);
365 if (default_isolate_ == NULL) {
366 isolate_key_ = Thread::CreateThreadLocalKey();
367 thread_id_key_ = Thread::CreateThreadLocalKey();
368 per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
369 thread_data_table_ = new Isolate::ThreadDataTable();
370 default_isolate_ = new Isolate();
371 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000372 // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000373 // because a non-null thread data may be already set.
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000374 if (Thread::GetThreadLocal(isolate_key_) == NULL) {
375 Thread::SetThreadLocal(isolate_key_, default_isolate_);
lrn@chromium.org1c092762011-05-09 09:42:16 +0000376 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000377}
378
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000379struct StaticInitializer {
380 StaticInitializer() {
381 Isolate::EnsureDefaultIsolate();
382 }
383} static_initializer;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000384
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000385#ifdef ENABLE_DEBUGGER_SUPPORT
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000386Debugger* Isolate::GetDefaultIsolateDebugger() {
387 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000388 return default_isolate_->debugger();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000389}
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000390#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000391
392
393StackGuard* Isolate::GetDefaultIsolateStackGuard() {
394 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000395 return default_isolate_->stack_guard();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000396}
397
398
399void Isolate::EnterDefaultIsolate() {
400 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000401 ASSERT(default_isolate_ != NULL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000402
403 PerIsolateThreadData* data = CurrentPerIsolateThreadData();
404 // If not yet in default isolate - enter it.
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000405 if (data == NULL || data->isolate() != default_isolate_) {
406 default_isolate_->Enter();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000407 }
408}
409
410
411Isolate* Isolate::GetDefaultIsolateForLocking() {
412 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000413 return default_isolate_;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000414}
415
416
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000417Address Isolate::get_address_from_id(Isolate::AddressId id) {
418 return isolate_addresses_[id];
419}
420
421
422char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
423 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
424 Iterate(v, thread);
425 return thread_storage + sizeof(ThreadLocalTop);
426}
427
428
429void Isolate::IterateThread(ThreadVisitor* v) {
430 v->VisitThread(this, thread_local_top());
431}
432
433
434void Isolate::IterateThread(ThreadVisitor* v, char* t) {
435 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
436 v->VisitThread(this, thread);
437}
438
439
440void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
441 // Visit the roots from the top for a given thread.
442 Object* pending;
443 // The pending exception can sometimes be a failure. We can't show
444 // that to the GC, which only understands objects.
445 if (thread->pending_exception_->ToObject(&pending)) {
446 v->VisitPointer(&pending);
447 thread->pending_exception_ = pending; // In case GC updated it.
448 }
449 v->VisitPointer(&(thread->pending_message_obj_));
450 v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
451 v->VisitPointer(BitCast<Object**>(&(thread->context_)));
452 Object* scheduled;
453 if (thread->scheduled_exception_->ToObject(&scheduled)) {
454 v->VisitPointer(&scheduled);
455 thread->scheduled_exception_ = scheduled;
456 }
457
458 for (v8::TryCatch* block = thread->TryCatchHandler();
459 block != NULL;
460 block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
461 v->VisitPointer(BitCast<Object**>(&(block->exception_)));
462 v->VisitPointer(BitCast<Object**>(&(block->message_)));
463 }
464
465 // Iterate over pointers on native execution stack.
466 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
467 it.frame()->Iterate(v);
468 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +0000469
470 // Iterate pointers in live lookup results.
471 thread->top_lookup_result_->Iterate(v);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000472}
473
474
475void Isolate::Iterate(ObjectVisitor* v) {
476 ThreadLocalTop* current_t = thread_local_top();
477 Iterate(v, current_t);
478}
479
yangguo@chromium.org304cc332012-07-24 07:59:48 +0000480void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
481 for (DeferredHandles* deferred = deferred_handles_head_;
482 deferred != NULL;
483 deferred = deferred->next_) {
484 deferred->Iterate(visitor);
485 }
486}
487
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000488
489void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
490 // The ARM simulator has a separate JS stack. We therefore register
491 // the C++ try catch handler with the simulator and get back an
492 // address that can be used for comparisons with addresses into the
493 // JS stack. When running without the simulator, the address
494 // returned will be the address of the C++ try catch handler itself.
495 Address address = reinterpret_cast<Address>(
496 SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
497 thread_local_top()->set_try_catch_handler_address(address);
498}
499
500
501void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
502 ASSERT(thread_local_top()->TryCatchHandler() == that);
503 thread_local_top()->set_try_catch_handler_address(
504 reinterpret_cast<Address>(that->next_));
505 thread_local_top()->catcher_ = NULL;
506 SimulatorStack::UnregisterCTryCatch();
507}
508
509
510Handle<String> Isolate::StackTraceString() {
511 if (stack_trace_nesting_level_ == 0) {
512 stack_trace_nesting_level_++;
513 HeapStringAllocator allocator;
514 StringStream::ClearMentionedObjectCache();
515 StringStream accumulator(&allocator);
516 incomplete_message_ = &accumulator;
517 PrintStack(&accumulator);
518 Handle<String> stack_trace = accumulator.ToString();
519 incomplete_message_ = NULL;
520 stack_trace_nesting_level_ = 0;
521 return stack_trace;
522 } else if (stack_trace_nesting_level_ == 1) {
523 stack_trace_nesting_level_++;
524 OS::PrintError(
525 "\n\nAttempt to print stack while printing stack (double fault)\n");
526 OS::PrintError(
527 "If you are lucky you may find a partial stack dump on stdout.\n\n");
528 incomplete_message_->OutputToStdOut();
529 return factory()->empty_symbol();
530 } else {
531 OS::Abort();
532 // Unreachable
533 return factory()->empty_symbol();
534 }
535}
536
537
jkummerow@chromium.org67255be2012-09-05 16:44:50 +0000538void Isolate::PushStackTraceAndDie(unsigned int magic,
539 Object* object,
540 Map* map,
541 unsigned int magic2) {
542 const int kMaxStackTraceSize = 8192;
543 Handle<String> trace = StackTraceString();
544 char buffer[kMaxStackTraceSize];
545 int length = Min(kMaxStackTraceSize - 1, trace->length());
546 String::WriteToFlat(*trace, buffer, 0, length);
547 buffer[length] = '\0';
548 OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n",
549 magic, magic2,
550 static_cast<void*>(object), static_cast<void*>(map),
551 buffer);
552 OS::Abort();
553}
554
555
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +0000556// Determines whether the given stack frame should be displayed in
557// a stack trace. The caller is the error constructor that asked
558// for the stack trace to be collected. The first time a construct
559// call to this function is encountered it is skipped. The seen_caller
560// in/out parameter is used to remember if the caller has been seen
561// yet.
562static bool IsVisibleInStackTrace(StackFrame* raw_frame,
563 Object* caller,
564 bool* seen_caller) {
565 // Only display JS frames.
566 if (!raw_frame->is_java_script()) return false;
567 JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
568 Object* raw_fun = frame->function();
569 // Not sure when this can happen but skip it just in case.
570 if (!raw_fun->IsJSFunction()) return false;
571 if ((raw_fun == caller) && !(*seen_caller)) {
572 *seen_caller = true;
573 return false;
574 }
575 // Skip all frames until we've seen the caller.
576 if (!(*seen_caller)) return false;
577 // Also, skip non-visible built-in functions and any call with the builtins
578 // object as receiver, so as to not reveal either the builtins object or
579 // an internal function.
580 // The --builtins-in-stack-traces command line flag allows including
581 // internal call sites in the stack trace for debugging purposes.
582 if (!FLAG_builtins_in_stack_traces) {
583 JSFunction* fun = JSFunction::cast(raw_fun);
584 if (frame->receiver()->IsJSBuiltinsObject() ||
585 (fun->IsBuiltin() && !fun->shared()->native())) {
586 return false;
587 }
588 }
589 return true;
590}
591
592
593Handle<JSArray> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
594 Handle<Object> caller,
595 int limit) {
596 limit = Max(limit, 0); // Ensure that limit is not negative.
597 int initial_size = Min(limit, 10);
598 Handle<FixedArray> elements =
599 factory()->NewFixedArrayWithHoles(initial_size * 4);
600
601 // If the caller parameter is a function we skip frames until we're
602 // under it before starting to collect.
603 bool seen_caller = !caller->IsJSFunction();
604 int cursor = 0;
605 int frames_seen = 0;
606 for (StackFrameIterator iter(this);
607 !iter.done() && frames_seen < limit;
608 iter.Advance()) {
609 StackFrame* raw_frame = iter.frame();
610 if (IsVisibleInStackTrace(raw_frame, *caller, &seen_caller)) {
611 frames_seen++;
612 JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
613 // Set initial size to the maximum inlining level + 1 for the outermost
614 // function.
615 List<FrameSummary> frames(Compiler::kMaxInliningLevels + 1);
616 frame->Summarize(&frames);
617 for (int i = frames.length() - 1; i >= 0; i--) {
618 if (cursor + 4 > elements->length()) {
619 int new_capacity = JSObject::NewElementsCapacity(elements->length());
620 Handle<FixedArray> new_elements =
621 factory()->NewFixedArrayWithHoles(new_capacity);
622 for (int i = 0; i < cursor; i++) {
623 new_elements->set(i, elements->get(i));
624 }
625 elements = new_elements;
626 }
627 ASSERT(cursor + 4 <= elements->length());
628
629 Handle<Object> recv = frames[i].receiver();
630 Handle<JSFunction> fun = frames[i].function();
631 Handle<Code> code = frames[i].code();
632 Handle<Smi> offset(Smi::FromInt(frames[i].offset()));
633 elements->set(cursor++, *recv);
634 elements->set(cursor++, *fun);
635 elements->set(cursor++, *code);
636 elements->set(cursor++, *offset);
637 }
638 }
639 }
640 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
641 result->set_length(Smi::FromInt(cursor));
642 return result;
643}
644
645
646void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +0000647 if (capture_stack_trace_for_uncaught_exceptions_) {
648 // Capture stack trace for a detailed exception message.
649 Handle<String> key = factory()->hidden_stack_trace_symbol();
650 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
651 stack_trace_for_uncaught_exceptions_frame_limit_,
652 stack_trace_for_uncaught_exceptions_options_);
653 JSObject::SetHiddenProperty(error_object, key, stack_trace);
654 }
655}
656
657
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000658Handle<JSArray> Isolate::CaptureCurrentStackTrace(
659 int frame_limit, StackTrace::StackTraceOptions options) {
660 // Ensure no negative values.
661 int limit = Max(frame_limit, 0);
662 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
663
664 Handle<String> column_key = factory()->LookupAsciiSymbol("column");
665 Handle<String> line_key = factory()->LookupAsciiSymbol("lineNumber");
666 Handle<String> script_key = factory()->LookupAsciiSymbol("scriptName");
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000667 Handle<String> script_name_or_source_url_key =
668 factory()->LookupAsciiSymbol("scriptNameOrSourceURL");
669 Handle<String> function_key = factory()->LookupAsciiSymbol("functionName");
670 Handle<String> eval_key = factory()->LookupAsciiSymbol("isEval");
671 Handle<String> constructor_key =
672 factory()->LookupAsciiSymbol("isConstructor");
673
674 StackTraceFrameIterator it(this);
675 int frames_seen = 0;
676 while (!it.done() && (frames_seen < limit)) {
677 JavaScriptFrame* frame = it.frame();
678 // Set initial size to the maximum inlining level + 1 for the outermost
679 // function.
680 List<FrameSummary> frames(Compiler::kMaxInliningLevels + 1);
681 frame->Summarize(&frames);
682 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
683 // Create a JSObject to hold the information for the StackFrame.
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000684 Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000685
686 Handle<JSFunction> fun = frames[i].function();
687 Handle<Script> script(Script::cast(fun->shared()->script()));
688
689 if (options & StackTrace::kLineNumber) {
690 int script_line_offset = script->line_offset()->value();
691 int position = frames[i].code()->SourcePosition(frames[i].pc());
692 int line_number = GetScriptLineNumber(script, position);
693 // line_number is already shifted by the script_line_offset.
694 int relative_line_number = line_number - script_line_offset;
695 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
696 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
697 int start = (relative_line_number == 0) ? 0 :
698 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
699 int column_offset = position - start;
700 if (relative_line_number == 0) {
701 // For the case where the code is on the same line as the script
702 // tag.
703 column_offset += script->column_offset()->value();
704 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000705 CHECK_NOT_EMPTY_HANDLE(
706 this,
707 JSObject::SetLocalPropertyIgnoreAttributes(
708 stack_frame, column_key,
709 Handle<Smi>(Smi::FromInt(column_offset + 1)), NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000710 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000711 CHECK_NOT_EMPTY_HANDLE(
712 this,
713 JSObject::SetLocalPropertyIgnoreAttributes(
714 stack_frame, line_key,
715 Handle<Smi>(Smi::FromInt(line_number + 1)), NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000716 }
717
718 if (options & StackTrace::kScriptName) {
719 Handle<Object> script_name(script->name(), this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000720 CHECK_NOT_EMPTY_HANDLE(this,
721 JSObject::SetLocalPropertyIgnoreAttributes(
722 stack_frame, script_key, script_name, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000723 }
724
725 if (options & StackTrace::kScriptNameOrSourceURL) {
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +0000726 Handle<Object> result = GetScriptNameOrSourceURL(script);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000727 CHECK_NOT_EMPTY_HANDLE(this,
728 JSObject::SetLocalPropertyIgnoreAttributes(
729 stack_frame, script_name_or_source_url_key,
730 result, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000731 }
732
733 if (options & StackTrace::kFunctionName) {
734 Handle<Object> fun_name(fun->shared()->name(), this);
735 if (fun_name->ToBoolean()->IsFalse()) {
736 fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
737 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000738 CHECK_NOT_EMPTY_HANDLE(this,
739 JSObject::SetLocalPropertyIgnoreAttributes(
740 stack_frame, function_key, fun_name, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000741 }
742
743 if (options & StackTrace::kIsEval) {
744 int type = Smi::cast(script->compilation_type())->value();
745 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
746 factory()->true_value() : factory()->false_value();
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000747 CHECK_NOT_EMPTY_HANDLE(this,
748 JSObject::SetLocalPropertyIgnoreAttributes(
749 stack_frame, eval_key, is_eval, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000750 }
751
752 if (options & StackTrace::kIsConstructor) {
753 Handle<Object> is_constructor = (frames[i].is_constructor()) ?
754 factory()->true_value() : factory()->false_value();
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000755 CHECK_NOT_EMPTY_HANDLE(this,
756 JSObject::SetLocalPropertyIgnoreAttributes(
757 stack_frame, constructor_key,
758 is_constructor, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000759 }
760
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000761 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000762 frames_seen++;
763 }
764 it.Advance();
765 }
766
767 stack_trace->set_length(Smi::FromInt(frames_seen));
768 return stack_trace;
769}
770
771
772void Isolate::PrintStack() {
773 if (stack_trace_nesting_level_ == 0) {
774 stack_trace_nesting_level_++;
775
776 StringAllocator* allocator;
777 if (preallocated_message_space_ == NULL) {
778 allocator = new HeapStringAllocator();
779 } else {
780 allocator = preallocated_message_space_;
781 }
782
783 StringStream::ClearMentionedObjectCache();
784 StringStream accumulator(allocator);
785 incomplete_message_ = &accumulator;
786 PrintStack(&accumulator);
787 accumulator.OutputToStdOut();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +0000788 InitializeLoggingAndCounters();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000789 accumulator.Log();
790 incomplete_message_ = NULL;
791 stack_trace_nesting_level_ = 0;
792 if (preallocated_message_space_ == NULL) {
793 // Remove the HeapStringAllocator created above.
794 delete allocator;
795 }
796 } else if (stack_trace_nesting_level_ == 1) {
797 stack_trace_nesting_level_++;
798 OS::PrintError(
799 "\n\nAttempt to print stack while printing stack (double fault)\n");
800 OS::PrintError(
801 "If you are lucky you may find a partial stack dump on stdout.\n\n");
802 incomplete_message_->OutputToStdOut();
803 }
804}
805
806
807static void PrintFrames(StringStream* accumulator,
808 StackFrame::PrintMode mode) {
809 StackFrameIterator it;
810 for (int i = 0; !it.done(); it.Advance()) {
811 it.frame()->Print(accumulator, mode, i++);
812 }
813}
814
815
816void Isolate::PrintStack(StringStream* accumulator) {
817 if (!IsInitialized()) {
818 accumulator->Add(
819 "\n==== Stack trace is not available ==========================\n\n");
820 accumulator->Add(
821 "\n==== Isolate for the thread is not initialized =============\n\n");
822 return;
823 }
824 // The MentionedObjectCache is not GC-proof at the moment.
825 AssertNoAllocation nogc;
826 ASSERT(StringStream::IsMentionedObjectCacheClear());
827
828 // Avoid printing anything if there are no frames.
829 if (c_entry_fp(thread_local_top()) == 0) return;
830
831 accumulator->Add(
832 "\n==== Stack trace ============================================\n\n");
833 PrintFrames(accumulator, StackFrame::OVERVIEW);
834
835 accumulator->Add(
836 "\n==== Details ================================================\n\n");
837 PrintFrames(accumulator, StackFrame::DETAILS);
838
839 accumulator->PrintMentionedObjectCache();
840 accumulator->Add("=====================\n\n");
841}
842
843
844void Isolate::SetFailedAccessCheckCallback(
845 v8::FailedAccessCheckCallback callback) {
846 thread_local_top()->failed_access_check_callback_ = callback;
847}
848
849
850void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
851 if (!thread_local_top()->failed_access_check_callback_) return;
852
853 ASSERT(receiver->IsAccessCheckNeeded());
854 ASSERT(context());
855
856 // Get the data object from access check info.
857 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
858 if (!constructor->shared()->IsApiFunction()) return;
859 Object* data_obj =
860 constructor->shared()->get_api_func_data()->access_check_info();
861 if (data_obj == heap_.undefined_value()) return;
862
863 HandleScope scope;
864 Handle<JSObject> receiver_handle(receiver);
865 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000866 { VMState state(this, EXTERNAL);
867 thread_local_top()->failed_access_check_callback_(
868 v8::Utils::ToLocal(receiver_handle),
869 type,
870 v8::Utils::ToLocal(data));
871 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000872}
873
874
875enum MayAccessDecision {
876 YES, NO, UNKNOWN
877};
878
879
880static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
881 JSObject* receiver,
882 v8::AccessType type) {
883 // During bootstrapping, callback functions are not enabled yet.
884 if (isolate->bootstrapper()->IsActive()) return YES;
885
886 if (receiver->IsJSGlobalProxy()) {
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000887 Object* receiver_context = JSGlobalProxy::cast(receiver)->native_context();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000888 if (!receiver_context->IsContext()) return NO;
889
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000890 // Get the native context of current top context.
891 // avoid using Isolate::native_context() because it uses Handle.
892 Context* native_context =
893 isolate->context()->global_object()->native_context();
894 if (receiver_context == native_context) return YES;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000895
896 if (Context::cast(receiver_context)->security_token() ==
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000897 native_context->security_token())
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000898 return YES;
899 }
900
901 return UNKNOWN;
902}
903
904
905bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
906 v8::AccessType type) {
907 ASSERT(receiver->IsAccessCheckNeeded());
908
909 // The callers of this method are not expecting a GC.
910 AssertNoAllocation no_gc;
911
912 // Skip checks for hidden properties access. Note, we do not
913 // require existence of a context in this case.
914 if (key == heap_.hidden_symbol()) return true;
915
916 // Check for compatibility between the security tokens in the
917 // current lexical context and the accessed object.
918 ASSERT(context());
919
920 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
921 if (decision != UNKNOWN) return decision == YES;
922
923 // Get named access check callback
924 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
925 if (!constructor->shared()->IsApiFunction()) return false;
926
927 Object* data_obj =
928 constructor->shared()->get_api_func_data()->access_check_info();
929 if (data_obj == heap_.undefined_value()) return false;
930
931 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
932 v8::NamedSecurityCallback callback =
933 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
934
935 if (!callback) return false;
936
937 HandleScope scope(this);
938 Handle<JSObject> receiver_handle(receiver, this);
939 Handle<Object> key_handle(key, this);
940 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
941 LOG(this, ApiNamedSecurityCheck(key));
942 bool result = false;
943 {
944 // Leaving JavaScript.
945 VMState state(this, EXTERNAL);
946 result = callback(v8::Utils::ToLocal(receiver_handle),
947 v8::Utils::ToLocal(key_handle),
948 type,
949 v8::Utils::ToLocal(data));
950 }
951 return result;
952}
953
954
955bool Isolate::MayIndexedAccess(JSObject* receiver,
956 uint32_t index,
957 v8::AccessType type) {
958 ASSERT(receiver->IsAccessCheckNeeded());
959 // Check for compatibility between the security tokens in the
960 // current lexical context and the accessed object.
961 ASSERT(context());
962
963 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
964 if (decision != UNKNOWN) return decision == YES;
965
966 // Get indexed access check callback
967 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
968 if (!constructor->shared()->IsApiFunction()) return false;
969
970 Object* data_obj =
971 constructor->shared()->get_api_func_data()->access_check_info();
972 if (data_obj == heap_.undefined_value()) return false;
973
974 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
975 v8::IndexedSecurityCallback callback =
976 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
977
978 if (!callback) return false;
979
980 HandleScope scope(this);
981 Handle<JSObject> receiver_handle(receiver, this);
982 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
983 LOG(this, ApiIndexedSecurityCheck(index));
984 bool result = false;
985 {
986 // Leaving JavaScript.
987 VMState state(this, EXTERNAL);
988 result = callback(v8::Utils::ToLocal(receiver_handle),
989 index,
990 type,
991 v8::Utils::ToLocal(data));
992 }
993 return result;
994}
995
996
997const char* const Isolate::kStackOverflowMessage =
998 "Uncaught RangeError: Maximum call stack size exceeded";
999
1000
1001Failure* Isolate::StackOverflow() {
1002 HandleScope scope;
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001003 // At this point we cannot create an Error object using its javascript
1004 // constructor. Instead, we copy the pre-constructed boilerplate and
1005 // attach the stack trace as a hidden property.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001006 Handle<String> key = factory()->stack_overflow_symbol();
1007 Handle<JSObject> boilerplate =
1008 Handle<JSObject>::cast(GetProperty(js_builtins_object(), key));
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001009 Handle<JSObject> exception = Copy(boilerplate);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001010 DoThrow(*exception, NULL);
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001011
1012 // Get stack trace limit.
1013 Handle<Object> error = GetProperty(js_builtins_object(), "$Error");
1014 if (!error->IsJSObject()) return Failure::Exception();
1015 Handle<Object> stack_trace_limit =
1016 GetProperty(Handle<JSObject>::cast(error), "stackTraceLimit");
1017 if (!stack_trace_limit->IsNumber()) return Failure::Exception();
1018 int limit = static_cast<int>(stack_trace_limit->Number());
1019
1020 Handle<JSArray> stack_trace = CaptureSimpleStackTrace(
1021 exception, factory()->undefined_value(), limit);
1022 JSObject::SetHiddenProperty(exception,
1023 factory()->hidden_stack_trace_symbol(),
1024 stack_trace);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001025 return Failure::Exception();
1026}
1027
1028
1029Failure* Isolate::TerminateExecution() {
1030 DoThrow(heap_.termination_exception(), NULL);
1031 return Failure::Exception();
1032}
1033
1034
1035Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
1036 DoThrow(exception, location);
1037 return Failure::Exception();
1038}
1039
1040
mmassi@chromium.org7028c052012-06-13 11:51:58 +00001041Failure* Isolate::ReThrow(MaybeObject* exception) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001042 bool can_be_caught_externally = false;
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001043 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1044 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1045
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001046 thread_local_top()->catcher_ = can_be_caught_externally ?
1047 try_catch_handler() : NULL;
1048
1049 // Set the exception being re-thrown.
1050 set_pending_exception(exception);
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001051 if (exception->IsFailure()) return exception->ToFailureUnchecked();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001052 return Failure::Exception();
1053}
1054
1055
1056Failure* Isolate::ThrowIllegalOperation() {
1057 return Throw(heap_.illegal_access_symbol());
1058}
1059
1060
1061void Isolate::ScheduleThrow(Object* exception) {
1062 // When scheduling a throw we first throw the exception to get the
1063 // error reporting if it is uncaught before rescheduling it.
1064 Throw(exception);
yangguo@chromium.orgd2899aa2012-06-21 11:16:20 +00001065 thread_local_top()->scheduled_exception_ = pending_exception();
1066 thread_local_top()->external_caught_exception_ = false;
1067 clear_pending_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001068}
1069
1070
1071Failure* Isolate::PromoteScheduledException() {
1072 MaybeObject* thrown = scheduled_exception();
1073 clear_scheduled_exception();
1074 // Re-throw the exception to avoid getting repeated error reporting.
1075 return ReThrow(thrown);
1076}
1077
1078
1079void Isolate::PrintCurrentStackTrace(FILE* out) {
1080 StackTraceFrameIterator it(this);
1081 while (!it.done()) {
1082 HandleScope scope;
1083 // Find code position if recorded in relocation info.
1084 JavaScriptFrame* frame = it.frame();
1085 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1086 Handle<Object> pos_obj(Smi::FromInt(pos));
1087 // Fetch function and receiver.
1088 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
1089 Handle<Object> recv(frame->receiver());
1090 // Advance to the next JavaScript frame and determine if the
1091 // current frame is the top-level frame.
1092 it.Advance();
1093 Handle<Object> is_top_level = it.done()
1094 ? factory()->true_value()
1095 : factory()->false_value();
1096 // Generate and print stack trace line.
1097 Handle<String> line =
1098 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1099 if (line->length() > 0) {
1100 line->PrintOn(out);
1101 fprintf(out, "\n");
1102 }
1103 }
1104}
1105
1106
1107void Isolate::ComputeLocation(MessageLocation* target) {
1108 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1109 StackTraceFrameIterator it(this);
1110 if (!it.done()) {
1111 JavaScriptFrame* frame = it.frame();
1112 JSFunction* fun = JSFunction::cast(frame->function());
1113 Object* script = fun->shared()->script();
1114 if (script->IsScript() &&
1115 !(Script::cast(script)->source()->IsUndefined())) {
1116 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1117 // Compute the location from the function and the reloc info.
1118 Handle<Script> casted_script(Script::cast(script));
1119 *target = MessageLocation(casted_script, pos, pos + 1);
1120 }
1121 }
1122}
1123
1124
1125bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1126 bool catchable_by_javascript) {
1127 // Find the top-most try-catch handler.
1128 StackHandler* handler =
1129 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001130 while (handler != NULL && !handler->is_catch()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001131 handler = handler->next();
1132 }
1133
1134 // Get the address of the external handler so we can compare the address to
1135 // determine which one is closer to the top of the stack.
1136 Address external_handler_address =
1137 thread_local_top()->try_catch_handler_address();
1138
1139 // The exception has been externally caught if and only if there is
1140 // an external handler which is on top of the top-most try-catch
1141 // handler.
1142 *can_be_caught_externally = external_handler_address != NULL &&
1143 (handler == NULL || handler->address() > external_handler_address ||
1144 !catchable_by_javascript);
1145
1146 if (*can_be_caught_externally) {
1147 // Only report the exception if the external handler is verbose.
1148 return try_catch_handler()->is_verbose_;
1149 } else {
1150 // Report the exception if it isn't caught by JavaScript code.
1151 return handler == NULL;
1152 }
1153}
1154
1155
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001156bool Isolate::IsErrorObject(Handle<Object> obj) {
1157 if (!obj->IsJSObject()) return false;
1158
1159 String* error_key = *(factory()->LookupAsciiSymbol("$Error"));
1160 Object* error_constructor =
1161 js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1162
1163 for (Object* prototype = *obj; !prototype->IsNull();
1164 prototype = prototype->GetPrototype()) {
1165 if (!prototype->IsJSObject()) return false;
1166 if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1167 return true;
1168 }
1169 }
1170 return false;
1171}
1172
1173
1174void Isolate::DoThrow(Object* exception, MessageLocation* location) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001175 ASSERT(!has_pending_exception());
1176
1177 HandleScope scope;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001178 Handle<Object> exception_handle(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001179
1180 // Determine reporting and whether the exception is caught externally.
1181 bool catchable_by_javascript = is_catchable_by_javascript(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001182 bool can_be_caught_externally = false;
1183 bool should_report_exception =
1184 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1185 bool report_exception = catchable_by_javascript && should_report_exception;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001186 bool try_catch_needs_message =
1187 can_be_caught_externally && try_catch_handler()->capture_message_;
1188 bool bootstrapping = bootstrapper()->IsActive();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001189
1190#ifdef ENABLE_DEBUGGER_SUPPORT
1191 // Notify debugger of exception.
1192 if (catchable_by_javascript) {
1193 debugger_->OnException(exception_handle, report_exception);
1194 }
1195#endif
1196
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001197 // Generate the message if required.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001198 if (report_exception || try_catch_needs_message) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001199 MessageLocation potential_computed_location;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001200 if (location == NULL) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001201 // If no location was specified we use a computed one instead.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001202 ComputeLocation(&potential_computed_location);
1203 location = &potential_computed_location;
1204 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001205 // It's not safe to try to make message objects or collect stack traces
1206 // while the bootstrapper is active since the infrastructure may not have
1207 // been properly initialized.
1208 if (!bootstrapping) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001209 Handle<String> stack_trace;
1210 if (FLAG_trace_exception) stack_trace = StackTraceString();
1211 Handle<JSArray> stack_trace_object;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001212 if (capture_stack_trace_for_uncaught_exceptions_) {
1213 if (IsErrorObject(exception_handle)) {
1214 // We fetch the stack trace that corresponds to this error object.
1215 String* key = heap()->hidden_stack_trace_symbol();
1216 Object* stack_property =
1217 JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1218 // Property lookup may have failed. In this case it's probably not
1219 // a valid Error object.
1220 if (stack_property->IsJSArray()) {
1221 stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1222 }
1223 }
1224 if (stack_trace_object.is_null()) {
1225 // Not an error object, we capture at throw site.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001226 stack_trace_object = CaptureCurrentStackTrace(
1227 stack_trace_for_uncaught_exceptions_frame_limit_,
1228 stack_trace_for_uncaught_exceptions_options_);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001229 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001230 }
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001231
1232 Handle<Object> exception_arg = exception_handle;
1233 // If the exception argument is a custom object, turn it into a string
1234 // before throwing as uncaught exception. Note that the pending
1235 // exception object to be set later must not be turned into a string.
1236 if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001237 bool failed = false;
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001238 exception_arg = Execution::ToDetailString(exception_arg, &failed);
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001239 if (failed) {
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001240 exception_arg = factory()->LookupAsciiSymbol("exception");
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001241 }
1242 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001243 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1244 "uncaught_exception",
1245 location,
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001246 HandleVector<Object>(&exception_arg, 1),
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001247 stack_trace,
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001248 stack_trace_object);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001249 thread_local_top()->pending_message_obj_ = *message_obj;
1250 if (location != NULL) {
1251 thread_local_top()->pending_message_script_ = *location->script();
1252 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1253 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1254 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +00001255 } else if (location != NULL && !location->script().is_null()) {
1256 // We are bootstrapping and caught an error where the location is set
1257 // and we have a script for the location.
1258 // In this case we could have an extension (or an internal error
1259 // somewhere) and we print out the line number at which the error occured
1260 // to the console for easier debugging.
1261 int line_number = GetScriptLineNumberSafe(location->script(),
1262 location->start_pos());
verwaest@chromium.org37141392012-05-31 13:27:02 +00001263 if (exception->IsString()) {
1264 OS::PrintError(
1265 "Extension or internal compilation error: %s in %s at line %d.\n",
1266 *String::cast(exception)->ToCString(),
1267 *String::cast(location->script()->name())->ToCString(),
danno@chromium.org81cac2b2012-07-10 11:28:27 +00001268 line_number + 1);
verwaest@chromium.org37141392012-05-31 13:27:02 +00001269 } else {
1270 OS::PrintError(
1271 "Extension or internal compilation error in %s at line %d.\n",
1272 *String::cast(location->script()->name())->ToCString(),
danno@chromium.org81cac2b2012-07-10 11:28:27 +00001273 line_number + 1);
verwaest@chromium.org37141392012-05-31 13:27:02 +00001274 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001275 }
1276 }
1277
1278 // Save the message for reporting if the the exception remains uncaught.
1279 thread_local_top()->has_pending_message_ = report_exception;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001280
1281 // Do not forget to clean catcher_ if currently thrown exception cannot
1282 // be caught. If necessary, ReThrow will update the catcher.
1283 thread_local_top()->catcher_ = can_be_caught_externally ?
1284 try_catch_handler() : NULL;
1285
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001286 set_pending_exception(*exception_handle);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001287}
1288
1289
1290bool Isolate::IsExternallyCaught() {
1291 ASSERT(has_pending_exception());
1292
1293 if ((thread_local_top()->catcher_ == NULL) ||
1294 (try_catch_handler() != thread_local_top()->catcher_)) {
1295 // When throwing the exception, we found no v8::TryCatch
1296 // which should care about this exception.
1297 return false;
1298 }
1299
1300 if (!is_catchable_by_javascript(pending_exception())) {
1301 return true;
1302 }
1303
1304 // Get the address of the external handler so we can compare the address to
1305 // determine which one is closer to the top of the stack.
1306 Address external_handler_address =
1307 thread_local_top()->try_catch_handler_address();
1308 ASSERT(external_handler_address != NULL);
1309
1310 // The exception has been externally caught if and only if there is
1311 // an external handler which is on top of the top-most try-finally
1312 // handler.
1313 // There should be no try-catch blocks as they would prohibit us from
1314 // finding external catcher in the first place (see catcher_ check above).
1315 //
1316 // Note, that finally clause would rethrow an exception unless it's
1317 // aborted by jumps in control flow like return, break, etc. and we'll
1318 // have another chances to set proper v8::TryCatch.
1319 StackHandler* handler =
1320 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1321 while (handler != NULL && handler->address() < external_handler_address) {
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001322 ASSERT(!handler->is_catch());
1323 if (handler->is_finally()) return false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001324
1325 handler = handler->next();
1326 }
1327
1328 return true;
1329}
1330
1331
1332void Isolate::ReportPendingMessages() {
1333 ASSERT(has_pending_exception());
1334 PropagatePendingExceptionToExternalTryCatch();
1335
1336 // If the pending exception is OutOfMemoryException set out_of_memory in
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001337 // the native context. Note: We have to mark the native context here
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001338 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1339 // set it.
1340 HandleScope scope;
1341 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1342 context()->mark_out_of_memory();
1343 } else if (thread_local_top_.pending_exception_ ==
1344 heap()->termination_exception()) {
1345 // Do nothing: if needed, the exception has been already propagated to
1346 // v8::TryCatch.
1347 } else {
1348 if (thread_local_top_.has_pending_message_) {
1349 thread_local_top_.has_pending_message_ = false;
1350 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1351 HandleScope scope;
1352 Handle<Object> message_obj(thread_local_top_.pending_message_obj_);
1353 if (thread_local_top_.pending_message_script_ != NULL) {
1354 Handle<Script> script(thread_local_top_.pending_message_script_);
1355 int start_pos = thread_local_top_.pending_message_start_pos_;
1356 int end_pos = thread_local_top_.pending_message_end_pos_;
1357 MessageLocation location(script, start_pos, end_pos);
1358 MessageHandler::ReportMessage(this, &location, message_obj);
1359 } else {
1360 MessageHandler::ReportMessage(this, NULL, message_obj);
1361 }
1362 }
1363 }
1364 }
1365 clear_pending_message();
1366}
1367
1368
1369void Isolate::TraceException(bool flag) {
1370 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1371}
1372
1373
1374bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1375 ASSERT(has_pending_exception());
1376 PropagatePendingExceptionToExternalTryCatch();
1377
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001378 // Always reschedule out of memory exceptions.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001379 if (!is_out_of_memory()) {
1380 bool is_termination_exception =
1381 pending_exception() == heap_.termination_exception();
1382
1383 // Do not reschedule the exception if this is the bottom call.
1384 bool clear_exception = is_bottom_call;
1385
1386 if (is_termination_exception) {
1387 if (is_bottom_call) {
1388 thread_local_top()->external_caught_exception_ = false;
1389 clear_pending_exception();
1390 return false;
1391 }
1392 } else if (thread_local_top()->external_caught_exception_) {
1393 // If the exception is externally caught, clear it if there are no
1394 // JavaScript frames on the way to the C++ frame that has the
1395 // external handler.
1396 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1397 Address external_handler_address =
1398 thread_local_top()->try_catch_handler_address();
1399 JavaScriptFrameIterator it;
1400 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1401 clear_exception = true;
1402 }
1403 }
1404
1405 // Clear the exception if needed.
1406 if (clear_exception) {
1407 thread_local_top()->external_caught_exception_ = false;
1408 clear_pending_exception();
1409 return false;
1410 }
1411 }
1412
1413 // Reschedule the exception.
1414 thread_local_top()->scheduled_exception_ = pending_exception();
1415 clear_pending_exception();
1416 return true;
1417}
1418
1419
1420void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1421 bool capture,
1422 int frame_limit,
1423 StackTrace::StackTraceOptions options) {
1424 capture_stack_trace_for_uncaught_exceptions_ = capture;
1425 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1426 stack_trace_for_uncaught_exceptions_options_ = options;
1427}
1428
1429
1430bool Isolate::is_out_of_memory() {
1431 if (has_pending_exception()) {
1432 MaybeObject* e = pending_exception();
1433 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1434 return true;
1435 }
1436 }
1437 if (has_scheduled_exception()) {
1438 MaybeObject* e = scheduled_exception();
1439 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1440 return true;
1441 }
1442 }
1443 return false;
1444}
1445
1446
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001447Handle<Context> Isolate::native_context() {
1448 GlobalObject* global = thread_local_top()->context_->global_object();
1449 return Handle<Context>(global->native_context());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001450}
1451
1452
yangguo@chromium.org355cfd12012-08-29 15:32:24 +00001453Handle<Context> Isolate::global_context() {
1454 GlobalObject* global = thread_local_top()->context_->global_object();
1455 return Handle<Context>(global->global_context());
1456}
1457
1458
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001459Handle<Context> Isolate::GetCallingNativeContext() {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001460 JavaScriptFrameIterator it;
1461#ifdef ENABLE_DEBUGGER_SUPPORT
1462 if (debug_->InDebugger()) {
1463 while (!it.done()) {
1464 JavaScriptFrame* frame = it.frame();
1465 Context* context = Context::cast(frame->context());
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001466 if (context->native_context() == *debug_->debug_context()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001467 it.Advance();
1468 } else {
1469 break;
1470 }
1471 }
1472 }
1473#endif // ENABLE_DEBUGGER_SUPPORT
1474 if (it.done()) return Handle<Context>::null();
1475 JavaScriptFrame* frame = it.frame();
1476 Context* context = Context::cast(frame->context());
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001477 return Handle<Context>(context->native_context());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001478}
1479
1480
1481char* Isolate::ArchiveThread(char* to) {
1482 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1483 RuntimeProfiler::IsolateExitedJS(this);
1484 }
1485 memcpy(to, reinterpret_cast<char*>(thread_local_top()),
1486 sizeof(ThreadLocalTop));
1487 InitializeThreadLocal();
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001488 clear_pending_exception();
1489 clear_pending_message();
1490 clear_scheduled_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001491 return to + sizeof(ThreadLocalTop);
1492}
1493
1494
1495char* Isolate::RestoreThread(char* from) {
1496 memcpy(reinterpret_cast<char*>(thread_local_top()), from,
1497 sizeof(ThreadLocalTop));
1498 // This might be just paranoia, but it seems to be needed in case a
1499 // thread_local_top_ is restored on a separate OS thread.
1500#ifdef USE_SIMULATOR
1501#ifdef V8_TARGET_ARCH_ARM
1502 thread_local_top()->simulator_ = Simulator::current(this);
1503#elif V8_TARGET_ARCH_MIPS
1504 thread_local_top()->simulator_ = Simulator::current(this);
1505#endif
1506#endif
1507 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1508 RuntimeProfiler::IsolateEnteredJS(this);
1509 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001510 ASSERT(context() == NULL || context()->IsContext());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001511 return from + sizeof(ThreadLocalTop);
1512}
1513
1514
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001515Isolate::ThreadDataTable::ThreadDataTable()
1516 : list_(NULL) {
1517}
1518
1519
1520Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001521 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1522 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001523 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1524 if (data->Matches(isolate, thread_id)) return data;
1525 }
1526 return NULL;
1527}
1528
1529
1530void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1531 if (list_ != NULL) list_->prev_ = data;
1532 data->next_ = list_;
1533 list_ = data;
1534}
1535
1536
1537void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1538 if (list_ == data) list_ = data->next_;
1539 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1540 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001541 delete data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001542}
1543
1544
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001545void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1546 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001547 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1548 if (data != NULL) {
1549 Remove(data);
1550 }
1551}
1552
1553
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001554void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1555 PerIsolateThreadData* data = list_;
1556 while (data != NULL) {
1557 PerIsolateThreadData* next = data->next_;
1558 if (data->isolate() == isolate) Remove(data);
1559 data = next;
1560 }
1561}
1562
1563
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001564#ifdef DEBUG
1565#define TRACE_ISOLATE(tag) \
1566 do { \
1567 if (FLAG_trace_isolates) { \
1568 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
1569 } \
1570 } while (false)
1571#else
1572#define TRACE_ISOLATE(tag)
1573#endif
1574
1575
1576Isolate::Isolate()
1577 : state_(UNINITIALIZED),
yangguo@chromium.orgefdb9d72012-04-26 08:21:05 +00001578 embedder_data_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001579 entry_stack_(NULL),
1580 stack_trace_nesting_level_(0),
1581 incomplete_message_(NULL),
1582 preallocated_memory_thread_(NULL),
1583 preallocated_message_space_(NULL),
1584 bootstrapper_(NULL),
1585 runtime_profiler_(NULL),
1586 compilation_cache_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001587 counters_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001588 code_range_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001589 // Must be initialized early to allow v8::SetResourceConstraints calls.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001590 break_access_(OS::CreateMutex()),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001591 debugger_initialized_(false),
1592 // Must be initialized early to allow v8::Debug calls.
1593 debugger_access_(OS::CreateMutex()),
1594 logger_(NULL),
1595 stats_table_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001596 stub_cache_(NULL),
1597 deoptimizer_data_(NULL),
1598 capture_stack_trace_for_uncaught_exceptions_(false),
1599 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1600 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1601 transcendental_cache_(NULL),
1602 memory_allocator_(NULL),
1603 keyed_lookup_cache_(NULL),
1604 context_slot_cache_(NULL),
1605 descriptor_lookup_cache_(NULL),
1606 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001607 unicode_cache_(NULL),
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001608 runtime_zone_(this),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001609 in_use_list_(0),
1610 free_list_(0),
1611 preallocated_storage_preallocated_(false),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001612 inner_pointer_to_code_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001613 write_input_buffer_(NULL),
1614 global_handles_(NULL),
1615 context_switcher_(NULL),
1616 thread_manager_(NULL),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001617 fp_stubs_generated_(false),
ricow@chromium.org27bf2882011-11-17 08:34:43 +00001618 has_installed_extensions_(false),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001619 string_tracker_(NULL),
1620 regexp_stack_(NULL),
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001621 date_cache_(NULL),
yangguo@chromium.org304cc332012-07-24 07:59:48 +00001622 context_exit_happened_(false),
1623 deferred_handles_head_(NULL),
1624 optimizing_compiler_thread_(this) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001625 TRACE_ISOLATE(constructor);
1626
1627 memset(isolate_addresses_, 0,
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001628 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001629
1630 heap_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001631 stack_guard_.isolate_ = this;
1632
lrn@chromium.org1c092762011-05-09 09:42:16 +00001633 // ThreadManager is initialized early to support locking an isolate
1634 // before it is entered.
1635 thread_manager_ = new ThreadManager();
1636 thread_manager_->isolate_ = this;
1637
lrn@chromium.org7516f052011-03-30 08:52:27 +00001638#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
1639 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001640 simulator_initialized_ = false;
1641 simulator_i_cache_ = NULL;
1642 simulator_redirection_ = NULL;
1643#endif
1644
1645#ifdef DEBUG
1646 // heap_histograms_ initializes itself.
1647 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1648 memset(code_kind_statistics_, 0,
1649 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
1650#endif
1651
1652#ifdef ENABLE_DEBUGGER_SUPPORT
1653 debug_ = NULL;
1654 debugger_ = NULL;
1655#endif
1656
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001657 handle_scope_data_.Initialize();
1658
1659#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1660 name##_ = (initial_value);
1661 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1662#undef ISOLATE_INIT_EXECUTE
1663
1664#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1665 memset(name##_, 0, sizeof(type) * length);
1666 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1667#undef ISOLATE_INIT_ARRAY_EXECUTE
1668}
1669
1670void Isolate::TearDown() {
1671 TRACE_ISOLATE(tear_down);
1672
1673 // Temporarily set this isolate as current so that various parts of
1674 // the isolate can access it in their destructors without having a
1675 // direct pointer. We don't use Enter/Exit here to avoid
1676 // initializing the thread data.
1677 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1678 Isolate* saved_isolate = UncheckedCurrent();
1679 SetIsolateThreadLocals(this, NULL);
1680
1681 Deinit();
1682
danno@chromium.org8c0a43f2012-04-03 08:37:53 +00001683 { ScopedLock lock(process_wide_mutex_);
1684 thread_data_table_->RemoveAllThreads(this);
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001685 }
1686
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001687 if (serialize_partial_snapshot_cache_ != NULL) {
1688 delete[] serialize_partial_snapshot_cache_;
1689 serialize_partial_snapshot_cache_ = NULL;
1690 }
1691
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001692 if (!IsDefaultIsolate()) {
1693 delete this;
1694 }
1695
1696 // Restore the previous current isolate.
1697 SetIsolateThreadLocals(saved_isolate, saved_data);
1698}
1699
1700
1701void Isolate::Deinit() {
1702 if (state_ == INITIALIZED) {
1703 TRACE_ISOLATE(deinit);
1704
yangguo@chromium.org304cc332012-07-24 07:59:48 +00001705 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Stop();
1706
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001707 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
1708
1709 // We must stop the logger before we tear down other components.
1710 logger_->EnsureTickerStopped();
1711
1712 delete deoptimizer_data_;
1713 deoptimizer_data_ = NULL;
1714 if (FLAG_preemption) {
1715 v8::Locker locker;
1716 v8::Locker::StopPreemption();
1717 }
1718 builtins_.TearDown();
1719 bootstrapper_->TearDown();
1720
1721 // Remove the external reference to the preallocated stack memory.
1722 delete preallocated_message_space_;
1723 preallocated_message_space_ = NULL;
1724 PreallocatedMemoryThreadStop();
1725
1726 HeapProfiler::TearDown();
1727 CpuProfiler::TearDown();
1728 if (runtime_profiler_ != NULL) {
1729 runtime_profiler_->TearDown();
1730 delete runtime_profiler_;
1731 runtime_profiler_ = NULL;
1732 }
1733 heap_.TearDown();
1734 logger_->TearDown();
1735
1736 // The default isolate is re-initializable due to legacy API.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001737 state_ = UNINITIALIZED;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001738 }
1739}
1740
1741
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001742void Isolate::PushToPartialSnapshotCache(Object* obj) {
1743 int length = serialize_partial_snapshot_cache_length();
1744 int capacity = serialize_partial_snapshot_cache_capacity();
1745
1746 if (length >= capacity) {
1747 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1748 Object** new_array = new Object*[new_capacity];
1749 for (int i = 0; i < length; i++) {
1750 new_array[i] = serialize_partial_snapshot_cache()[i];
1751 }
1752 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1753 set_serialize_partial_snapshot_cache(new_array);
1754 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1755 }
1756
1757 serialize_partial_snapshot_cache()[length] = obj;
1758 set_serialize_partial_snapshot_cache_length(length + 1);
1759}
1760
1761
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001762void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1763 PerIsolateThreadData* data) {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +00001764 Thread::SetThreadLocal(isolate_key_, isolate);
1765 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001766}
1767
1768
1769Isolate::~Isolate() {
1770 TRACE_ISOLATE(destructor);
1771
danno@chromium.orgb6451162011-08-17 14:33:23 +00001772 // Has to be called while counters_ are still alive.
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001773 runtime_zone_.DeleteKeptSegment();
danno@chromium.orgb6451162011-08-17 14:33:23 +00001774
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001775 delete[] assembler_spare_buffer_;
1776 assembler_spare_buffer_ = NULL;
1777
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001778 delete unicode_cache_;
1779 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001780
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001781 delete date_cache_;
1782 date_cache_ = NULL;
1783
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001784 delete regexp_stack_;
1785 regexp_stack_ = NULL;
1786
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001787 delete descriptor_lookup_cache_;
1788 descriptor_lookup_cache_ = NULL;
1789 delete context_slot_cache_;
1790 context_slot_cache_ = NULL;
1791 delete keyed_lookup_cache_;
1792 keyed_lookup_cache_ = NULL;
1793
1794 delete transcendental_cache_;
1795 transcendental_cache_ = NULL;
1796 delete stub_cache_;
1797 stub_cache_ = NULL;
1798 delete stats_table_;
1799 stats_table_ = NULL;
1800
1801 delete logger_;
1802 logger_ = NULL;
1803
1804 delete counters_;
1805 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001806
1807 delete handle_scope_implementer_;
1808 handle_scope_implementer_ = NULL;
1809 delete break_access_;
1810 break_access_ = NULL;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001811 delete debugger_access_;
1812 debugger_access_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001813
1814 delete compilation_cache_;
1815 compilation_cache_ = NULL;
1816 delete bootstrapper_;
1817 bootstrapper_ = NULL;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001818 delete inner_pointer_to_code_cache_;
1819 inner_pointer_to_code_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001820 delete write_input_buffer_;
1821 write_input_buffer_ = NULL;
1822
1823 delete context_switcher_;
1824 context_switcher_ = NULL;
1825 delete thread_manager_;
1826 thread_manager_ = NULL;
1827
1828 delete string_tracker_;
1829 string_tracker_ = NULL;
1830
1831 delete memory_allocator_;
1832 memory_allocator_ = NULL;
1833 delete code_range_;
1834 code_range_ = NULL;
1835 delete global_handles_;
1836 global_handles_ = NULL;
1837
danno@chromium.orgb6451162011-08-17 14:33:23 +00001838 delete external_reference_table_;
1839 external_reference_table_ = NULL;
1840
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001841#ifdef ENABLE_DEBUGGER_SUPPORT
1842 delete debugger_;
1843 debugger_ = NULL;
1844 delete debug_;
1845 debug_ = NULL;
1846#endif
1847}
1848
1849
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001850void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +00001851 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001852 thread_local_top_.Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001853}
1854
1855
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001856void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1857 ASSERT(has_pending_exception());
1858
1859 bool external_caught = IsExternallyCaught();
1860 thread_local_top_.external_caught_exception_ = external_caught;
1861
1862 if (!external_caught) return;
1863
1864 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1865 // Do not propagate OOM exception: we should kill VM asap.
1866 } else if (thread_local_top_.pending_exception_ ==
1867 heap()->termination_exception()) {
1868 try_catch_handler()->can_continue_ = false;
1869 try_catch_handler()->exception_ = heap()->null_value();
1870 } else {
1871 // At this point all non-object (failure) exceptions have
1872 // been dealt with so this shouldn't fail.
1873 ASSERT(!pending_exception()->IsFailure());
1874 try_catch_handler()->can_continue_ = true;
1875 try_catch_handler()->exception_ = pending_exception();
1876 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1877 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
1878 }
1879 }
1880}
1881
1882
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001883void Isolate::InitializeLoggingAndCounters() {
1884 if (logger_ == NULL) {
1885 logger_ = new Logger;
1886 }
1887 if (counters_ == NULL) {
1888 counters_ = new Counters;
1889 }
1890}
1891
1892
1893void Isolate::InitializeDebugger() {
1894#ifdef ENABLE_DEBUGGER_SUPPORT
1895 ScopedLock lock(debugger_access_);
1896 if (NoBarrier_Load(&debugger_initialized_)) return;
1897 InitializeLoggingAndCounters();
1898 debug_ = new Debug(this);
1899 debugger_ = new Debugger(this);
1900 Release_Store(&debugger_initialized_, true);
1901#endif
1902}
1903
1904
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001905bool Isolate::Init(Deserializer* des) {
1906 ASSERT(state_ != INITIALIZED);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001907 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001908 TRACE_ISOLATE(init);
1909
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001910 // The initialization process does not handle memory exhaustion.
1911 DisallowAllocationFailure disallow_allocation_failure;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001912
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001913 InitializeLoggingAndCounters();
1914
1915 InitializeDebugger();
1916
1917 memory_allocator_ = new MemoryAllocator(this);
1918 code_range_ = new CodeRange(this);
1919
1920 // Safe after setting Heap::isolate_, initializing StackGuard and
1921 // ensuring that Isolate::Current() == this.
1922 heap_.SetStackLimits();
1923
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001924#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1925 isolate_addresses_[Isolate::k##CamelName##Address] = \
1926 reinterpret_cast<Address>(hacker_name##_address());
1927 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001928#undef C
1929
1930 string_tracker_ = new StringTracker();
1931 string_tracker_->isolate_ = this;
1932 compilation_cache_ = new CompilationCache(this);
1933 transcendental_cache_ = new TranscendentalCache();
1934 keyed_lookup_cache_ = new KeyedLookupCache();
1935 context_slot_cache_ = new ContextSlotCache();
1936 descriptor_lookup_cache_ = new DescriptorLookupCache();
1937 unicode_cache_ = new UnicodeCache();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001938 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001939 write_input_buffer_ = new StringInputBuffer();
1940 global_handles_ = new GlobalHandles(this);
1941 bootstrapper_ = new Bootstrapper();
1942 handle_scope_implementer_ = new HandleScopeImplementer(this);
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001943 stub_cache_ = new StubCache(this, runtime_zone());
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001944 regexp_stack_ = new RegExpStack();
1945 regexp_stack_->isolate_ = this;
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001946 date_cache_ = new DateCache();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001947
1948 // Enable logging before setting up the heap
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001949 logger_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001950
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001951 CpuProfiler::SetUp();
1952 HeapProfiler::SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001953
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001954 // Initialize other runtime facilities
1955#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +00001956#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
lrn@chromium.org1c092762011-05-09 09:42:16 +00001957 Simulator::Initialize(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001958#endif
1959#endif
1960
1961 { // NOLINT
1962 // Ensure that the thread has a valid stack guard. The v8::Locker object
1963 // will ensure this too, but we don't have to use lockers if we are only
1964 // using one thread.
1965 ExecutionAccess lock(this);
1966 stack_guard_.InitThread(lock);
1967 }
1968
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001969 // SetUp the object heap.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001970 const bool create_heap_objects = (des == NULL);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001971 ASSERT(!heap_.HasBeenSetUp());
1972 if (!heap_.SetUp(create_heap_objects)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001973 V8::SetFatalError();
1974 return false;
1975 }
1976
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001977 if (create_heap_objects) {
1978 // Terminate the cache array with the sentinel so we can iterate.
1979 PushToPartialSnapshotCache(heap_.undefined_value());
1980 }
1981
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001982 InitializeThreadLocal();
1983
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001984 bootstrapper_->Initialize(create_heap_objects);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001985 builtins_.SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001986
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001987 // Only preallocate on the first initialization.
1988 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
1989 // Start the thread which will set aside some memory.
1990 PreallocatedMemoryThreadStart();
1991 preallocated_message_space_ =
1992 new NoAllocationStringAllocator(
1993 preallocated_memory_thread_->data(),
1994 preallocated_memory_thread_->length());
1995 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
1996 }
1997
1998 if (FLAG_preemption) {
1999 v8::Locker locker;
2000 v8::Locker::StartPreemption(100);
2001 }
2002
2003#ifdef ENABLE_DEBUGGER_SUPPORT
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002004 debug_->SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002005#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002006
2007 // If we are deserializing, read the state into the now-empty heap.
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002008 if (!create_heap_objects) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002009 des->Deserialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002010 }
ulan@chromium.org812308e2012-02-29 15:58:45 +00002011 stub_cache_->Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002012
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00002013 // Finish initialization of ThreadLocal after deserialization is done.
2014 clear_pending_exception();
2015 clear_pending_message();
2016 clear_scheduled_exception();
2017
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002018 // Deserializing may put strange things in the root array's copy of the
2019 // stack guard.
2020 heap_.SetStackLimits();
2021
mstarzinger@chromium.org88d326b2012-04-23 12:57:22 +00002022 // Quiet the heap NaN if needed on target platform.
jkummerow@chromium.org28583c92012-07-16 11:31:55 +00002023 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
mstarzinger@chromium.org88d326b2012-04-23 12:57:22 +00002024
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002025 deoptimizer_data_ = new DeoptimizerData;
2026 runtime_profiler_ = new RuntimeProfiler(this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002027 runtime_profiler_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002028
2029 // If we are deserializing, log non-function code objects and compiled
2030 // functions found in the snapshot.
yangguo@chromium.org355cfd12012-08-29 15:32:24 +00002031 if (create_heap_objects &&
2032 (FLAG_log_code || FLAG_ll_prof || logger_->is_logging_code_events())) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002033 HandleScope scope;
2034 LOG(this, LogCodeObjects());
2035 LOG(this, LogCompiledFunctions());
2036 }
2037
yangguo@chromium.orgefdb9d72012-04-26 08:21:05 +00002038 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, state_)),
2039 Internals::kIsolateStateOffset);
2040 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2041 Internals::kIsolateEmbedderDataOffset);
2042 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2043 Internals::kIsolateRootsOffset);
2044
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002045 state_ = INITIALIZED;
rossberg@chromium.org994edf62012-02-06 10:12:55 +00002046 time_millis_at_init_ = OS::TimeCurrentMillis();
yangguo@chromium.org304cc332012-07-24 07:59:48 +00002047 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Start();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002048 return true;
2049}
2050
2051
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002052// Initialized lazily to allow early
2053// v8::V8::SetAddHistogramSampleFunction calls.
2054StatsTable* Isolate::stats_table() {
2055 if (stats_table_ == NULL) {
2056 stats_table_ = new StatsTable;
2057 }
2058 return stats_table_;
2059}
2060
2061
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002062void Isolate::Enter() {
2063 Isolate* current_isolate = NULL;
2064 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2065 if (current_data != NULL) {
2066 current_isolate = current_data->isolate_;
2067 ASSERT(current_isolate != NULL);
2068 if (current_isolate == this) {
2069 ASSERT(Current() == this);
2070 ASSERT(entry_stack_ != NULL);
2071 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00002072 entry_stack_->previous_thread_data->thread_id().Equals(
2073 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002074 // Same thread re-enters the isolate, no need to re-init anything.
2075 entry_stack_->entry_count++;
2076 return;
2077 }
2078 }
2079
2080 // Threads can have default isolate set into TLS as Current but not yet have
2081 // PerIsolateThreadData for it, as it requires more advanced phase of the
2082 // initialization. For example, a thread might be the one that system used for
2083 // static initializers - in this case the default isolate is set in TLS but
2084 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2085 // there, use the isolate set in TLS.
2086 if (current_isolate == NULL) {
2087 current_isolate = Isolate::UncheckedCurrent();
2088 }
2089
2090 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2091 ASSERT(data != NULL);
2092 ASSERT(data->isolate_ == this);
2093
2094 EntryStackItem* item = new EntryStackItem(current_data,
2095 current_isolate,
2096 entry_stack_);
2097 entry_stack_ = item;
2098
2099 SetIsolateThreadLocals(this, data);
2100
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002101 // In case it's the first time some thread enters the isolate.
2102 set_thread_id(data->thread_id());
2103}
2104
2105
2106void Isolate::Exit() {
2107 ASSERT(entry_stack_ != NULL);
2108 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00002109 entry_stack_->previous_thread_data->thread_id().Equals(
2110 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002111
2112 if (--entry_stack_->entry_count > 0) return;
2113
2114 ASSERT(CurrentPerIsolateThreadData() != NULL);
2115 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2116
2117 // Pop the stack.
2118 EntryStackItem* item = entry_stack_;
2119 entry_stack_ = item->previous_item;
2120
2121 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2122 Isolate* previous_isolate = item->previous_isolate;
2123
2124 delete item;
2125
2126 // Reinit the current thread for the isolate it was running before this one.
2127 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2128}
2129
2130
yangguo@chromium.org304cc332012-07-24 07:59:48 +00002131void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2132 deferred->next_ = deferred_handles_head_;
2133 if (deferred_handles_head_ != NULL) {
2134 deferred_handles_head_->previous_ = deferred;
2135 }
2136 deferred_handles_head_ = deferred;
2137}
2138
2139
2140void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2141#ifdef DEBUG
2142 // In debug mode assert that the linked list is well-formed.
2143 DeferredHandles* deferred_iterator = deferred;
2144 while (deferred_iterator->previous_ != NULL) {
2145 deferred_iterator = deferred_iterator->previous_;
2146 }
2147 ASSERT(deferred_handles_head_ == deferred_iterator);
2148#endif
2149 if (deferred_handles_head_ == deferred) {
2150 deferred_handles_head_ = deferred_handles_head_->next_;
2151 }
2152 if (deferred->next_ != NULL) {
2153 deferred->next_->previous_ = deferred->previous_;
2154 }
2155 if (deferred->previous_ != NULL) {
2156 deferred->previous_->next_ = deferred->next_;
2157 }
2158}
2159
2160
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002161#ifdef DEBUG
2162#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2163const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2164ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2165ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2166#undef ISOLATE_FIELD_OFFSET
2167#endif
2168
2169} } // namespace v8::internal