blob: 128136faa0b83d47ba0ed90fa972cf04282e1d2f [file] [log] [blame]
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001// Copyright 2012 the V8 project authors. All rights reserved.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include <stdlib.h>
29
30#include "v8.h"
31
32#include "ast.h"
33#include "bootstrapper.h"
34#include "codegen.h"
35#include "compilation-cache.h"
36#include "debug.h"
37#include "deoptimizer.h"
38#include "heap-profiler.h"
39#include "hydrogen.h"
40#include "isolate.h"
41#include "lithium-allocator.h"
42#include "log.h"
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000043#include "messages.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000044#include "regexp-stack.h"
45#include "runtime-profiler.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000046#include "scopeinfo.h"
47#include "serialize.h"
48#include "simulator.h"
49#include "spaces.h"
50#include "stub-cache.h"
51#include "version.h"
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000052#include "vm-state-inl.h"
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000053
54
55namespace v8 {
56namespace internal {
57
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000058Atomic32 ThreadId::highest_thread_id_ = 0;
59
60int ThreadId::AllocateThreadId() {
61 int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
62 return new_id;
63}
64
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000065
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000066int ThreadId::GetCurrentThreadId() {
67 int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
68 if (thread_id == 0) {
69 thread_id = AllocateThreadId();
70 Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
71 }
72 return thread_id;
73}
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000074
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000075
76ThreadLocalTop::ThreadLocalTop() {
77 InitializeInternal();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +000078 // This flag may be set using v8::V8::IgnoreOutOfMemoryException()
79 // before an isolate is initialized. The initialize methods below do
80 // not touch it to preserve its value.
81 ignore_out_of_memory_ = false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000082}
83
84
85void ThreadLocalTop::InitializeInternal() {
86 c_entry_fp_ = 0;
87 handler_ = 0;
88#ifdef USE_SIMULATOR
89 simulator_ = NULL;
90#endif
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000091 js_entry_sp_ = NULL;
92 external_callback_ = NULL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000093 current_vm_state_ = EXTERNAL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +000094 try_catch_handler_address_ = NULL;
95 context_ = NULL;
96 thread_id_ = ThreadId::Invalid();
97 external_caught_exception_ = false;
98 failed_access_check_callback_ = NULL;
99 save_context_ = NULL;
100 catcher_ = NULL;
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +0000101 top_lookup_result_ = NULL;
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +0000102
103 // These members are re-initialized later after deserialization
104 // is complete.
105 pending_exception_ = NULL;
106 has_pending_message_ = false;
107 pending_message_obj_ = NULL;
108 pending_message_script_ = NULL;
109 scheduled_exception_ = NULL;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000110}
111
112
113void ThreadLocalTop::Initialize() {
114 InitializeInternal();
115#ifdef USE_SIMULATOR
116#ifdef V8_TARGET_ARCH_ARM
117 simulator_ = Simulator::current(isolate_);
118#elif V8_TARGET_ARCH_MIPS
119 simulator_ = Simulator::current(isolate_);
120#endif
121#endif
122 thread_id_ = ThreadId::Current();
123}
124
125
126v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
127 return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
128}
129
130
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000131// Create a dummy thread that will wait forever on a semaphore. The only
132// purpose for this thread is to have some stack area to save essential data
133// into for use by a stacks only core dump (aka minidump).
134class PreallocatedMemoryThread: public Thread {
135 public:
136 char* data() {
137 if (data_ready_semaphore_ != NULL) {
138 // Initial access is guarded until the data has been published.
139 data_ready_semaphore_->Wait();
140 delete data_ready_semaphore_;
141 data_ready_semaphore_ = NULL;
142 }
143 return data_;
144 }
145
146 unsigned length() {
147 if (data_ready_semaphore_ != NULL) {
148 // Initial access is guarded until the data has been published.
149 data_ready_semaphore_->Wait();
150 delete data_ready_semaphore_;
151 data_ready_semaphore_ = NULL;
152 }
153 return length_;
154 }
155
156 // Stop the PreallocatedMemoryThread and release its resources.
157 void StopThread() {
158 keep_running_ = false;
159 wait_for_ever_semaphore_->Signal();
160
161 // Wait for the thread to terminate.
162 Join();
163
164 if (data_ready_semaphore_ != NULL) {
165 delete data_ready_semaphore_;
166 data_ready_semaphore_ = NULL;
167 }
168
169 delete wait_for_ever_semaphore_;
170 wait_for_ever_semaphore_ = NULL;
171 }
172
173 protected:
174 // When the thread starts running it will allocate a fixed number of bytes
175 // on the stack and publish the location of this memory for others to use.
176 void Run() {
177 EmbeddedVector<char, 15 * 1024> local_buffer;
178
179 // Initialize the buffer with a known good value.
180 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
181 local_buffer.length());
182
183 // Publish the local buffer and signal its availability.
184 data_ = local_buffer.start();
185 length_ = local_buffer.length();
186 data_ready_semaphore_->Signal();
187
188 while (keep_running_) {
189 // This thread will wait here until the end of time.
190 wait_for_ever_semaphore_->Wait();
191 }
192
193 // Make sure we access the buffer after the wait to remove all possibility
194 // of it being optimized away.
195 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
196 local_buffer.length());
197 }
198
199
200 private:
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000201 PreallocatedMemoryThread()
202 : Thread("v8:PreallocMem"),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000203 keep_running_(true),
204 wait_for_ever_semaphore_(OS::CreateSemaphore(0)),
205 data_ready_semaphore_(OS::CreateSemaphore(0)),
206 data_(NULL),
207 length_(0) {
208 }
209
210 // Used to make sure that the thread keeps looping even for spurious wakeups.
211 bool keep_running_;
212
213 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
214 Semaphore* wait_for_ever_semaphore_;
215 // Semaphore to signal that the data has been initialized.
216 Semaphore* data_ready_semaphore_;
217
218 // Location and size of the preallocated memory block.
219 char* data_;
220 unsigned length_;
221
222 friend class Isolate;
223
224 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
225};
226
227
228void Isolate::PreallocatedMemoryThreadStart() {
229 if (preallocated_memory_thread_ != NULL) return;
svenpanne@chromium.org6d786c92011-06-15 10:58:27 +0000230 preallocated_memory_thread_ = new PreallocatedMemoryThread();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000231 preallocated_memory_thread_->Start();
232}
233
234
235void Isolate::PreallocatedMemoryThreadStop() {
236 if (preallocated_memory_thread_ == NULL) return;
237 preallocated_memory_thread_->StopThread();
238 // Done with the thread entirely.
239 delete preallocated_memory_thread_;
240 preallocated_memory_thread_ = NULL;
241}
242
243
lrn@chromium.org7516f052011-03-30 08:52:27 +0000244void Isolate::PreallocatedStorageInit(size_t size) {
245 ASSERT(free_list_.next_ == &free_list_);
246 ASSERT(free_list_.previous_ == &free_list_);
247 PreallocatedStorage* free_chunk =
248 reinterpret_cast<PreallocatedStorage*>(new char[size]);
249 free_list_.next_ = free_list_.previous_ = free_chunk;
250 free_chunk->next_ = free_chunk->previous_ = &free_list_;
251 free_chunk->size_ = size - sizeof(PreallocatedStorage);
252 preallocated_storage_preallocated_ = true;
253}
254
255
256void* Isolate::PreallocatedStorageNew(size_t size) {
257 if (!preallocated_storage_preallocated_) {
258 return FreeStoreAllocationPolicy::New(size);
259 }
260 ASSERT(free_list_.next_ != &free_list_);
261 ASSERT(free_list_.previous_ != &free_list_);
262
263 size = (size + kPointerSize - 1) & ~(kPointerSize - 1);
264 // Search for exact fit.
265 for (PreallocatedStorage* storage = free_list_.next_;
266 storage != &free_list_;
267 storage = storage->next_) {
268 if (storage->size_ == size) {
269 storage->Unlink();
270 storage->LinkTo(&in_use_list_);
271 return reinterpret_cast<void*>(storage + 1);
272 }
273 }
274 // Search for first fit.
275 for (PreallocatedStorage* storage = free_list_.next_;
276 storage != &free_list_;
277 storage = storage->next_) {
278 if (storage->size_ >= size + sizeof(PreallocatedStorage)) {
279 storage->Unlink();
280 storage->LinkTo(&in_use_list_);
281 PreallocatedStorage* left_over =
282 reinterpret_cast<PreallocatedStorage*>(
283 reinterpret_cast<char*>(storage + 1) + size);
284 left_over->size_ = storage->size_ - size - sizeof(PreallocatedStorage);
285 ASSERT(size + left_over->size_ + sizeof(PreallocatedStorage) ==
286 storage->size_);
287 storage->size_ = size;
288 left_over->LinkTo(&free_list_);
289 return reinterpret_cast<void*>(storage + 1);
290 }
291 }
292 // Allocation failure.
293 ASSERT(false);
294 return NULL;
295}
296
297
298// We don't attempt to coalesce.
299void Isolate::PreallocatedStorageDelete(void* p) {
300 if (p == NULL) {
301 return;
302 }
303 if (!preallocated_storage_preallocated_) {
304 FreeStoreAllocationPolicy::Delete(p);
305 return;
306 }
307 PreallocatedStorage* storage = reinterpret_cast<PreallocatedStorage*>(p) - 1;
308 ASSERT(storage->next_->previous_ == storage);
309 ASSERT(storage->previous_->next_ == storage);
310 storage->Unlink();
311 storage->LinkTo(&free_list_);
312}
313
314
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000315Isolate* Isolate::default_isolate_ = NULL;
316Thread::LocalStorageKey Isolate::isolate_key_;
317Thread::LocalStorageKey Isolate::thread_id_key_;
318Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
319Mutex* Isolate::process_wide_mutex_ = OS::CreateMutex();
320Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000321
322
323class IsolateInitializer {
324 public:
325 IsolateInitializer() {
326 Isolate::EnsureDefaultIsolate();
327 }
328};
329
330static IsolateInitializer* EnsureDefaultIsolateAllocated() {
331 // TODO(isolates): Use the system threading API to do this once?
332 static IsolateInitializer static_initializer;
333 return &static_initializer;
334}
335
336// This variable only needed to trigger static intialization.
337static IsolateInitializer* static_initializer = EnsureDefaultIsolateAllocated();
338
339
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000340
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000341
342
343Isolate::PerIsolateThreadData* Isolate::AllocatePerIsolateThreadData(
344 ThreadId thread_id) {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000345 ASSERT(!thread_id.Equals(ThreadId::Invalid()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000346 PerIsolateThreadData* per_thread = new PerIsolateThreadData(this, thread_id);
347 {
348 ScopedLock lock(process_wide_mutex_);
349 ASSERT(thread_data_table_->Lookup(this, thread_id) == NULL);
350 thread_data_table_->Insert(per_thread);
351 ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
352 }
353 return per_thread;
354}
355
356
357Isolate::PerIsolateThreadData*
358 Isolate::FindOrAllocatePerThreadDataForThisThread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000359 ThreadId thread_id = ThreadId::Current();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000360 PerIsolateThreadData* per_thread = NULL;
361 {
362 ScopedLock lock(process_wide_mutex_);
363 per_thread = thread_data_table_->Lookup(this, thread_id);
364 if (per_thread == NULL) {
365 per_thread = AllocatePerIsolateThreadData(thread_id);
366 }
367 }
368 return per_thread;
369}
370
371
lrn@chromium.org1c092762011-05-09 09:42:16 +0000372Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
373 ThreadId thread_id = ThreadId::Current();
374 PerIsolateThreadData* per_thread = NULL;
375 {
376 ScopedLock lock(process_wide_mutex_);
377 per_thread = thread_data_table_->Lookup(this, thread_id);
378 }
379 return per_thread;
380}
381
382
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000383void Isolate::EnsureDefaultIsolate() {
384 ScopedLock lock(process_wide_mutex_);
385 if (default_isolate_ == NULL) {
386 isolate_key_ = Thread::CreateThreadLocalKey();
387 thread_id_key_ = Thread::CreateThreadLocalKey();
388 per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
389 thread_data_table_ = new Isolate::ThreadDataTable();
390 default_isolate_ = new Isolate();
391 }
392 // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
393 // becase a non-null thread data may be already set.
lrn@chromium.org1c092762011-05-09 09:42:16 +0000394 if (Thread::GetThreadLocal(isolate_key_) == NULL) {
395 Thread::SetThreadLocal(isolate_key_, default_isolate_);
396 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000397}
398
399
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000400#ifdef ENABLE_DEBUGGER_SUPPORT
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000401Debugger* Isolate::GetDefaultIsolateDebugger() {
402 EnsureDefaultIsolate();
403 return default_isolate_->debugger();
404}
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000405#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000406
407
408StackGuard* Isolate::GetDefaultIsolateStackGuard() {
409 EnsureDefaultIsolate();
410 return default_isolate_->stack_guard();
411}
412
413
414void Isolate::EnterDefaultIsolate() {
415 EnsureDefaultIsolate();
416 ASSERT(default_isolate_ != NULL);
417
418 PerIsolateThreadData* data = CurrentPerIsolateThreadData();
419 // If not yet in default isolate - enter it.
420 if (data == NULL || data->isolate() != default_isolate_) {
421 default_isolate_->Enter();
422 }
423}
424
425
426Isolate* Isolate::GetDefaultIsolateForLocking() {
427 EnsureDefaultIsolate();
428 return default_isolate_;
429}
430
431
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000432Address Isolate::get_address_from_id(Isolate::AddressId id) {
433 return isolate_addresses_[id];
434}
435
436
437char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
438 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
439 Iterate(v, thread);
440 return thread_storage + sizeof(ThreadLocalTop);
441}
442
443
444void Isolate::IterateThread(ThreadVisitor* v) {
445 v->VisitThread(this, thread_local_top());
446}
447
448
449void Isolate::IterateThread(ThreadVisitor* v, char* t) {
450 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
451 v->VisitThread(this, thread);
452}
453
454
455void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
456 // Visit the roots from the top for a given thread.
457 Object* pending;
458 // The pending exception can sometimes be a failure. We can't show
459 // that to the GC, which only understands objects.
460 if (thread->pending_exception_->ToObject(&pending)) {
461 v->VisitPointer(&pending);
462 thread->pending_exception_ = pending; // In case GC updated it.
463 }
464 v->VisitPointer(&(thread->pending_message_obj_));
465 v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
466 v->VisitPointer(BitCast<Object**>(&(thread->context_)));
467 Object* scheduled;
468 if (thread->scheduled_exception_->ToObject(&scheduled)) {
469 v->VisitPointer(&scheduled);
470 thread->scheduled_exception_ = scheduled;
471 }
472
473 for (v8::TryCatch* block = thread->TryCatchHandler();
474 block != NULL;
475 block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
476 v->VisitPointer(BitCast<Object**>(&(block->exception_)));
477 v->VisitPointer(BitCast<Object**>(&(block->message_)));
478 }
479
480 // Iterate over pointers on native execution stack.
481 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
482 it.frame()->Iterate(v);
483 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +0000484
485 // Iterate pointers in live lookup results.
486 thread->top_lookup_result_->Iterate(v);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000487}
488
489
490void Isolate::Iterate(ObjectVisitor* v) {
491 ThreadLocalTop* current_t = thread_local_top();
492 Iterate(v, current_t);
493}
494
495
496void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
497 // The ARM simulator has a separate JS stack. We therefore register
498 // the C++ try catch handler with the simulator and get back an
499 // address that can be used for comparisons with addresses into the
500 // JS stack. When running without the simulator, the address
501 // returned will be the address of the C++ try catch handler itself.
502 Address address = reinterpret_cast<Address>(
503 SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
504 thread_local_top()->set_try_catch_handler_address(address);
505}
506
507
508void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
509 ASSERT(thread_local_top()->TryCatchHandler() == that);
510 thread_local_top()->set_try_catch_handler_address(
511 reinterpret_cast<Address>(that->next_));
512 thread_local_top()->catcher_ = NULL;
513 SimulatorStack::UnregisterCTryCatch();
514}
515
516
517Handle<String> Isolate::StackTraceString() {
518 if (stack_trace_nesting_level_ == 0) {
519 stack_trace_nesting_level_++;
520 HeapStringAllocator allocator;
521 StringStream::ClearMentionedObjectCache();
522 StringStream accumulator(&allocator);
523 incomplete_message_ = &accumulator;
524 PrintStack(&accumulator);
525 Handle<String> stack_trace = accumulator.ToString();
526 incomplete_message_ = NULL;
527 stack_trace_nesting_level_ = 0;
528 return stack_trace;
529 } else if (stack_trace_nesting_level_ == 1) {
530 stack_trace_nesting_level_++;
531 OS::PrintError(
532 "\n\nAttempt to print stack while printing stack (double fault)\n");
533 OS::PrintError(
534 "If you are lucky you may find a partial stack dump on stdout.\n\n");
535 incomplete_message_->OutputToStdOut();
536 return factory()->empty_symbol();
537 } else {
538 OS::Abort();
539 // Unreachable
540 return factory()->empty_symbol();
541 }
542}
543
544
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +0000545void Isolate::CaptureAndSetCurrentStackTraceFor(Handle<JSObject> error_object) {
546 if (capture_stack_trace_for_uncaught_exceptions_) {
547 // Capture stack trace for a detailed exception message.
548 Handle<String> key = factory()->hidden_stack_trace_symbol();
549 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
550 stack_trace_for_uncaught_exceptions_frame_limit_,
551 stack_trace_for_uncaught_exceptions_options_);
552 JSObject::SetHiddenProperty(error_object, key, stack_trace);
553 }
554}
555
556
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000557Handle<JSArray> Isolate::CaptureCurrentStackTrace(
558 int frame_limit, StackTrace::StackTraceOptions options) {
559 // Ensure no negative values.
560 int limit = Max(frame_limit, 0);
561 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
562
563 Handle<String> column_key = factory()->LookupAsciiSymbol("column");
564 Handle<String> line_key = factory()->LookupAsciiSymbol("lineNumber");
565 Handle<String> script_key = factory()->LookupAsciiSymbol("scriptName");
566 Handle<String> name_or_source_url_key =
567 factory()->LookupAsciiSymbol("nameOrSourceURL");
568 Handle<String> script_name_or_source_url_key =
569 factory()->LookupAsciiSymbol("scriptNameOrSourceURL");
570 Handle<String> function_key = factory()->LookupAsciiSymbol("functionName");
571 Handle<String> eval_key = factory()->LookupAsciiSymbol("isEval");
572 Handle<String> constructor_key =
573 factory()->LookupAsciiSymbol("isConstructor");
574
575 StackTraceFrameIterator it(this);
576 int frames_seen = 0;
577 while (!it.done() && (frames_seen < limit)) {
578 JavaScriptFrame* frame = it.frame();
579 // Set initial size to the maximum inlining level + 1 for the outermost
580 // function.
581 List<FrameSummary> frames(Compiler::kMaxInliningLevels + 1);
582 frame->Summarize(&frames);
583 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
584 // Create a JSObject to hold the information for the StackFrame.
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000585 Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000586
587 Handle<JSFunction> fun = frames[i].function();
588 Handle<Script> script(Script::cast(fun->shared()->script()));
589
590 if (options & StackTrace::kLineNumber) {
591 int script_line_offset = script->line_offset()->value();
592 int position = frames[i].code()->SourcePosition(frames[i].pc());
593 int line_number = GetScriptLineNumber(script, position);
594 // line_number is already shifted by the script_line_offset.
595 int relative_line_number = line_number - script_line_offset;
596 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
597 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
598 int start = (relative_line_number == 0) ? 0 :
599 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
600 int column_offset = position - start;
601 if (relative_line_number == 0) {
602 // For the case where the code is on the same line as the script
603 // tag.
604 column_offset += script->column_offset()->value();
605 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000606 CHECK_NOT_EMPTY_HANDLE(
607 this,
608 JSObject::SetLocalPropertyIgnoreAttributes(
609 stack_frame, column_key,
610 Handle<Smi>(Smi::FromInt(column_offset + 1)), NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000611 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000612 CHECK_NOT_EMPTY_HANDLE(
613 this,
614 JSObject::SetLocalPropertyIgnoreAttributes(
615 stack_frame, line_key,
616 Handle<Smi>(Smi::FromInt(line_number + 1)), NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000617 }
618
619 if (options & StackTrace::kScriptName) {
620 Handle<Object> script_name(script->name(), this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000621 CHECK_NOT_EMPTY_HANDLE(this,
622 JSObject::SetLocalPropertyIgnoreAttributes(
623 stack_frame, script_key, script_name, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000624 }
625
626 if (options & StackTrace::kScriptNameOrSourceURL) {
627 Handle<Object> script_name(script->name(), this);
628 Handle<JSValue> script_wrapper = GetScriptWrapper(script);
629 Handle<Object> property = GetProperty(script_wrapper,
630 name_or_source_url_key);
631 ASSERT(property->IsJSFunction());
632 Handle<JSFunction> method = Handle<JSFunction>::cast(property);
633 bool caught_exception;
634 Handle<Object> result = Execution::TryCall(method, script_wrapper, 0,
635 NULL, &caught_exception);
636 if (caught_exception) {
637 result = factory()->undefined_value();
638 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000639 CHECK_NOT_EMPTY_HANDLE(this,
640 JSObject::SetLocalPropertyIgnoreAttributes(
641 stack_frame, script_name_or_source_url_key,
642 result, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000643 }
644
645 if (options & StackTrace::kFunctionName) {
646 Handle<Object> fun_name(fun->shared()->name(), this);
647 if (fun_name->ToBoolean()->IsFalse()) {
648 fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
649 }
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000650 CHECK_NOT_EMPTY_HANDLE(this,
651 JSObject::SetLocalPropertyIgnoreAttributes(
652 stack_frame, function_key, fun_name, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000653 }
654
655 if (options & StackTrace::kIsEval) {
656 int type = Smi::cast(script->compilation_type())->value();
657 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
658 factory()->true_value() : factory()->false_value();
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000659 CHECK_NOT_EMPTY_HANDLE(this,
660 JSObject::SetLocalPropertyIgnoreAttributes(
661 stack_frame, eval_key, is_eval, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000662 }
663
664 if (options & StackTrace::kIsConstructor) {
665 Handle<Object> is_constructor = (frames[i].is_constructor()) ?
666 factory()->true_value() : factory()->false_value();
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000667 CHECK_NOT_EMPTY_HANDLE(this,
668 JSObject::SetLocalPropertyIgnoreAttributes(
669 stack_frame, constructor_key,
670 is_constructor, NONE));
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000671 }
672
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +0000673 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000674 frames_seen++;
675 }
676 it.Advance();
677 }
678
679 stack_trace->set_length(Smi::FromInt(frames_seen));
680 return stack_trace;
681}
682
683
684void Isolate::PrintStack() {
685 if (stack_trace_nesting_level_ == 0) {
686 stack_trace_nesting_level_++;
687
688 StringAllocator* allocator;
689 if (preallocated_message_space_ == NULL) {
690 allocator = new HeapStringAllocator();
691 } else {
692 allocator = preallocated_message_space_;
693 }
694
695 StringStream::ClearMentionedObjectCache();
696 StringStream accumulator(allocator);
697 incomplete_message_ = &accumulator;
698 PrintStack(&accumulator);
699 accumulator.OutputToStdOut();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +0000700 InitializeLoggingAndCounters();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000701 accumulator.Log();
702 incomplete_message_ = NULL;
703 stack_trace_nesting_level_ = 0;
704 if (preallocated_message_space_ == NULL) {
705 // Remove the HeapStringAllocator created above.
706 delete allocator;
707 }
708 } else if (stack_trace_nesting_level_ == 1) {
709 stack_trace_nesting_level_++;
710 OS::PrintError(
711 "\n\nAttempt to print stack while printing stack (double fault)\n");
712 OS::PrintError(
713 "If you are lucky you may find a partial stack dump on stdout.\n\n");
714 incomplete_message_->OutputToStdOut();
715 }
716}
717
718
719static void PrintFrames(StringStream* accumulator,
720 StackFrame::PrintMode mode) {
721 StackFrameIterator it;
722 for (int i = 0; !it.done(); it.Advance()) {
723 it.frame()->Print(accumulator, mode, i++);
724 }
725}
726
727
728void Isolate::PrintStack(StringStream* accumulator) {
729 if (!IsInitialized()) {
730 accumulator->Add(
731 "\n==== Stack trace is not available ==========================\n\n");
732 accumulator->Add(
733 "\n==== Isolate for the thread is not initialized =============\n\n");
734 return;
735 }
736 // The MentionedObjectCache is not GC-proof at the moment.
737 AssertNoAllocation nogc;
738 ASSERT(StringStream::IsMentionedObjectCacheClear());
739
740 // Avoid printing anything if there are no frames.
741 if (c_entry_fp(thread_local_top()) == 0) return;
742
743 accumulator->Add(
744 "\n==== Stack trace ============================================\n\n");
745 PrintFrames(accumulator, StackFrame::OVERVIEW);
746
747 accumulator->Add(
748 "\n==== Details ================================================\n\n");
749 PrintFrames(accumulator, StackFrame::DETAILS);
750
751 accumulator->PrintMentionedObjectCache();
752 accumulator->Add("=====================\n\n");
753}
754
755
756void Isolate::SetFailedAccessCheckCallback(
757 v8::FailedAccessCheckCallback callback) {
758 thread_local_top()->failed_access_check_callback_ = callback;
759}
760
761
762void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
763 if (!thread_local_top()->failed_access_check_callback_) return;
764
765 ASSERT(receiver->IsAccessCheckNeeded());
766 ASSERT(context());
767
768 // Get the data object from access check info.
769 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
770 if (!constructor->shared()->IsApiFunction()) return;
771 Object* data_obj =
772 constructor->shared()->get_api_func_data()->access_check_info();
773 if (data_obj == heap_.undefined_value()) return;
774
775 HandleScope scope;
776 Handle<JSObject> receiver_handle(receiver);
777 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
jkummerow@chromium.orgf7a58842012-02-21 10:08:21 +0000778 { VMState state(this, EXTERNAL);
779 thread_local_top()->failed_access_check_callback_(
780 v8::Utils::ToLocal(receiver_handle),
781 type,
782 v8::Utils::ToLocal(data));
783 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000784}
785
786
787enum MayAccessDecision {
788 YES, NO, UNKNOWN
789};
790
791
792static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
793 JSObject* receiver,
794 v8::AccessType type) {
795 // During bootstrapping, callback functions are not enabled yet.
796 if (isolate->bootstrapper()->IsActive()) return YES;
797
798 if (receiver->IsJSGlobalProxy()) {
799 Object* receiver_context = JSGlobalProxy::cast(receiver)->context();
800 if (!receiver_context->IsContext()) return NO;
801
802 // Get the global context of current top context.
803 // avoid using Isolate::global_context() because it uses Handle.
804 Context* global_context = isolate->context()->global()->global_context();
805 if (receiver_context == global_context) return YES;
806
807 if (Context::cast(receiver_context)->security_token() ==
808 global_context->security_token())
809 return YES;
810 }
811
812 return UNKNOWN;
813}
814
815
816bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
817 v8::AccessType type) {
818 ASSERT(receiver->IsAccessCheckNeeded());
819
820 // The callers of this method are not expecting a GC.
821 AssertNoAllocation no_gc;
822
823 // Skip checks for hidden properties access. Note, we do not
824 // require existence of a context in this case.
825 if (key == heap_.hidden_symbol()) return true;
826
827 // Check for compatibility between the security tokens in the
828 // current lexical context and the accessed object.
829 ASSERT(context());
830
831 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
832 if (decision != UNKNOWN) return decision == YES;
833
834 // Get named access check callback
835 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
836 if (!constructor->shared()->IsApiFunction()) return false;
837
838 Object* data_obj =
839 constructor->shared()->get_api_func_data()->access_check_info();
840 if (data_obj == heap_.undefined_value()) return false;
841
842 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
843 v8::NamedSecurityCallback callback =
844 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
845
846 if (!callback) return false;
847
848 HandleScope scope(this);
849 Handle<JSObject> receiver_handle(receiver, this);
850 Handle<Object> key_handle(key, this);
851 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
852 LOG(this, ApiNamedSecurityCheck(key));
853 bool result = false;
854 {
855 // Leaving JavaScript.
856 VMState state(this, EXTERNAL);
857 result = callback(v8::Utils::ToLocal(receiver_handle),
858 v8::Utils::ToLocal(key_handle),
859 type,
860 v8::Utils::ToLocal(data));
861 }
862 return result;
863}
864
865
866bool Isolate::MayIndexedAccess(JSObject* receiver,
867 uint32_t index,
868 v8::AccessType type) {
869 ASSERT(receiver->IsAccessCheckNeeded());
870 // Check for compatibility between the security tokens in the
871 // current lexical context and the accessed object.
872 ASSERT(context());
873
874 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
875 if (decision != UNKNOWN) return decision == YES;
876
877 // Get indexed access check callback
878 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
879 if (!constructor->shared()->IsApiFunction()) return false;
880
881 Object* data_obj =
882 constructor->shared()->get_api_func_data()->access_check_info();
883 if (data_obj == heap_.undefined_value()) return false;
884
885 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
886 v8::IndexedSecurityCallback callback =
887 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
888
889 if (!callback) return false;
890
891 HandleScope scope(this);
892 Handle<JSObject> receiver_handle(receiver, this);
893 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
894 LOG(this, ApiIndexedSecurityCheck(index));
895 bool result = false;
896 {
897 // Leaving JavaScript.
898 VMState state(this, EXTERNAL);
899 result = callback(v8::Utils::ToLocal(receiver_handle),
900 index,
901 type,
902 v8::Utils::ToLocal(data));
903 }
904 return result;
905}
906
907
908const char* const Isolate::kStackOverflowMessage =
909 "Uncaught RangeError: Maximum call stack size exceeded";
910
911
912Failure* Isolate::StackOverflow() {
913 HandleScope scope;
914 Handle<String> key = factory()->stack_overflow_symbol();
915 Handle<JSObject> boilerplate =
916 Handle<JSObject>::cast(GetProperty(js_builtins_object(), key));
917 Handle<Object> exception = Copy(boilerplate);
918 // TODO(1240995): To avoid having to call JavaScript code to compute
919 // the message for stack overflow exceptions which is very likely to
920 // double fault with another stack overflow exception, we use a
921 // precomputed message.
922 DoThrow(*exception, NULL);
923 return Failure::Exception();
924}
925
926
927Failure* Isolate::TerminateExecution() {
928 DoThrow(heap_.termination_exception(), NULL);
929 return Failure::Exception();
930}
931
932
933Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
934 DoThrow(exception, location);
935 return Failure::Exception();
936}
937
938
939Failure* Isolate::ReThrow(MaybeObject* exception, MessageLocation* location) {
940 bool can_be_caught_externally = false;
ager@chromium.orgea91cc52011-05-23 06:06:11 +0000941 bool catchable_by_javascript = is_catchable_by_javascript(exception);
942 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
943
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000944 thread_local_top()->catcher_ = can_be_caught_externally ?
945 try_catch_handler() : NULL;
946
947 // Set the exception being re-thrown.
948 set_pending_exception(exception);
ager@chromium.orgea91cc52011-05-23 06:06:11 +0000949 if (exception->IsFailure()) return exception->ToFailureUnchecked();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000950 return Failure::Exception();
951}
952
953
954Failure* Isolate::ThrowIllegalOperation() {
955 return Throw(heap_.illegal_access_symbol());
956}
957
958
959void Isolate::ScheduleThrow(Object* exception) {
960 // When scheduling a throw we first throw the exception to get the
961 // error reporting if it is uncaught before rescheduling it.
962 Throw(exception);
963 thread_local_top()->scheduled_exception_ = pending_exception();
964 thread_local_top()->external_caught_exception_ = false;
965 clear_pending_exception();
966}
967
968
969Failure* Isolate::PromoteScheduledException() {
970 MaybeObject* thrown = scheduled_exception();
971 clear_scheduled_exception();
972 // Re-throw the exception to avoid getting repeated error reporting.
973 return ReThrow(thrown);
974}
975
976
977void Isolate::PrintCurrentStackTrace(FILE* out) {
978 StackTraceFrameIterator it(this);
979 while (!it.done()) {
980 HandleScope scope;
981 // Find code position if recorded in relocation info.
982 JavaScriptFrame* frame = it.frame();
983 int pos = frame->LookupCode()->SourcePosition(frame->pc());
984 Handle<Object> pos_obj(Smi::FromInt(pos));
985 // Fetch function and receiver.
986 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
987 Handle<Object> recv(frame->receiver());
988 // Advance to the next JavaScript frame and determine if the
989 // current frame is the top-level frame.
990 it.Advance();
991 Handle<Object> is_top_level = it.done()
992 ? factory()->true_value()
993 : factory()->false_value();
994 // Generate and print stack trace line.
995 Handle<String> line =
996 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
997 if (line->length() > 0) {
998 line->PrintOn(out);
999 fprintf(out, "\n");
1000 }
1001 }
1002}
1003
1004
1005void Isolate::ComputeLocation(MessageLocation* target) {
1006 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1007 StackTraceFrameIterator it(this);
1008 if (!it.done()) {
1009 JavaScriptFrame* frame = it.frame();
1010 JSFunction* fun = JSFunction::cast(frame->function());
1011 Object* script = fun->shared()->script();
1012 if (script->IsScript() &&
1013 !(Script::cast(script)->source()->IsUndefined())) {
1014 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1015 // Compute the location from the function and the reloc info.
1016 Handle<Script> casted_script(Script::cast(script));
1017 *target = MessageLocation(casted_script, pos, pos + 1);
1018 }
1019 }
1020}
1021
1022
1023bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1024 bool catchable_by_javascript) {
1025 // Find the top-most try-catch handler.
1026 StackHandler* handler =
1027 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001028 while (handler != NULL && !handler->is_catch()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001029 handler = handler->next();
1030 }
1031
1032 // Get the address of the external handler so we can compare the address to
1033 // determine which one is closer to the top of the stack.
1034 Address external_handler_address =
1035 thread_local_top()->try_catch_handler_address();
1036
1037 // The exception has been externally caught if and only if there is
1038 // an external handler which is on top of the top-most try-catch
1039 // handler.
1040 *can_be_caught_externally = external_handler_address != NULL &&
1041 (handler == NULL || handler->address() > external_handler_address ||
1042 !catchable_by_javascript);
1043
1044 if (*can_be_caught_externally) {
1045 // Only report the exception if the external handler is verbose.
1046 return try_catch_handler()->is_verbose_;
1047 } else {
1048 // Report the exception if it isn't caught by JavaScript code.
1049 return handler == NULL;
1050 }
1051}
1052
1053
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001054bool Isolate::IsErrorObject(Handle<Object> obj) {
1055 if (!obj->IsJSObject()) return false;
1056
1057 String* error_key = *(factory()->LookupAsciiSymbol("$Error"));
1058 Object* error_constructor =
1059 js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1060
1061 for (Object* prototype = *obj; !prototype->IsNull();
1062 prototype = prototype->GetPrototype()) {
1063 if (!prototype->IsJSObject()) return false;
1064 if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1065 return true;
1066 }
1067 }
1068 return false;
1069}
1070
1071
1072void Isolate::DoThrow(Object* exception, MessageLocation* location) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001073 ASSERT(!has_pending_exception());
1074
1075 HandleScope scope;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001076 Handle<Object> exception_handle(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001077
1078 // Determine reporting and whether the exception is caught externally.
1079 bool catchable_by_javascript = is_catchable_by_javascript(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001080 bool can_be_caught_externally = false;
1081 bool should_report_exception =
1082 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1083 bool report_exception = catchable_by_javascript && should_report_exception;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001084 bool try_catch_needs_message =
1085 can_be_caught_externally && try_catch_handler()->capture_message_;
1086 bool bootstrapping = bootstrapper()->IsActive();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001087
1088#ifdef ENABLE_DEBUGGER_SUPPORT
1089 // Notify debugger of exception.
1090 if (catchable_by_javascript) {
1091 debugger_->OnException(exception_handle, report_exception);
1092 }
1093#endif
1094
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001095 // Generate the message if required.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001096 if (report_exception || try_catch_needs_message) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001097 MessageLocation potential_computed_location;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001098 if (location == NULL) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001099 // If no location was specified we use a computed one instead.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001100 ComputeLocation(&potential_computed_location);
1101 location = &potential_computed_location;
1102 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001103 // It's not safe to try to make message objects or collect stack traces
1104 // while the bootstrapper is active since the infrastructure may not have
1105 // been properly initialized.
1106 if (!bootstrapping) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001107 Handle<String> stack_trace;
1108 if (FLAG_trace_exception) stack_trace = StackTraceString();
1109 Handle<JSArray> stack_trace_object;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001110 if (capture_stack_trace_for_uncaught_exceptions_) {
1111 if (IsErrorObject(exception_handle)) {
1112 // We fetch the stack trace that corresponds to this error object.
1113 String* key = heap()->hidden_stack_trace_symbol();
1114 Object* stack_property =
1115 JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1116 // Property lookup may have failed. In this case it's probably not
1117 // a valid Error object.
1118 if (stack_property->IsJSArray()) {
1119 stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1120 }
1121 }
1122 if (stack_trace_object.is_null()) {
1123 // Not an error object, we capture at throw site.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001124 stack_trace_object = CaptureCurrentStackTrace(
1125 stack_trace_for_uncaught_exceptions_frame_limit_,
1126 stack_trace_for_uncaught_exceptions_options_);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001127 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001128 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001129 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1130 "uncaught_exception",
1131 location,
1132 HandleVector<Object>(&exception_handle, 1),
1133 stack_trace,
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001134 stack_trace_object);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001135 thread_local_top()->pending_message_obj_ = *message_obj;
1136 if (location != NULL) {
1137 thread_local_top()->pending_message_script_ = *location->script();
1138 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1139 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1140 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +00001141 } else if (location != NULL && !location->script().is_null()) {
1142 // We are bootstrapping and caught an error where the location is set
1143 // and we have a script for the location.
1144 // In this case we could have an extension (or an internal error
1145 // somewhere) and we print out the line number at which the error occured
1146 // to the console for easier debugging.
1147 int line_number = GetScriptLineNumberSafe(location->script(),
1148 location->start_pos());
1149 OS::PrintError("Extension or internal compilation error at line %d.\n",
1150 line_number);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001151 }
1152 }
1153
1154 // Save the message for reporting if the the exception remains uncaught.
1155 thread_local_top()->has_pending_message_ = report_exception;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001156
1157 // Do not forget to clean catcher_ if currently thrown exception cannot
1158 // be caught. If necessary, ReThrow will update the catcher.
1159 thread_local_top()->catcher_ = can_be_caught_externally ?
1160 try_catch_handler() : NULL;
1161
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001162 set_pending_exception(*exception_handle);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001163}
1164
1165
1166bool Isolate::IsExternallyCaught() {
1167 ASSERT(has_pending_exception());
1168
1169 if ((thread_local_top()->catcher_ == NULL) ||
1170 (try_catch_handler() != thread_local_top()->catcher_)) {
1171 // When throwing the exception, we found no v8::TryCatch
1172 // which should care about this exception.
1173 return false;
1174 }
1175
1176 if (!is_catchable_by_javascript(pending_exception())) {
1177 return true;
1178 }
1179
1180 // Get the address of the external handler so we can compare the address to
1181 // determine which one is closer to the top of the stack.
1182 Address external_handler_address =
1183 thread_local_top()->try_catch_handler_address();
1184 ASSERT(external_handler_address != NULL);
1185
1186 // The exception has been externally caught if and only if there is
1187 // an external handler which is on top of the top-most try-finally
1188 // handler.
1189 // There should be no try-catch blocks as they would prohibit us from
1190 // finding external catcher in the first place (see catcher_ check above).
1191 //
1192 // Note, that finally clause would rethrow an exception unless it's
1193 // aborted by jumps in control flow like return, break, etc. and we'll
1194 // have another chances to set proper v8::TryCatch.
1195 StackHandler* handler =
1196 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1197 while (handler != NULL && handler->address() < external_handler_address) {
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001198 ASSERT(!handler->is_catch());
1199 if (handler->is_finally()) return false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001200
1201 handler = handler->next();
1202 }
1203
1204 return true;
1205}
1206
1207
1208void Isolate::ReportPendingMessages() {
1209 ASSERT(has_pending_exception());
1210 PropagatePendingExceptionToExternalTryCatch();
1211
1212 // If the pending exception is OutOfMemoryException set out_of_memory in
1213 // the global context. Note: We have to mark the global context here
1214 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1215 // set it.
1216 HandleScope scope;
1217 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1218 context()->mark_out_of_memory();
1219 } else if (thread_local_top_.pending_exception_ ==
1220 heap()->termination_exception()) {
1221 // Do nothing: if needed, the exception has been already propagated to
1222 // v8::TryCatch.
1223 } else {
1224 if (thread_local_top_.has_pending_message_) {
1225 thread_local_top_.has_pending_message_ = false;
1226 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1227 HandleScope scope;
1228 Handle<Object> message_obj(thread_local_top_.pending_message_obj_);
1229 if (thread_local_top_.pending_message_script_ != NULL) {
1230 Handle<Script> script(thread_local_top_.pending_message_script_);
1231 int start_pos = thread_local_top_.pending_message_start_pos_;
1232 int end_pos = thread_local_top_.pending_message_end_pos_;
1233 MessageLocation location(script, start_pos, end_pos);
1234 MessageHandler::ReportMessage(this, &location, message_obj);
1235 } else {
1236 MessageHandler::ReportMessage(this, NULL, message_obj);
1237 }
1238 }
1239 }
1240 }
1241 clear_pending_message();
1242}
1243
1244
1245void Isolate::TraceException(bool flag) {
1246 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1247}
1248
1249
1250bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1251 ASSERT(has_pending_exception());
1252 PropagatePendingExceptionToExternalTryCatch();
1253
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001254 // Always reschedule out of memory exceptions.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001255 if (!is_out_of_memory()) {
1256 bool is_termination_exception =
1257 pending_exception() == heap_.termination_exception();
1258
1259 // Do not reschedule the exception if this is the bottom call.
1260 bool clear_exception = is_bottom_call;
1261
1262 if (is_termination_exception) {
1263 if (is_bottom_call) {
1264 thread_local_top()->external_caught_exception_ = false;
1265 clear_pending_exception();
1266 return false;
1267 }
1268 } else if (thread_local_top()->external_caught_exception_) {
1269 // If the exception is externally caught, clear it if there are no
1270 // JavaScript frames on the way to the C++ frame that has the
1271 // external handler.
1272 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1273 Address external_handler_address =
1274 thread_local_top()->try_catch_handler_address();
1275 JavaScriptFrameIterator it;
1276 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1277 clear_exception = true;
1278 }
1279 }
1280
1281 // Clear the exception if needed.
1282 if (clear_exception) {
1283 thread_local_top()->external_caught_exception_ = false;
1284 clear_pending_exception();
1285 return false;
1286 }
1287 }
1288
1289 // Reschedule the exception.
1290 thread_local_top()->scheduled_exception_ = pending_exception();
1291 clear_pending_exception();
1292 return true;
1293}
1294
1295
1296void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1297 bool capture,
1298 int frame_limit,
1299 StackTrace::StackTraceOptions options) {
1300 capture_stack_trace_for_uncaught_exceptions_ = capture;
1301 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1302 stack_trace_for_uncaught_exceptions_options_ = options;
1303}
1304
1305
1306bool Isolate::is_out_of_memory() {
1307 if (has_pending_exception()) {
1308 MaybeObject* e = pending_exception();
1309 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1310 return true;
1311 }
1312 }
1313 if (has_scheduled_exception()) {
1314 MaybeObject* e = scheduled_exception();
1315 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1316 return true;
1317 }
1318 }
1319 return false;
1320}
1321
1322
1323Handle<Context> Isolate::global_context() {
1324 GlobalObject* global = thread_local_top()->context_->global();
1325 return Handle<Context>(global->global_context());
1326}
1327
1328
1329Handle<Context> Isolate::GetCallingGlobalContext() {
1330 JavaScriptFrameIterator it;
1331#ifdef ENABLE_DEBUGGER_SUPPORT
1332 if (debug_->InDebugger()) {
1333 while (!it.done()) {
1334 JavaScriptFrame* frame = it.frame();
1335 Context* context = Context::cast(frame->context());
1336 if (context->global_context() == *debug_->debug_context()) {
1337 it.Advance();
1338 } else {
1339 break;
1340 }
1341 }
1342 }
1343#endif // ENABLE_DEBUGGER_SUPPORT
1344 if (it.done()) return Handle<Context>::null();
1345 JavaScriptFrame* frame = it.frame();
1346 Context* context = Context::cast(frame->context());
1347 return Handle<Context>(context->global_context());
1348}
1349
1350
1351char* Isolate::ArchiveThread(char* to) {
1352 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1353 RuntimeProfiler::IsolateExitedJS(this);
1354 }
1355 memcpy(to, reinterpret_cast<char*>(thread_local_top()),
1356 sizeof(ThreadLocalTop));
1357 InitializeThreadLocal();
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001358 clear_pending_exception();
1359 clear_pending_message();
1360 clear_scheduled_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001361 return to + sizeof(ThreadLocalTop);
1362}
1363
1364
1365char* Isolate::RestoreThread(char* from) {
1366 memcpy(reinterpret_cast<char*>(thread_local_top()), from,
1367 sizeof(ThreadLocalTop));
1368 // This might be just paranoia, but it seems to be needed in case a
1369 // thread_local_top_ is restored on a separate OS thread.
1370#ifdef USE_SIMULATOR
1371#ifdef V8_TARGET_ARCH_ARM
1372 thread_local_top()->simulator_ = Simulator::current(this);
1373#elif V8_TARGET_ARCH_MIPS
1374 thread_local_top()->simulator_ = Simulator::current(this);
1375#endif
1376#endif
1377 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1378 RuntimeProfiler::IsolateEnteredJS(this);
1379 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001380 ASSERT(context() == NULL || context()->IsContext());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001381 return from + sizeof(ThreadLocalTop);
1382}
1383
1384
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001385Isolate::ThreadDataTable::ThreadDataTable()
1386 : list_(NULL) {
1387}
1388
1389
1390Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001391 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1392 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001393 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1394 if (data->Matches(isolate, thread_id)) return data;
1395 }
1396 return NULL;
1397}
1398
1399
1400void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1401 if (list_ != NULL) list_->prev_ = data;
1402 data->next_ = list_;
1403 list_ = data;
1404}
1405
1406
1407void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1408 if (list_ == data) list_ = data->next_;
1409 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1410 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001411 delete data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001412}
1413
1414
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001415void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1416 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001417 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1418 if (data != NULL) {
1419 Remove(data);
1420 }
1421}
1422
1423
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001424void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1425 PerIsolateThreadData* data = list_;
1426 while (data != NULL) {
1427 PerIsolateThreadData* next = data->next_;
1428 if (data->isolate() == isolate) Remove(data);
1429 data = next;
1430 }
1431}
1432
1433
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001434#ifdef DEBUG
1435#define TRACE_ISOLATE(tag) \
1436 do { \
1437 if (FLAG_trace_isolates) { \
1438 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
1439 } \
1440 } while (false)
1441#else
1442#define TRACE_ISOLATE(tag)
1443#endif
1444
1445
1446Isolate::Isolate()
1447 : state_(UNINITIALIZED),
1448 entry_stack_(NULL),
1449 stack_trace_nesting_level_(0),
1450 incomplete_message_(NULL),
1451 preallocated_memory_thread_(NULL),
1452 preallocated_message_space_(NULL),
1453 bootstrapper_(NULL),
1454 runtime_profiler_(NULL),
1455 compilation_cache_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001456 counters_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001457 code_range_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001458 // Must be initialized early to allow v8::SetResourceConstraints calls.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001459 break_access_(OS::CreateMutex()),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001460 debugger_initialized_(false),
1461 // Must be initialized early to allow v8::Debug calls.
1462 debugger_access_(OS::CreateMutex()),
1463 logger_(NULL),
1464 stats_table_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001465 stub_cache_(NULL),
1466 deoptimizer_data_(NULL),
1467 capture_stack_trace_for_uncaught_exceptions_(false),
1468 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1469 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1470 transcendental_cache_(NULL),
1471 memory_allocator_(NULL),
1472 keyed_lookup_cache_(NULL),
1473 context_slot_cache_(NULL),
1474 descriptor_lookup_cache_(NULL),
1475 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001476 unicode_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001477 in_use_list_(0),
1478 free_list_(0),
1479 preallocated_storage_preallocated_(false),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001480 inner_pointer_to_code_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001481 write_input_buffer_(NULL),
1482 global_handles_(NULL),
1483 context_switcher_(NULL),
1484 thread_manager_(NULL),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001485 fp_stubs_generated_(false),
ricow@chromium.org27bf2882011-11-17 08:34:43 +00001486 has_installed_extensions_(false),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001487 string_tracker_(NULL),
1488 regexp_stack_(NULL),
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001489 embedder_data_(NULL),
1490 context_exit_happened_(false) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001491 TRACE_ISOLATE(constructor);
1492
1493 memset(isolate_addresses_, 0,
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001494 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001495
1496 heap_.isolate_ = this;
1497 zone_.isolate_ = this;
1498 stack_guard_.isolate_ = this;
1499
lrn@chromium.org1c092762011-05-09 09:42:16 +00001500 // ThreadManager is initialized early to support locking an isolate
1501 // before it is entered.
1502 thread_manager_ = new ThreadManager();
1503 thread_manager_->isolate_ = this;
1504
lrn@chromium.org7516f052011-03-30 08:52:27 +00001505#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
1506 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001507 simulator_initialized_ = false;
1508 simulator_i_cache_ = NULL;
1509 simulator_redirection_ = NULL;
1510#endif
1511
1512#ifdef DEBUG
1513 // heap_histograms_ initializes itself.
1514 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1515 memset(code_kind_statistics_, 0,
1516 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
1517#endif
1518
1519#ifdef ENABLE_DEBUGGER_SUPPORT
1520 debug_ = NULL;
1521 debugger_ = NULL;
1522#endif
1523
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001524 handle_scope_data_.Initialize();
1525
1526#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1527 name##_ = (initial_value);
1528 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1529#undef ISOLATE_INIT_EXECUTE
1530
1531#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1532 memset(name##_, 0, sizeof(type) * length);
1533 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1534#undef ISOLATE_INIT_ARRAY_EXECUTE
1535}
1536
1537void Isolate::TearDown() {
1538 TRACE_ISOLATE(tear_down);
1539
1540 // Temporarily set this isolate as current so that various parts of
1541 // the isolate can access it in their destructors without having a
1542 // direct pointer. We don't use Enter/Exit here to avoid
1543 // initializing the thread data.
1544 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1545 Isolate* saved_isolate = UncheckedCurrent();
1546 SetIsolateThreadLocals(this, NULL);
1547
1548 Deinit();
1549
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001550 { ScopedLock lock(process_wide_mutex_);
1551 thread_data_table_->RemoveAllThreads(this);
1552 }
1553
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001554 if (!IsDefaultIsolate()) {
1555 delete this;
1556 }
1557
1558 // Restore the previous current isolate.
1559 SetIsolateThreadLocals(saved_isolate, saved_data);
1560}
1561
1562
1563void Isolate::Deinit() {
1564 if (state_ == INITIALIZED) {
1565 TRACE_ISOLATE(deinit);
1566
1567 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
1568
1569 // We must stop the logger before we tear down other components.
1570 logger_->EnsureTickerStopped();
1571
1572 delete deoptimizer_data_;
1573 deoptimizer_data_ = NULL;
1574 if (FLAG_preemption) {
1575 v8::Locker locker;
1576 v8::Locker::StopPreemption();
1577 }
1578 builtins_.TearDown();
1579 bootstrapper_->TearDown();
1580
1581 // Remove the external reference to the preallocated stack memory.
1582 delete preallocated_message_space_;
1583 preallocated_message_space_ = NULL;
1584 PreallocatedMemoryThreadStop();
1585
1586 HeapProfiler::TearDown();
1587 CpuProfiler::TearDown();
1588 if (runtime_profiler_ != NULL) {
1589 runtime_profiler_->TearDown();
1590 delete runtime_profiler_;
1591 runtime_profiler_ = NULL;
1592 }
1593 heap_.TearDown();
1594 logger_->TearDown();
1595
1596 // The default isolate is re-initializable due to legacy API.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001597 state_ = UNINITIALIZED;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001598 }
1599}
1600
1601
1602void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1603 PerIsolateThreadData* data) {
1604 Thread::SetThreadLocal(isolate_key_, isolate);
1605 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1606}
1607
1608
1609Isolate::~Isolate() {
1610 TRACE_ISOLATE(destructor);
1611
danno@chromium.orgb6451162011-08-17 14:33:23 +00001612 // Has to be called while counters_ are still alive.
1613 zone_.DeleteKeptSegment();
1614
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001615 delete[] assembler_spare_buffer_;
1616 assembler_spare_buffer_ = NULL;
1617
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001618 delete unicode_cache_;
1619 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001620
1621 delete regexp_stack_;
1622 regexp_stack_ = NULL;
1623
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001624 delete descriptor_lookup_cache_;
1625 descriptor_lookup_cache_ = NULL;
1626 delete context_slot_cache_;
1627 context_slot_cache_ = NULL;
1628 delete keyed_lookup_cache_;
1629 keyed_lookup_cache_ = NULL;
1630
1631 delete transcendental_cache_;
1632 transcendental_cache_ = NULL;
1633 delete stub_cache_;
1634 stub_cache_ = NULL;
1635 delete stats_table_;
1636 stats_table_ = NULL;
1637
1638 delete logger_;
1639 logger_ = NULL;
1640
1641 delete counters_;
1642 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001643
1644 delete handle_scope_implementer_;
1645 handle_scope_implementer_ = NULL;
1646 delete break_access_;
1647 break_access_ = NULL;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001648 delete debugger_access_;
1649 debugger_access_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001650
1651 delete compilation_cache_;
1652 compilation_cache_ = NULL;
1653 delete bootstrapper_;
1654 bootstrapper_ = NULL;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001655 delete inner_pointer_to_code_cache_;
1656 inner_pointer_to_code_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001657 delete write_input_buffer_;
1658 write_input_buffer_ = NULL;
1659
1660 delete context_switcher_;
1661 context_switcher_ = NULL;
1662 delete thread_manager_;
1663 thread_manager_ = NULL;
1664
1665 delete string_tracker_;
1666 string_tracker_ = NULL;
1667
1668 delete memory_allocator_;
1669 memory_allocator_ = NULL;
1670 delete code_range_;
1671 code_range_ = NULL;
1672 delete global_handles_;
1673 global_handles_ = NULL;
1674
danno@chromium.orgb6451162011-08-17 14:33:23 +00001675 delete external_reference_table_;
1676 external_reference_table_ = NULL;
1677
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001678#ifdef ENABLE_DEBUGGER_SUPPORT
1679 delete debugger_;
1680 debugger_ = NULL;
1681 delete debug_;
1682 debug_ = NULL;
1683#endif
1684}
1685
1686
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001687void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +00001688 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001689 thread_local_top_.Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001690}
1691
1692
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001693void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1694 ASSERT(has_pending_exception());
1695
1696 bool external_caught = IsExternallyCaught();
1697 thread_local_top_.external_caught_exception_ = external_caught;
1698
1699 if (!external_caught) return;
1700
1701 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1702 // Do not propagate OOM exception: we should kill VM asap.
1703 } else if (thread_local_top_.pending_exception_ ==
1704 heap()->termination_exception()) {
1705 try_catch_handler()->can_continue_ = false;
1706 try_catch_handler()->exception_ = heap()->null_value();
1707 } else {
1708 // At this point all non-object (failure) exceptions have
1709 // been dealt with so this shouldn't fail.
1710 ASSERT(!pending_exception()->IsFailure());
1711 try_catch_handler()->can_continue_ = true;
1712 try_catch_handler()->exception_ = pending_exception();
1713 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1714 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
1715 }
1716 }
1717}
1718
1719
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001720void Isolate::InitializeLoggingAndCounters() {
1721 if (logger_ == NULL) {
1722 logger_ = new Logger;
1723 }
1724 if (counters_ == NULL) {
1725 counters_ = new Counters;
1726 }
1727}
1728
1729
1730void Isolate::InitializeDebugger() {
1731#ifdef ENABLE_DEBUGGER_SUPPORT
1732 ScopedLock lock(debugger_access_);
1733 if (NoBarrier_Load(&debugger_initialized_)) return;
1734 InitializeLoggingAndCounters();
1735 debug_ = new Debug(this);
1736 debugger_ = new Debugger(this);
1737 Release_Store(&debugger_initialized_, true);
1738#endif
1739}
1740
1741
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001742bool Isolate::Init(Deserializer* des) {
1743 ASSERT(state_ != INITIALIZED);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001744 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001745 TRACE_ISOLATE(init);
1746
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001747#ifdef DEBUG
1748 // The initialization process does not handle memory exhaustion.
1749 DisallowAllocationFailure disallow_allocation_failure;
1750#endif
1751
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001752 InitializeLoggingAndCounters();
1753
1754 InitializeDebugger();
1755
1756 memory_allocator_ = new MemoryAllocator(this);
1757 code_range_ = new CodeRange(this);
1758
1759 // Safe after setting Heap::isolate_, initializing StackGuard and
1760 // ensuring that Isolate::Current() == this.
1761 heap_.SetStackLimits();
1762
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001763#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1764 isolate_addresses_[Isolate::k##CamelName##Address] = \
1765 reinterpret_cast<Address>(hacker_name##_address());
1766 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001767#undef C
1768
1769 string_tracker_ = new StringTracker();
1770 string_tracker_->isolate_ = this;
1771 compilation_cache_ = new CompilationCache(this);
1772 transcendental_cache_ = new TranscendentalCache();
1773 keyed_lookup_cache_ = new KeyedLookupCache();
1774 context_slot_cache_ = new ContextSlotCache();
1775 descriptor_lookup_cache_ = new DescriptorLookupCache();
1776 unicode_cache_ = new UnicodeCache();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001777 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001778 write_input_buffer_ = new StringInputBuffer();
1779 global_handles_ = new GlobalHandles(this);
1780 bootstrapper_ = new Bootstrapper();
1781 handle_scope_implementer_ = new HandleScopeImplementer(this);
1782 stub_cache_ = new StubCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001783 regexp_stack_ = new RegExpStack();
1784 regexp_stack_->isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001785
1786 // Enable logging before setting up the heap
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001787 logger_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001788
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001789 CpuProfiler::SetUp();
1790 HeapProfiler::SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001791
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001792 // Initialize other runtime facilities
1793#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +00001794#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
lrn@chromium.org1c092762011-05-09 09:42:16 +00001795 Simulator::Initialize(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001796#endif
1797#endif
1798
1799 { // NOLINT
1800 // Ensure that the thread has a valid stack guard. The v8::Locker object
1801 // will ensure this too, but we don't have to use lockers if we are only
1802 // using one thread.
1803 ExecutionAccess lock(this);
1804 stack_guard_.InitThread(lock);
1805 }
1806
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001807 // SetUp the object heap.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001808 const bool create_heap_objects = (des == NULL);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001809 ASSERT(!heap_.HasBeenSetUp());
1810 if (!heap_.SetUp(create_heap_objects)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001811 V8::SetFatalError();
1812 return false;
1813 }
1814
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001815 InitializeThreadLocal();
1816
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001817 bootstrapper_->Initialize(create_heap_objects);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001818 builtins_.SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001819
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001820 // Only preallocate on the first initialization.
1821 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
1822 // Start the thread which will set aside some memory.
1823 PreallocatedMemoryThreadStart();
1824 preallocated_message_space_ =
1825 new NoAllocationStringAllocator(
1826 preallocated_memory_thread_->data(),
1827 preallocated_memory_thread_->length());
1828 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
1829 }
1830
1831 if (FLAG_preemption) {
1832 v8::Locker locker;
1833 v8::Locker::StartPreemption(100);
1834 }
1835
1836#ifdef ENABLE_DEBUGGER_SUPPORT
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001837 debug_->SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001838#endif
1839 stub_cache_->Initialize(create_heap_objects);
1840
1841 // If we are deserializing, read the state into the now-empty heap.
1842 if (des != NULL) {
1843 des->Deserialize();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001844 stub_cache_->Initialize(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001845 }
1846
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001847 // Finish initialization of ThreadLocal after deserialization is done.
1848 clear_pending_exception();
1849 clear_pending_message();
1850 clear_scheduled_exception();
1851
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001852 // Deserializing may put strange things in the root array's copy of the
1853 // stack guard.
1854 heap_.SetStackLimits();
1855
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001856 deoptimizer_data_ = new DeoptimizerData;
1857 runtime_profiler_ = new RuntimeProfiler(this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001858 runtime_profiler_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001859
1860 // If we are deserializing, log non-function code objects and compiled
1861 // functions found in the snapshot.
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +00001862 if (des != NULL && (FLAG_log_code || FLAG_ll_prof)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001863 HandleScope scope;
1864 LOG(this, LogCodeObjects());
1865 LOG(this, LogCompiledFunctions());
1866 }
1867
1868 state_ = INITIALIZED;
rossberg@chromium.org994edf62012-02-06 10:12:55 +00001869 time_millis_at_init_ = OS::TimeCurrentMillis();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001870 return true;
1871}
1872
1873
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001874// Initialized lazily to allow early
1875// v8::V8::SetAddHistogramSampleFunction calls.
1876StatsTable* Isolate::stats_table() {
1877 if (stats_table_ == NULL) {
1878 stats_table_ = new StatsTable;
1879 }
1880 return stats_table_;
1881}
1882
1883
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001884void Isolate::Enter() {
1885 Isolate* current_isolate = NULL;
1886 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
1887 if (current_data != NULL) {
1888 current_isolate = current_data->isolate_;
1889 ASSERT(current_isolate != NULL);
1890 if (current_isolate == this) {
1891 ASSERT(Current() == this);
1892 ASSERT(entry_stack_ != NULL);
1893 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001894 entry_stack_->previous_thread_data->thread_id().Equals(
1895 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001896 // Same thread re-enters the isolate, no need to re-init anything.
1897 entry_stack_->entry_count++;
1898 return;
1899 }
1900 }
1901
1902 // Threads can have default isolate set into TLS as Current but not yet have
1903 // PerIsolateThreadData for it, as it requires more advanced phase of the
1904 // initialization. For example, a thread might be the one that system used for
1905 // static initializers - in this case the default isolate is set in TLS but
1906 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
1907 // there, use the isolate set in TLS.
1908 if (current_isolate == NULL) {
1909 current_isolate = Isolate::UncheckedCurrent();
1910 }
1911
1912 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
1913 ASSERT(data != NULL);
1914 ASSERT(data->isolate_ == this);
1915
1916 EntryStackItem* item = new EntryStackItem(current_data,
1917 current_isolate,
1918 entry_stack_);
1919 entry_stack_ = item;
1920
1921 SetIsolateThreadLocals(this, data);
1922
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001923 // In case it's the first time some thread enters the isolate.
1924 set_thread_id(data->thread_id());
1925}
1926
1927
1928void Isolate::Exit() {
1929 ASSERT(entry_stack_ != NULL);
1930 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001931 entry_stack_->previous_thread_data->thread_id().Equals(
1932 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001933
1934 if (--entry_stack_->entry_count > 0) return;
1935
1936 ASSERT(CurrentPerIsolateThreadData() != NULL);
1937 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
1938
1939 // Pop the stack.
1940 EntryStackItem* item = entry_stack_;
1941 entry_stack_ = item->previous_item;
1942
1943 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
1944 Isolate* previous_isolate = item->previous_isolate;
1945
1946 delete item;
1947
1948 // Reinit the current thread for the isolate it was running before this one.
1949 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
1950}
1951
1952
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001953#ifdef DEBUG
1954#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1955const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
1956ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
1957ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
1958#undef ISOLATE_FIELD_OFFSET
1959#endif
1960
1961} } // namespace v8::internal