blob: 29ccfdec29bccb06c7a4f234554cabe0e18d5cad [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"
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +000043#include "marking-thread.h"
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000044#include "messages.h"
jkummerow@chromium.org1456e702012-03-30 08:38:13 +000045#include "platform.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000046#include "regexp-stack.h"
47#include "runtime-profiler.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000048#include "scopeinfo.h"
49#include "serialize.h"
50#include "simulator.h"
51#include "spaces.h"
52#include "stub-cache.h"
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +000053#include "sweeper-thread.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000054#include "version.h"
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000055#include "vm-state-inl.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000056
57
58namespace v8 {
59namespace internal {
60
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000061Atomic32 ThreadId::highest_thread_id_ = 0;
62
63int ThreadId::AllocateThreadId() {
64 int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
65 return new_id;
66}
67
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000068
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000069int ThreadId::GetCurrentThreadId() {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000070 int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000071 if (thread_id == 0) {
72 thread_id = AllocateThreadId();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +000073 Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000074 }
75 return thread_id;
76}
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000077
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000078
79ThreadLocalTop::ThreadLocalTop() {
80 InitializeInternal();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +000081 // This flag may be set using v8::V8::IgnoreOutOfMemoryException()
82 // before an isolate is initialized. The initialize methods below do
83 // not touch it to preserve its value.
84 ignore_out_of_memory_ = false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000085}
86
87
88void ThreadLocalTop::InitializeInternal() {
89 c_entry_fp_ = 0;
90 handler_ = 0;
91#ifdef USE_SIMULATOR
92 simulator_ = NULL;
93#endif
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000094 js_entry_sp_ = NULL;
95 external_callback_ = NULL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000096 current_vm_state_ = EXTERNAL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000097 try_catch_handler_address_ = NULL;
98 context_ = NULL;
99 thread_id_ = ThreadId::Invalid();
100 external_caught_exception_ = false;
101 failed_access_check_callback_ = NULL;
102 save_context_ = NULL;
103 catcher_ = NULL;
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +0000104 top_lookup_result_ = NULL;
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +0000105
106 // These members are re-initialized later after deserialization
107 // is complete.
108 pending_exception_ = NULL;
109 has_pending_message_ = false;
110 pending_message_obj_ = NULL;
111 pending_message_script_ = NULL;
112 scheduled_exception_ = NULL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000113}
114
115
116void ThreadLocalTop::Initialize() {
117 InitializeInternal();
118#ifdef USE_SIMULATOR
119#ifdef V8_TARGET_ARCH_ARM
120 simulator_ = Simulator::current(isolate_);
121#elif V8_TARGET_ARCH_MIPS
122 simulator_ = Simulator::current(isolate_);
123#endif
124#endif
125 thread_id_ = ThreadId::Current();
126}
127
128
129v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
130 return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
131}
132
133
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000134// Create a dummy thread that will wait forever on a semaphore. The only
135// purpose for this thread is to have some stack area to save essential data
136// into for use by a stacks only core dump (aka minidump).
137class PreallocatedMemoryThread: public Thread {
138 public:
139 char* data() {
140 if (data_ready_semaphore_ != NULL) {
141 // Initial access is guarded until the data has been published.
142 data_ready_semaphore_->Wait();
143 delete data_ready_semaphore_;
144 data_ready_semaphore_ = NULL;
145 }
146 return data_;
147 }
148
149 unsigned length() {
150 if (data_ready_semaphore_ != NULL) {
151 // Initial access is guarded until the data has been published.
152 data_ready_semaphore_->Wait();
153 delete data_ready_semaphore_;
154 data_ready_semaphore_ = NULL;
155 }
156 return length_;
157 }
158
159 // Stop the PreallocatedMemoryThread and release its resources.
160 void StopThread() {
161 keep_running_ = false;
162 wait_for_ever_semaphore_->Signal();
163
164 // Wait for the thread to terminate.
165 Join();
166
167 if (data_ready_semaphore_ != NULL) {
168 delete data_ready_semaphore_;
169 data_ready_semaphore_ = NULL;
170 }
171
172 delete wait_for_ever_semaphore_;
173 wait_for_ever_semaphore_ = NULL;
174 }
175
176 protected:
177 // When the thread starts running it will allocate a fixed number of bytes
178 // on the stack and publish the location of this memory for others to use.
179 void Run() {
180 EmbeddedVector<char, 15 * 1024> local_buffer;
181
182 // Initialize the buffer with a known good value.
183 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
184 local_buffer.length());
185
186 // Publish the local buffer and signal its availability.
187 data_ = local_buffer.start();
188 length_ = local_buffer.length();
189 data_ready_semaphore_->Signal();
190
191 while (keep_running_) {
192 // This thread will wait here until the end of time.
193 wait_for_ever_semaphore_->Wait();
194 }
195
196 // Make sure we access the buffer after the wait to remove all possibility
197 // of it being optimized away.
198 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
199 local_buffer.length());
200 }
201
202
203 private:
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000204 PreallocatedMemoryThread()
205 : Thread("v8:PreallocMem"),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000206 keep_running_(true),
207 wait_for_ever_semaphore_(OS::CreateSemaphore(0)),
208 data_ready_semaphore_(OS::CreateSemaphore(0)),
209 data_(NULL),
210 length_(0) {
211 }
212
213 // Used to make sure that the thread keeps looping even for spurious wakeups.
214 bool keep_running_;
215
216 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
217 Semaphore* wait_for_ever_semaphore_;
218 // Semaphore to signal that the data has been initialized.
219 Semaphore* data_ready_semaphore_;
220
221 // Location and size of the preallocated memory block.
222 char* data_;
223 unsigned length_;
224
225 friend class Isolate;
226
227 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
228};
229
230
231void Isolate::PreallocatedMemoryThreadStart() {
232 if (preallocated_memory_thread_ != NULL) return;
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000233 preallocated_memory_thread_ = new PreallocatedMemoryThread();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000234 preallocated_memory_thread_->Start();
235}
236
237
238void Isolate::PreallocatedMemoryThreadStop() {
239 if (preallocated_memory_thread_ == NULL) return;
240 preallocated_memory_thread_->StopThread();
241 // Done with the thread entirely.
242 delete preallocated_memory_thread_;
243 preallocated_memory_thread_ = NULL;
244}
245
246
lrn@chromium.org7516f052011-03-30 08:52:27 +0000247void Isolate::PreallocatedStorageInit(size_t size) {
248 ASSERT(free_list_.next_ == &free_list_);
249 ASSERT(free_list_.previous_ == &free_list_);
250 PreallocatedStorage* free_chunk =
251 reinterpret_cast<PreallocatedStorage*>(new char[size]);
252 free_list_.next_ = free_list_.previous_ = free_chunk;
253 free_chunk->next_ = free_chunk->previous_ = &free_list_;
254 free_chunk->size_ = size - sizeof(PreallocatedStorage);
255 preallocated_storage_preallocated_ = true;
256}
257
258
259void* Isolate::PreallocatedStorageNew(size_t size) {
260 if (!preallocated_storage_preallocated_) {
rossberg@chromium.org400388e2012-06-06 09:29:22 +0000261 return FreeStoreAllocationPolicy().New(size);
lrn@chromium.org7516f052011-03-30 08:52:27 +0000262 }
263 ASSERT(free_list_.next_ != &free_list_);
264 ASSERT(free_list_.previous_ != &free_list_);
265
266 size = (size + kPointerSize - 1) & ~(kPointerSize - 1);
267 // Search for exact fit.
268 for (PreallocatedStorage* storage = free_list_.next_;
269 storage != &free_list_;
270 storage = storage->next_) {
271 if (storage->size_ == size) {
272 storage->Unlink();
273 storage->LinkTo(&in_use_list_);
274 return reinterpret_cast<void*>(storage + 1);
275 }
276 }
277 // Search for first fit.
278 for (PreallocatedStorage* storage = free_list_.next_;
279 storage != &free_list_;
280 storage = storage->next_) {
281 if (storage->size_ >= size + sizeof(PreallocatedStorage)) {
282 storage->Unlink();
283 storage->LinkTo(&in_use_list_);
284 PreallocatedStorage* left_over =
285 reinterpret_cast<PreallocatedStorage*>(
286 reinterpret_cast<char*>(storage + 1) + size);
287 left_over->size_ = storage->size_ - size - sizeof(PreallocatedStorage);
288 ASSERT(size + left_over->size_ + sizeof(PreallocatedStorage) ==
289 storage->size_);
290 storage->size_ = size;
291 left_over->LinkTo(&free_list_);
292 return reinterpret_cast<void*>(storage + 1);
293 }
294 }
295 // Allocation failure.
296 ASSERT(false);
297 return NULL;
298}
299
300
301// We don't attempt to coalesce.
302void Isolate::PreallocatedStorageDelete(void* p) {
303 if (p == NULL) {
304 return;
305 }
306 if (!preallocated_storage_preallocated_) {
307 FreeStoreAllocationPolicy::Delete(p);
308 return;
309 }
310 PreallocatedStorage* storage = reinterpret_cast<PreallocatedStorage*>(p) - 1;
311 ASSERT(storage->next_->previous_ == storage);
312 ASSERT(storage->previous_->next_ == storage);
313 storage->Unlink();
314 storage->LinkTo(&free_list_);
315}
316
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000317Isolate* Isolate::default_isolate_ = NULL;
318Thread::LocalStorageKey Isolate::isolate_key_;
319Thread::LocalStorageKey Isolate::thread_id_key_;
320Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
321Mutex* Isolate::process_wide_mutex_ = OS::CreateMutex();
322Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
323
324
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000325Isolate::PerIsolateThreadData* Isolate::AllocatePerIsolateThreadData(
326 ThreadId thread_id) {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000327 ASSERT(!thread_id.Equals(ThreadId::Invalid()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000328 PerIsolateThreadData* per_thread = new PerIsolateThreadData(this, thread_id);
329 {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000330 ScopedLock lock(process_wide_mutex_);
331 ASSERT(thread_data_table_->Lookup(this, thread_id) == NULL);
332 thread_data_table_->Insert(per_thread);
333 ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000334 }
335 return per_thread;
336}
337
338
339Isolate::PerIsolateThreadData*
340 Isolate::FindOrAllocatePerThreadDataForThisThread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000341 ThreadId thread_id = ThreadId::Current();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000342 PerIsolateThreadData* per_thread = NULL;
343 {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000344 ScopedLock lock(process_wide_mutex_);
345 per_thread = thread_data_table_->Lookup(this, thread_id);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000346 if (per_thread == NULL) {
347 per_thread = AllocatePerIsolateThreadData(thread_id);
348 }
349 }
350 return per_thread;
351}
352
353
lrn@chromium.org1c092762011-05-09 09:42:16 +0000354Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
355 ThreadId thread_id = ThreadId::Current();
356 PerIsolateThreadData* per_thread = NULL;
357 {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000358 ScopedLock lock(process_wide_mutex_);
359 per_thread = thread_data_table_->Lookup(this, thread_id);
lrn@chromium.org1c092762011-05-09 09:42:16 +0000360 }
361 return per_thread;
362}
363
364
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000365void Isolate::EnsureDefaultIsolate() {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000366 ScopedLock lock(process_wide_mutex_);
367 if (default_isolate_ == NULL) {
368 isolate_key_ = Thread::CreateThreadLocalKey();
369 thread_id_key_ = Thread::CreateThreadLocalKey();
370 per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
371 thread_data_table_ = new Isolate::ThreadDataTable();
372 default_isolate_ = new Isolate();
373 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000374 // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
jkummerow@chromium.org1456e702012-03-30 08:38:13 +0000375 // because a non-null thread data may be already set.
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000376 if (Thread::GetThreadLocal(isolate_key_) == NULL) {
377 Thread::SetThreadLocal(isolate_key_, default_isolate_);
lrn@chromium.org1c092762011-05-09 09:42:16 +0000378 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000379}
380
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000381struct StaticInitializer {
382 StaticInitializer() {
383 Isolate::EnsureDefaultIsolate();
384 }
385} static_initializer;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000386
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000387#ifdef ENABLE_DEBUGGER_SUPPORT
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000388Debugger* Isolate::GetDefaultIsolateDebugger() {
389 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000390 return default_isolate_->debugger();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000391}
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000392#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000393
394
395StackGuard* Isolate::GetDefaultIsolateStackGuard() {
396 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000397 return default_isolate_->stack_guard();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000398}
399
400
401void Isolate::EnterDefaultIsolate() {
402 EnsureDefaultIsolate();
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000403 ASSERT(default_isolate_ != NULL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000404
405 PerIsolateThreadData* data = CurrentPerIsolateThreadData();
406 // If not yet in default isolate - enter it.
danno@chromium.org8c0a43f2012-04-03 08:37:53 +0000407 if (data == NULL || data->isolate() != default_isolate_) {
408 default_isolate_->Enter();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000409 }
410}
411
412
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000413v8::Isolate* Isolate::GetDefaultIsolateForLocking() {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000414 EnsureDefaultIsolate();
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000415 return reinterpret_cast<v8::Isolate*>(default_isolate_);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000416}
417
418
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000419Address Isolate::get_address_from_id(Isolate::AddressId id) {
420 return isolate_addresses_[id];
421}
422
423
424char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
425 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
426 Iterate(v, thread);
427 return thread_storage + sizeof(ThreadLocalTop);
428}
429
430
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000431void Isolate::IterateThread(ThreadVisitor* v, char* t) {
432 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
433 v->VisitThread(this, thread);
434}
435
436
437void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
438 // Visit the roots from the top for a given thread.
439 Object* pending;
440 // The pending exception can sometimes be a failure. We can't show
441 // that to the GC, which only understands objects.
442 if (thread->pending_exception_->ToObject(&pending)) {
443 v->VisitPointer(&pending);
444 thread->pending_exception_ = pending; // In case GC updated it.
445 }
446 v->VisitPointer(&(thread->pending_message_obj_));
447 v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
448 v->VisitPointer(BitCast<Object**>(&(thread->context_)));
449 Object* scheduled;
450 if (thread->scheduled_exception_->ToObject(&scheduled)) {
451 v->VisitPointer(&scheduled);
452 thread->scheduled_exception_ = scheduled;
453 }
454
455 for (v8::TryCatch* block = thread->TryCatchHandler();
456 block != NULL;
457 block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
458 v->VisitPointer(BitCast<Object**>(&(block->exception_)));
459 v->VisitPointer(BitCast<Object**>(&(block->message_)));
460 }
461
462 // Iterate over pointers on native execution stack.
463 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
464 it.frame()->Iterate(v);
465 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +0000466
467 // Iterate pointers in live lookup results.
468 thread->top_lookup_result_->Iterate(v);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000469}
470
471
472void Isolate::Iterate(ObjectVisitor* v) {
473 ThreadLocalTop* current_t = thread_local_top();
474 Iterate(v, current_t);
475}
476
yangguo@chromium.org304cc332012-07-24 07:59:48 +0000477void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
478 for (DeferredHandles* deferred = deferred_handles_head_;
479 deferred != NULL;
480 deferred = deferred->next_) {
481 deferred->Iterate(visitor);
482 }
483}
484
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000485
486void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
487 // The ARM simulator has a separate JS stack. We therefore register
488 // the C++ try catch handler with the simulator and get back an
489 // address that can be used for comparisons with addresses into the
490 // JS stack. When running without the simulator, the address
491 // returned will be the address of the C++ try catch handler itself.
492 Address address = reinterpret_cast<Address>(
493 SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
494 thread_local_top()->set_try_catch_handler_address(address);
495}
496
497
498void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
499 ASSERT(thread_local_top()->TryCatchHandler() == that);
500 thread_local_top()->set_try_catch_handler_address(
501 reinterpret_cast<Address>(that->next_));
502 thread_local_top()->catcher_ = NULL;
503 SimulatorStack::UnregisterCTryCatch();
504}
505
506
507Handle<String> Isolate::StackTraceString() {
508 if (stack_trace_nesting_level_ == 0) {
509 stack_trace_nesting_level_++;
510 HeapStringAllocator allocator;
511 StringStream::ClearMentionedObjectCache();
512 StringStream accumulator(&allocator);
513 incomplete_message_ = &accumulator;
514 PrintStack(&accumulator);
515 Handle<String> stack_trace = accumulator.ToString();
516 incomplete_message_ = NULL;
517 stack_trace_nesting_level_ = 0;
518 return stack_trace;
519 } else if (stack_trace_nesting_level_ == 1) {
520 stack_trace_nesting_level_++;
521 OS::PrintError(
522 "\n\nAttempt to print stack while printing stack (double fault)\n");
523 OS::PrintError(
524 "If you are lucky you may find a partial stack dump on stdout.\n\n");
525 incomplete_message_->OutputToStdOut();
526 return factory()->empty_symbol();
527 } else {
528 OS::Abort();
529 // Unreachable
530 return factory()->empty_symbol();
531 }
532}
533
534
jkummerow@chromium.org67255be2012-09-05 16:44:50 +0000535void Isolate::PushStackTraceAndDie(unsigned int magic,
536 Object* object,
537 Map* map,
538 unsigned int magic2) {
539 const int kMaxStackTraceSize = 8192;
540 Handle<String> trace = StackTraceString();
jkummerow@chromium.org59297c72013-01-09 16:32:23 +0000541 uint8_t buffer[kMaxStackTraceSize];
jkummerow@chromium.org67255be2012-09-05 16:44:50 +0000542 int length = Min(kMaxStackTraceSize - 1, trace->length());
543 String::WriteToFlat(*trace, buffer, 0, length);
544 buffer[length] = '\0';
jkummerow@chromium.org59297c72013-01-09 16:32:23 +0000545 // TODO(dcarney): convert buffer to utf8?
jkummerow@chromium.org67255be2012-09-05 16:44:50 +0000546 OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n",
547 magic, magic2,
548 static_cast<void*>(object), static_cast<void*>(map),
jkummerow@chromium.org59297c72013-01-09 16:32:23 +0000549 reinterpret_cast<char*>(buffer));
jkummerow@chromium.org67255be2012-09-05 16:44:50 +0000550 OS::Abort();
551}
552
553
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +0000554// Determines whether the given stack frame should be displayed in
555// a stack trace. The caller is the error constructor that asked
556// for the stack trace to be collected. The first time a construct
557// call to this function is encountered it is skipped. The seen_caller
558// in/out parameter is used to remember if the caller has been seen
559// yet.
560static bool IsVisibleInStackTrace(StackFrame* raw_frame,
561 Object* caller,
562 bool* seen_caller) {
563 // Only display JS frames.
564 if (!raw_frame->is_java_script()) return false;
565 JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
566 Object* raw_fun = frame->function();
567 // Not sure when this can happen but skip it just in case.
568 if (!raw_fun->IsJSFunction()) return false;
569 if ((raw_fun == caller) && !(*seen_caller)) {
570 *seen_caller = true;
571 return false;
572 }
573 // Skip all frames until we've seen the caller.
574 if (!(*seen_caller)) return false;
575 // Also, skip non-visible built-in functions and any call with the builtins
576 // object as receiver, so as to not reveal either the builtins object or
577 // an internal function.
578 // The --builtins-in-stack-traces command line flag allows including
579 // internal call sites in the stack trace for debugging purposes.
580 if (!FLAG_builtins_in_stack_traces) {
581 JSFunction* fun = JSFunction::cast(raw_fun);
582 if (frame->receiver()->IsJSBuiltinsObject() ||
583 (fun->IsBuiltin() && !fun->shared()->native())) {
584 return false;
585 }
586 }
587 return true;
588}
589
590
591Handle<JSArray> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
592 Handle<Object> caller,
593 int limit) {
594 limit = Max(limit, 0); // Ensure that limit is not negative.
595 int initial_size = Min(limit, 10);
596 Handle<FixedArray> elements =
597 factory()->NewFixedArrayWithHoles(initial_size * 4);
598
599 // If the caller parameter is a function we skip frames until we're
600 // under it before starting to collect.
601 bool seen_caller = !caller->IsJSFunction();
602 int cursor = 0;
603 int frames_seen = 0;
604 for (StackFrameIterator iter(this);
605 !iter.done() && frames_seen < limit;
606 iter.Advance()) {
607 StackFrame* raw_frame = iter.frame();
608 if (IsVisibleInStackTrace(raw_frame, *caller, &seen_caller)) {
609 frames_seen++;
610 JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
611 // Set initial size to the maximum inlining level + 1 for the outermost
612 // function.
613 List<FrameSummary> frames(Compiler::kMaxInliningLevels + 1);
614 frame->Summarize(&frames);
615 for (int i = frames.length() - 1; i >= 0; i--) {
616 if (cursor + 4 > elements->length()) {
617 int new_capacity = JSObject::NewElementsCapacity(elements->length());
618 Handle<FixedArray> new_elements =
619 factory()->NewFixedArrayWithHoles(new_capacity);
620 for (int i = 0; i < cursor; i++) {
621 new_elements->set(i, elements->get(i));
622 }
623 elements = new_elements;
624 }
625 ASSERT(cursor + 4 <= elements->length());
626
627 Handle<Object> recv = frames[i].receiver();
628 Handle<JSFunction> fun = frames[i].function();
629 Handle<Code> code = frames[i].code();
ulan@chromium.org09d7ab52013-02-25 15:50:35 +0000630 Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +0000631 elements->set(cursor++, *recv);
632 elements->set(cursor++, *fun);
633 elements->set(cursor++, *code);
634 elements->set(cursor++, *offset);
635 }
636 }
637 }
638 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
639 result->set_length(Smi::FromInt(cursor));
640 return result;
641}
642
643
644void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +0000645 if (capture_stack_trace_for_uncaught_exceptions_) {
646 // Capture stack trace for a detailed exception message.
647 Handle<String> key = factory()->hidden_stack_trace_symbol();
648 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
649 stack_trace_for_uncaught_exceptions_frame_limit_,
650 stack_trace_for_uncaught_exceptions_options_);
651 JSObject::SetHiddenProperty(error_object, key, stack_trace);
652 }
653}
654
655
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000656Handle<JSArray> Isolate::CaptureCurrentStackTrace(
657 int frame_limit, StackTrace::StackTraceOptions options) {
658 // Ensure no negative values.
659 int limit = Max(frame_limit, 0);
660 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
661
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000662 Handle<String> column_key =
663 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("column"));
664 Handle<String> line_key =
665 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("lineNumber"));
666 Handle<String> script_key =
667 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("scriptName"));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000668 Handle<String> script_name_or_source_url_key =
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000669 factory()->LookupOneByteSymbol(
670 STATIC_ASCII_VECTOR("scriptNameOrSourceURL"));
671 Handle<String> function_key =
672 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("functionName"));
673 Handle<String> eval_key =
674 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("isEval"));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000675 Handle<String> constructor_key =
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000676 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("isConstructor"));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000677
678 StackTraceFrameIterator it(this);
679 int frames_seen = 0;
680 while (!it.done() && (frames_seen < limit)) {
681 JavaScriptFrame* frame = it.frame();
682 // Set initial size to the maximum inlining level + 1 for the outermost
683 // function.
684 List<FrameSummary> frames(Compiler::kMaxInliningLevels + 1);
685 frame->Summarize(&frames);
686 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
687 // Create a JSObject to hold the information for the StackFrame.
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000688 Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000689
690 Handle<JSFunction> fun = frames[i].function();
691 Handle<Script> script(Script::cast(fun->shared()->script()));
692
693 if (options & StackTrace::kLineNumber) {
694 int script_line_offset = script->line_offset()->value();
695 int position = frames[i].code()->SourcePosition(frames[i].pc());
696 int line_number = GetScriptLineNumber(script, position);
697 // line_number is already shifted by the script_line_offset.
698 int relative_line_number = line_number - script_line_offset;
699 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
700 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
701 int start = (relative_line_number == 0) ? 0 :
702 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
703 int column_offset = position - start;
704 if (relative_line_number == 0) {
705 // For the case where the code is on the same line as the script
706 // tag.
707 column_offset += script->column_offset()->value();
708 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000709 CHECK_NOT_EMPTY_HANDLE(
710 this,
711 JSObject::SetLocalPropertyIgnoreAttributes(
712 stack_frame, column_key,
ulan@chromium.org09d7ab52013-02-25 15:50:35 +0000713 Handle<Smi>(Smi::FromInt(column_offset + 1), this), NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000714 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000715 CHECK_NOT_EMPTY_HANDLE(
716 this,
717 JSObject::SetLocalPropertyIgnoreAttributes(
718 stack_frame, line_key,
ulan@chromium.org09d7ab52013-02-25 15:50:35 +0000719 Handle<Smi>(Smi::FromInt(line_number + 1), this), NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000720 }
721
722 if (options & StackTrace::kScriptName) {
723 Handle<Object> script_name(script->name(), this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000724 CHECK_NOT_EMPTY_HANDLE(this,
725 JSObject::SetLocalPropertyIgnoreAttributes(
726 stack_frame, script_key, script_name, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000727 }
728
729 if (options & StackTrace::kScriptNameOrSourceURL) {
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +0000730 Handle<Object> result = GetScriptNameOrSourceURL(script);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000731 CHECK_NOT_EMPTY_HANDLE(this,
732 JSObject::SetLocalPropertyIgnoreAttributes(
733 stack_frame, script_name_or_source_url_key,
734 result, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000735 }
736
737 if (options & StackTrace::kFunctionName) {
738 Handle<Object> fun_name(fun->shared()->name(), this);
739 if (fun_name->ToBoolean()->IsFalse()) {
740 fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
741 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000742 CHECK_NOT_EMPTY_HANDLE(this,
743 JSObject::SetLocalPropertyIgnoreAttributes(
744 stack_frame, function_key, fun_name, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000745 }
746
747 if (options & StackTrace::kIsEval) {
748 int type = Smi::cast(script->compilation_type())->value();
749 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
750 factory()->true_value() : factory()->false_value();
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000751 CHECK_NOT_EMPTY_HANDLE(this,
752 JSObject::SetLocalPropertyIgnoreAttributes(
753 stack_frame, eval_key, is_eval, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000754 }
755
756 if (options & StackTrace::kIsConstructor) {
757 Handle<Object> is_constructor = (frames[i].is_constructor()) ?
758 factory()->true_value() : factory()->false_value();
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000759 CHECK_NOT_EMPTY_HANDLE(this,
760 JSObject::SetLocalPropertyIgnoreAttributes(
761 stack_frame, constructor_key,
762 is_constructor, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000763 }
764
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000765 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000766 frames_seen++;
767 }
768 it.Advance();
769 }
770
771 stack_trace->set_length(Smi::FromInt(frames_seen));
772 return stack_trace;
773}
774
775
776void Isolate::PrintStack() {
777 if (stack_trace_nesting_level_ == 0) {
778 stack_trace_nesting_level_++;
779
780 StringAllocator* allocator;
781 if (preallocated_message_space_ == NULL) {
782 allocator = new HeapStringAllocator();
783 } else {
784 allocator = preallocated_message_space_;
785 }
786
787 StringStream::ClearMentionedObjectCache();
788 StringStream accumulator(allocator);
789 incomplete_message_ = &accumulator;
790 PrintStack(&accumulator);
791 accumulator.OutputToStdOut();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +0000792 InitializeLoggingAndCounters();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000793 accumulator.Log();
794 incomplete_message_ = NULL;
795 stack_trace_nesting_level_ = 0;
796 if (preallocated_message_space_ == NULL) {
797 // Remove the HeapStringAllocator created above.
798 delete allocator;
799 }
800 } else if (stack_trace_nesting_level_ == 1) {
801 stack_trace_nesting_level_++;
802 OS::PrintError(
803 "\n\nAttempt to print stack while printing stack (double fault)\n");
804 OS::PrintError(
805 "If you are lucky you may find a partial stack dump on stdout.\n\n");
806 incomplete_message_->OutputToStdOut();
807 }
808}
809
810
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000811static void PrintFrames(Isolate* isolate,
812 StringStream* accumulator,
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000813 StackFrame::PrintMode mode) {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000814 StackFrameIterator it(isolate);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000815 for (int i = 0; !it.done(); it.Advance()) {
816 it.frame()->Print(accumulator, mode, i++);
817 }
818}
819
820
821void Isolate::PrintStack(StringStream* accumulator) {
822 if (!IsInitialized()) {
823 accumulator->Add(
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000824 "\n==== JS stack trace is not available =======================\n\n");
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000825 accumulator->Add(
826 "\n==== Isolate for the thread is not initialized =============\n\n");
827 return;
828 }
829 // The MentionedObjectCache is not GC-proof at the moment.
830 AssertNoAllocation nogc;
831 ASSERT(StringStream::IsMentionedObjectCacheClear());
832
833 // Avoid printing anything if there are no frames.
834 if (c_entry_fp(thread_local_top()) == 0) return;
835
836 accumulator->Add(
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000837 "\n==== JS stack trace =========================================\n\n");
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000838 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000839
840 accumulator->Add(
841 "\n==== Details ================================================\n\n");
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000842 PrintFrames(this, accumulator, StackFrame::DETAILS);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000843
844 accumulator->PrintMentionedObjectCache();
845 accumulator->Add("=====================\n\n");
846}
847
848
849void Isolate::SetFailedAccessCheckCallback(
850 v8::FailedAccessCheckCallback callback) {
851 thread_local_top()->failed_access_check_callback_ = callback;
852}
853
854
855void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
856 if (!thread_local_top()->failed_access_check_callback_) return;
857
858 ASSERT(receiver->IsAccessCheckNeeded());
859 ASSERT(context());
860
861 // Get the data object from access check info.
862 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
863 if (!constructor->shared()->IsApiFunction()) return;
864 Object* data_obj =
865 constructor->shared()->get_api_func_data()->access_check_info();
866 if (data_obj == heap_.undefined_value()) return;
867
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +0000868 HandleScope scope(this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000869 Handle<JSObject> receiver_handle(receiver);
ulan@chromium.org09d7ab52013-02-25 15:50:35 +0000870 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000871 { VMState state(this, EXTERNAL);
872 thread_local_top()->failed_access_check_callback_(
873 v8::Utils::ToLocal(receiver_handle),
874 type,
875 v8::Utils::ToLocal(data));
876 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000877}
878
879
880enum MayAccessDecision {
881 YES, NO, UNKNOWN
882};
883
884
885static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
886 JSObject* receiver,
887 v8::AccessType type) {
888 // During bootstrapping, callback functions are not enabled yet.
889 if (isolate->bootstrapper()->IsActive()) return YES;
890
891 if (receiver->IsJSGlobalProxy()) {
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000892 Object* receiver_context = JSGlobalProxy::cast(receiver)->native_context();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000893 if (!receiver_context->IsContext()) return NO;
894
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000895 // Get the native context of current top context.
896 // avoid using Isolate::native_context() because it uses Handle.
897 Context* native_context =
898 isolate->context()->global_object()->native_context();
899 if (receiver_context == native_context) return YES;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000900
901 if (Context::cast(receiver_context)->security_token() ==
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000902 native_context->security_token())
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000903 return YES;
904 }
905
906 return UNKNOWN;
907}
908
909
910bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
911 v8::AccessType type) {
912 ASSERT(receiver->IsAccessCheckNeeded());
913
914 // The callers of this method are not expecting a GC.
915 AssertNoAllocation no_gc;
916
917 // Skip checks for hidden properties access. Note, we do not
918 // require existence of a context in this case.
919 if (key == heap_.hidden_symbol()) return true;
920
921 // Check for compatibility between the security tokens in the
922 // current lexical context and the accessed object.
923 ASSERT(context());
924
925 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
926 if (decision != UNKNOWN) return decision == YES;
927
928 // Get named access check callback
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000929 // TODO(dcarney): revert
930 Map* map = receiver->map();
931 CHECK(map->IsMap());
932 CHECK(map->constructor()->IsJSFunction());
933 JSFunction* constructor = JSFunction::cast(map->constructor());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000934 if (!constructor->shared()->IsApiFunction()) return false;
935
936 Object* data_obj =
937 constructor->shared()->get_api_func_data()->access_check_info();
938 if (data_obj == heap_.undefined_value()) return false;
939
940 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
941 v8::NamedSecurityCallback callback =
942 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
943
944 if (!callback) return false;
945
946 HandleScope scope(this);
947 Handle<JSObject> receiver_handle(receiver, this);
948 Handle<Object> key_handle(key, this);
949 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
950 LOG(this, ApiNamedSecurityCheck(key));
951 bool result = false;
952 {
953 // Leaving JavaScript.
954 VMState state(this, EXTERNAL);
955 result = callback(v8::Utils::ToLocal(receiver_handle),
956 v8::Utils::ToLocal(key_handle),
957 type,
958 v8::Utils::ToLocal(data));
959 }
960 return result;
961}
962
963
964bool Isolate::MayIndexedAccess(JSObject* receiver,
965 uint32_t index,
966 v8::AccessType type) {
967 ASSERT(receiver->IsAccessCheckNeeded());
968 // Check for compatibility between the security tokens in the
969 // current lexical context and the accessed object.
970 ASSERT(context());
971
972 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
973 if (decision != UNKNOWN) return decision == YES;
974
975 // Get indexed access check callback
976 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
977 if (!constructor->shared()->IsApiFunction()) return false;
978
979 Object* data_obj =
980 constructor->shared()->get_api_func_data()->access_check_info();
981 if (data_obj == heap_.undefined_value()) return false;
982
983 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
984 v8::IndexedSecurityCallback callback =
985 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
986
987 if (!callback) return false;
988
989 HandleScope scope(this);
990 Handle<JSObject> receiver_handle(receiver, this);
991 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
992 LOG(this, ApiIndexedSecurityCheck(index));
993 bool result = false;
994 {
995 // Leaving JavaScript.
996 VMState state(this, EXTERNAL);
997 result = callback(v8::Utils::ToLocal(receiver_handle),
998 index,
999 type,
1000 v8::Utils::ToLocal(data));
1001 }
1002 return result;
1003}
1004
1005
1006const char* const Isolate::kStackOverflowMessage =
1007 "Uncaught RangeError: Maximum call stack size exceeded";
1008
1009
1010Failure* Isolate::StackOverflow() {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001011 HandleScope scope(this);
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001012 // At this point we cannot create an Error object using its javascript
1013 // constructor. Instead, we copy the pre-constructed boilerplate and
1014 // attach the stack trace as a hidden property.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001015 Handle<String> key = factory()->stack_overflow_symbol();
1016 Handle<JSObject> boilerplate =
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00001017 Handle<JSObject>::cast(GetProperty(this, js_builtins_object(), key));
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001018 Handle<JSObject> exception = Copy(boilerplate);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001019 DoThrow(*exception, NULL);
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001020
1021 // Get stack trace limit.
1022 Handle<Object> error = GetProperty(js_builtins_object(), "$Error");
1023 if (!error->IsJSObject()) return Failure::Exception();
1024 Handle<Object> stack_trace_limit =
1025 GetProperty(Handle<JSObject>::cast(error), "stackTraceLimit");
1026 if (!stack_trace_limit->IsNumber()) return Failure::Exception();
1027 int limit = static_cast<int>(stack_trace_limit->Number());
1028
1029 Handle<JSArray> stack_trace = CaptureSimpleStackTrace(
1030 exception, factory()->undefined_value(), limit);
1031 JSObject::SetHiddenProperty(exception,
1032 factory()->hidden_stack_trace_symbol(),
1033 stack_trace);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001034 return Failure::Exception();
1035}
1036
1037
1038Failure* Isolate::TerminateExecution() {
1039 DoThrow(heap_.termination_exception(), NULL);
1040 return Failure::Exception();
1041}
1042
1043
1044Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
1045 DoThrow(exception, location);
1046 return Failure::Exception();
1047}
1048
1049
mmassi@chromium.org7028c052012-06-13 11:51:58 +00001050Failure* Isolate::ReThrow(MaybeObject* exception) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001051 bool can_be_caught_externally = false;
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001052 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1053 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1054
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001055 thread_local_top()->catcher_ = can_be_caught_externally ?
1056 try_catch_handler() : NULL;
1057
1058 // Set the exception being re-thrown.
1059 set_pending_exception(exception);
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001060 if (exception->IsFailure()) return exception->ToFailureUnchecked();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001061 return Failure::Exception();
1062}
1063
1064
1065Failure* Isolate::ThrowIllegalOperation() {
1066 return Throw(heap_.illegal_access_symbol());
1067}
1068
1069
1070void Isolate::ScheduleThrow(Object* exception) {
1071 // When scheduling a throw we first throw the exception to get the
1072 // error reporting if it is uncaught before rescheduling it.
1073 Throw(exception);
mmassi@chromium.org49a44672012-12-04 13:52:03 +00001074 PropagatePendingExceptionToExternalTryCatch();
1075 if (has_pending_exception()) {
1076 thread_local_top()->scheduled_exception_ = pending_exception();
1077 thread_local_top()->external_caught_exception_ = false;
1078 clear_pending_exception();
1079 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001080}
1081
1082
1083Failure* Isolate::PromoteScheduledException() {
1084 MaybeObject* thrown = scheduled_exception();
1085 clear_scheduled_exception();
1086 // Re-throw the exception to avoid getting repeated error reporting.
1087 return ReThrow(thrown);
1088}
1089
1090
1091void Isolate::PrintCurrentStackTrace(FILE* out) {
1092 StackTraceFrameIterator it(this);
1093 while (!it.done()) {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001094 HandleScope scope(this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001095 // Find code position if recorded in relocation info.
1096 JavaScriptFrame* frame = it.frame();
1097 int pos = frame->LookupCode()->SourcePosition(frame->pc());
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00001098 Handle<Object> pos_obj(Smi::FromInt(pos), this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001099 // Fetch function and receiver.
1100 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00001101 Handle<Object> recv(frame->receiver(), this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001102 // Advance to the next JavaScript frame and determine if the
1103 // current frame is the top-level frame.
1104 it.Advance();
1105 Handle<Object> is_top_level = it.done()
1106 ? factory()->true_value()
1107 : factory()->false_value();
1108 // Generate and print stack trace line.
1109 Handle<String> line =
1110 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1111 if (line->length() > 0) {
1112 line->PrintOn(out);
1113 fprintf(out, "\n");
1114 }
1115 }
1116}
1117
1118
1119void Isolate::ComputeLocation(MessageLocation* target) {
1120 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1121 StackTraceFrameIterator it(this);
1122 if (!it.done()) {
1123 JavaScriptFrame* frame = it.frame();
1124 JSFunction* fun = JSFunction::cast(frame->function());
1125 Object* script = fun->shared()->script();
1126 if (script->IsScript() &&
1127 !(Script::cast(script)->source()->IsUndefined())) {
1128 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1129 // Compute the location from the function and the reloc info.
1130 Handle<Script> casted_script(Script::cast(script));
1131 *target = MessageLocation(casted_script, pos, pos + 1);
1132 }
1133 }
1134}
1135
1136
1137bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1138 bool catchable_by_javascript) {
1139 // Find the top-most try-catch handler.
1140 StackHandler* handler =
1141 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001142 while (handler != NULL && !handler->is_catch()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001143 handler = handler->next();
1144 }
1145
1146 // Get the address of the external handler so we can compare the address to
1147 // determine which one is closer to the top of the stack.
1148 Address external_handler_address =
1149 thread_local_top()->try_catch_handler_address();
1150
1151 // The exception has been externally caught if and only if there is
1152 // an external handler which is on top of the top-most try-catch
1153 // handler.
1154 *can_be_caught_externally = external_handler_address != NULL &&
1155 (handler == NULL || handler->address() > external_handler_address ||
1156 !catchable_by_javascript);
1157
1158 if (*can_be_caught_externally) {
1159 // Only report the exception if the external handler is verbose.
1160 return try_catch_handler()->is_verbose_;
1161 } else {
1162 // Report the exception if it isn't caught by JavaScript code.
1163 return handler == NULL;
1164 }
1165}
1166
1167
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001168bool Isolate::IsErrorObject(Handle<Object> obj) {
1169 if (!obj->IsJSObject()) return false;
1170
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001171 String* error_key =
1172 *(factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("$Error")));
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001173 Object* error_constructor =
1174 js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1175
1176 for (Object* prototype = *obj; !prototype->IsNull();
1177 prototype = prototype->GetPrototype()) {
1178 if (!prototype->IsJSObject()) return false;
1179 if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1180 return true;
1181 }
1182 }
1183 return false;
1184}
1185
1186
1187void Isolate::DoThrow(Object* exception, MessageLocation* location) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001188 ASSERT(!has_pending_exception());
1189
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001190 HandleScope scope(this);
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00001191 Handle<Object> exception_handle(exception, this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001192
1193 // Determine reporting and whether the exception is caught externally.
1194 bool catchable_by_javascript = is_catchable_by_javascript(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001195 bool can_be_caught_externally = false;
1196 bool should_report_exception =
1197 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1198 bool report_exception = catchable_by_javascript && should_report_exception;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001199 bool try_catch_needs_message =
1200 can_be_caught_externally && try_catch_handler()->capture_message_;
1201 bool bootstrapping = bootstrapper()->IsActive();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001202
1203#ifdef ENABLE_DEBUGGER_SUPPORT
1204 // Notify debugger of exception.
1205 if (catchable_by_javascript) {
1206 debugger_->OnException(exception_handle, report_exception);
1207 }
1208#endif
1209
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001210 // Generate the message if required.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001211 if (report_exception || try_catch_needs_message) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001212 MessageLocation potential_computed_location;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001213 if (location == NULL) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001214 // If no location was specified we use a computed one instead.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001215 ComputeLocation(&potential_computed_location);
1216 location = &potential_computed_location;
1217 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001218 // It's not safe to try to make message objects or collect stack traces
1219 // while the bootstrapper is active since the infrastructure may not have
1220 // been properly initialized.
1221 if (!bootstrapping) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001222 Handle<String> stack_trace;
1223 if (FLAG_trace_exception) stack_trace = StackTraceString();
1224 Handle<JSArray> stack_trace_object;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001225 if (capture_stack_trace_for_uncaught_exceptions_) {
1226 if (IsErrorObject(exception_handle)) {
1227 // We fetch the stack trace that corresponds to this error object.
1228 String* key = heap()->hidden_stack_trace_symbol();
1229 Object* stack_property =
1230 JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1231 // Property lookup may have failed. In this case it's probably not
1232 // a valid Error object.
1233 if (stack_property->IsJSArray()) {
1234 stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1235 }
1236 }
1237 if (stack_trace_object.is_null()) {
1238 // Not an error object, we capture at throw site.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001239 stack_trace_object = CaptureCurrentStackTrace(
1240 stack_trace_for_uncaught_exceptions_frame_limit_,
1241 stack_trace_for_uncaught_exceptions_options_);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001242 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001243 }
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001244
1245 Handle<Object> exception_arg = exception_handle;
1246 // If the exception argument is a custom object, turn it into a string
1247 // before throwing as uncaught exception. Note that the pending
1248 // exception object to be set later must not be turned into a string.
1249 if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001250 bool failed = false;
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001251 exception_arg = Execution::ToDetailString(exception_arg, &failed);
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001252 if (failed) {
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001253 exception_arg =
1254 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("exception"));
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001255 }
1256 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001257 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1258 "uncaught_exception",
1259 location,
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001260 HandleVector<Object>(&exception_arg, 1),
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001261 stack_trace,
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001262 stack_trace_object);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001263 thread_local_top()->pending_message_obj_ = *message_obj;
1264 if (location != NULL) {
1265 thread_local_top()->pending_message_script_ = *location->script();
1266 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1267 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1268 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +00001269 } else if (location != NULL && !location->script().is_null()) {
1270 // We are bootstrapping and caught an error where the location is set
1271 // and we have a script for the location.
1272 // In this case we could have an extension (or an internal error
1273 // somewhere) and we print out the line number at which the error occured
1274 // to the console for easier debugging.
1275 int line_number = GetScriptLineNumberSafe(location->script(),
1276 location->start_pos());
verwaest@chromium.org37141392012-05-31 13:27:02 +00001277 if (exception->IsString()) {
1278 OS::PrintError(
1279 "Extension or internal compilation error: %s in %s at line %d.\n",
1280 *String::cast(exception)->ToCString(),
1281 *String::cast(location->script()->name())->ToCString(),
danno@chromium.org81cac2b2012-07-10 11:28:27 +00001282 line_number + 1);
verwaest@chromium.org37141392012-05-31 13:27:02 +00001283 } else {
1284 OS::PrintError(
1285 "Extension or internal compilation error in %s at line %d.\n",
1286 *String::cast(location->script()->name())->ToCString(),
danno@chromium.org81cac2b2012-07-10 11:28:27 +00001287 line_number + 1);
verwaest@chromium.org37141392012-05-31 13:27:02 +00001288 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001289 }
1290 }
1291
1292 // Save the message for reporting if the the exception remains uncaught.
1293 thread_local_top()->has_pending_message_ = report_exception;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001294
1295 // Do not forget to clean catcher_ if currently thrown exception cannot
1296 // be caught. If necessary, ReThrow will update the catcher.
1297 thread_local_top()->catcher_ = can_be_caught_externally ?
1298 try_catch_handler() : NULL;
1299
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001300 set_pending_exception(*exception_handle);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001301}
1302
1303
1304bool Isolate::IsExternallyCaught() {
1305 ASSERT(has_pending_exception());
1306
1307 if ((thread_local_top()->catcher_ == NULL) ||
1308 (try_catch_handler() != thread_local_top()->catcher_)) {
1309 // When throwing the exception, we found no v8::TryCatch
1310 // which should care about this exception.
1311 return false;
1312 }
1313
1314 if (!is_catchable_by_javascript(pending_exception())) {
1315 return true;
1316 }
1317
1318 // Get the address of the external handler so we can compare the address to
1319 // determine which one is closer to the top of the stack.
1320 Address external_handler_address =
1321 thread_local_top()->try_catch_handler_address();
1322 ASSERT(external_handler_address != NULL);
1323
1324 // The exception has been externally caught if and only if there is
1325 // an external handler which is on top of the top-most try-finally
1326 // handler.
1327 // There should be no try-catch blocks as they would prohibit us from
1328 // finding external catcher in the first place (see catcher_ check above).
1329 //
1330 // Note, that finally clause would rethrow an exception unless it's
1331 // aborted by jumps in control flow like return, break, etc. and we'll
1332 // have another chances to set proper v8::TryCatch.
1333 StackHandler* handler =
1334 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1335 while (handler != NULL && handler->address() < external_handler_address) {
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001336 ASSERT(!handler->is_catch());
1337 if (handler->is_finally()) return false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001338
1339 handler = handler->next();
1340 }
1341
1342 return true;
1343}
1344
1345
1346void Isolate::ReportPendingMessages() {
1347 ASSERT(has_pending_exception());
1348 PropagatePendingExceptionToExternalTryCatch();
1349
1350 // If the pending exception is OutOfMemoryException set out_of_memory in
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001351 // the native context. Note: We have to mark the native context here
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001352 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1353 // set it.
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001354 HandleScope scope(this);
jkummerow@chromium.org59297c72013-01-09 16:32:23 +00001355 if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001356 context()->mark_out_of_memory();
1357 } else if (thread_local_top_.pending_exception_ ==
1358 heap()->termination_exception()) {
1359 // Do nothing: if needed, the exception has been already propagated to
1360 // v8::TryCatch.
1361 } else {
1362 if (thread_local_top_.has_pending_message_) {
1363 thread_local_top_.has_pending_message_ = false;
1364 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001365 HandleScope scope(this);
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00001366 Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1367 this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001368 if (thread_local_top_.pending_message_script_ != NULL) {
1369 Handle<Script> script(thread_local_top_.pending_message_script_);
1370 int start_pos = thread_local_top_.pending_message_start_pos_;
1371 int end_pos = thread_local_top_.pending_message_end_pos_;
1372 MessageLocation location(script, start_pos, end_pos);
1373 MessageHandler::ReportMessage(this, &location, message_obj);
1374 } else {
1375 MessageHandler::ReportMessage(this, NULL, message_obj);
1376 }
1377 }
1378 }
1379 }
1380 clear_pending_message();
1381}
1382
1383
mmassi@chromium.org49a44672012-12-04 13:52:03 +00001384MessageLocation Isolate::GetMessageLocation() {
1385 ASSERT(has_pending_exception());
1386
jkummerow@chromium.org59297c72013-01-09 16:32:23 +00001387 if (!thread_local_top_.pending_exception_->IsOutOfMemory() &&
mmassi@chromium.org49a44672012-12-04 13:52:03 +00001388 thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1389 thread_local_top_.has_pending_message_ &&
1390 !thread_local_top_.pending_message_obj_->IsTheHole() &&
1391 thread_local_top_.pending_message_script_ != NULL) {
1392 Handle<Script> script(thread_local_top_.pending_message_script_);
1393 int start_pos = thread_local_top_.pending_message_start_pos_;
1394 int end_pos = thread_local_top_.pending_message_end_pos_;
1395 return MessageLocation(script, start_pos, end_pos);
1396 }
1397
1398 return MessageLocation();
1399}
1400
1401
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001402void Isolate::TraceException(bool flag) {
1403 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1404}
1405
1406
1407bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1408 ASSERT(has_pending_exception());
1409 PropagatePendingExceptionToExternalTryCatch();
1410
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001411 // Always reschedule out of memory exceptions.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001412 if (!is_out_of_memory()) {
1413 bool is_termination_exception =
1414 pending_exception() == heap_.termination_exception();
1415
1416 // Do not reschedule the exception if this is the bottom call.
1417 bool clear_exception = is_bottom_call;
1418
1419 if (is_termination_exception) {
1420 if (is_bottom_call) {
1421 thread_local_top()->external_caught_exception_ = false;
1422 clear_pending_exception();
1423 return false;
1424 }
1425 } else if (thread_local_top()->external_caught_exception_) {
1426 // If the exception is externally caught, clear it if there are no
1427 // JavaScript frames on the way to the C++ frame that has the
1428 // external handler.
1429 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1430 Address external_handler_address =
1431 thread_local_top()->try_catch_handler_address();
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001432 JavaScriptFrameIterator it(this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001433 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1434 clear_exception = true;
1435 }
1436 }
1437
1438 // Clear the exception if needed.
1439 if (clear_exception) {
1440 thread_local_top()->external_caught_exception_ = false;
1441 clear_pending_exception();
1442 return false;
1443 }
1444 }
1445
1446 // Reschedule the exception.
1447 thread_local_top()->scheduled_exception_ = pending_exception();
1448 clear_pending_exception();
1449 return true;
1450}
1451
1452
1453void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1454 bool capture,
1455 int frame_limit,
1456 StackTrace::StackTraceOptions options) {
1457 capture_stack_trace_for_uncaught_exceptions_ = capture;
1458 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1459 stack_trace_for_uncaught_exceptions_options_ = options;
1460}
1461
1462
1463bool Isolate::is_out_of_memory() {
1464 if (has_pending_exception()) {
1465 MaybeObject* e = pending_exception();
1466 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1467 return true;
1468 }
1469 }
1470 if (has_scheduled_exception()) {
1471 MaybeObject* e = scheduled_exception();
1472 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1473 return true;
1474 }
1475 }
1476 return false;
1477}
1478
1479
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001480Handle<Context> Isolate::native_context() {
1481 GlobalObject* global = thread_local_top()->context_->global_object();
1482 return Handle<Context>(global->native_context());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001483}
1484
1485
yangguo@chromium.org355cfd12012-08-29 15:32:24 +00001486Handle<Context> Isolate::global_context() {
1487 GlobalObject* global = thread_local_top()->context_->global_object();
1488 return Handle<Context>(global->global_context());
1489}
1490
1491
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001492Handle<Context> Isolate::GetCallingNativeContext() {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001493 JavaScriptFrameIterator it(this);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001494#ifdef ENABLE_DEBUGGER_SUPPORT
1495 if (debug_->InDebugger()) {
1496 while (!it.done()) {
1497 JavaScriptFrame* frame = it.frame();
1498 Context* context = Context::cast(frame->context());
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001499 if (context->native_context() == *debug_->debug_context()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001500 it.Advance();
1501 } else {
1502 break;
1503 }
1504 }
1505 }
1506#endif // ENABLE_DEBUGGER_SUPPORT
1507 if (it.done()) return Handle<Context>::null();
1508 JavaScriptFrame* frame = it.frame();
1509 Context* context = Context::cast(frame->context());
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001510 return Handle<Context>(context->native_context());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001511}
1512
1513
1514char* Isolate::ArchiveThread(char* to) {
1515 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1516 RuntimeProfiler::IsolateExitedJS(this);
1517 }
1518 memcpy(to, reinterpret_cast<char*>(thread_local_top()),
1519 sizeof(ThreadLocalTop));
1520 InitializeThreadLocal();
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001521 clear_pending_exception();
1522 clear_pending_message();
1523 clear_scheduled_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001524 return to + sizeof(ThreadLocalTop);
1525}
1526
1527
1528char* Isolate::RestoreThread(char* from) {
1529 memcpy(reinterpret_cast<char*>(thread_local_top()), from,
1530 sizeof(ThreadLocalTop));
1531 // This might be just paranoia, but it seems to be needed in case a
1532 // thread_local_top_ is restored on a separate OS thread.
1533#ifdef USE_SIMULATOR
1534#ifdef V8_TARGET_ARCH_ARM
1535 thread_local_top()->simulator_ = Simulator::current(this);
1536#elif V8_TARGET_ARCH_MIPS
1537 thread_local_top()->simulator_ = Simulator::current(this);
1538#endif
1539#endif
1540 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1541 RuntimeProfiler::IsolateEnteredJS(this);
1542 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001543 ASSERT(context() == NULL || context()->IsContext());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001544 return from + sizeof(ThreadLocalTop);
1545}
1546
1547
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001548Isolate::ThreadDataTable::ThreadDataTable()
1549 : list_(NULL) {
1550}
1551
1552
hpayer@chromium.org7c3372b2013-02-13 17:26:04 +00001553Isolate::ThreadDataTable::~ThreadDataTable() {
1554 // TODO(svenpanne) The assertion below would fire if an embedder does not
1555 // cleanly dispose all Isolates before disposing v8, so we are conservative
1556 // and leave it out for now.
1557 // ASSERT_EQ(NULL, list_);
1558}
1559
1560
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001561Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001562 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1563 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001564 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1565 if (data->Matches(isolate, thread_id)) return data;
1566 }
1567 return NULL;
1568}
1569
1570
1571void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1572 if (list_ != NULL) list_->prev_ = data;
1573 data->next_ = list_;
1574 list_ = data;
1575}
1576
1577
1578void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1579 if (list_ == data) list_ = data->next_;
1580 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1581 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001582 delete data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001583}
1584
1585
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001586void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1587 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001588 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1589 if (data != NULL) {
1590 Remove(data);
1591 }
1592}
1593
1594
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001595void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1596 PerIsolateThreadData* data = list_;
1597 while (data != NULL) {
1598 PerIsolateThreadData* next = data->next_;
1599 if (data->isolate() == isolate) Remove(data);
1600 data = next;
1601 }
1602}
1603
1604
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001605#ifdef DEBUG
1606#define TRACE_ISOLATE(tag) \
1607 do { \
1608 if (FLAG_trace_isolates) { \
1609 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
1610 } \
1611 } while (false)
1612#else
1613#define TRACE_ISOLATE(tag)
1614#endif
1615
1616
1617Isolate::Isolate()
1618 : state_(UNINITIALIZED),
yangguo@chromium.orgefdb9d72012-04-26 08:21:05 +00001619 embedder_data_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001620 entry_stack_(NULL),
1621 stack_trace_nesting_level_(0),
1622 incomplete_message_(NULL),
1623 preallocated_memory_thread_(NULL),
1624 preallocated_message_space_(NULL),
1625 bootstrapper_(NULL),
1626 runtime_profiler_(NULL),
1627 compilation_cache_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001628 counters_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001629 code_range_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001630 // Must be initialized early to allow v8::SetResourceConstraints calls.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001631 break_access_(OS::CreateMutex()),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001632 debugger_initialized_(false),
1633 // Must be initialized early to allow v8::Debug calls.
1634 debugger_access_(OS::CreateMutex()),
1635 logger_(NULL),
1636 stats_table_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001637 stub_cache_(NULL),
1638 deoptimizer_data_(NULL),
1639 capture_stack_trace_for_uncaught_exceptions_(false),
1640 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1641 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1642 transcendental_cache_(NULL),
1643 memory_allocator_(NULL),
1644 keyed_lookup_cache_(NULL),
1645 context_slot_cache_(NULL),
1646 descriptor_lookup_cache_(NULL),
1647 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001648 unicode_cache_(NULL),
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001649 runtime_zone_(this),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001650 in_use_list_(0),
1651 free_list_(0),
1652 preallocated_storage_preallocated_(false),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001653 inner_pointer_to_code_cache_(NULL),
yangguo@chromium.org4cd70b42013-01-04 08:57:54 +00001654 write_iterator_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001655 global_handles_(NULL),
1656 context_switcher_(NULL),
1657 thread_manager_(NULL),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001658 fp_stubs_generated_(false),
ricow@chromium.org27bf2882011-11-17 08:34:43 +00001659 has_installed_extensions_(false),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001660 string_tracker_(NULL),
1661 regexp_stack_(NULL),
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001662 date_cache_(NULL),
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001663 code_stub_interface_descriptors_(NULL),
yangguo@chromium.org304cc332012-07-24 07:59:48 +00001664 context_exit_happened_(false),
1665 deferred_handles_head_(NULL),
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00001666 optimizing_compiler_thread_(this),
1667 marking_thread_(NULL),
1668 sweeper_thread_(NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001669 TRACE_ISOLATE(constructor);
1670
1671 memset(isolate_addresses_, 0,
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001672 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001673
1674 heap_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001675 stack_guard_.isolate_ = this;
1676
lrn@chromium.org1c092762011-05-09 09:42:16 +00001677 // ThreadManager is initialized early to support locking an isolate
1678 // before it is entered.
1679 thread_manager_ = new ThreadManager();
1680 thread_manager_->isolate_ = this;
1681
lrn@chromium.org7516f052011-03-30 08:52:27 +00001682#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
1683 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001684 simulator_initialized_ = false;
1685 simulator_i_cache_ = NULL;
1686 simulator_redirection_ = NULL;
1687#endif
1688
1689#ifdef DEBUG
1690 // heap_histograms_ initializes itself.
1691 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1692 memset(code_kind_statistics_, 0,
1693 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
yangguo@chromium.org003650e2013-01-24 16:31:08 +00001694
1695 allow_handle_deref_ = true;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001696#endif
1697
1698#ifdef ENABLE_DEBUGGER_SUPPORT
1699 debug_ = NULL;
1700 debugger_ = NULL;
1701#endif
1702
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001703 handle_scope_data_.Initialize();
1704
1705#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1706 name##_ = (initial_value);
1707 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1708#undef ISOLATE_INIT_EXECUTE
1709
1710#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1711 memset(name##_, 0, sizeof(type) * length);
1712 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1713#undef ISOLATE_INIT_ARRAY_EXECUTE
1714}
1715
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00001716
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001717void Isolate::TearDown() {
1718 TRACE_ISOLATE(tear_down);
1719
1720 // Temporarily set this isolate as current so that various parts of
1721 // the isolate can access it in their destructors without having a
1722 // direct pointer. We don't use Enter/Exit here to avoid
1723 // initializing the thread data.
1724 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1725 Isolate* saved_isolate = UncheckedCurrent();
1726 SetIsolateThreadLocals(this, NULL);
1727
1728 Deinit();
1729
danno@chromium.org8c0a43f2012-04-03 08:37:53 +00001730 { ScopedLock lock(process_wide_mutex_);
1731 thread_data_table_->RemoveAllThreads(this);
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001732 }
1733
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001734 if (serialize_partial_snapshot_cache_ != NULL) {
1735 delete[] serialize_partial_snapshot_cache_;
1736 serialize_partial_snapshot_cache_ = NULL;
1737 }
1738
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001739 if (!IsDefaultIsolate()) {
1740 delete this;
1741 }
1742
1743 // Restore the previous current isolate.
1744 SetIsolateThreadLocals(saved_isolate, saved_data);
1745}
1746
1747
hpayer@chromium.org7c3372b2013-02-13 17:26:04 +00001748void Isolate::GlobalTearDown() {
1749 delete thread_data_table_;
1750}
1751
1752
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001753void Isolate::Deinit() {
1754 if (state_ == INITIALIZED) {
1755 TRACE_ISOLATE(deinit);
1756
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00001757 if (FLAG_concurrent_sweeping || FLAG_parallel_sweeping) {
1758 for (int i = 0; i < FLAG_sweeper_threads; i++) {
1759 sweeper_thread_[i]->Stop();
1760 delete sweeper_thread_[i];
1761 }
1762 delete[] sweeper_thread_;
1763 }
1764
1765 if (FLAG_parallel_marking) {
1766 for (int i = 0; i < FLAG_marking_threads; i++) {
1767 marking_thread_[i]->Stop();
1768 delete marking_thread_[i];
1769 }
1770 delete[] marking_thread_;
1771 }
1772
yangguo@chromium.org304cc332012-07-24 07:59:48 +00001773 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Stop();
1774
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001775 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
1776
1777 // We must stop the logger before we tear down other components.
1778 logger_->EnsureTickerStopped();
1779
1780 delete deoptimizer_data_;
1781 deoptimizer_data_ = NULL;
1782 if (FLAG_preemption) {
yangguo@chromium.org46a2a512013-01-18 16:29:40 +00001783 v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001784 v8::Locker::StopPreemption();
1785 }
1786 builtins_.TearDown();
1787 bootstrapper_->TearDown();
1788
1789 // Remove the external reference to the preallocated stack memory.
1790 delete preallocated_message_space_;
1791 preallocated_message_space_ = NULL;
1792 PreallocatedMemoryThreadStop();
1793
1794 HeapProfiler::TearDown();
1795 CpuProfiler::TearDown();
1796 if (runtime_profiler_ != NULL) {
1797 runtime_profiler_->TearDown();
1798 delete runtime_profiler_;
1799 runtime_profiler_ = NULL;
1800 }
1801 heap_.TearDown();
1802 logger_->TearDown();
1803
1804 // The default isolate is re-initializable due to legacy API.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001805 state_ = UNINITIALIZED;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001806 }
1807}
1808
1809
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001810void Isolate::PushToPartialSnapshotCache(Object* obj) {
1811 int length = serialize_partial_snapshot_cache_length();
1812 int capacity = serialize_partial_snapshot_cache_capacity();
1813
1814 if (length >= capacity) {
1815 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1816 Object** new_array = new Object*[new_capacity];
1817 for (int i = 0; i < length; i++) {
1818 new_array[i] = serialize_partial_snapshot_cache()[i];
1819 }
1820 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1821 set_serialize_partial_snapshot_cache(new_array);
1822 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1823 }
1824
1825 serialize_partial_snapshot_cache()[length] = obj;
1826 set_serialize_partial_snapshot_cache_length(length + 1);
1827}
1828
1829
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001830void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1831 PerIsolateThreadData* data) {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +00001832 Thread::SetThreadLocal(isolate_key_, isolate);
1833 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001834}
1835
1836
1837Isolate::~Isolate() {
1838 TRACE_ISOLATE(destructor);
1839
danno@chromium.orgb6451162011-08-17 14:33:23 +00001840 // Has to be called while counters_ are still alive.
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001841 runtime_zone_.DeleteKeptSegment();
danno@chromium.orgb6451162011-08-17 14:33:23 +00001842
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001843 delete[] assembler_spare_buffer_;
1844 assembler_spare_buffer_ = NULL;
1845
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001846 delete unicode_cache_;
1847 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001848
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001849 delete date_cache_;
1850 date_cache_ = NULL;
1851
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001852 delete[] code_stub_interface_descriptors_;
1853 code_stub_interface_descriptors_ = NULL;
1854
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001855 delete regexp_stack_;
1856 regexp_stack_ = NULL;
1857
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001858 delete descriptor_lookup_cache_;
1859 descriptor_lookup_cache_ = NULL;
1860 delete context_slot_cache_;
1861 context_slot_cache_ = NULL;
1862 delete keyed_lookup_cache_;
1863 keyed_lookup_cache_ = NULL;
1864
1865 delete transcendental_cache_;
1866 transcendental_cache_ = NULL;
1867 delete stub_cache_;
1868 stub_cache_ = NULL;
1869 delete stats_table_;
1870 stats_table_ = NULL;
1871
1872 delete logger_;
1873 logger_ = NULL;
1874
1875 delete counters_;
1876 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001877
1878 delete handle_scope_implementer_;
1879 handle_scope_implementer_ = NULL;
1880 delete break_access_;
1881 break_access_ = NULL;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001882 delete debugger_access_;
1883 debugger_access_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001884
1885 delete compilation_cache_;
1886 compilation_cache_ = NULL;
1887 delete bootstrapper_;
1888 bootstrapper_ = NULL;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001889 delete inner_pointer_to_code_cache_;
1890 inner_pointer_to_code_cache_ = NULL;
yangguo@chromium.org4cd70b42013-01-04 08:57:54 +00001891 delete write_iterator_;
1892 write_iterator_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001893
1894 delete context_switcher_;
1895 context_switcher_ = NULL;
1896 delete thread_manager_;
1897 thread_manager_ = NULL;
1898
1899 delete string_tracker_;
1900 string_tracker_ = NULL;
1901
1902 delete memory_allocator_;
1903 memory_allocator_ = NULL;
1904 delete code_range_;
1905 code_range_ = NULL;
1906 delete global_handles_;
1907 global_handles_ = NULL;
1908
danno@chromium.orgb6451162011-08-17 14:33:23 +00001909 delete external_reference_table_;
1910 external_reference_table_ = NULL;
1911
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001912#ifdef ENABLE_DEBUGGER_SUPPORT
1913 delete debugger_;
1914 debugger_ = NULL;
1915 delete debug_;
1916 debug_ = NULL;
1917#endif
1918}
1919
1920
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001921void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +00001922 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001923 thread_local_top_.Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001924}
1925
1926
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001927void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1928 ASSERT(has_pending_exception());
1929
1930 bool external_caught = IsExternallyCaught();
1931 thread_local_top_.external_caught_exception_ = external_caught;
1932
1933 if (!external_caught) return;
1934
jkummerow@chromium.org59297c72013-01-09 16:32:23 +00001935 if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001936 // Do not propagate OOM exception: we should kill VM asap.
1937 } else if (thread_local_top_.pending_exception_ ==
1938 heap()->termination_exception()) {
1939 try_catch_handler()->can_continue_ = false;
1940 try_catch_handler()->exception_ = heap()->null_value();
1941 } else {
1942 // At this point all non-object (failure) exceptions have
1943 // been dealt with so this shouldn't fail.
1944 ASSERT(!pending_exception()->IsFailure());
1945 try_catch_handler()->can_continue_ = true;
1946 try_catch_handler()->exception_ = pending_exception();
1947 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1948 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
1949 }
1950 }
1951}
1952
1953
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001954void Isolate::InitializeLoggingAndCounters() {
1955 if (logger_ == NULL) {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00001956 logger_ = new Logger(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001957 }
1958 if (counters_ == NULL) {
1959 counters_ = new Counters;
1960 }
1961}
1962
1963
1964void Isolate::InitializeDebugger() {
1965#ifdef ENABLE_DEBUGGER_SUPPORT
1966 ScopedLock lock(debugger_access_);
1967 if (NoBarrier_Load(&debugger_initialized_)) return;
1968 InitializeLoggingAndCounters();
1969 debug_ = new Debug(this);
1970 debugger_ = new Debugger(this);
1971 Release_Store(&debugger_initialized_, true);
1972#endif
1973}
1974
1975
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001976bool Isolate::Init(Deserializer* des) {
1977 ASSERT(state_ != INITIALIZED);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001978 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001979 TRACE_ISOLATE(init);
1980
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001981 // The initialization process does not handle memory exhaustion.
1982 DisallowAllocationFailure disallow_allocation_failure;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001983
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001984 InitializeLoggingAndCounters();
1985
1986 InitializeDebugger();
1987
1988 memory_allocator_ = new MemoryAllocator(this);
1989 code_range_ = new CodeRange(this);
1990
1991 // Safe after setting Heap::isolate_, initializing StackGuard and
1992 // ensuring that Isolate::Current() == this.
1993 heap_.SetStackLimits();
1994
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001995#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1996 isolate_addresses_[Isolate::k##CamelName##Address] = \
1997 reinterpret_cast<Address>(hacker_name##_address());
1998 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001999#undef C
2000
2001 string_tracker_ = new StringTracker();
2002 string_tracker_->isolate_ = this;
2003 compilation_cache_ = new CompilationCache(this);
2004 transcendental_cache_ = new TranscendentalCache();
2005 keyed_lookup_cache_ = new KeyedLookupCache();
2006 context_slot_cache_ = new ContextSlotCache();
2007 descriptor_lookup_cache_ = new DescriptorLookupCache();
2008 unicode_cache_ = new UnicodeCache();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00002009 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
yangguo@chromium.org4cd70b42013-01-04 08:57:54 +00002010 write_iterator_ = new ConsStringIteratorOp();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002011 global_handles_ = new GlobalHandles(this);
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00002012 bootstrapper_ = new Bootstrapper(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002013 handle_scope_implementer_ = new HandleScopeImplementer(this);
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002014 stub_cache_ = new StubCache(this, runtime_zone());
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002015 regexp_stack_ = new RegExpStack();
2016 regexp_stack_->isolate_ = this;
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00002017 date_cache_ = new DateCache();
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002018 code_stub_interface_descriptors_ =
2019 new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002020
2021 // Enable logging before setting up the heap
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002022 logger_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002023
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002024 CpuProfiler::SetUp();
2025 HeapProfiler::SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002026
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002027 // Initialize other runtime facilities
2028#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +00002029#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
lrn@chromium.org1c092762011-05-09 09:42:16 +00002030 Simulator::Initialize(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002031#endif
2032#endif
2033
2034 { // NOLINT
2035 // Ensure that the thread has a valid stack guard. The v8::Locker object
2036 // will ensure this too, but we don't have to use lockers if we are only
2037 // using one thread.
2038 ExecutionAccess lock(this);
2039 stack_guard_.InitThread(lock);
2040 }
2041
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002042 // SetUp the object heap.
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002043 ASSERT(!heap_.HasBeenSetUp());
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00002044 if (!heap_.SetUp()) {
yangguo@chromium.org9768bf12013-01-11 14:51:07 +00002045 V8::FatalProcessOutOfMemory("heap setup");
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002046 return false;
2047 }
2048
ulan@chromium.org09d7ab52013-02-25 15:50:35 +00002049 deoptimizer_data_ = new DeoptimizerData;
2050
2051 const bool create_heap_objects = (des == NULL);
2052 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2053 V8::FatalProcessOutOfMemory("heap object creation");
2054 return false;
2055 }
2056
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002057 if (create_heap_objects) {
2058 // Terminate the cache array with the sentinel so we can iterate.
2059 PushToPartialSnapshotCache(heap_.undefined_value());
2060 }
2061
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00002062 InitializeThreadLocal();
2063
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002064 bootstrapper_->Initialize(create_heap_objects);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002065 builtins_.SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002066
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002067 // Only preallocate on the first initialization.
2068 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
2069 // Start the thread which will set aside some memory.
2070 PreallocatedMemoryThreadStart();
2071 preallocated_message_space_ =
2072 new NoAllocationStringAllocator(
2073 preallocated_memory_thread_->data(),
2074 preallocated_memory_thread_->length());
2075 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
2076 }
2077
2078 if (FLAG_preemption) {
yangguo@chromium.org46a2a512013-01-18 16:29:40 +00002079 v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002080 v8::Locker::StartPreemption(100);
2081 }
2082
2083#ifdef ENABLE_DEBUGGER_SUPPORT
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002084 debug_->SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002085#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002086
2087 // If we are deserializing, read the state into the now-empty heap.
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002088 if (!create_heap_objects) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002089 des->Deserialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002090 }
ulan@chromium.org812308e2012-02-29 15:58:45 +00002091 stub_cache_->Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002092
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00002093 // Finish initialization of ThreadLocal after deserialization is done.
2094 clear_pending_exception();
2095 clear_pending_message();
2096 clear_scheduled_exception();
2097
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002098 // Deserializing may put strange things in the root array's copy of the
2099 // stack guard.
2100 heap_.SetStackLimits();
2101
mstarzinger@chromium.org88d326b2012-04-23 12:57:22 +00002102 // Quiet the heap NaN if needed on target platform.
jkummerow@chromium.org28583c92012-07-16 11:31:55 +00002103 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
mstarzinger@chromium.org88d326b2012-04-23 12:57:22 +00002104
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002105 runtime_profiler_ = new RuntimeProfiler(this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002106 runtime_profiler_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002107
2108 // If we are deserializing, log non-function code objects and compiled
2109 // functions found in the snapshot.
ulan@chromium.org8e8d8822012-11-23 14:36:46 +00002110 if (!create_heap_objects &&
yangguo@chromium.org355cfd12012-08-29 15:32:24 +00002111 (FLAG_log_code || FLAG_ll_prof || logger_->is_logging_code_events())) {
yangguo@chromium.orgc03a1922013-02-19 13:55:47 +00002112 HandleScope scope(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002113 LOG(this, LogCodeObjects());
2114 LOG(this, LogCompiledFunctions());
2115 }
2116
yangguo@chromium.orgefdb9d72012-04-26 08:21:05 +00002117 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, state_)),
2118 Internals::kIsolateStateOffset);
2119 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2120 Internals::kIsolateEmbedderDataOffset);
2121 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2122 Internals::kIsolateRootsOffset);
2123
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002124 state_ = INITIALIZED;
rossberg@chromium.org994edf62012-02-06 10:12:55 +00002125 time_millis_at_init_ = OS::TimeCurrentMillis();
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002126
2127 if (!create_heap_objects) {
2128 // Now that the heap is consistent, it's OK to generate the code for the
2129 // deopt entry table that might have been referred to by optimized code in
2130 // the snapshot.
2131 HandleScope scope(this);
2132 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2133 Deoptimizer::LAZY,
2134 kDeoptTableSerializeEntryCount - 1);
2135 }
2136
mstarzinger@chromium.org068ea0a2013-01-30 09:39:44 +00002137 if (!Serializer::enabled()) {
2138 // Ensure that the stub failure trampoline has been generated.
2139 HandleScope scope(this);
2140 CodeStub::GenerateFPStubs();
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00002141 StubFailureTrampolineStub::GenerateAheadOfTime();
mstarzinger@chromium.org068ea0a2013-01-30 09:39:44 +00002142 }
2143
yangguo@chromium.org304cc332012-07-24 07:59:48 +00002144 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Start();
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00002145
2146 if (FLAG_parallel_marking) {
2147 if (FLAG_marking_threads < 1) {
2148 FLAG_marking_threads = 1;
2149 }
2150 marking_thread_ = new MarkingThread*[FLAG_marking_threads];
2151 for (int i = 0; i < FLAG_marking_threads; i++) {
2152 marking_thread_[i] = new MarkingThread(this);
2153 marking_thread_[i]->Start();
2154 }
2155 }
2156
2157 if (FLAG_parallel_sweeping || FLAG_concurrent_sweeping) {
2158 if (FLAG_sweeper_threads < 1) {
2159 FLAG_sweeper_threads = 1;
2160 }
2161 sweeper_thread_ = new SweeperThread*[FLAG_sweeper_threads];
2162 for (int i = 0; i < FLAG_sweeper_threads; i++) {
2163 sweeper_thread_[i] = new SweeperThread(this);
2164 sweeper_thread_[i]->Start();
2165 }
2166 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002167 return true;
2168}
2169
2170
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002171// Initialized lazily to allow early
2172// v8::V8::SetAddHistogramSampleFunction calls.
2173StatsTable* Isolate::stats_table() {
2174 if (stats_table_ == NULL) {
2175 stats_table_ = new StatsTable;
2176 }
2177 return stats_table_;
2178}
2179
2180
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002181void Isolate::Enter() {
2182 Isolate* current_isolate = NULL;
2183 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2184 if (current_data != NULL) {
2185 current_isolate = current_data->isolate_;
2186 ASSERT(current_isolate != NULL);
2187 if (current_isolate == this) {
2188 ASSERT(Current() == this);
2189 ASSERT(entry_stack_ != NULL);
2190 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00002191 entry_stack_->previous_thread_data->thread_id().Equals(
2192 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002193 // Same thread re-enters the isolate, no need to re-init anything.
2194 entry_stack_->entry_count++;
2195 return;
2196 }
2197 }
2198
2199 // Threads can have default isolate set into TLS as Current but not yet have
2200 // PerIsolateThreadData for it, as it requires more advanced phase of the
2201 // initialization. For example, a thread might be the one that system used for
2202 // static initializers - in this case the default isolate is set in TLS but
2203 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2204 // there, use the isolate set in TLS.
2205 if (current_isolate == NULL) {
2206 current_isolate = Isolate::UncheckedCurrent();
2207 }
2208
2209 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2210 ASSERT(data != NULL);
2211 ASSERT(data->isolate_ == this);
2212
2213 EntryStackItem* item = new EntryStackItem(current_data,
2214 current_isolate,
2215 entry_stack_);
2216 entry_stack_ = item;
2217
2218 SetIsolateThreadLocals(this, data);
2219
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002220 // In case it's the first time some thread enters the isolate.
2221 set_thread_id(data->thread_id());
2222}
2223
2224
2225void Isolate::Exit() {
2226 ASSERT(entry_stack_ != NULL);
2227 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00002228 entry_stack_->previous_thread_data->thread_id().Equals(
2229 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002230
2231 if (--entry_stack_->entry_count > 0) return;
2232
2233 ASSERT(CurrentPerIsolateThreadData() != NULL);
2234 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2235
2236 // Pop the stack.
2237 EntryStackItem* item = entry_stack_;
2238 entry_stack_ = item->previous_item;
2239
2240 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2241 Isolate* previous_isolate = item->previous_isolate;
2242
2243 delete item;
2244
2245 // Reinit the current thread for the isolate it was running before this one.
2246 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2247}
2248
2249
yangguo@chromium.org304cc332012-07-24 07:59:48 +00002250void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2251 deferred->next_ = deferred_handles_head_;
2252 if (deferred_handles_head_ != NULL) {
2253 deferred_handles_head_->previous_ = deferred;
2254 }
2255 deferred_handles_head_ = deferred;
2256}
2257
2258
2259void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2260#ifdef DEBUG
2261 // In debug mode assert that the linked list is well-formed.
2262 DeferredHandles* deferred_iterator = deferred;
2263 while (deferred_iterator->previous_ != NULL) {
2264 deferred_iterator = deferred_iterator->previous_;
2265 }
2266 ASSERT(deferred_handles_head_ == deferred_iterator);
2267#endif
2268 if (deferred_handles_head_ == deferred) {
2269 deferred_handles_head_ = deferred_handles_head_->next_;
2270 }
2271 if (deferred->next_ != NULL) {
2272 deferred->next_->previous_ = deferred->previous_;
2273 }
2274 if (deferred->previous_ != NULL) {
2275 deferred->previous_->next_ = deferred->next_;
2276 }
2277}
2278
2279
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002280CodeStubInterfaceDescriptor*
2281 Isolate::code_stub_interface_descriptor(int index) {
2282 return code_stub_interface_descriptors_ + index;
2283}
2284
2285
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002286#ifdef DEBUG
2287#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2288const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2289ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2290ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2291#undef ISOLATE_FIELD_OFFSET
2292#endif
2293
2294} } // namespace v8::internal