blob: cb63b2b3bf16808a0e28d63c6cd2670c207456c6 [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();
630 Handle<Smi> offset(Smi::FromInt(frames[i].offset()));
631 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,
713 Handle<Smi>(Smi::FromInt(column_offset + 1)), 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,
719 Handle<Smi>(Smi::FromInt(line_number + 1)), 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
811static void PrintFrames(StringStream* accumulator,
812 StackFrame::PrintMode mode) {
813 StackFrameIterator it;
814 for (int i = 0; !it.done(); it.Advance()) {
815 it.frame()->Print(accumulator, mode, i++);
816 }
817}
818
819
820void Isolate::PrintStack(StringStream* accumulator) {
821 if (!IsInitialized()) {
822 accumulator->Add(
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000823 "\n==== JS stack trace is not available =======================\n\n");
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000824 accumulator->Add(
825 "\n==== Isolate for the thread is not initialized =============\n\n");
826 return;
827 }
828 // The MentionedObjectCache is not GC-proof at the moment.
829 AssertNoAllocation nogc;
830 ASSERT(StringStream::IsMentionedObjectCacheClear());
831
832 // Avoid printing anything if there are no frames.
833 if (c_entry_fp(thread_local_top()) == 0) return;
834
835 accumulator->Add(
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +0000836 "\n==== JS stack trace =========================================\n\n");
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000837 PrintFrames(accumulator, StackFrame::OVERVIEW);
838
839 accumulator->Add(
840 "\n==== Details ================================================\n\n");
841 PrintFrames(accumulator, StackFrame::DETAILS);
842
843 accumulator->PrintMentionedObjectCache();
844 accumulator->Add("=====================\n\n");
845}
846
847
848void Isolate::SetFailedAccessCheckCallback(
849 v8::FailedAccessCheckCallback callback) {
850 thread_local_top()->failed_access_check_callback_ = callback;
851}
852
853
854void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
855 if (!thread_local_top()->failed_access_check_callback_) return;
856
857 ASSERT(receiver->IsAccessCheckNeeded());
858 ASSERT(context());
859
860 // Get the data object from access check info.
861 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
862 if (!constructor->shared()->IsApiFunction()) return;
863 Object* data_obj =
864 constructor->shared()->get_api_func_data()->access_check_info();
865 if (data_obj == heap_.undefined_value()) return;
866
867 HandleScope scope;
868 Handle<JSObject> receiver_handle(receiver);
869 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000870 { VMState state(this, EXTERNAL);
871 thread_local_top()->failed_access_check_callback_(
872 v8::Utils::ToLocal(receiver_handle),
873 type,
874 v8::Utils::ToLocal(data));
875 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000876}
877
878
879enum MayAccessDecision {
880 YES, NO, UNKNOWN
881};
882
883
884static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
885 JSObject* receiver,
886 v8::AccessType type) {
887 // During bootstrapping, callback functions are not enabled yet.
888 if (isolate->bootstrapper()->IsActive()) return YES;
889
890 if (receiver->IsJSGlobalProxy()) {
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000891 Object* receiver_context = JSGlobalProxy::cast(receiver)->native_context();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000892 if (!receiver_context->IsContext()) return NO;
893
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000894 // Get the native context of current top context.
895 // avoid using Isolate::native_context() because it uses Handle.
896 Context* native_context =
897 isolate->context()->global_object()->native_context();
898 if (receiver_context == native_context) return YES;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000899
900 if (Context::cast(receiver_context)->security_token() ==
yangguo@chromium.org46839fb2012-08-28 09:06:19 +0000901 native_context->security_token())
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000902 return YES;
903 }
904
905 return UNKNOWN;
906}
907
908
909bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
910 v8::AccessType type) {
911 ASSERT(receiver->IsAccessCheckNeeded());
912
913 // The callers of this method are not expecting a GC.
914 AssertNoAllocation no_gc;
915
916 // Skip checks for hidden properties access. Note, we do not
917 // require existence of a context in this case.
918 if (key == heap_.hidden_symbol()) return true;
919
920 // Check for compatibility between the security tokens in the
921 // current lexical context and the accessed object.
922 ASSERT(context());
923
924 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
925 if (decision != UNKNOWN) return decision == YES;
926
927 // Get named access check callback
yangguo@chromium.org46a2a512013-01-18 16:29:40 +0000928 // TODO(dcarney): revert
929 Map* map = receiver->map();
930 CHECK(map->IsMap());
931 CHECK(map->constructor()->IsJSFunction());
932 JSFunction* constructor = JSFunction::cast(map->constructor());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000933 if (!constructor->shared()->IsApiFunction()) return false;
934
935 Object* data_obj =
936 constructor->shared()->get_api_func_data()->access_check_info();
937 if (data_obj == heap_.undefined_value()) return false;
938
939 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
940 v8::NamedSecurityCallback callback =
941 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
942
943 if (!callback) return false;
944
945 HandleScope scope(this);
946 Handle<JSObject> receiver_handle(receiver, this);
947 Handle<Object> key_handle(key, this);
948 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
949 LOG(this, ApiNamedSecurityCheck(key));
950 bool result = false;
951 {
952 // Leaving JavaScript.
953 VMState state(this, EXTERNAL);
954 result = callback(v8::Utils::ToLocal(receiver_handle),
955 v8::Utils::ToLocal(key_handle),
956 type,
957 v8::Utils::ToLocal(data));
958 }
959 return result;
960}
961
962
963bool Isolate::MayIndexedAccess(JSObject* receiver,
964 uint32_t index,
965 v8::AccessType type) {
966 ASSERT(receiver->IsAccessCheckNeeded());
967 // Check for compatibility between the security tokens in the
968 // current lexical context and the accessed object.
969 ASSERT(context());
970
971 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
972 if (decision != UNKNOWN) return decision == YES;
973
974 // Get indexed access check callback
975 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
976 if (!constructor->shared()->IsApiFunction()) return false;
977
978 Object* data_obj =
979 constructor->shared()->get_api_func_data()->access_check_info();
980 if (data_obj == heap_.undefined_value()) return false;
981
982 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
983 v8::IndexedSecurityCallback callback =
984 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
985
986 if (!callback) return false;
987
988 HandleScope scope(this);
989 Handle<JSObject> receiver_handle(receiver, this);
990 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
991 LOG(this, ApiIndexedSecurityCheck(index));
992 bool result = false;
993 {
994 // Leaving JavaScript.
995 VMState state(this, EXTERNAL);
996 result = callback(v8::Utils::ToLocal(receiver_handle),
997 index,
998 type,
999 v8::Utils::ToLocal(data));
1000 }
1001 return result;
1002}
1003
1004
1005const char* const Isolate::kStackOverflowMessage =
1006 "Uncaught RangeError: Maximum call stack size exceeded";
1007
1008
1009Failure* Isolate::StackOverflow() {
1010 HandleScope scope;
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001011 // At this point we cannot create an Error object using its javascript
1012 // constructor. Instead, we copy the pre-constructed boilerplate and
1013 // attach the stack trace as a hidden property.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001014 Handle<String> key = factory()->stack_overflow_symbol();
1015 Handle<JSObject> boilerplate =
1016 Handle<JSObject>::cast(GetProperty(js_builtins_object(), key));
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001017 Handle<JSObject> exception = Copy(boilerplate);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001018 DoThrow(*exception, NULL);
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001019
1020 // Get stack trace limit.
1021 Handle<Object> error = GetProperty(js_builtins_object(), "$Error");
1022 if (!error->IsJSObject()) return Failure::Exception();
1023 Handle<Object> stack_trace_limit =
1024 GetProperty(Handle<JSObject>::cast(error), "stackTraceLimit");
1025 if (!stack_trace_limit->IsNumber()) return Failure::Exception();
1026 int limit = static_cast<int>(stack_trace_limit->Number());
1027
1028 Handle<JSArray> stack_trace = CaptureSimpleStackTrace(
1029 exception, factory()->undefined_value(), limit);
1030 JSObject::SetHiddenProperty(exception,
1031 factory()->hidden_stack_trace_symbol(),
1032 stack_trace);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001033 return Failure::Exception();
1034}
1035
1036
1037Failure* Isolate::TerminateExecution() {
1038 DoThrow(heap_.termination_exception(), NULL);
1039 return Failure::Exception();
1040}
1041
1042
1043Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
1044 DoThrow(exception, location);
1045 return Failure::Exception();
1046}
1047
1048
mmassi@chromium.org7028c052012-06-13 11:51:58 +00001049Failure* Isolate::ReThrow(MaybeObject* exception) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001050 bool can_be_caught_externally = false;
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001051 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1052 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1053
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001054 thread_local_top()->catcher_ = can_be_caught_externally ?
1055 try_catch_handler() : NULL;
1056
1057 // Set the exception being re-thrown.
1058 set_pending_exception(exception);
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001059 if (exception->IsFailure()) return exception->ToFailureUnchecked();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001060 return Failure::Exception();
1061}
1062
1063
1064Failure* Isolate::ThrowIllegalOperation() {
1065 return Throw(heap_.illegal_access_symbol());
1066}
1067
1068
1069void Isolate::ScheduleThrow(Object* exception) {
1070 // When scheduling a throw we first throw the exception to get the
1071 // error reporting if it is uncaught before rescheduling it.
1072 Throw(exception);
mmassi@chromium.org49a44672012-12-04 13:52:03 +00001073 PropagatePendingExceptionToExternalTryCatch();
1074 if (has_pending_exception()) {
1075 thread_local_top()->scheduled_exception_ = pending_exception();
1076 thread_local_top()->external_caught_exception_ = false;
1077 clear_pending_exception();
1078 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001079}
1080
1081
1082Failure* Isolate::PromoteScheduledException() {
1083 MaybeObject* thrown = scheduled_exception();
1084 clear_scheduled_exception();
1085 // Re-throw the exception to avoid getting repeated error reporting.
1086 return ReThrow(thrown);
1087}
1088
1089
1090void Isolate::PrintCurrentStackTrace(FILE* out) {
1091 StackTraceFrameIterator it(this);
1092 while (!it.done()) {
1093 HandleScope scope;
1094 // Find code position if recorded in relocation info.
1095 JavaScriptFrame* frame = it.frame();
1096 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1097 Handle<Object> pos_obj(Smi::FromInt(pos));
1098 // Fetch function and receiver.
1099 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
1100 Handle<Object> recv(frame->receiver());
1101 // Advance to the next JavaScript frame and determine if the
1102 // current frame is the top-level frame.
1103 it.Advance();
1104 Handle<Object> is_top_level = it.done()
1105 ? factory()->true_value()
1106 : factory()->false_value();
1107 // Generate and print stack trace line.
1108 Handle<String> line =
1109 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1110 if (line->length() > 0) {
1111 line->PrintOn(out);
1112 fprintf(out, "\n");
1113 }
1114 }
1115}
1116
1117
1118void Isolate::ComputeLocation(MessageLocation* target) {
1119 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1120 StackTraceFrameIterator it(this);
1121 if (!it.done()) {
1122 JavaScriptFrame* frame = it.frame();
1123 JSFunction* fun = JSFunction::cast(frame->function());
1124 Object* script = fun->shared()->script();
1125 if (script->IsScript() &&
1126 !(Script::cast(script)->source()->IsUndefined())) {
1127 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1128 // Compute the location from the function and the reloc info.
1129 Handle<Script> casted_script(Script::cast(script));
1130 *target = MessageLocation(casted_script, pos, pos + 1);
1131 }
1132 }
1133}
1134
1135
1136bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1137 bool catchable_by_javascript) {
1138 // Find the top-most try-catch handler.
1139 StackHandler* handler =
1140 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001141 while (handler != NULL && !handler->is_catch()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001142 handler = handler->next();
1143 }
1144
1145 // Get the address of the external handler so we can compare the address to
1146 // determine which one is closer to the top of the stack.
1147 Address external_handler_address =
1148 thread_local_top()->try_catch_handler_address();
1149
1150 // The exception has been externally caught if and only if there is
1151 // an external handler which is on top of the top-most try-catch
1152 // handler.
1153 *can_be_caught_externally = external_handler_address != NULL &&
1154 (handler == NULL || handler->address() > external_handler_address ||
1155 !catchable_by_javascript);
1156
1157 if (*can_be_caught_externally) {
1158 // Only report the exception if the external handler is verbose.
1159 return try_catch_handler()->is_verbose_;
1160 } else {
1161 // Report the exception if it isn't caught by JavaScript code.
1162 return handler == NULL;
1163 }
1164}
1165
1166
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001167bool Isolate::IsErrorObject(Handle<Object> obj) {
1168 if (!obj->IsJSObject()) return false;
1169
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001170 String* error_key =
1171 *(factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("$Error")));
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001172 Object* error_constructor =
1173 js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1174
1175 for (Object* prototype = *obj; !prototype->IsNull();
1176 prototype = prototype->GetPrototype()) {
1177 if (!prototype->IsJSObject()) return false;
1178 if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1179 return true;
1180 }
1181 }
1182 return false;
1183}
1184
1185
1186void Isolate::DoThrow(Object* exception, MessageLocation* location) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001187 ASSERT(!has_pending_exception());
1188
1189 HandleScope scope;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001190 Handle<Object> exception_handle(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001191
1192 // Determine reporting and whether the exception is caught externally.
1193 bool catchable_by_javascript = is_catchable_by_javascript(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001194 bool can_be_caught_externally = false;
1195 bool should_report_exception =
1196 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1197 bool report_exception = catchable_by_javascript && should_report_exception;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001198 bool try_catch_needs_message =
1199 can_be_caught_externally && try_catch_handler()->capture_message_;
1200 bool bootstrapping = bootstrapper()->IsActive();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001201
1202#ifdef ENABLE_DEBUGGER_SUPPORT
1203 // Notify debugger of exception.
1204 if (catchable_by_javascript) {
1205 debugger_->OnException(exception_handle, report_exception);
1206 }
1207#endif
1208
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001209 // Generate the message if required.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001210 if (report_exception || try_catch_needs_message) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001211 MessageLocation potential_computed_location;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001212 if (location == NULL) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001213 // If no location was specified we use a computed one instead.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001214 ComputeLocation(&potential_computed_location);
1215 location = &potential_computed_location;
1216 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001217 // It's not safe to try to make message objects or collect stack traces
1218 // while the bootstrapper is active since the infrastructure may not have
1219 // been properly initialized.
1220 if (!bootstrapping) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001221 Handle<String> stack_trace;
1222 if (FLAG_trace_exception) stack_trace = StackTraceString();
1223 Handle<JSArray> stack_trace_object;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001224 if (capture_stack_trace_for_uncaught_exceptions_) {
1225 if (IsErrorObject(exception_handle)) {
1226 // We fetch the stack trace that corresponds to this error object.
1227 String* key = heap()->hidden_stack_trace_symbol();
1228 Object* stack_property =
1229 JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1230 // Property lookup may have failed. In this case it's probably not
1231 // a valid Error object.
1232 if (stack_property->IsJSArray()) {
1233 stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1234 }
1235 }
1236 if (stack_trace_object.is_null()) {
1237 // Not an error object, we capture at throw site.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001238 stack_trace_object = CaptureCurrentStackTrace(
1239 stack_trace_for_uncaught_exceptions_frame_limit_,
1240 stack_trace_for_uncaught_exceptions_options_);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001241 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001242 }
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001243
1244 Handle<Object> exception_arg = exception_handle;
1245 // If the exception argument is a custom object, turn it into a string
1246 // before throwing as uncaught exception. Note that the pending
1247 // exception object to be set later must not be turned into a string.
1248 if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001249 bool failed = false;
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001250 exception_arg = Execution::ToDetailString(exception_arg, &failed);
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001251 if (failed) {
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001252 exception_arg =
1253 factory()->LookupOneByteSymbol(STATIC_ASCII_VECTOR("exception"));
mvstanton@chromium.orge4ac3ef2012-11-12 14:53:34 +00001254 }
1255 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001256 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1257 "uncaught_exception",
1258 location,
yangguo@chromium.orgeeb44b62012-11-13 13:56:09 +00001259 HandleVector<Object>(&exception_arg, 1),
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001260 stack_trace,
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001261 stack_trace_object);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001262 thread_local_top()->pending_message_obj_ = *message_obj;
1263 if (location != NULL) {
1264 thread_local_top()->pending_message_script_ = *location->script();
1265 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1266 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1267 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +00001268 } else if (location != NULL && !location->script().is_null()) {
1269 // We are bootstrapping and caught an error where the location is set
1270 // and we have a script for the location.
1271 // In this case we could have an extension (or an internal error
1272 // somewhere) and we print out the line number at which the error occured
1273 // to the console for easier debugging.
1274 int line_number = GetScriptLineNumberSafe(location->script(),
1275 location->start_pos());
verwaest@chromium.org37141392012-05-31 13:27:02 +00001276 if (exception->IsString()) {
1277 OS::PrintError(
1278 "Extension or internal compilation error: %s in %s at line %d.\n",
1279 *String::cast(exception)->ToCString(),
1280 *String::cast(location->script()->name())->ToCString(),
danno@chromium.org81cac2b2012-07-10 11:28:27 +00001281 line_number + 1);
verwaest@chromium.org37141392012-05-31 13:27:02 +00001282 } else {
1283 OS::PrintError(
1284 "Extension or internal compilation error in %s at line %d.\n",
1285 *String::cast(location->script()->name())->ToCString(),
danno@chromium.org81cac2b2012-07-10 11:28:27 +00001286 line_number + 1);
verwaest@chromium.org37141392012-05-31 13:27:02 +00001287 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001288 }
1289 }
1290
1291 // Save the message for reporting if the the exception remains uncaught.
1292 thread_local_top()->has_pending_message_ = report_exception;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001293
1294 // Do not forget to clean catcher_ if currently thrown exception cannot
1295 // be caught. If necessary, ReThrow will update the catcher.
1296 thread_local_top()->catcher_ = can_be_caught_externally ?
1297 try_catch_handler() : NULL;
1298
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001299 set_pending_exception(*exception_handle);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001300}
1301
1302
1303bool Isolate::IsExternallyCaught() {
1304 ASSERT(has_pending_exception());
1305
1306 if ((thread_local_top()->catcher_ == NULL) ||
1307 (try_catch_handler() != thread_local_top()->catcher_)) {
1308 // When throwing the exception, we found no v8::TryCatch
1309 // which should care about this exception.
1310 return false;
1311 }
1312
1313 if (!is_catchable_by_javascript(pending_exception())) {
1314 return true;
1315 }
1316
1317 // Get the address of the external handler so we can compare the address to
1318 // determine which one is closer to the top of the stack.
1319 Address external_handler_address =
1320 thread_local_top()->try_catch_handler_address();
1321 ASSERT(external_handler_address != NULL);
1322
1323 // The exception has been externally caught if and only if there is
1324 // an external handler which is on top of the top-most try-finally
1325 // handler.
1326 // There should be no try-catch blocks as they would prohibit us from
1327 // finding external catcher in the first place (see catcher_ check above).
1328 //
1329 // Note, that finally clause would rethrow an exception unless it's
1330 // aborted by jumps in control flow like return, break, etc. and we'll
1331 // have another chances to set proper v8::TryCatch.
1332 StackHandler* handler =
1333 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1334 while (handler != NULL && handler->address() < external_handler_address) {
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001335 ASSERT(!handler->is_catch());
1336 if (handler->is_finally()) return false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001337
1338 handler = handler->next();
1339 }
1340
1341 return true;
1342}
1343
1344
1345void Isolate::ReportPendingMessages() {
1346 ASSERT(has_pending_exception());
1347 PropagatePendingExceptionToExternalTryCatch();
1348
1349 // If the pending exception is OutOfMemoryException set out_of_memory in
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001350 // the native context. Note: We have to mark the native context here
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001351 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1352 // set it.
1353 HandleScope scope;
jkummerow@chromium.org59297c72013-01-09 16:32:23 +00001354 if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001355 context()->mark_out_of_memory();
1356 } else if (thread_local_top_.pending_exception_ ==
1357 heap()->termination_exception()) {
1358 // Do nothing: if needed, the exception has been already propagated to
1359 // v8::TryCatch.
1360 } else {
1361 if (thread_local_top_.has_pending_message_) {
1362 thread_local_top_.has_pending_message_ = false;
1363 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1364 HandleScope scope;
1365 Handle<Object> message_obj(thread_local_top_.pending_message_obj_);
1366 if (thread_local_top_.pending_message_script_ != NULL) {
1367 Handle<Script> script(thread_local_top_.pending_message_script_);
1368 int start_pos = thread_local_top_.pending_message_start_pos_;
1369 int end_pos = thread_local_top_.pending_message_end_pos_;
1370 MessageLocation location(script, start_pos, end_pos);
1371 MessageHandler::ReportMessage(this, &location, message_obj);
1372 } else {
1373 MessageHandler::ReportMessage(this, NULL, message_obj);
1374 }
1375 }
1376 }
1377 }
1378 clear_pending_message();
1379}
1380
1381
mmassi@chromium.org49a44672012-12-04 13:52:03 +00001382MessageLocation Isolate::GetMessageLocation() {
1383 ASSERT(has_pending_exception());
1384
jkummerow@chromium.org59297c72013-01-09 16:32:23 +00001385 if (!thread_local_top_.pending_exception_->IsOutOfMemory() &&
mmassi@chromium.org49a44672012-12-04 13:52:03 +00001386 thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1387 thread_local_top_.has_pending_message_ &&
1388 !thread_local_top_.pending_message_obj_->IsTheHole() &&
1389 thread_local_top_.pending_message_script_ != NULL) {
1390 Handle<Script> script(thread_local_top_.pending_message_script_);
1391 int start_pos = thread_local_top_.pending_message_start_pos_;
1392 int end_pos = thread_local_top_.pending_message_end_pos_;
1393 return MessageLocation(script, start_pos, end_pos);
1394 }
1395
1396 return MessageLocation();
1397}
1398
1399
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001400void Isolate::TraceException(bool flag) {
1401 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1402}
1403
1404
1405bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1406 ASSERT(has_pending_exception());
1407 PropagatePendingExceptionToExternalTryCatch();
1408
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001409 // Always reschedule out of memory exceptions.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001410 if (!is_out_of_memory()) {
1411 bool is_termination_exception =
1412 pending_exception() == heap_.termination_exception();
1413
1414 // Do not reschedule the exception if this is the bottom call.
1415 bool clear_exception = is_bottom_call;
1416
1417 if (is_termination_exception) {
1418 if (is_bottom_call) {
1419 thread_local_top()->external_caught_exception_ = false;
1420 clear_pending_exception();
1421 return false;
1422 }
1423 } else if (thread_local_top()->external_caught_exception_) {
1424 // If the exception is externally caught, clear it if there are no
1425 // JavaScript frames on the way to the C++ frame that has the
1426 // external handler.
1427 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1428 Address external_handler_address =
1429 thread_local_top()->try_catch_handler_address();
1430 JavaScriptFrameIterator it;
1431 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1432 clear_exception = true;
1433 }
1434 }
1435
1436 // Clear the exception if needed.
1437 if (clear_exception) {
1438 thread_local_top()->external_caught_exception_ = false;
1439 clear_pending_exception();
1440 return false;
1441 }
1442 }
1443
1444 // Reschedule the exception.
1445 thread_local_top()->scheduled_exception_ = pending_exception();
1446 clear_pending_exception();
1447 return true;
1448}
1449
1450
1451void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1452 bool capture,
1453 int frame_limit,
1454 StackTrace::StackTraceOptions options) {
1455 capture_stack_trace_for_uncaught_exceptions_ = capture;
1456 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1457 stack_trace_for_uncaught_exceptions_options_ = options;
1458}
1459
1460
1461bool Isolate::is_out_of_memory() {
1462 if (has_pending_exception()) {
1463 MaybeObject* e = pending_exception();
1464 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1465 return true;
1466 }
1467 }
1468 if (has_scheduled_exception()) {
1469 MaybeObject* e = scheduled_exception();
1470 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1471 return true;
1472 }
1473 }
1474 return false;
1475}
1476
1477
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001478Handle<Context> Isolate::native_context() {
1479 GlobalObject* global = thread_local_top()->context_->global_object();
1480 return Handle<Context>(global->native_context());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001481}
1482
1483
yangguo@chromium.org355cfd12012-08-29 15:32:24 +00001484Handle<Context> Isolate::global_context() {
1485 GlobalObject* global = thread_local_top()->context_->global_object();
1486 return Handle<Context>(global->global_context());
1487}
1488
1489
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001490Handle<Context> Isolate::GetCallingNativeContext() {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001491 JavaScriptFrameIterator it;
1492#ifdef ENABLE_DEBUGGER_SUPPORT
1493 if (debug_->InDebugger()) {
1494 while (!it.done()) {
1495 JavaScriptFrame* frame = it.frame();
1496 Context* context = Context::cast(frame->context());
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001497 if (context->native_context() == *debug_->debug_context()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001498 it.Advance();
1499 } else {
1500 break;
1501 }
1502 }
1503 }
1504#endif // ENABLE_DEBUGGER_SUPPORT
1505 if (it.done()) return Handle<Context>::null();
1506 JavaScriptFrame* frame = it.frame();
1507 Context* context = Context::cast(frame->context());
yangguo@chromium.org46839fb2012-08-28 09:06:19 +00001508 return Handle<Context>(context->native_context());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001509}
1510
1511
1512char* Isolate::ArchiveThread(char* to) {
1513 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1514 RuntimeProfiler::IsolateExitedJS(this);
1515 }
1516 memcpy(to, reinterpret_cast<char*>(thread_local_top()),
1517 sizeof(ThreadLocalTop));
1518 InitializeThreadLocal();
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001519 clear_pending_exception();
1520 clear_pending_message();
1521 clear_scheduled_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001522 return to + sizeof(ThreadLocalTop);
1523}
1524
1525
1526char* Isolate::RestoreThread(char* from) {
1527 memcpy(reinterpret_cast<char*>(thread_local_top()), from,
1528 sizeof(ThreadLocalTop));
1529 // This might be just paranoia, but it seems to be needed in case a
1530 // thread_local_top_ is restored on a separate OS thread.
1531#ifdef USE_SIMULATOR
1532#ifdef V8_TARGET_ARCH_ARM
1533 thread_local_top()->simulator_ = Simulator::current(this);
1534#elif V8_TARGET_ARCH_MIPS
1535 thread_local_top()->simulator_ = Simulator::current(this);
1536#endif
1537#endif
1538 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1539 RuntimeProfiler::IsolateEnteredJS(this);
1540 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001541 ASSERT(context() == NULL || context()->IsContext());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001542 return from + sizeof(ThreadLocalTop);
1543}
1544
1545
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001546Isolate::ThreadDataTable::ThreadDataTable()
1547 : list_(NULL) {
1548}
1549
1550
hpayer@chromium.org7c3372b2013-02-13 17:26:04 +00001551Isolate::ThreadDataTable::~ThreadDataTable() {
1552 // TODO(svenpanne) The assertion below would fire if an embedder does not
1553 // cleanly dispose all Isolates before disposing v8, so we are conservative
1554 // and leave it out for now.
1555 // ASSERT_EQ(NULL, list_);
1556}
1557
1558
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001559Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001560 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1561 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001562 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1563 if (data->Matches(isolate, thread_id)) return data;
1564 }
1565 return NULL;
1566}
1567
1568
1569void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1570 if (list_ != NULL) list_->prev_ = data;
1571 data->next_ = list_;
1572 list_ = data;
1573}
1574
1575
1576void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1577 if (list_ == data) list_ = data->next_;
1578 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1579 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001580 delete data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001581}
1582
1583
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001584void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1585 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001586 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1587 if (data != NULL) {
1588 Remove(data);
1589 }
1590}
1591
1592
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001593void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1594 PerIsolateThreadData* data = list_;
1595 while (data != NULL) {
1596 PerIsolateThreadData* next = data->next_;
1597 if (data->isolate() == isolate) Remove(data);
1598 data = next;
1599 }
1600}
1601
1602
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001603#ifdef DEBUG
1604#define TRACE_ISOLATE(tag) \
1605 do { \
1606 if (FLAG_trace_isolates) { \
1607 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
1608 } \
1609 } while (false)
1610#else
1611#define TRACE_ISOLATE(tag)
1612#endif
1613
1614
1615Isolate::Isolate()
1616 : state_(UNINITIALIZED),
yangguo@chromium.orgefdb9d72012-04-26 08:21:05 +00001617 embedder_data_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001618 entry_stack_(NULL),
1619 stack_trace_nesting_level_(0),
1620 incomplete_message_(NULL),
1621 preallocated_memory_thread_(NULL),
1622 preallocated_message_space_(NULL),
1623 bootstrapper_(NULL),
1624 runtime_profiler_(NULL),
1625 compilation_cache_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001626 counters_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001627 code_range_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001628 // Must be initialized early to allow v8::SetResourceConstraints calls.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001629 break_access_(OS::CreateMutex()),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001630 debugger_initialized_(false),
1631 // Must be initialized early to allow v8::Debug calls.
1632 debugger_access_(OS::CreateMutex()),
1633 logger_(NULL),
1634 stats_table_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001635 stub_cache_(NULL),
1636 deoptimizer_data_(NULL),
1637 capture_stack_trace_for_uncaught_exceptions_(false),
1638 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1639 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1640 transcendental_cache_(NULL),
1641 memory_allocator_(NULL),
1642 keyed_lookup_cache_(NULL),
1643 context_slot_cache_(NULL),
1644 descriptor_lookup_cache_(NULL),
1645 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001646 unicode_cache_(NULL),
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001647 runtime_zone_(this),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001648 in_use_list_(0),
1649 free_list_(0),
1650 preallocated_storage_preallocated_(false),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001651 inner_pointer_to_code_cache_(NULL),
yangguo@chromium.org4cd70b42013-01-04 08:57:54 +00001652 write_iterator_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001653 global_handles_(NULL),
1654 context_switcher_(NULL),
1655 thread_manager_(NULL),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001656 fp_stubs_generated_(false),
ricow@chromium.org27bf2882011-11-17 08:34:43 +00001657 has_installed_extensions_(false),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001658 string_tracker_(NULL),
1659 regexp_stack_(NULL),
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001660 date_cache_(NULL),
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001661 code_stub_interface_descriptors_(NULL),
yangguo@chromium.org304cc332012-07-24 07:59:48 +00001662 context_exit_happened_(false),
1663 deferred_handles_head_(NULL),
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00001664 optimizing_compiler_thread_(this),
1665 marking_thread_(NULL),
1666 sweeper_thread_(NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001667 TRACE_ISOLATE(constructor);
1668
1669 memset(isolate_addresses_, 0,
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001670 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001671
1672 heap_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001673 stack_guard_.isolate_ = this;
1674
lrn@chromium.org1c092762011-05-09 09:42:16 +00001675 // ThreadManager is initialized early to support locking an isolate
1676 // before it is entered.
1677 thread_manager_ = new ThreadManager();
1678 thread_manager_->isolate_ = this;
1679
lrn@chromium.org7516f052011-03-30 08:52:27 +00001680#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
1681 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001682 simulator_initialized_ = false;
1683 simulator_i_cache_ = NULL;
1684 simulator_redirection_ = NULL;
1685#endif
1686
1687#ifdef DEBUG
1688 // heap_histograms_ initializes itself.
1689 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1690 memset(code_kind_statistics_, 0,
1691 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
yangguo@chromium.org003650e2013-01-24 16:31:08 +00001692
1693 allow_handle_deref_ = true;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001694#endif
1695
1696#ifdef ENABLE_DEBUGGER_SUPPORT
1697 debug_ = NULL;
1698 debugger_ = NULL;
1699#endif
1700
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001701 handle_scope_data_.Initialize();
1702
1703#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1704 name##_ = (initial_value);
1705 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1706#undef ISOLATE_INIT_EXECUTE
1707
1708#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1709 memset(name##_, 0, sizeof(type) * length);
1710 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1711#undef ISOLATE_INIT_ARRAY_EXECUTE
1712}
1713
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00001714
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001715void Isolate::TearDown() {
1716 TRACE_ISOLATE(tear_down);
1717
1718 // Temporarily set this isolate as current so that various parts of
1719 // the isolate can access it in their destructors without having a
1720 // direct pointer. We don't use Enter/Exit here to avoid
1721 // initializing the thread data.
1722 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1723 Isolate* saved_isolate = UncheckedCurrent();
1724 SetIsolateThreadLocals(this, NULL);
1725
1726 Deinit();
1727
danno@chromium.org8c0a43f2012-04-03 08:37:53 +00001728 { ScopedLock lock(process_wide_mutex_);
1729 thread_data_table_->RemoveAllThreads(this);
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001730 }
1731
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001732 if (serialize_partial_snapshot_cache_ != NULL) {
1733 delete[] serialize_partial_snapshot_cache_;
1734 serialize_partial_snapshot_cache_ = NULL;
1735 }
1736
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001737 if (!IsDefaultIsolate()) {
1738 delete this;
1739 }
1740
1741 // Restore the previous current isolate.
1742 SetIsolateThreadLocals(saved_isolate, saved_data);
1743}
1744
1745
hpayer@chromium.org7c3372b2013-02-13 17:26:04 +00001746void Isolate::GlobalTearDown() {
1747 delete thread_data_table_;
1748}
1749
1750
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001751void Isolate::Deinit() {
1752 if (state_ == INITIALIZED) {
1753 TRACE_ISOLATE(deinit);
1754
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00001755 if (FLAG_concurrent_sweeping || FLAG_parallel_sweeping) {
1756 for (int i = 0; i < FLAG_sweeper_threads; i++) {
1757 sweeper_thread_[i]->Stop();
1758 delete sweeper_thread_[i];
1759 }
1760 delete[] sweeper_thread_;
1761 }
1762
1763 if (FLAG_parallel_marking) {
1764 for (int i = 0; i < FLAG_marking_threads; i++) {
1765 marking_thread_[i]->Stop();
1766 delete marking_thread_[i];
1767 }
1768 delete[] marking_thread_;
1769 }
1770
yangguo@chromium.org304cc332012-07-24 07:59:48 +00001771 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Stop();
1772
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001773 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
1774
1775 // We must stop the logger before we tear down other components.
1776 logger_->EnsureTickerStopped();
1777
1778 delete deoptimizer_data_;
1779 deoptimizer_data_ = NULL;
1780 if (FLAG_preemption) {
yangguo@chromium.org46a2a512013-01-18 16:29:40 +00001781 v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001782 v8::Locker::StopPreemption();
1783 }
1784 builtins_.TearDown();
1785 bootstrapper_->TearDown();
1786
1787 // Remove the external reference to the preallocated stack memory.
1788 delete preallocated_message_space_;
1789 preallocated_message_space_ = NULL;
1790 PreallocatedMemoryThreadStop();
1791
1792 HeapProfiler::TearDown();
1793 CpuProfiler::TearDown();
1794 if (runtime_profiler_ != NULL) {
1795 runtime_profiler_->TearDown();
1796 delete runtime_profiler_;
1797 runtime_profiler_ = NULL;
1798 }
1799 heap_.TearDown();
1800 logger_->TearDown();
1801
1802 // The default isolate is re-initializable due to legacy API.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001803 state_ = UNINITIALIZED;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001804 }
1805}
1806
1807
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001808void Isolate::PushToPartialSnapshotCache(Object* obj) {
1809 int length = serialize_partial_snapshot_cache_length();
1810 int capacity = serialize_partial_snapshot_cache_capacity();
1811
1812 if (length >= capacity) {
1813 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1814 Object** new_array = new Object*[new_capacity];
1815 for (int i = 0; i < length; i++) {
1816 new_array[i] = serialize_partial_snapshot_cache()[i];
1817 }
1818 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1819 set_serialize_partial_snapshot_cache(new_array);
1820 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1821 }
1822
1823 serialize_partial_snapshot_cache()[length] = obj;
1824 set_serialize_partial_snapshot_cache_length(length + 1);
1825}
1826
1827
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001828void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1829 PerIsolateThreadData* data) {
danno@chromium.org8c0a43f2012-04-03 08:37:53 +00001830 Thread::SetThreadLocal(isolate_key_, isolate);
1831 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001832}
1833
1834
1835Isolate::~Isolate() {
1836 TRACE_ISOLATE(destructor);
1837
danno@chromium.orgb6451162011-08-17 14:33:23 +00001838 // Has to be called while counters_ are still alive.
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00001839 runtime_zone_.DeleteKeptSegment();
danno@chromium.orgb6451162011-08-17 14:33:23 +00001840
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001841 delete[] assembler_spare_buffer_;
1842 assembler_spare_buffer_ = NULL;
1843
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001844 delete unicode_cache_;
1845 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001846
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00001847 delete date_cache_;
1848 date_cache_ = NULL;
1849
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00001850 delete[] code_stub_interface_descriptors_;
1851 code_stub_interface_descriptors_ = NULL;
1852
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001853 delete regexp_stack_;
1854 regexp_stack_ = NULL;
1855
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001856 delete descriptor_lookup_cache_;
1857 descriptor_lookup_cache_ = NULL;
1858 delete context_slot_cache_;
1859 context_slot_cache_ = NULL;
1860 delete keyed_lookup_cache_;
1861 keyed_lookup_cache_ = NULL;
1862
1863 delete transcendental_cache_;
1864 transcendental_cache_ = NULL;
1865 delete stub_cache_;
1866 stub_cache_ = NULL;
1867 delete stats_table_;
1868 stats_table_ = NULL;
1869
1870 delete logger_;
1871 logger_ = NULL;
1872
1873 delete counters_;
1874 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001875
1876 delete handle_scope_implementer_;
1877 handle_scope_implementer_ = NULL;
1878 delete break_access_;
1879 break_access_ = NULL;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001880 delete debugger_access_;
1881 debugger_access_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001882
1883 delete compilation_cache_;
1884 compilation_cache_ = NULL;
1885 delete bootstrapper_;
1886 bootstrapper_ = NULL;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001887 delete inner_pointer_to_code_cache_;
1888 inner_pointer_to_code_cache_ = NULL;
yangguo@chromium.org4cd70b42013-01-04 08:57:54 +00001889 delete write_iterator_;
1890 write_iterator_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001891
1892 delete context_switcher_;
1893 context_switcher_ = NULL;
1894 delete thread_manager_;
1895 thread_manager_ = NULL;
1896
1897 delete string_tracker_;
1898 string_tracker_ = NULL;
1899
1900 delete memory_allocator_;
1901 memory_allocator_ = NULL;
1902 delete code_range_;
1903 code_range_ = NULL;
1904 delete global_handles_;
1905 global_handles_ = NULL;
1906
danno@chromium.orgb6451162011-08-17 14:33:23 +00001907 delete external_reference_table_;
1908 external_reference_table_ = NULL;
1909
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001910#ifdef ENABLE_DEBUGGER_SUPPORT
1911 delete debugger_;
1912 debugger_ = NULL;
1913 delete debug_;
1914 debug_ = NULL;
1915#endif
1916}
1917
1918
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001919void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +00001920 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001921 thread_local_top_.Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001922}
1923
1924
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001925void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1926 ASSERT(has_pending_exception());
1927
1928 bool external_caught = IsExternallyCaught();
1929 thread_local_top_.external_caught_exception_ = external_caught;
1930
1931 if (!external_caught) return;
1932
jkummerow@chromium.org59297c72013-01-09 16:32:23 +00001933 if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001934 // Do not propagate OOM exception: we should kill VM asap.
1935 } else if (thread_local_top_.pending_exception_ ==
1936 heap()->termination_exception()) {
1937 try_catch_handler()->can_continue_ = false;
1938 try_catch_handler()->exception_ = heap()->null_value();
1939 } else {
1940 // At this point all non-object (failure) exceptions have
1941 // been dealt with so this shouldn't fail.
1942 ASSERT(!pending_exception()->IsFailure());
1943 try_catch_handler()->can_continue_ = true;
1944 try_catch_handler()->exception_ = pending_exception();
1945 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1946 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
1947 }
1948 }
1949}
1950
1951
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001952void Isolate::InitializeLoggingAndCounters() {
1953 if (logger_ == NULL) {
1954 logger_ = new Logger;
1955 }
1956 if (counters_ == NULL) {
1957 counters_ = new Counters;
1958 }
1959}
1960
1961
1962void Isolate::InitializeDebugger() {
1963#ifdef ENABLE_DEBUGGER_SUPPORT
1964 ScopedLock lock(debugger_access_);
1965 if (NoBarrier_Load(&debugger_initialized_)) return;
1966 InitializeLoggingAndCounters();
1967 debug_ = new Debug(this);
1968 debugger_ = new Debugger(this);
1969 Release_Store(&debugger_initialized_, true);
1970#endif
1971}
1972
1973
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001974bool Isolate::Init(Deserializer* des) {
1975 ASSERT(state_ != INITIALIZED);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001976 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001977 TRACE_ISOLATE(init);
1978
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001979 // The initialization process does not handle memory exhaustion.
1980 DisallowAllocationFailure disallow_allocation_failure;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001981
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001982 InitializeLoggingAndCounters();
1983
1984 InitializeDebugger();
1985
1986 memory_allocator_ = new MemoryAllocator(this);
1987 code_range_ = new CodeRange(this);
1988
1989 // Safe after setting Heap::isolate_, initializing StackGuard and
1990 // ensuring that Isolate::Current() == this.
1991 heap_.SetStackLimits();
1992
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001993#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1994 isolate_addresses_[Isolate::k##CamelName##Address] = \
1995 reinterpret_cast<Address>(hacker_name##_address());
1996 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001997#undef C
1998
1999 string_tracker_ = new StringTracker();
2000 string_tracker_->isolate_ = this;
2001 compilation_cache_ = new CompilationCache(this);
2002 transcendental_cache_ = new TranscendentalCache();
2003 keyed_lookup_cache_ = new KeyedLookupCache();
2004 context_slot_cache_ = new ContextSlotCache();
2005 descriptor_lookup_cache_ = new DescriptorLookupCache();
2006 unicode_cache_ = new UnicodeCache();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00002007 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
yangguo@chromium.org4cd70b42013-01-04 08:57:54 +00002008 write_iterator_ = new ConsStringIteratorOp();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002009 global_handles_ = new GlobalHandles(this);
2010 bootstrapper_ = new Bootstrapper();
2011 handle_scope_implementer_ = new HandleScopeImplementer(this);
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002012 stub_cache_ = new StubCache(this, runtime_zone());
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002013 regexp_stack_ = new RegExpStack();
2014 regexp_stack_->isolate_ = this;
svenpanne@chromium.org4efbdb12012-03-12 08:18:42 +00002015 date_cache_ = new DateCache();
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002016 code_stub_interface_descriptors_ =
2017 new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
2018 memset(code_stub_interface_descriptors_, 0,
2019 kPointerSize * 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.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002043 const bool create_heap_objects = (des == NULL);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002044 ASSERT(!heap_.HasBeenSetUp());
2045 if (!heap_.SetUp(create_heap_objects)) {
yangguo@chromium.org9768bf12013-01-11 14:51:07 +00002046 V8::FatalProcessOutOfMemory("heap setup");
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002047 return false;
2048 }
2049
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002050 if (create_heap_objects) {
2051 // Terminate the cache array with the sentinel so we can iterate.
2052 PushToPartialSnapshotCache(heap_.undefined_value());
2053 }
2054
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00002055 InitializeThreadLocal();
2056
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002057 bootstrapper_->Initialize(create_heap_objects);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002058 builtins_.SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002059
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002060 // Only preallocate on the first initialization.
2061 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
2062 // Start the thread which will set aside some memory.
2063 PreallocatedMemoryThreadStart();
2064 preallocated_message_space_ =
2065 new NoAllocationStringAllocator(
2066 preallocated_memory_thread_->data(),
2067 preallocated_memory_thread_->length());
2068 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
2069 }
2070
2071 if (FLAG_preemption) {
yangguo@chromium.org46a2a512013-01-18 16:29:40 +00002072 v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002073 v8::Locker::StartPreemption(100);
2074 }
2075
2076#ifdef ENABLE_DEBUGGER_SUPPORT
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002077 debug_->SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002078#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002079
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002080 deoptimizer_data_ = new DeoptimizerData;
2081
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002082 // If we are deserializing, read the state into the now-empty heap.
yangguo@chromium.org5a11aaf2012-06-20 11:29:00 +00002083 if (!create_heap_objects) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002084 des->Deserialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002085 }
ulan@chromium.org812308e2012-02-29 15:58:45 +00002086 stub_cache_->Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002087
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00002088 // Finish initialization of ThreadLocal after deserialization is done.
2089 clear_pending_exception();
2090 clear_pending_message();
2091 clear_scheduled_exception();
2092
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002093 // Deserializing may put strange things in the root array's copy of the
2094 // stack guard.
2095 heap_.SetStackLimits();
2096
mstarzinger@chromium.org88d326b2012-04-23 12:57:22 +00002097 // Quiet the heap NaN if needed on target platform.
jkummerow@chromium.org28583c92012-07-16 11:31:55 +00002098 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
mstarzinger@chromium.org88d326b2012-04-23 12:57:22 +00002099
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002100 runtime_profiler_ = new RuntimeProfiler(this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00002101 runtime_profiler_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002102
2103 // If we are deserializing, log non-function code objects and compiled
2104 // functions found in the snapshot.
ulan@chromium.org8e8d8822012-11-23 14:36:46 +00002105 if (!create_heap_objects &&
yangguo@chromium.org355cfd12012-08-29 15:32:24 +00002106 (FLAG_log_code || FLAG_ll_prof || logger_->is_logging_code_events())) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002107 HandleScope scope;
2108 LOG(this, LogCodeObjects());
2109 LOG(this, LogCompiledFunctions());
2110 }
2111
yangguo@chromium.orgefdb9d72012-04-26 08:21:05 +00002112 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, state_)),
2113 Internals::kIsolateStateOffset);
2114 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2115 Internals::kIsolateEmbedderDataOffset);
2116 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2117 Internals::kIsolateRootsOffset);
2118
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002119 state_ = INITIALIZED;
rossberg@chromium.org994edf62012-02-06 10:12:55 +00002120 time_millis_at_init_ = OS::TimeCurrentMillis();
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002121
2122 if (!create_heap_objects) {
2123 // Now that the heap is consistent, it's OK to generate the code for the
2124 // deopt entry table that might have been referred to by optimized code in
2125 // the snapshot.
2126 HandleScope scope(this);
2127 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2128 Deoptimizer::LAZY,
2129 kDeoptTableSerializeEntryCount - 1);
2130 }
2131
mstarzinger@chromium.org068ea0a2013-01-30 09:39:44 +00002132 if (!Serializer::enabled()) {
2133 // Ensure that the stub failure trampoline has been generated.
2134 HandleScope scope(this);
2135 CodeStub::GenerateFPStubs();
mmassi@chromium.org2f0efde2013-02-06 14:12:58 +00002136 StubFailureTrampolineStub::GenerateAheadOfTime();
mstarzinger@chromium.org068ea0a2013-01-30 09:39:44 +00002137 }
2138
yangguo@chromium.org304cc332012-07-24 07:59:48 +00002139 if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Start();
mstarzinger@chromium.orge3b8d0f2013-02-01 09:06:41 +00002140
2141 if (FLAG_parallel_marking) {
2142 if (FLAG_marking_threads < 1) {
2143 FLAG_marking_threads = 1;
2144 }
2145 marking_thread_ = new MarkingThread*[FLAG_marking_threads];
2146 for (int i = 0; i < FLAG_marking_threads; i++) {
2147 marking_thread_[i] = new MarkingThread(this);
2148 marking_thread_[i]->Start();
2149 }
2150 }
2151
2152 if (FLAG_parallel_sweeping || FLAG_concurrent_sweeping) {
2153 if (FLAG_sweeper_threads < 1) {
2154 FLAG_sweeper_threads = 1;
2155 }
2156 sweeper_thread_ = new SweeperThread*[FLAG_sweeper_threads];
2157 for (int i = 0; i < FLAG_sweeper_threads; i++) {
2158 sweeper_thread_[i] = new SweeperThread(this);
2159 sweeper_thread_[i]->Start();
2160 }
2161 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002162 return true;
2163}
2164
2165
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00002166// Initialized lazily to allow early
2167// v8::V8::SetAddHistogramSampleFunction calls.
2168StatsTable* Isolate::stats_table() {
2169 if (stats_table_ == NULL) {
2170 stats_table_ = new StatsTable;
2171 }
2172 return stats_table_;
2173}
2174
2175
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002176void Isolate::Enter() {
2177 Isolate* current_isolate = NULL;
2178 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2179 if (current_data != NULL) {
2180 current_isolate = current_data->isolate_;
2181 ASSERT(current_isolate != NULL);
2182 if (current_isolate == this) {
2183 ASSERT(Current() == this);
2184 ASSERT(entry_stack_ != NULL);
2185 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00002186 entry_stack_->previous_thread_data->thread_id().Equals(
2187 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002188 // Same thread re-enters the isolate, no need to re-init anything.
2189 entry_stack_->entry_count++;
2190 return;
2191 }
2192 }
2193
2194 // Threads can have default isolate set into TLS as Current but not yet have
2195 // PerIsolateThreadData for it, as it requires more advanced phase of the
2196 // initialization. For example, a thread might be the one that system used for
2197 // static initializers - in this case the default isolate is set in TLS but
2198 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2199 // there, use the isolate set in TLS.
2200 if (current_isolate == NULL) {
2201 current_isolate = Isolate::UncheckedCurrent();
2202 }
2203
2204 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2205 ASSERT(data != NULL);
2206 ASSERT(data->isolate_ == this);
2207
2208 EntryStackItem* item = new EntryStackItem(current_data,
2209 current_isolate,
2210 entry_stack_);
2211 entry_stack_ = item;
2212
2213 SetIsolateThreadLocals(this, data);
2214
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002215 // In case it's the first time some thread enters the isolate.
2216 set_thread_id(data->thread_id());
2217}
2218
2219
2220void Isolate::Exit() {
2221 ASSERT(entry_stack_ != NULL);
2222 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00002223 entry_stack_->previous_thread_data->thread_id().Equals(
2224 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002225
2226 if (--entry_stack_->entry_count > 0) return;
2227
2228 ASSERT(CurrentPerIsolateThreadData() != NULL);
2229 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2230
2231 // Pop the stack.
2232 EntryStackItem* item = entry_stack_;
2233 entry_stack_ = item->previous_item;
2234
2235 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2236 Isolate* previous_isolate = item->previous_isolate;
2237
2238 delete item;
2239
2240 // Reinit the current thread for the isolate it was running before this one.
2241 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2242}
2243
2244
yangguo@chromium.org304cc332012-07-24 07:59:48 +00002245void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2246 deferred->next_ = deferred_handles_head_;
2247 if (deferred_handles_head_ != NULL) {
2248 deferred_handles_head_->previous_ = deferred;
2249 }
2250 deferred_handles_head_ = deferred;
2251}
2252
2253
2254void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2255#ifdef DEBUG
2256 // In debug mode assert that the linked list is well-formed.
2257 DeferredHandles* deferred_iterator = deferred;
2258 while (deferred_iterator->previous_ != NULL) {
2259 deferred_iterator = deferred_iterator->previous_;
2260 }
2261 ASSERT(deferred_handles_head_ == deferred_iterator);
2262#endif
2263 if (deferred_handles_head_ == deferred) {
2264 deferred_handles_head_ = deferred_handles_head_->next_;
2265 }
2266 if (deferred->next_ != NULL) {
2267 deferred->next_->previous_ = deferred->previous_;
2268 }
2269 if (deferred->previous_ != NULL) {
2270 deferred->previous_->next_ = deferred->next_;
2271 }
2272}
2273
2274
yangguo@chromium.orga6bbcc82012-12-21 12:35:02 +00002275CodeStubInterfaceDescriptor*
2276 Isolate::code_stub_interface_descriptor(int index) {
2277 return code_stub_interface_descriptors_ + index;
2278}
2279
2280
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002281#ifdef DEBUG
2282#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2283const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2284ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2285ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2286#undef ISOLATE_FIELD_OFFSET
2287#endif
2288
2289} } // namespace v8::internal