blob: 96c45b13606a44737b7dbc0884c8b8cfa7d6cddd [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());
778 thread_local_top()->failed_access_check_callback_(
779 v8::Utils::ToLocal(receiver_handle),
780 type,
781 v8::Utils::ToLocal(data));
782}
783
784
785enum MayAccessDecision {
786 YES, NO, UNKNOWN
787};
788
789
790static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
791 JSObject* receiver,
792 v8::AccessType type) {
793 // During bootstrapping, callback functions are not enabled yet.
794 if (isolate->bootstrapper()->IsActive()) return YES;
795
796 if (receiver->IsJSGlobalProxy()) {
797 Object* receiver_context = JSGlobalProxy::cast(receiver)->context();
798 if (!receiver_context->IsContext()) return NO;
799
800 // Get the global context of current top context.
801 // avoid using Isolate::global_context() because it uses Handle.
802 Context* global_context = isolate->context()->global()->global_context();
803 if (receiver_context == global_context) return YES;
804
805 if (Context::cast(receiver_context)->security_token() ==
806 global_context->security_token())
807 return YES;
808 }
809
810 return UNKNOWN;
811}
812
813
814bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
815 v8::AccessType type) {
816 ASSERT(receiver->IsAccessCheckNeeded());
817
818 // The callers of this method are not expecting a GC.
819 AssertNoAllocation no_gc;
820
821 // Skip checks for hidden properties access. Note, we do not
822 // require existence of a context in this case.
823 if (key == heap_.hidden_symbol()) return true;
824
825 // Check for compatibility between the security tokens in the
826 // current lexical context and the accessed object.
827 ASSERT(context());
828
829 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
830 if (decision != UNKNOWN) return decision == YES;
831
832 // Get named access check callback
833 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
834 if (!constructor->shared()->IsApiFunction()) return false;
835
836 Object* data_obj =
837 constructor->shared()->get_api_func_data()->access_check_info();
838 if (data_obj == heap_.undefined_value()) return false;
839
840 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
841 v8::NamedSecurityCallback callback =
842 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
843
844 if (!callback) return false;
845
846 HandleScope scope(this);
847 Handle<JSObject> receiver_handle(receiver, this);
848 Handle<Object> key_handle(key, this);
849 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
850 LOG(this, ApiNamedSecurityCheck(key));
851 bool result = false;
852 {
853 // Leaving JavaScript.
854 VMState state(this, EXTERNAL);
855 result = callback(v8::Utils::ToLocal(receiver_handle),
856 v8::Utils::ToLocal(key_handle),
857 type,
858 v8::Utils::ToLocal(data));
859 }
860 return result;
861}
862
863
864bool Isolate::MayIndexedAccess(JSObject* receiver,
865 uint32_t index,
866 v8::AccessType type) {
867 ASSERT(receiver->IsAccessCheckNeeded());
868 // Check for compatibility between the security tokens in the
869 // current lexical context and the accessed object.
870 ASSERT(context());
871
872 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
873 if (decision != UNKNOWN) return decision == YES;
874
875 // Get indexed access check callback
876 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
877 if (!constructor->shared()->IsApiFunction()) return false;
878
879 Object* data_obj =
880 constructor->shared()->get_api_func_data()->access_check_info();
881 if (data_obj == heap_.undefined_value()) return false;
882
883 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
884 v8::IndexedSecurityCallback callback =
885 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
886
887 if (!callback) return false;
888
889 HandleScope scope(this);
890 Handle<JSObject> receiver_handle(receiver, this);
891 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
892 LOG(this, ApiIndexedSecurityCheck(index));
893 bool result = false;
894 {
895 // Leaving JavaScript.
896 VMState state(this, EXTERNAL);
897 result = callback(v8::Utils::ToLocal(receiver_handle),
898 index,
899 type,
900 v8::Utils::ToLocal(data));
901 }
902 return result;
903}
904
905
906const char* const Isolate::kStackOverflowMessage =
907 "Uncaught RangeError: Maximum call stack size exceeded";
908
909
910Failure* Isolate::StackOverflow() {
911 HandleScope scope;
912 Handle<String> key = factory()->stack_overflow_symbol();
913 Handle<JSObject> boilerplate =
914 Handle<JSObject>::cast(GetProperty(js_builtins_object(), key));
915 Handle<Object> exception = Copy(boilerplate);
916 // TODO(1240995): To avoid having to call JavaScript code to compute
917 // the message for stack overflow exceptions which is very likely to
918 // double fault with another stack overflow exception, we use a
919 // precomputed message.
920 DoThrow(*exception, NULL);
921 return Failure::Exception();
922}
923
924
925Failure* Isolate::TerminateExecution() {
926 DoThrow(heap_.termination_exception(), NULL);
927 return Failure::Exception();
928}
929
930
931Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
932 DoThrow(exception, location);
933 return Failure::Exception();
934}
935
936
937Failure* Isolate::ReThrow(MaybeObject* exception, MessageLocation* location) {
938 bool can_be_caught_externally = false;
ager@chromium.orgea91cc52011-05-23 06:06:11 +0000939 bool catchable_by_javascript = is_catchable_by_javascript(exception);
940 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
941
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000942 thread_local_top()->catcher_ = can_be_caught_externally ?
943 try_catch_handler() : NULL;
944
945 // Set the exception being re-thrown.
946 set_pending_exception(exception);
ager@chromium.orgea91cc52011-05-23 06:06:11 +0000947 if (exception->IsFailure()) return exception->ToFailureUnchecked();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000948 return Failure::Exception();
949}
950
951
952Failure* Isolate::ThrowIllegalOperation() {
953 return Throw(heap_.illegal_access_symbol());
954}
955
956
957void Isolate::ScheduleThrow(Object* exception) {
958 // When scheduling a throw we first throw the exception to get the
959 // error reporting if it is uncaught before rescheduling it.
960 Throw(exception);
961 thread_local_top()->scheduled_exception_ = pending_exception();
962 thread_local_top()->external_caught_exception_ = false;
963 clear_pending_exception();
964}
965
966
967Failure* Isolate::PromoteScheduledException() {
968 MaybeObject* thrown = scheduled_exception();
969 clear_scheduled_exception();
970 // Re-throw the exception to avoid getting repeated error reporting.
971 return ReThrow(thrown);
972}
973
974
975void Isolate::PrintCurrentStackTrace(FILE* out) {
976 StackTraceFrameIterator it(this);
977 while (!it.done()) {
978 HandleScope scope;
979 // Find code position if recorded in relocation info.
980 JavaScriptFrame* frame = it.frame();
981 int pos = frame->LookupCode()->SourcePosition(frame->pc());
982 Handle<Object> pos_obj(Smi::FromInt(pos));
983 // Fetch function and receiver.
984 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
985 Handle<Object> recv(frame->receiver());
986 // Advance to the next JavaScript frame and determine if the
987 // current frame is the top-level frame.
988 it.Advance();
989 Handle<Object> is_top_level = it.done()
990 ? factory()->true_value()
991 : factory()->false_value();
992 // Generate and print stack trace line.
993 Handle<String> line =
994 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
995 if (line->length() > 0) {
996 line->PrintOn(out);
997 fprintf(out, "\n");
998 }
999 }
1000}
1001
1002
1003void Isolate::ComputeLocation(MessageLocation* target) {
1004 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1005 StackTraceFrameIterator it(this);
1006 if (!it.done()) {
1007 JavaScriptFrame* frame = it.frame();
1008 JSFunction* fun = JSFunction::cast(frame->function());
1009 Object* script = fun->shared()->script();
1010 if (script->IsScript() &&
1011 !(Script::cast(script)->source()->IsUndefined())) {
1012 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1013 // Compute the location from the function and the reloc info.
1014 Handle<Script> casted_script(Script::cast(script));
1015 *target = MessageLocation(casted_script, pos, pos + 1);
1016 }
1017 }
1018}
1019
1020
1021bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1022 bool catchable_by_javascript) {
1023 // Find the top-most try-catch handler.
1024 StackHandler* handler =
1025 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001026 while (handler != NULL && !handler->is_catch()) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001027 handler = handler->next();
1028 }
1029
1030 // Get the address of the external handler so we can compare the address to
1031 // determine which one is closer to the top of the stack.
1032 Address external_handler_address =
1033 thread_local_top()->try_catch_handler_address();
1034
1035 // The exception has been externally caught if and only if there is
1036 // an external handler which is on top of the top-most try-catch
1037 // handler.
1038 *can_be_caught_externally = external_handler_address != NULL &&
1039 (handler == NULL || handler->address() > external_handler_address ||
1040 !catchable_by_javascript);
1041
1042 if (*can_be_caught_externally) {
1043 // Only report the exception if the external handler is verbose.
1044 return try_catch_handler()->is_verbose_;
1045 } else {
1046 // Report the exception if it isn't caught by JavaScript code.
1047 return handler == NULL;
1048 }
1049}
1050
1051
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001052bool Isolate::IsErrorObject(Handle<Object> obj) {
1053 if (!obj->IsJSObject()) return false;
1054
1055 String* error_key = *(factory()->LookupAsciiSymbol("$Error"));
1056 Object* error_constructor =
1057 js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1058
1059 for (Object* prototype = *obj; !prototype->IsNull();
1060 prototype = prototype->GetPrototype()) {
1061 if (!prototype->IsJSObject()) return false;
1062 if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1063 return true;
1064 }
1065 }
1066 return false;
1067}
1068
1069
1070void Isolate::DoThrow(Object* exception, MessageLocation* location) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001071 ASSERT(!has_pending_exception());
1072
1073 HandleScope scope;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001074 Handle<Object> exception_handle(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001075
1076 // Determine reporting and whether the exception is caught externally.
1077 bool catchable_by_javascript = is_catchable_by_javascript(exception);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001078 bool can_be_caught_externally = false;
1079 bool should_report_exception =
1080 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1081 bool report_exception = catchable_by_javascript && should_report_exception;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001082 bool try_catch_needs_message =
1083 can_be_caught_externally && try_catch_handler()->capture_message_;
1084 bool bootstrapping = bootstrapper()->IsActive();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001085
1086#ifdef ENABLE_DEBUGGER_SUPPORT
1087 // Notify debugger of exception.
1088 if (catchable_by_javascript) {
1089 debugger_->OnException(exception_handle, report_exception);
1090 }
1091#endif
1092
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001093 // Generate the message if required.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001094 if (report_exception || try_catch_needs_message) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001095 MessageLocation potential_computed_location;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001096 if (location == NULL) {
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001097 // If no location was specified we use a computed one instead.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001098 ComputeLocation(&potential_computed_location);
1099 location = &potential_computed_location;
1100 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001101 // It's not safe to try to make message objects or collect stack traces
1102 // while the bootstrapper is active since the infrastructure may not have
1103 // been properly initialized.
1104 if (!bootstrapping) {
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001105 Handle<String> stack_trace;
1106 if (FLAG_trace_exception) stack_trace = StackTraceString();
1107 Handle<JSArray> stack_trace_object;
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001108 if (capture_stack_trace_for_uncaught_exceptions_) {
1109 if (IsErrorObject(exception_handle)) {
1110 // We fetch the stack trace that corresponds to this error object.
1111 String* key = heap()->hidden_stack_trace_symbol();
1112 Object* stack_property =
1113 JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1114 // Property lookup may have failed. In this case it's probably not
1115 // a valid Error object.
1116 if (stack_property->IsJSArray()) {
1117 stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1118 }
1119 }
1120 if (stack_trace_object.is_null()) {
1121 // Not an error object, we capture at throw site.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001122 stack_trace_object = CaptureCurrentStackTrace(
1123 stack_trace_for_uncaught_exceptions_frame_limit_,
1124 stack_trace_for_uncaught_exceptions_options_);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001125 }
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001126 }
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001127 Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1128 "uncaught_exception",
1129 location,
1130 HandleVector<Object>(&exception_handle, 1),
1131 stack_trace,
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001132 stack_trace_object);
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001133 thread_local_top()->pending_message_obj_ = *message_obj;
1134 if (location != NULL) {
1135 thread_local_top()->pending_message_script_ = *location->script();
1136 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1137 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1138 }
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +00001139 } else if (location != NULL && !location->script().is_null()) {
1140 // We are bootstrapping and caught an error where the location is set
1141 // and we have a script for the location.
1142 // In this case we could have an extension (or an internal error
1143 // somewhere) and we print out the line number at which the error occured
1144 // to the console for easier debugging.
1145 int line_number = GetScriptLineNumberSafe(location->script(),
1146 location->start_pos());
1147 OS::PrintError("Extension or internal compilation error at line %d.\n",
1148 line_number);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001149 }
1150 }
1151
1152 // Save the message for reporting if the the exception remains uncaught.
1153 thread_local_top()->has_pending_message_ = report_exception;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001154
1155 // Do not forget to clean catcher_ if currently thrown exception cannot
1156 // be caught. If necessary, ReThrow will update the catcher.
1157 thread_local_top()->catcher_ = can_be_caught_externally ?
1158 try_catch_handler() : NULL;
1159
jkummerow@chromium.orgab7dad42012-02-07 12:07:34 +00001160 set_pending_exception(*exception_handle);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001161}
1162
1163
1164bool Isolate::IsExternallyCaught() {
1165 ASSERT(has_pending_exception());
1166
1167 if ((thread_local_top()->catcher_ == NULL) ||
1168 (try_catch_handler() != thread_local_top()->catcher_)) {
1169 // When throwing the exception, we found no v8::TryCatch
1170 // which should care about this exception.
1171 return false;
1172 }
1173
1174 if (!is_catchable_by_javascript(pending_exception())) {
1175 return true;
1176 }
1177
1178 // Get the address of the external handler so we can compare the address to
1179 // determine which one is closer to the top of the stack.
1180 Address external_handler_address =
1181 thread_local_top()->try_catch_handler_address();
1182 ASSERT(external_handler_address != NULL);
1183
1184 // The exception has been externally caught if and only if there is
1185 // an external handler which is on top of the top-most try-finally
1186 // handler.
1187 // There should be no try-catch blocks as they would prohibit us from
1188 // finding external catcher in the first place (see catcher_ check above).
1189 //
1190 // Note, that finally clause would rethrow an exception unless it's
1191 // aborted by jumps in control flow like return, break, etc. and we'll
1192 // have another chances to set proper v8::TryCatch.
1193 StackHandler* handler =
1194 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1195 while (handler != NULL && handler->address() < external_handler_address) {
yangguo@chromium.org78d1ad42012-02-09 13:53:47 +00001196 ASSERT(!handler->is_catch());
1197 if (handler->is_finally()) return false;
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001198
1199 handler = handler->next();
1200 }
1201
1202 return true;
1203}
1204
1205
1206void Isolate::ReportPendingMessages() {
1207 ASSERT(has_pending_exception());
1208 PropagatePendingExceptionToExternalTryCatch();
1209
1210 // If the pending exception is OutOfMemoryException set out_of_memory in
1211 // the global context. Note: We have to mark the global context here
1212 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1213 // set it.
1214 HandleScope scope;
1215 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1216 context()->mark_out_of_memory();
1217 } else if (thread_local_top_.pending_exception_ ==
1218 heap()->termination_exception()) {
1219 // Do nothing: if needed, the exception has been already propagated to
1220 // v8::TryCatch.
1221 } else {
1222 if (thread_local_top_.has_pending_message_) {
1223 thread_local_top_.has_pending_message_ = false;
1224 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1225 HandleScope scope;
1226 Handle<Object> message_obj(thread_local_top_.pending_message_obj_);
1227 if (thread_local_top_.pending_message_script_ != NULL) {
1228 Handle<Script> script(thread_local_top_.pending_message_script_);
1229 int start_pos = thread_local_top_.pending_message_start_pos_;
1230 int end_pos = thread_local_top_.pending_message_end_pos_;
1231 MessageLocation location(script, start_pos, end_pos);
1232 MessageHandler::ReportMessage(this, &location, message_obj);
1233 } else {
1234 MessageHandler::ReportMessage(this, NULL, message_obj);
1235 }
1236 }
1237 }
1238 }
1239 clear_pending_message();
1240}
1241
1242
1243void Isolate::TraceException(bool flag) {
1244 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1245}
1246
1247
1248bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1249 ASSERT(has_pending_exception());
1250 PropagatePendingExceptionToExternalTryCatch();
1251
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001252 // Always reschedule out of memory exceptions.
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001253 if (!is_out_of_memory()) {
1254 bool is_termination_exception =
1255 pending_exception() == heap_.termination_exception();
1256
1257 // Do not reschedule the exception if this is the bottom call.
1258 bool clear_exception = is_bottom_call;
1259
1260 if (is_termination_exception) {
1261 if (is_bottom_call) {
1262 thread_local_top()->external_caught_exception_ = false;
1263 clear_pending_exception();
1264 return false;
1265 }
1266 } else if (thread_local_top()->external_caught_exception_) {
1267 // If the exception is externally caught, clear it if there are no
1268 // JavaScript frames on the way to the C++ frame that has the
1269 // external handler.
1270 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1271 Address external_handler_address =
1272 thread_local_top()->try_catch_handler_address();
1273 JavaScriptFrameIterator it;
1274 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1275 clear_exception = true;
1276 }
1277 }
1278
1279 // Clear the exception if needed.
1280 if (clear_exception) {
1281 thread_local_top()->external_caught_exception_ = false;
1282 clear_pending_exception();
1283 return false;
1284 }
1285 }
1286
1287 // Reschedule the exception.
1288 thread_local_top()->scheduled_exception_ = pending_exception();
1289 clear_pending_exception();
1290 return true;
1291}
1292
1293
1294void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1295 bool capture,
1296 int frame_limit,
1297 StackTrace::StackTraceOptions options) {
1298 capture_stack_trace_for_uncaught_exceptions_ = capture;
1299 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1300 stack_trace_for_uncaught_exceptions_options_ = options;
1301}
1302
1303
1304bool Isolate::is_out_of_memory() {
1305 if (has_pending_exception()) {
1306 MaybeObject* e = pending_exception();
1307 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1308 return true;
1309 }
1310 }
1311 if (has_scheduled_exception()) {
1312 MaybeObject* e = scheduled_exception();
1313 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1314 return true;
1315 }
1316 }
1317 return false;
1318}
1319
1320
1321Handle<Context> Isolate::global_context() {
1322 GlobalObject* global = thread_local_top()->context_->global();
1323 return Handle<Context>(global->global_context());
1324}
1325
1326
1327Handle<Context> Isolate::GetCallingGlobalContext() {
1328 JavaScriptFrameIterator it;
1329#ifdef ENABLE_DEBUGGER_SUPPORT
1330 if (debug_->InDebugger()) {
1331 while (!it.done()) {
1332 JavaScriptFrame* frame = it.frame();
1333 Context* context = Context::cast(frame->context());
1334 if (context->global_context() == *debug_->debug_context()) {
1335 it.Advance();
1336 } else {
1337 break;
1338 }
1339 }
1340 }
1341#endif // ENABLE_DEBUGGER_SUPPORT
1342 if (it.done()) return Handle<Context>::null();
1343 JavaScriptFrame* frame = it.frame();
1344 Context* context = Context::cast(frame->context());
1345 return Handle<Context>(context->global_context());
1346}
1347
1348
1349char* Isolate::ArchiveThread(char* to) {
1350 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1351 RuntimeProfiler::IsolateExitedJS(this);
1352 }
1353 memcpy(to, reinterpret_cast<char*>(thread_local_top()),
1354 sizeof(ThreadLocalTop));
1355 InitializeThreadLocal();
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001356 clear_pending_exception();
1357 clear_pending_message();
1358 clear_scheduled_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001359 return to + sizeof(ThreadLocalTop);
1360}
1361
1362
1363char* Isolate::RestoreThread(char* from) {
1364 memcpy(reinterpret_cast<char*>(thread_local_top()), from,
1365 sizeof(ThreadLocalTop));
1366 // This might be just paranoia, but it seems to be needed in case a
1367 // thread_local_top_ is restored on a separate OS thread.
1368#ifdef USE_SIMULATOR
1369#ifdef V8_TARGET_ARCH_ARM
1370 thread_local_top()->simulator_ = Simulator::current(this);
1371#elif V8_TARGET_ARCH_MIPS
1372 thread_local_top()->simulator_ = Simulator::current(this);
1373#endif
1374#endif
1375 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1376 RuntimeProfiler::IsolateEnteredJS(this);
1377 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001378 ASSERT(context() == NULL || context()->IsContext());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001379 return from + sizeof(ThreadLocalTop);
1380}
1381
1382
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001383Isolate::ThreadDataTable::ThreadDataTable()
1384 : list_(NULL) {
1385}
1386
1387
1388Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001389 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1390 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001391 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1392 if (data->Matches(isolate, thread_id)) return data;
1393 }
1394 return NULL;
1395}
1396
1397
1398void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1399 if (list_ != NULL) list_->prev_ = data;
1400 data->next_ = list_;
1401 list_ = data;
1402}
1403
1404
1405void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1406 if (list_ == data) list_ = data->next_;
1407 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1408 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001409 delete data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001410}
1411
1412
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001413void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1414 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001415 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1416 if (data != NULL) {
1417 Remove(data);
1418 }
1419}
1420
1421
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001422void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1423 PerIsolateThreadData* data = list_;
1424 while (data != NULL) {
1425 PerIsolateThreadData* next = data->next_;
1426 if (data->isolate() == isolate) Remove(data);
1427 data = next;
1428 }
1429}
1430
1431
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001432#ifdef DEBUG
1433#define TRACE_ISOLATE(tag) \
1434 do { \
1435 if (FLAG_trace_isolates) { \
1436 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
1437 } \
1438 } while (false)
1439#else
1440#define TRACE_ISOLATE(tag)
1441#endif
1442
1443
1444Isolate::Isolate()
1445 : state_(UNINITIALIZED),
1446 entry_stack_(NULL),
1447 stack_trace_nesting_level_(0),
1448 incomplete_message_(NULL),
1449 preallocated_memory_thread_(NULL),
1450 preallocated_message_space_(NULL),
1451 bootstrapper_(NULL),
1452 runtime_profiler_(NULL),
1453 compilation_cache_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001454 counters_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001455 code_range_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001456 // Must be initialized early to allow v8::SetResourceConstraints calls.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001457 break_access_(OS::CreateMutex()),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001458 debugger_initialized_(false),
1459 // Must be initialized early to allow v8::Debug calls.
1460 debugger_access_(OS::CreateMutex()),
1461 logger_(NULL),
1462 stats_table_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001463 stub_cache_(NULL),
1464 deoptimizer_data_(NULL),
1465 capture_stack_trace_for_uncaught_exceptions_(false),
1466 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1467 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1468 transcendental_cache_(NULL),
1469 memory_allocator_(NULL),
1470 keyed_lookup_cache_(NULL),
1471 context_slot_cache_(NULL),
1472 descriptor_lookup_cache_(NULL),
1473 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001474 unicode_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001475 in_use_list_(0),
1476 free_list_(0),
1477 preallocated_storage_preallocated_(false),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001478 inner_pointer_to_code_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001479 write_input_buffer_(NULL),
1480 global_handles_(NULL),
1481 context_switcher_(NULL),
1482 thread_manager_(NULL),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001483 fp_stubs_generated_(false),
ricow@chromium.org27bf2882011-11-17 08:34:43 +00001484 has_installed_extensions_(false),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001485 string_tracker_(NULL),
1486 regexp_stack_(NULL),
ulan@chromium.org2efb9002012-01-19 15:36:35 +00001487 embedder_data_(NULL),
1488 context_exit_happened_(false) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001489 TRACE_ISOLATE(constructor);
1490
1491 memset(isolate_addresses_, 0,
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001492 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001493
1494 heap_.isolate_ = this;
1495 zone_.isolate_ = this;
1496 stack_guard_.isolate_ = this;
1497
lrn@chromium.org1c092762011-05-09 09:42:16 +00001498 // ThreadManager is initialized early to support locking an isolate
1499 // before it is entered.
1500 thread_manager_ = new ThreadManager();
1501 thread_manager_->isolate_ = this;
1502
lrn@chromium.org7516f052011-03-30 08:52:27 +00001503#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
1504 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001505 simulator_initialized_ = false;
1506 simulator_i_cache_ = NULL;
1507 simulator_redirection_ = NULL;
1508#endif
1509
1510#ifdef DEBUG
1511 // heap_histograms_ initializes itself.
1512 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1513 memset(code_kind_statistics_, 0,
1514 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
1515#endif
1516
1517#ifdef ENABLE_DEBUGGER_SUPPORT
1518 debug_ = NULL;
1519 debugger_ = NULL;
1520#endif
1521
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001522 handle_scope_data_.Initialize();
1523
1524#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1525 name##_ = (initial_value);
1526 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1527#undef ISOLATE_INIT_EXECUTE
1528
1529#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1530 memset(name##_, 0, sizeof(type) * length);
1531 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1532#undef ISOLATE_INIT_ARRAY_EXECUTE
1533}
1534
1535void Isolate::TearDown() {
1536 TRACE_ISOLATE(tear_down);
1537
1538 // Temporarily set this isolate as current so that various parts of
1539 // the isolate can access it in their destructors without having a
1540 // direct pointer. We don't use Enter/Exit here to avoid
1541 // initializing the thread data.
1542 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1543 Isolate* saved_isolate = UncheckedCurrent();
1544 SetIsolateThreadLocals(this, NULL);
1545
1546 Deinit();
1547
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001548 { ScopedLock lock(process_wide_mutex_);
1549 thread_data_table_->RemoveAllThreads(this);
1550 }
1551
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001552 if (!IsDefaultIsolate()) {
1553 delete this;
1554 }
1555
1556 // Restore the previous current isolate.
1557 SetIsolateThreadLocals(saved_isolate, saved_data);
1558}
1559
1560
1561void Isolate::Deinit() {
1562 if (state_ == INITIALIZED) {
1563 TRACE_ISOLATE(deinit);
1564
1565 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
1566
1567 // We must stop the logger before we tear down other components.
1568 logger_->EnsureTickerStopped();
1569
1570 delete deoptimizer_data_;
1571 deoptimizer_data_ = NULL;
1572 if (FLAG_preemption) {
1573 v8::Locker locker;
1574 v8::Locker::StopPreemption();
1575 }
1576 builtins_.TearDown();
1577 bootstrapper_->TearDown();
1578
1579 // Remove the external reference to the preallocated stack memory.
1580 delete preallocated_message_space_;
1581 preallocated_message_space_ = NULL;
1582 PreallocatedMemoryThreadStop();
1583
1584 HeapProfiler::TearDown();
1585 CpuProfiler::TearDown();
1586 if (runtime_profiler_ != NULL) {
1587 runtime_profiler_->TearDown();
1588 delete runtime_profiler_;
1589 runtime_profiler_ = NULL;
1590 }
1591 heap_.TearDown();
1592 logger_->TearDown();
1593
1594 // The default isolate is re-initializable due to legacy API.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001595 state_ = UNINITIALIZED;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001596 }
1597}
1598
1599
1600void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1601 PerIsolateThreadData* data) {
1602 Thread::SetThreadLocal(isolate_key_, isolate);
1603 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1604}
1605
1606
1607Isolate::~Isolate() {
1608 TRACE_ISOLATE(destructor);
1609
danno@chromium.orgb6451162011-08-17 14:33:23 +00001610 // Has to be called while counters_ are still alive.
1611 zone_.DeleteKeptSegment();
1612
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001613 delete[] assembler_spare_buffer_;
1614 assembler_spare_buffer_ = NULL;
1615
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001616 delete unicode_cache_;
1617 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001618
1619 delete regexp_stack_;
1620 regexp_stack_ = NULL;
1621
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001622 delete descriptor_lookup_cache_;
1623 descriptor_lookup_cache_ = NULL;
1624 delete context_slot_cache_;
1625 context_slot_cache_ = NULL;
1626 delete keyed_lookup_cache_;
1627 keyed_lookup_cache_ = NULL;
1628
1629 delete transcendental_cache_;
1630 transcendental_cache_ = NULL;
1631 delete stub_cache_;
1632 stub_cache_ = NULL;
1633 delete stats_table_;
1634 stats_table_ = NULL;
1635
1636 delete logger_;
1637 logger_ = NULL;
1638
1639 delete counters_;
1640 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001641
1642 delete handle_scope_implementer_;
1643 handle_scope_implementer_ = NULL;
1644 delete break_access_;
1645 break_access_ = NULL;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001646 delete debugger_access_;
1647 debugger_access_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001648
1649 delete compilation_cache_;
1650 compilation_cache_ = NULL;
1651 delete bootstrapper_;
1652 bootstrapper_ = NULL;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001653 delete inner_pointer_to_code_cache_;
1654 inner_pointer_to_code_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001655 delete write_input_buffer_;
1656 write_input_buffer_ = NULL;
1657
1658 delete context_switcher_;
1659 context_switcher_ = NULL;
1660 delete thread_manager_;
1661 thread_manager_ = NULL;
1662
1663 delete string_tracker_;
1664 string_tracker_ = NULL;
1665
1666 delete memory_allocator_;
1667 memory_allocator_ = NULL;
1668 delete code_range_;
1669 code_range_ = NULL;
1670 delete global_handles_;
1671 global_handles_ = NULL;
1672
danno@chromium.orgb6451162011-08-17 14:33:23 +00001673 delete external_reference_table_;
1674 external_reference_table_ = NULL;
1675
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001676#ifdef ENABLE_DEBUGGER_SUPPORT
1677 delete debugger_;
1678 debugger_ = NULL;
1679 delete debug_;
1680 debug_ = NULL;
1681#endif
1682}
1683
1684
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001685void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +00001686 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001687 thread_local_top_.Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001688}
1689
1690
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001691void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1692 ASSERT(has_pending_exception());
1693
1694 bool external_caught = IsExternallyCaught();
1695 thread_local_top_.external_caught_exception_ = external_caught;
1696
1697 if (!external_caught) return;
1698
1699 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1700 // Do not propagate OOM exception: we should kill VM asap.
1701 } else if (thread_local_top_.pending_exception_ ==
1702 heap()->termination_exception()) {
1703 try_catch_handler()->can_continue_ = false;
1704 try_catch_handler()->exception_ = heap()->null_value();
1705 } else {
1706 // At this point all non-object (failure) exceptions have
1707 // been dealt with so this shouldn't fail.
1708 ASSERT(!pending_exception()->IsFailure());
1709 try_catch_handler()->can_continue_ = true;
1710 try_catch_handler()->exception_ = pending_exception();
1711 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1712 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
1713 }
1714 }
1715}
1716
1717
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001718void Isolate::InitializeLoggingAndCounters() {
1719 if (logger_ == NULL) {
1720 logger_ = new Logger;
1721 }
1722 if (counters_ == NULL) {
1723 counters_ = new Counters;
1724 }
1725}
1726
1727
1728void Isolate::InitializeDebugger() {
1729#ifdef ENABLE_DEBUGGER_SUPPORT
1730 ScopedLock lock(debugger_access_);
1731 if (NoBarrier_Load(&debugger_initialized_)) return;
1732 InitializeLoggingAndCounters();
1733 debug_ = new Debug(this);
1734 debugger_ = new Debugger(this);
1735 Release_Store(&debugger_initialized_, true);
1736#endif
1737}
1738
1739
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001740bool Isolate::Init(Deserializer* des) {
1741 ASSERT(state_ != INITIALIZED);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001742 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001743 TRACE_ISOLATE(init);
1744
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001745#ifdef DEBUG
1746 // The initialization process does not handle memory exhaustion.
1747 DisallowAllocationFailure disallow_allocation_failure;
1748#endif
1749
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001750 InitializeLoggingAndCounters();
1751
1752 InitializeDebugger();
1753
1754 memory_allocator_ = new MemoryAllocator(this);
1755 code_range_ = new CodeRange(this);
1756
1757 // Safe after setting Heap::isolate_, initializing StackGuard and
1758 // ensuring that Isolate::Current() == this.
1759 heap_.SetStackLimits();
1760
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001761#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1762 isolate_addresses_[Isolate::k##CamelName##Address] = \
1763 reinterpret_cast<Address>(hacker_name##_address());
1764 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001765#undef C
1766
1767 string_tracker_ = new StringTracker();
1768 string_tracker_->isolate_ = this;
1769 compilation_cache_ = new CompilationCache(this);
1770 transcendental_cache_ = new TranscendentalCache();
1771 keyed_lookup_cache_ = new KeyedLookupCache();
1772 context_slot_cache_ = new ContextSlotCache();
1773 descriptor_lookup_cache_ = new DescriptorLookupCache();
1774 unicode_cache_ = new UnicodeCache();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001775 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001776 write_input_buffer_ = new StringInputBuffer();
1777 global_handles_ = new GlobalHandles(this);
1778 bootstrapper_ = new Bootstrapper();
1779 handle_scope_implementer_ = new HandleScopeImplementer(this);
1780 stub_cache_ = new StubCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001781 regexp_stack_ = new RegExpStack();
1782 regexp_stack_->isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001783
1784 // Enable logging before setting up the heap
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001785 logger_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001786
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001787 CpuProfiler::SetUp();
1788 HeapProfiler::SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001789
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001790 // Initialize other runtime facilities
1791#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +00001792#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
lrn@chromium.org1c092762011-05-09 09:42:16 +00001793 Simulator::Initialize(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001794#endif
1795#endif
1796
1797 { // NOLINT
1798 // Ensure that the thread has a valid stack guard. The v8::Locker object
1799 // will ensure this too, but we don't have to use lockers if we are only
1800 // using one thread.
1801 ExecutionAccess lock(this);
1802 stack_guard_.InitThread(lock);
1803 }
1804
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001805 // SetUp the object heap.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001806 const bool create_heap_objects = (des == NULL);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001807 ASSERT(!heap_.HasBeenSetUp());
1808 if (!heap_.SetUp(create_heap_objects)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001809 V8::SetFatalError();
1810 return false;
1811 }
1812
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001813 InitializeThreadLocal();
1814
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001815 bootstrapper_->Initialize(create_heap_objects);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001816 builtins_.SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001817
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001818 // Only preallocate on the first initialization.
1819 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
1820 // Start the thread which will set aside some memory.
1821 PreallocatedMemoryThreadStart();
1822 preallocated_message_space_ =
1823 new NoAllocationStringAllocator(
1824 preallocated_memory_thread_->data(),
1825 preallocated_memory_thread_->length());
1826 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
1827 }
1828
1829 if (FLAG_preemption) {
1830 v8::Locker locker;
1831 v8::Locker::StartPreemption(100);
1832 }
1833
1834#ifdef ENABLE_DEBUGGER_SUPPORT
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001835 debug_->SetUp(create_heap_objects);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001836#endif
1837 stub_cache_->Initialize(create_heap_objects);
1838
1839 // If we are deserializing, read the state into the now-empty heap.
1840 if (des != NULL) {
1841 des->Deserialize();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001842 stub_cache_->Initialize(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001843 }
1844
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001845 // Finish initialization of ThreadLocal after deserialization is done.
1846 clear_pending_exception();
1847 clear_pending_message();
1848 clear_scheduled_exception();
1849
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001850 // Deserializing may put strange things in the root array's copy of the
1851 // stack guard.
1852 heap_.SetStackLimits();
1853
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001854 deoptimizer_data_ = new DeoptimizerData;
1855 runtime_profiler_ = new RuntimeProfiler(this);
erik.corry@gmail.comf2038fb2012-01-16 11:42:08 +00001856 runtime_profiler_->SetUp();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001857
1858 // If we are deserializing, log non-function code objects and compiled
1859 // functions found in the snapshot.
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +00001860 if (des != NULL && (FLAG_log_code || FLAG_ll_prof)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001861 HandleScope scope;
1862 LOG(this, LogCodeObjects());
1863 LOG(this, LogCompiledFunctions());
1864 }
1865
1866 state_ = INITIALIZED;
rossberg@chromium.org994edf62012-02-06 10:12:55 +00001867 time_millis_at_init_ = OS::TimeCurrentMillis();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001868 return true;
1869}
1870
1871
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001872// Initialized lazily to allow early
1873// v8::V8::SetAddHistogramSampleFunction calls.
1874StatsTable* Isolate::stats_table() {
1875 if (stats_table_ == NULL) {
1876 stats_table_ = new StatsTable;
1877 }
1878 return stats_table_;
1879}
1880
1881
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001882void Isolate::Enter() {
1883 Isolate* current_isolate = NULL;
1884 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
1885 if (current_data != NULL) {
1886 current_isolate = current_data->isolate_;
1887 ASSERT(current_isolate != NULL);
1888 if (current_isolate == this) {
1889 ASSERT(Current() == this);
1890 ASSERT(entry_stack_ != NULL);
1891 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001892 entry_stack_->previous_thread_data->thread_id().Equals(
1893 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001894 // Same thread re-enters the isolate, no need to re-init anything.
1895 entry_stack_->entry_count++;
1896 return;
1897 }
1898 }
1899
1900 // Threads can have default isolate set into TLS as Current but not yet have
1901 // PerIsolateThreadData for it, as it requires more advanced phase of the
1902 // initialization. For example, a thread might be the one that system used for
1903 // static initializers - in this case the default isolate is set in TLS but
1904 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
1905 // there, use the isolate set in TLS.
1906 if (current_isolate == NULL) {
1907 current_isolate = Isolate::UncheckedCurrent();
1908 }
1909
1910 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
1911 ASSERT(data != NULL);
1912 ASSERT(data->isolate_ == this);
1913
1914 EntryStackItem* item = new EntryStackItem(current_data,
1915 current_isolate,
1916 entry_stack_);
1917 entry_stack_ = item;
1918
1919 SetIsolateThreadLocals(this, data);
1920
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001921 // In case it's the first time some thread enters the isolate.
1922 set_thread_id(data->thread_id());
1923}
1924
1925
1926void Isolate::Exit() {
1927 ASSERT(entry_stack_ != NULL);
1928 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001929 entry_stack_->previous_thread_data->thread_id().Equals(
1930 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001931
1932 if (--entry_stack_->entry_count > 0) return;
1933
1934 ASSERT(CurrentPerIsolateThreadData() != NULL);
1935 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
1936
1937 // Pop the stack.
1938 EntryStackItem* item = entry_stack_;
1939 entry_stack_ = item->previous_item;
1940
1941 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
1942 Isolate* previous_isolate = item->previous_isolate;
1943
1944 delete item;
1945
1946 // Reinit the current thread for the isolate it was running before this one.
1947 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
1948}
1949
1950
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001951#ifdef DEBUG
1952#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1953const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
1954ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
1955ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
1956#undef ISOLATE_FIELD_OFFSET
1957#endif
1958
1959} } // namespace v8::internal