blob: c235a23439dbc5b44ecd16d3396def081b38b7e4 [file] [log] [blame]
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001// Copyright 2011 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
545Handle<JSArray> Isolate::CaptureCurrentStackTrace(
546 int frame_limit, StackTrace::StackTraceOptions options) {
547 // Ensure no negative values.
548 int limit = Max(frame_limit, 0);
549 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
550
551 Handle<String> column_key = factory()->LookupAsciiSymbol("column");
552 Handle<String> line_key = factory()->LookupAsciiSymbol("lineNumber");
553 Handle<String> script_key = factory()->LookupAsciiSymbol("scriptName");
554 Handle<String> name_or_source_url_key =
555 factory()->LookupAsciiSymbol("nameOrSourceURL");
556 Handle<String> script_name_or_source_url_key =
557 factory()->LookupAsciiSymbol("scriptNameOrSourceURL");
558 Handle<String> function_key = factory()->LookupAsciiSymbol("functionName");
559 Handle<String> eval_key = factory()->LookupAsciiSymbol("isEval");
560 Handle<String> constructor_key =
561 factory()->LookupAsciiSymbol("isConstructor");
562
563 StackTraceFrameIterator it(this);
564 int frames_seen = 0;
565 while (!it.done() && (frames_seen < limit)) {
566 JavaScriptFrame* frame = it.frame();
567 // Set initial size to the maximum inlining level + 1 for the outermost
568 // function.
569 List<FrameSummary> frames(Compiler::kMaxInliningLevels + 1);
570 frame->Summarize(&frames);
571 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
572 // Create a JSObject to hold the information for the StackFrame.
573 Handle<JSObject> stackFrame = factory()->NewJSObject(object_function());
574
575 Handle<JSFunction> fun = frames[i].function();
576 Handle<Script> script(Script::cast(fun->shared()->script()));
577
578 if (options & StackTrace::kLineNumber) {
579 int script_line_offset = script->line_offset()->value();
580 int position = frames[i].code()->SourcePosition(frames[i].pc());
581 int line_number = GetScriptLineNumber(script, position);
582 // line_number is already shifted by the script_line_offset.
583 int relative_line_number = line_number - script_line_offset;
584 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
585 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
586 int start = (relative_line_number == 0) ? 0 :
587 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
588 int column_offset = position - start;
589 if (relative_line_number == 0) {
590 // For the case where the code is on the same line as the script
591 // tag.
592 column_offset += script->column_offset()->value();
593 }
594 SetLocalPropertyNoThrow(stackFrame, column_key,
595 Handle<Smi>(Smi::FromInt(column_offset + 1)));
596 }
597 SetLocalPropertyNoThrow(stackFrame, line_key,
598 Handle<Smi>(Smi::FromInt(line_number + 1)));
599 }
600
601 if (options & StackTrace::kScriptName) {
602 Handle<Object> script_name(script->name(), this);
603 SetLocalPropertyNoThrow(stackFrame, script_key, script_name);
604 }
605
606 if (options & StackTrace::kScriptNameOrSourceURL) {
607 Handle<Object> script_name(script->name(), this);
608 Handle<JSValue> script_wrapper = GetScriptWrapper(script);
609 Handle<Object> property = GetProperty(script_wrapper,
610 name_or_source_url_key);
611 ASSERT(property->IsJSFunction());
612 Handle<JSFunction> method = Handle<JSFunction>::cast(property);
613 bool caught_exception;
614 Handle<Object> result = Execution::TryCall(method, script_wrapper, 0,
615 NULL, &caught_exception);
616 if (caught_exception) {
617 result = factory()->undefined_value();
618 }
619 SetLocalPropertyNoThrow(stackFrame, script_name_or_source_url_key,
620 result);
621 }
622
623 if (options & StackTrace::kFunctionName) {
624 Handle<Object> fun_name(fun->shared()->name(), this);
625 if (fun_name->ToBoolean()->IsFalse()) {
626 fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
627 }
628 SetLocalPropertyNoThrow(stackFrame, function_key, fun_name);
629 }
630
631 if (options & StackTrace::kIsEval) {
632 int type = Smi::cast(script->compilation_type())->value();
633 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
634 factory()->true_value() : factory()->false_value();
635 SetLocalPropertyNoThrow(stackFrame, eval_key, is_eval);
636 }
637
638 if (options & StackTrace::kIsConstructor) {
639 Handle<Object> is_constructor = (frames[i].is_constructor()) ?
640 factory()->true_value() : factory()->false_value();
641 SetLocalPropertyNoThrow(stackFrame, constructor_key, is_constructor);
642 }
643
644 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stackFrame);
645 frames_seen++;
646 }
647 it.Advance();
648 }
649
650 stack_trace->set_length(Smi::FromInt(frames_seen));
651 return stack_trace;
652}
653
654
655void Isolate::PrintStack() {
656 if (stack_trace_nesting_level_ == 0) {
657 stack_trace_nesting_level_++;
658
659 StringAllocator* allocator;
660 if (preallocated_message_space_ == NULL) {
661 allocator = new HeapStringAllocator();
662 } else {
663 allocator = preallocated_message_space_;
664 }
665
666 StringStream::ClearMentionedObjectCache();
667 StringStream accumulator(allocator);
668 incomplete_message_ = &accumulator;
669 PrintStack(&accumulator);
670 accumulator.OutputToStdOut();
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +0000671 InitializeLoggingAndCounters();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000672 accumulator.Log();
673 incomplete_message_ = NULL;
674 stack_trace_nesting_level_ = 0;
675 if (preallocated_message_space_ == NULL) {
676 // Remove the HeapStringAllocator created above.
677 delete allocator;
678 }
679 } else if (stack_trace_nesting_level_ == 1) {
680 stack_trace_nesting_level_++;
681 OS::PrintError(
682 "\n\nAttempt to print stack while printing stack (double fault)\n");
683 OS::PrintError(
684 "If you are lucky you may find a partial stack dump on stdout.\n\n");
685 incomplete_message_->OutputToStdOut();
686 }
687}
688
689
690static void PrintFrames(StringStream* accumulator,
691 StackFrame::PrintMode mode) {
692 StackFrameIterator it;
693 for (int i = 0; !it.done(); it.Advance()) {
694 it.frame()->Print(accumulator, mode, i++);
695 }
696}
697
698
699void Isolate::PrintStack(StringStream* accumulator) {
700 if (!IsInitialized()) {
701 accumulator->Add(
702 "\n==== Stack trace is not available ==========================\n\n");
703 accumulator->Add(
704 "\n==== Isolate for the thread is not initialized =============\n\n");
705 return;
706 }
707 // The MentionedObjectCache is not GC-proof at the moment.
708 AssertNoAllocation nogc;
709 ASSERT(StringStream::IsMentionedObjectCacheClear());
710
711 // Avoid printing anything if there are no frames.
712 if (c_entry_fp(thread_local_top()) == 0) return;
713
714 accumulator->Add(
715 "\n==== Stack trace ============================================\n\n");
716 PrintFrames(accumulator, StackFrame::OVERVIEW);
717
718 accumulator->Add(
719 "\n==== Details ================================================\n\n");
720 PrintFrames(accumulator, StackFrame::DETAILS);
721
722 accumulator->PrintMentionedObjectCache();
723 accumulator->Add("=====================\n\n");
724}
725
726
727void Isolate::SetFailedAccessCheckCallback(
728 v8::FailedAccessCheckCallback callback) {
729 thread_local_top()->failed_access_check_callback_ = callback;
730}
731
732
733void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
734 if (!thread_local_top()->failed_access_check_callback_) return;
735
736 ASSERT(receiver->IsAccessCheckNeeded());
737 ASSERT(context());
738
739 // Get the data object from access check info.
740 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
741 if (!constructor->shared()->IsApiFunction()) return;
742 Object* data_obj =
743 constructor->shared()->get_api_func_data()->access_check_info();
744 if (data_obj == heap_.undefined_value()) return;
745
746 HandleScope scope;
747 Handle<JSObject> receiver_handle(receiver);
748 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
749 thread_local_top()->failed_access_check_callback_(
750 v8::Utils::ToLocal(receiver_handle),
751 type,
752 v8::Utils::ToLocal(data));
753}
754
755
756enum MayAccessDecision {
757 YES, NO, UNKNOWN
758};
759
760
761static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
762 JSObject* receiver,
763 v8::AccessType type) {
764 // During bootstrapping, callback functions are not enabled yet.
765 if (isolate->bootstrapper()->IsActive()) return YES;
766
767 if (receiver->IsJSGlobalProxy()) {
768 Object* receiver_context = JSGlobalProxy::cast(receiver)->context();
769 if (!receiver_context->IsContext()) return NO;
770
771 // Get the global context of current top context.
772 // avoid using Isolate::global_context() because it uses Handle.
773 Context* global_context = isolate->context()->global()->global_context();
774 if (receiver_context == global_context) return YES;
775
776 if (Context::cast(receiver_context)->security_token() ==
777 global_context->security_token())
778 return YES;
779 }
780
781 return UNKNOWN;
782}
783
784
785bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
786 v8::AccessType type) {
787 ASSERT(receiver->IsAccessCheckNeeded());
788
789 // The callers of this method are not expecting a GC.
790 AssertNoAllocation no_gc;
791
792 // Skip checks for hidden properties access. Note, we do not
793 // require existence of a context in this case.
794 if (key == heap_.hidden_symbol()) return true;
795
796 // Check for compatibility between the security tokens in the
797 // current lexical context and the accessed object.
798 ASSERT(context());
799
800 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
801 if (decision != UNKNOWN) return decision == YES;
802
803 // Get named access check callback
804 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
805 if (!constructor->shared()->IsApiFunction()) return false;
806
807 Object* data_obj =
808 constructor->shared()->get_api_func_data()->access_check_info();
809 if (data_obj == heap_.undefined_value()) return false;
810
811 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
812 v8::NamedSecurityCallback callback =
813 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
814
815 if (!callback) return false;
816
817 HandleScope scope(this);
818 Handle<JSObject> receiver_handle(receiver, this);
819 Handle<Object> key_handle(key, this);
820 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
821 LOG(this, ApiNamedSecurityCheck(key));
822 bool result = false;
823 {
824 // Leaving JavaScript.
825 VMState state(this, EXTERNAL);
826 result = callback(v8::Utils::ToLocal(receiver_handle),
827 v8::Utils::ToLocal(key_handle),
828 type,
829 v8::Utils::ToLocal(data));
830 }
831 return result;
832}
833
834
835bool Isolate::MayIndexedAccess(JSObject* receiver,
836 uint32_t index,
837 v8::AccessType type) {
838 ASSERT(receiver->IsAccessCheckNeeded());
839 // Check for compatibility between the security tokens in the
840 // current lexical context and the accessed object.
841 ASSERT(context());
842
843 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
844 if (decision != UNKNOWN) return decision == YES;
845
846 // Get indexed access check callback
847 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
848 if (!constructor->shared()->IsApiFunction()) return false;
849
850 Object* data_obj =
851 constructor->shared()->get_api_func_data()->access_check_info();
852 if (data_obj == heap_.undefined_value()) return false;
853
854 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
855 v8::IndexedSecurityCallback callback =
856 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
857
858 if (!callback) return false;
859
860 HandleScope scope(this);
861 Handle<JSObject> receiver_handle(receiver, this);
862 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
863 LOG(this, ApiIndexedSecurityCheck(index));
864 bool result = false;
865 {
866 // Leaving JavaScript.
867 VMState state(this, EXTERNAL);
868 result = callback(v8::Utils::ToLocal(receiver_handle),
869 index,
870 type,
871 v8::Utils::ToLocal(data));
872 }
873 return result;
874}
875
876
877const char* const Isolate::kStackOverflowMessage =
878 "Uncaught RangeError: Maximum call stack size exceeded";
879
880
881Failure* Isolate::StackOverflow() {
882 HandleScope scope;
883 Handle<String> key = factory()->stack_overflow_symbol();
884 Handle<JSObject> boilerplate =
885 Handle<JSObject>::cast(GetProperty(js_builtins_object(), key));
886 Handle<Object> exception = Copy(boilerplate);
887 // TODO(1240995): To avoid having to call JavaScript code to compute
888 // the message for stack overflow exceptions which is very likely to
889 // double fault with another stack overflow exception, we use a
890 // precomputed message.
891 DoThrow(*exception, NULL);
892 return Failure::Exception();
893}
894
895
896Failure* Isolate::TerminateExecution() {
897 DoThrow(heap_.termination_exception(), NULL);
898 return Failure::Exception();
899}
900
901
902Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
903 DoThrow(exception, location);
904 return Failure::Exception();
905}
906
907
908Failure* Isolate::ReThrow(MaybeObject* exception, MessageLocation* location) {
909 bool can_be_caught_externally = false;
ager@chromium.orgea91cc52011-05-23 06:06:11 +0000910 bool catchable_by_javascript = is_catchable_by_javascript(exception);
911 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
912
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000913 thread_local_top()->catcher_ = can_be_caught_externally ?
914 try_catch_handler() : NULL;
915
916 // Set the exception being re-thrown.
917 set_pending_exception(exception);
ager@chromium.orgea91cc52011-05-23 06:06:11 +0000918 if (exception->IsFailure()) return exception->ToFailureUnchecked();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +0000919 return Failure::Exception();
920}
921
922
923Failure* Isolate::ThrowIllegalOperation() {
924 return Throw(heap_.illegal_access_symbol());
925}
926
927
928void Isolate::ScheduleThrow(Object* exception) {
929 // When scheduling a throw we first throw the exception to get the
930 // error reporting if it is uncaught before rescheduling it.
931 Throw(exception);
932 thread_local_top()->scheduled_exception_ = pending_exception();
933 thread_local_top()->external_caught_exception_ = false;
934 clear_pending_exception();
935}
936
937
938Failure* Isolate::PromoteScheduledException() {
939 MaybeObject* thrown = scheduled_exception();
940 clear_scheduled_exception();
941 // Re-throw the exception to avoid getting repeated error reporting.
942 return ReThrow(thrown);
943}
944
945
946void Isolate::PrintCurrentStackTrace(FILE* out) {
947 StackTraceFrameIterator it(this);
948 while (!it.done()) {
949 HandleScope scope;
950 // Find code position if recorded in relocation info.
951 JavaScriptFrame* frame = it.frame();
952 int pos = frame->LookupCode()->SourcePosition(frame->pc());
953 Handle<Object> pos_obj(Smi::FromInt(pos));
954 // Fetch function and receiver.
955 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
956 Handle<Object> recv(frame->receiver());
957 // Advance to the next JavaScript frame and determine if the
958 // current frame is the top-level frame.
959 it.Advance();
960 Handle<Object> is_top_level = it.done()
961 ? factory()->true_value()
962 : factory()->false_value();
963 // Generate and print stack trace line.
964 Handle<String> line =
965 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
966 if (line->length() > 0) {
967 line->PrintOn(out);
968 fprintf(out, "\n");
969 }
970 }
971}
972
973
974void Isolate::ComputeLocation(MessageLocation* target) {
975 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
976 StackTraceFrameIterator it(this);
977 if (!it.done()) {
978 JavaScriptFrame* frame = it.frame();
979 JSFunction* fun = JSFunction::cast(frame->function());
980 Object* script = fun->shared()->script();
981 if (script->IsScript() &&
982 !(Script::cast(script)->source()->IsUndefined())) {
983 int pos = frame->LookupCode()->SourcePosition(frame->pc());
984 // Compute the location from the function and the reloc info.
985 Handle<Script> casted_script(Script::cast(script));
986 *target = MessageLocation(casted_script, pos, pos + 1);
987 }
988 }
989}
990
991
992bool Isolate::ShouldReportException(bool* can_be_caught_externally,
993 bool catchable_by_javascript) {
994 // Find the top-most try-catch handler.
995 StackHandler* handler =
996 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
997 while (handler != NULL && !handler->is_try_catch()) {
998 handler = handler->next();
999 }
1000
1001 // Get the address of the external handler so we can compare the address to
1002 // determine which one is closer to the top of the stack.
1003 Address external_handler_address =
1004 thread_local_top()->try_catch_handler_address();
1005
1006 // The exception has been externally caught if and only if there is
1007 // an external handler which is on top of the top-most try-catch
1008 // handler.
1009 *can_be_caught_externally = external_handler_address != NULL &&
1010 (handler == NULL || handler->address() > external_handler_address ||
1011 !catchable_by_javascript);
1012
1013 if (*can_be_caught_externally) {
1014 // Only report the exception if the external handler is verbose.
1015 return try_catch_handler()->is_verbose_;
1016 } else {
1017 // Report the exception if it isn't caught by JavaScript code.
1018 return handler == NULL;
1019 }
1020}
1021
1022
1023void Isolate::DoThrow(MaybeObject* exception, MessageLocation* location) {
1024 ASSERT(!has_pending_exception());
1025
1026 HandleScope scope;
1027 Object* exception_object = Smi::FromInt(0);
1028 bool is_object = exception->ToObject(&exception_object);
1029 Handle<Object> exception_handle(exception_object);
1030
1031 // Determine reporting and whether the exception is caught externally.
1032 bool catchable_by_javascript = is_catchable_by_javascript(exception);
1033 // Only real objects can be caught by JS.
1034 ASSERT(!catchable_by_javascript || is_object);
1035 bool can_be_caught_externally = false;
1036 bool should_report_exception =
1037 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1038 bool report_exception = catchable_by_javascript && should_report_exception;
1039
1040#ifdef ENABLE_DEBUGGER_SUPPORT
1041 // Notify debugger of exception.
1042 if (catchable_by_javascript) {
1043 debugger_->OnException(exception_handle, report_exception);
1044 }
1045#endif
1046
1047 // Generate the message.
1048 Handle<Object> message_obj;
1049 MessageLocation potential_computed_location;
1050 bool try_catch_needs_message =
1051 can_be_caught_externally &&
1052 try_catch_handler()->capture_message_;
1053 if (report_exception || try_catch_needs_message) {
1054 if (location == NULL) {
1055 // If no location was specified we use a computed one instead
1056 ComputeLocation(&potential_computed_location);
1057 location = &potential_computed_location;
1058 }
1059 if (!bootstrapper()->IsActive()) {
1060 // It's not safe to try to make message objects or collect stack
1061 // traces while the bootstrapper is active since the infrastructure
1062 // may not have been properly initialized.
1063 Handle<String> stack_trace;
1064 if (FLAG_trace_exception) stack_trace = StackTraceString();
1065 Handle<JSArray> stack_trace_object;
1066 if (report_exception && capture_stack_trace_for_uncaught_exceptions_) {
1067 stack_trace_object = CaptureCurrentStackTrace(
1068 stack_trace_for_uncaught_exceptions_frame_limit_,
1069 stack_trace_for_uncaught_exceptions_options_);
1070 }
1071 ASSERT(is_object); // Can't use the handle unless there's a real object.
1072 message_obj = MessageHandler::MakeMessageObject("uncaught_exception",
1073 location, HandleVector<Object>(&exception_handle, 1), stack_trace,
1074 stack_trace_object);
erik.corry@gmail.com394dbcf2011-10-27 07:38:48 +00001075 } else if (location != NULL && !location->script().is_null()) {
1076 // We are bootstrapping and caught an error where the location is set
1077 // and we have a script for the location.
1078 // In this case we could have an extension (or an internal error
1079 // somewhere) and we print out the line number at which the error occured
1080 // to the console for easier debugging.
1081 int line_number = GetScriptLineNumberSafe(location->script(),
1082 location->start_pos());
1083 OS::PrintError("Extension or internal compilation error at line %d.\n",
1084 line_number);
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001085 }
1086 }
1087
1088 // Save the message for reporting if the the exception remains uncaught.
1089 thread_local_top()->has_pending_message_ = report_exception;
1090 if (!message_obj.is_null()) {
1091 thread_local_top()->pending_message_obj_ = *message_obj;
1092 if (location != NULL) {
1093 thread_local_top()->pending_message_script_ = *location->script();
1094 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1095 thread_local_top()->pending_message_end_pos_ = location->end_pos();
1096 }
1097 }
1098
1099 // Do not forget to clean catcher_ if currently thrown exception cannot
1100 // be caught. If necessary, ReThrow will update the catcher.
1101 thread_local_top()->catcher_ = can_be_caught_externally ?
1102 try_catch_handler() : NULL;
1103
1104 // NOTE: Notifying the debugger or generating the message
1105 // may have caused new exceptions. For now, we just ignore
1106 // that and set the pending exception to the original one.
1107 if (is_object) {
1108 set_pending_exception(*exception_handle);
1109 } else {
1110 // Failures are not on the heap so they neither need nor work with handles.
1111 ASSERT(exception_handle->IsFailure());
1112 set_pending_exception(exception);
1113 }
1114}
1115
1116
1117bool Isolate::IsExternallyCaught() {
1118 ASSERT(has_pending_exception());
1119
1120 if ((thread_local_top()->catcher_ == NULL) ||
1121 (try_catch_handler() != thread_local_top()->catcher_)) {
1122 // When throwing the exception, we found no v8::TryCatch
1123 // which should care about this exception.
1124 return false;
1125 }
1126
1127 if (!is_catchable_by_javascript(pending_exception())) {
1128 return true;
1129 }
1130
1131 // Get the address of the external handler so we can compare the address to
1132 // determine which one is closer to the top of the stack.
1133 Address external_handler_address =
1134 thread_local_top()->try_catch_handler_address();
1135 ASSERT(external_handler_address != NULL);
1136
1137 // The exception has been externally caught if and only if there is
1138 // an external handler which is on top of the top-most try-finally
1139 // handler.
1140 // There should be no try-catch blocks as they would prohibit us from
1141 // finding external catcher in the first place (see catcher_ check above).
1142 //
1143 // Note, that finally clause would rethrow an exception unless it's
1144 // aborted by jumps in control flow like return, break, etc. and we'll
1145 // have another chances to set proper v8::TryCatch.
1146 StackHandler* handler =
1147 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1148 while (handler != NULL && handler->address() < external_handler_address) {
1149 ASSERT(!handler->is_try_catch());
1150 if (handler->is_try_finally()) return false;
1151
1152 handler = handler->next();
1153 }
1154
1155 return true;
1156}
1157
1158
1159void Isolate::ReportPendingMessages() {
1160 ASSERT(has_pending_exception());
1161 PropagatePendingExceptionToExternalTryCatch();
1162
1163 // If the pending exception is OutOfMemoryException set out_of_memory in
1164 // the global context. Note: We have to mark the global context here
1165 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1166 // set it.
1167 HandleScope scope;
1168 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1169 context()->mark_out_of_memory();
1170 } else if (thread_local_top_.pending_exception_ ==
1171 heap()->termination_exception()) {
1172 // Do nothing: if needed, the exception has been already propagated to
1173 // v8::TryCatch.
1174 } else {
1175 if (thread_local_top_.has_pending_message_) {
1176 thread_local_top_.has_pending_message_ = false;
1177 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1178 HandleScope scope;
1179 Handle<Object> message_obj(thread_local_top_.pending_message_obj_);
1180 if (thread_local_top_.pending_message_script_ != NULL) {
1181 Handle<Script> script(thread_local_top_.pending_message_script_);
1182 int start_pos = thread_local_top_.pending_message_start_pos_;
1183 int end_pos = thread_local_top_.pending_message_end_pos_;
1184 MessageLocation location(script, start_pos, end_pos);
1185 MessageHandler::ReportMessage(this, &location, message_obj);
1186 } else {
1187 MessageHandler::ReportMessage(this, NULL, message_obj);
1188 }
1189 }
1190 }
1191 }
1192 clear_pending_message();
1193}
1194
1195
1196void Isolate::TraceException(bool flag) {
1197 FLAG_trace_exception = flag; // TODO(isolates): This is an unfortunate use.
1198}
1199
1200
1201bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1202 ASSERT(has_pending_exception());
1203 PropagatePendingExceptionToExternalTryCatch();
1204
1205 // Allways reschedule out of memory exceptions.
1206 if (!is_out_of_memory()) {
1207 bool is_termination_exception =
1208 pending_exception() == heap_.termination_exception();
1209
1210 // Do not reschedule the exception if this is the bottom call.
1211 bool clear_exception = is_bottom_call;
1212
1213 if (is_termination_exception) {
1214 if (is_bottom_call) {
1215 thread_local_top()->external_caught_exception_ = false;
1216 clear_pending_exception();
1217 return false;
1218 }
1219 } else if (thread_local_top()->external_caught_exception_) {
1220 // If the exception is externally caught, clear it if there are no
1221 // JavaScript frames on the way to the C++ frame that has the
1222 // external handler.
1223 ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1224 Address external_handler_address =
1225 thread_local_top()->try_catch_handler_address();
1226 JavaScriptFrameIterator it;
1227 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1228 clear_exception = true;
1229 }
1230 }
1231
1232 // Clear the exception if needed.
1233 if (clear_exception) {
1234 thread_local_top()->external_caught_exception_ = false;
1235 clear_pending_exception();
1236 return false;
1237 }
1238 }
1239
1240 // Reschedule the exception.
1241 thread_local_top()->scheduled_exception_ = pending_exception();
1242 clear_pending_exception();
1243 return true;
1244}
1245
1246
1247void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1248 bool capture,
1249 int frame_limit,
1250 StackTrace::StackTraceOptions options) {
1251 capture_stack_trace_for_uncaught_exceptions_ = capture;
1252 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1253 stack_trace_for_uncaught_exceptions_options_ = options;
1254}
1255
1256
1257bool Isolate::is_out_of_memory() {
1258 if (has_pending_exception()) {
1259 MaybeObject* e = pending_exception();
1260 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1261 return true;
1262 }
1263 }
1264 if (has_scheduled_exception()) {
1265 MaybeObject* e = scheduled_exception();
1266 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1267 return true;
1268 }
1269 }
1270 return false;
1271}
1272
1273
1274Handle<Context> Isolate::global_context() {
1275 GlobalObject* global = thread_local_top()->context_->global();
1276 return Handle<Context>(global->global_context());
1277}
1278
1279
1280Handle<Context> Isolate::GetCallingGlobalContext() {
1281 JavaScriptFrameIterator it;
1282#ifdef ENABLE_DEBUGGER_SUPPORT
1283 if (debug_->InDebugger()) {
1284 while (!it.done()) {
1285 JavaScriptFrame* frame = it.frame();
1286 Context* context = Context::cast(frame->context());
1287 if (context->global_context() == *debug_->debug_context()) {
1288 it.Advance();
1289 } else {
1290 break;
1291 }
1292 }
1293 }
1294#endif // ENABLE_DEBUGGER_SUPPORT
1295 if (it.done()) return Handle<Context>::null();
1296 JavaScriptFrame* frame = it.frame();
1297 Context* context = Context::cast(frame->context());
1298 return Handle<Context>(context->global_context());
1299}
1300
1301
1302char* Isolate::ArchiveThread(char* to) {
1303 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1304 RuntimeProfiler::IsolateExitedJS(this);
1305 }
1306 memcpy(to, reinterpret_cast<char*>(thread_local_top()),
1307 sizeof(ThreadLocalTop));
1308 InitializeThreadLocal();
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001309 clear_pending_exception();
1310 clear_pending_message();
1311 clear_scheduled_exception();
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001312 return to + sizeof(ThreadLocalTop);
1313}
1314
1315
1316char* Isolate::RestoreThread(char* from) {
1317 memcpy(reinterpret_cast<char*>(thread_local_top()), from,
1318 sizeof(ThreadLocalTop));
1319 // This might be just paranoia, but it seems to be needed in case a
1320 // thread_local_top_ is restored on a separate OS thread.
1321#ifdef USE_SIMULATOR
1322#ifdef V8_TARGET_ARCH_ARM
1323 thread_local_top()->simulator_ = Simulator::current(this);
1324#elif V8_TARGET_ARCH_MIPS
1325 thread_local_top()->simulator_ = Simulator::current(this);
1326#endif
1327#endif
1328 if (RuntimeProfiler::IsEnabled() && current_vm_state() == JS) {
1329 RuntimeProfiler::IsolateEnteredJS(this);
1330 }
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001331 ASSERT(context() == NULL || context()->IsContext());
vegorov@chromium.org7304bca2011-05-16 12:14:13 +00001332 return from + sizeof(ThreadLocalTop);
1333}
1334
1335
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001336Isolate::ThreadDataTable::ThreadDataTable()
1337 : list_(NULL) {
1338}
1339
1340
1341Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001342 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1343 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001344 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1345 if (data->Matches(isolate, thread_id)) return data;
1346 }
1347 return NULL;
1348}
1349
1350
1351void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1352 if (list_ != NULL) list_->prev_ = data;
1353 data->next_ = list_;
1354 list_ = data;
1355}
1356
1357
1358void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1359 if (list_ == data) list_ = data->next_;
1360 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1361 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001362 delete data;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001363}
1364
1365
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001366void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1367 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001368 PerIsolateThreadData* data = Lookup(isolate, thread_id);
1369 if (data != NULL) {
1370 Remove(data);
1371 }
1372}
1373
1374
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001375void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1376 PerIsolateThreadData* data = list_;
1377 while (data != NULL) {
1378 PerIsolateThreadData* next = data->next_;
1379 if (data->isolate() == isolate) Remove(data);
1380 data = next;
1381 }
1382}
1383
1384
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001385#ifdef DEBUG
1386#define TRACE_ISOLATE(tag) \
1387 do { \
1388 if (FLAG_trace_isolates) { \
1389 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
1390 } \
1391 } while (false)
1392#else
1393#define TRACE_ISOLATE(tag)
1394#endif
1395
1396
1397Isolate::Isolate()
1398 : state_(UNINITIALIZED),
1399 entry_stack_(NULL),
1400 stack_trace_nesting_level_(0),
1401 incomplete_message_(NULL),
1402 preallocated_memory_thread_(NULL),
1403 preallocated_message_space_(NULL),
1404 bootstrapper_(NULL),
1405 runtime_profiler_(NULL),
1406 compilation_cache_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001407 counters_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001408 code_range_(NULL),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001409 // Must be initialized early to allow v8::SetResourceConstraints calls.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001410 break_access_(OS::CreateMutex()),
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001411 debugger_initialized_(false),
1412 // Must be initialized early to allow v8::Debug calls.
1413 debugger_access_(OS::CreateMutex()),
1414 logger_(NULL),
1415 stats_table_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001416 stub_cache_(NULL),
1417 deoptimizer_data_(NULL),
1418 capture_stack_trace_for_uncaught_exceptions_(false),
1419 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1420 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1421 transcendental_cache_(NULL),
1422 memory_allocator_(NULL),
1423 keyed_lookup_cache_(NULL),
1424 context_slot_cache_(NULL),
1425 descriptor_lookup_cache_(NULL),
1426 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001427 unicode_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001428 in_use_list_(0),
1429 free_list_(0),
1430 preallocated_storage_preallocated_(false),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001431 inner_pointer_to_code_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001432 write_input_buffer_(NULL),
1433 global_handles_(NULL),
1434 context_switcher_(NULL),
1435 thread_manager_(NULL),
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001436 fp_stubs_generated_(false),
ricow@chromium.org27bf2882011-11-17 08:34:43 +00001437 has_installed_extensions_(false),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001438 string_tracker_(NULL),
1439 regexp_stack_(NULL),
ager@chromium.orgea91cc52011-05-23 06:06:11 +00001440 embedder_data_(NULL) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001441 TRACE_ISOLATE(constructor);
1442
1443 memset(isolate_addresses_, 0,
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001444 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001445
1446 heap_.isolate_ = this;
1447 zone_.isolate_ = this;
1448 stack_guard_.isolate_ = this;
1449
lrn@chromium.org1c092762011-05-09 09:42:16 +00001450 // ThreadManager is initialized early to support locking an isolate
1451 // before it is entered.
1452 thread_manager_ = new ThreadManager();
1453 thread_manager_->isolate_ = this;
1454
lrn@chromium.org7516f052011-03-30 08:52:27 +00001455#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
1456 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001457 simulator_initialized_ = false;
1458 simulator_i_cache_ = NULL;
1459 simulator_redirection_ = NULL;
1460#endif
1461
1462#ifdef DEBUG
1463 // heap_histograms_ initializes itself.
1464 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1465 memset(code_kind_statistics_, 0,
1466 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
1467#endif
1468
1469#ifdef ENABLE_DEBUGGER_SUPPORT
1470 debug_ = NULL;
1471 debugger_ = NULL;
1472#endif
1473
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001474 handle_scope_data_.Initialize();
1475
1476#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1477 name##_ = (initial_value);
1478 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1479#undef ISOLATE_INIT_EXECUTE
1480
1481#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1482 memset(name##_, 0, sizeof(type) * length);
1483 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1484#undef ISOLATE_INIT_ARRAY_EXECUTE
1485}
1486
1487void Isolate::TearDown() {
1488 TRACE_ISOLATE(tear_down);
1489
1490 // Temporarily set this isolate as current so that various parts of
1491 // the isolate can access it in their destructors without having a
1492 // direct pointer. We don't use Enter/Exit here to avoid
1493 // initializing the thread data.
1494 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1495 Isolate* saved_isolate = UncheckedCurrent();
1496 SetIsolateThreadLocals(this, NULL);
1497
1498 Deinit();
1499
jkummerow@chromium.orge297f592011-06-08 10:05:15 +00001500 { ScopedLock lock(process_wide_mutex_);
1501 thread_data_table_->RemoveAllThreads(this);
1502 }
1503
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001504 if (!IsDefaultIsolate()) {
1505 delete this;
1506 }
1507
1508 // Restore the previous current isolate.
1509 SetIsolateThreadLocals(saved_isolate, saved_data);
1510}
1511
1512
1513void Isolate::Deinit() {
1514 if (state_ == INITIALIZED) {
1515 TRACE_ISOLATE(deinit);
1516
1517 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
1518
1519 // We must stop the logger before we tear down other components.
1520 logger_->EnsureTickerStopped();
1521
1522 delete deoptimizer_data_;
1523 deoptimizer_data_ = NULL;
1524 if (FLAG_preemption) {
1525 v8::Locker locker;
1526 v8::Locker::StopPreemption();
1527 }
1528 builtins_.TearDown();
1529 bootstrapper_->TearDown();
1530
1531 // Remove the external reference to the preallocated stack memory.
1532 delete preallocated_message_space_;
1533 preallocated_message_space_ = NULL;
1534 PreallocatedMemoryThreadStop();
1535
1536 HeapProfiler::TearDown();
1537 CpuProfiler::TearDown();
1538 if (runtime_profiler_ != NULL) {
1539 runtime_profiler_->TearDown();
1540 delete runtime_profiler_;
1541 runtime_profiler_ = NULL;
1542 }
1543 heap_.TearDown();
1544 logger_->TearDown();
1545
1546 // The default isolate is re-initializable due to legacy API.
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001547 state_ = UNINITIALIZED;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001548 }
1549}
1550
1551
1552void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1553 PerIsolateThreadData* data) {
1554 Thread::SetThreadLocal(isolate_key_, isolate);
1555 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1556}
1557
1558
1559Isolate::~Isolate() {
1560 TRACE_ISOLATE(destructor);
1561
danno@chromium.orgb6451162011-08-17 14:33:23 +00001562 // Has to be called while counters_ are still alive.
1563 zone_.DeleteKeptSegment();
1564
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001565 delete[] assembler_spare_buffer_;
1566 assembler_spare_buffer_ = NULL;
1567
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001568 delete unicode_cache_;
1569 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001570
1571 delete regexp_stack_;
1572 regexp_stack_ = NULL;
1573
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001574 delete descriptor_lookup_cache_;
1575 descriptor_lookup_cache_ = NULL;
1576 delete context_slot_cache_;
1577 context_slot_cache_ = NULL;
1578 delete keyed_lookup_cache_;
1579 keyed_lookup_cache_ = NULL;
1580
1581 delete transcendental_cache_;
1582 transcendental_cache_ = NULL;
1583 delete stub_cache_;
1584 stub_cache_ = NULL;
1585 delete stats_table_;
1586 stats_table_ = NULL;
1587
1588 delete logger_;
1589 logger_ = NULL;
1590
1591 delete counters_;
1592 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001593
1594 delete handle_scope_implementer_;
1595 handle_scope_implementer_ = NULL;
1596 delete break_access_;
1597 break_access_ = NULL;
rossberg@chromium.org28a37082011-08-22 11:03:23 +00001598 delete debugger_access_;
1599 debugger_access_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001600
1601 delete compilation_cache_;
1602 compilation_cache_ = NULL;
1603 delete bootstrapper_;
1604 bootstrapper_ = NULL;
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001605 delete inner_pointer_to_code_cache_;
1606 inner_pointer_to_code_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001607 delete write_input_buffer_;
1608 write_input_buffer_ = NULL;
1609
1610 delete context_switcher_;
1611 context_switcher_ = NULL;
1612 delete thread_manager_;
1613 thread_manager_ = NULL;
1614
1615 delete string_tracker_;
1616 string_tracker_ = NULL;
1617
1618 delete memory_allocator_;
1619 memory_allocator_ = NULL;
1620 delete code_range_;
1621 code_range_ = NULL;
1622 delete global_handles_;
1623 global_handles_ = NULL;
1624
danno@chromium.orgb6451162011-08-17 14:33:23 +00001625 delete external_reference_table_;
1626 external_reference_table_ = NULL;
1627
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001628#ifdef ENABLE_DEBUGGER_SUPPORT
1629 delete debugger_;
1630 debugger_ = NULL;
1631 delete debug_;
1632 debug_ = NULL;
1633#endif
1634}
1635
1636
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001637void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +00001638 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001639 thread_local_top_.Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001640}
1641
1642
karlklose@chromium.org44bc7082011-04-11 12:33:05 +00001643void Isolate::PropagatePendingExceptionToExternalTryCatch() {
1644 ASSERT(has_pending_exception());
1645
1646 bool external_caught = IsExternallyCaught();
1647 thread_local_top_.external_caught_exception_ = external_caught;
1648
1649 if (!external_caught) return;
1650
1651 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
1652 // Do not propagate OOM exception: we should kill VM asap.
1653 } else if (thread_local_top_.pending_exception_ ==
1654 heap()->termination_exception()) {
1655 try_catch_handler()->can_continue_ = false;
1656 try_catch_handler()->exception_ = heap()->null_value();
1657 } else {
1658 // At this point all non-object (failure) exceptions have
1659 // been dealt with so this shouldn't fail.
1660 ASSERT(!pending_exception()->IsFailure());
1661 try_catch_handler()->can_continue_ = true;
1662 try_catch_handler()->exception_ = pending_exception();
1663 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1664 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
1665 }
1666 }
1667}
1668
1669
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001670void Isolate::InitializeLoggingAndCounters() {
1671 if (logger_ == NULL) {
1672 logger_ = new Logger;
1673 }
1674 if (counters_ == NULL) {
1675 counters_ = new Counters;
1676 }
1677}
1678
1679
1680void Isolate::InitializeDebugger() {
1681#ifdef ENABLE_DEBUGGER_SUPPORT
1682 ScopedLock lock(debugger_access_);
1683 if (NoBarrier_Load(&debugger_initialized_)) return;
1684 InitializeLoggingAndCounters();
1685 debug_ = new Debug(this);
1686 debugger_ = new Debugger(this);
1687 Release_Store(&debugger_initialized_, true);
1688#endif
1689}
1690
1691
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001692bool Isolate::Init(Deserializer* des) {
1693 ASSERT(state_ != INITIALIZED);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001694 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001695 TRACE_ISOLATE(init);
1696
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001697#ifdef DEBUG
1698 // The initialization process does not handle memory exhaustion.
1699 DisallowAllocationFailure disallow_allocation_failure;
1700#endif
1701
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001702 InitializeLoggingAndCounters();
1703
1704 InitializeDebugger();
1705
1706 memory_allocator_ = new MemoryAllocator(this);
1707 code_range_ = new CodeRange(this);
1708
1709 // Safe after setting Heap::isolate_, initializing StackGuard and
1710 // ensuring that Isolate::Current() == this.
1711 heap_.SetStackLimits();
1712
kmillikin@chromium.org83e16822011-09-13 08:21:47 +00001713#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1714 isolate_addresses_[Isolate::k##CamelName##Address] = \
1715 reinterpret_cast<Address>(hacker_name##_address());
1716 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001717#undef C
1718
1719 string_tracker_ = new StringTracker();
1720 string_tracker_->isolate_ = this;
1721 compilation_cache_ = new CompilationCache(this);
1722 transcendental_cache_ = new TranscendentalCache();
1723 keyed_lookup_cache_ = new KeyedLookupCache();
1724 context_slot_cache_ = new ContextSlotCache();
1725 descriptor_lookup_cache_ = new DescriptorLookupCache();
1726 unicode_cache_ = new UnicodeCache();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001727 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001728 write_input_buffer_ = new StringInputBuffer();
1729 global_handles_ = new GlobalHandles(this);
1730 bootstrapper_ = new Bootstrapper();
1731 handle_scope_implementer_ = new HandleScopeImplementer(this);
1732 stub_cache_ = new StubCache(this);
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001733 regexp_stack_ = new RegExpStack();
1734 regexp_stack_->isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001735
1736 // Enable logging before setting up the heap
1737 logger_->Setup();
1738
1739 CpuProfiler::Setup();
1740 HeapProfiler::Setup();
1741
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001742 // Initialize other runtime facilities
1743#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +00001744#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
lrn@chromium.org1c092762011-05-09 09:42:16 +00001745 Simulator::Initialize(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001746#endif
1747#endif
1748
1749 { // NOLINT
1750 // Ensure that the thread has a valid stack guard. The v8::Locker object
1751 // will ensure this too, but we don't have to use lockers if we are only
1752 // using one thread.
1753 ExecutionAccess lock(this);
1754 stack_guard_.InitThread(lock);
1755 }
1756
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001757 // Setup the object heap.
1758 const bool create_heap_objects = (des == NULL);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001759 ASSERT(!heap_.HasBeenSetup());
1760 if (!heap_.Setup(create_heap_objects)) {
1761 V8::SetFatalError();
1762 return false;
1763 }
1764
jkummerow@chromium.orgddda9e82011-07-06 11:27:02 +00001765 InitializeThreadLocal();
1766
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001767 bootstrapper_->Initialize(create_heap_objects);
1768 builtins_.Setup(create_heap_objects);
1769
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001770 // Only preallocate on the first initialization.
1771 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
1772 // Start the thread which will set aside some memory.
1773 PreallocatedMemoryThreadStart();
1774 preallocated_message_space_ =
1775 new NoAllocationStringAllocator(
1776 preallocated_memory_thread_->data(),
1777 preallocated_memory_thread_->length());
1778 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
1779 }
1780
1781 if (FLAG_preemption) {
1782 v8::Locker locker;
1783 v8::Locker::StartPreemption(100);
1784 }
1785
1786#ifdef ENABLE_DEBUGGER_SUPPORT
1787 debug_->Setup(create_heap_objects);
1788#endif
1789 stub_cache_->Initialize(create_heap_objects);
1790
1791 // If we are deserializing, read the state into the now-empty heap.
1792 if (des != NULL) {
1793 des->Deserialize();
erik.corry@gmail.comc3b670f2011-10-05 21:44:48 +00001794 stub_cache_->Initialize(true);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001795 }
1796
svenpanne@chromium.orga8bb4d92011-10-10 13:20:40 +00001797 // Finish initialization of ThreadLocal after deserialization is done.
1798 clear_pending_exception();
1799 clear_pending_message();
1800 clear_scheduled_exception();
1801
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001802 // Deserializing may put strange things in the root array's copy of the
1803 // stack guard.
1804 heap_.SetStackLimits();
1805
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001806 deoptimizer_data_ = new DeoptimizerData;
1807 runtime_profiler_ = new RuntimeProfiler(this);
1808 runtime_profiler_->Setup();
1809
1810 // If we are deserializing, log non-function code objects and compiled
1811 // functions found in the snapshot.
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +00001812 if (des != NULL && (FLAG_log_code || FLAG_ll_prof)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001813 HandleScope scope;
1814 LOG(this, LogCodeObjects());
1815 LOG(this, LogCompiledFunctions());
1816 }
1817
1818 state_ = INITIALIZED;
1819 return true;
1820}
1821
1822
kmillikin@chromium.org7c2628c2011-08-10 11:27:35 +00001823// Initialized lazily to allow early
1824// v8::V8::SetAddHistogramSampleFunction calls.
1825StatsTable* Isolate::stats_table() {
1826 if (stats_table_ == NULL) {
1827 stats_table_ = new StatsTable;
1828 }
1829 return stats_table_;
1830}
1831
1832
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001833void Isolate::Enter() {
1834 Isolate* current_isolate = NULL;
1835 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
1836 if (current_data != NULL) {
1837 current_isolate = current_data->isolate_;
1838 ASSERT(current_isolate != NULL);
1839 if (current_isolate == this) {
1840 ASSERT(Current() == this);
1841 ASSERT(entry_stack_ != NULL);
1842 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001843 entry_stack_->previous_thread_data->thread_id().Equals(
1844 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001845 // Same thread re-enters the isolate, no need to re-init anything.
1846 entry_stack_->entry_count++;
1847 return;
1848 }
1849 }
1850
1851 // Threads can have default isolate set into TLS as Current but not yet have
1852 // PerIsolateThreadData for it, as it requires more advanced phase of the
1853 // initialization. For example, a thread might be the one that system used for
1854 // static initializers - in this case the default isolate is set in TLS but
1855 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
1856 // there, use the isolate set in TLS.
1857 if (current_isolate == NULL) {
1858 current_isolate = Isolate::UncheckedCurrent();
1859 }
1860
1861 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
1862 ASSERT(data != NULL);
1863 ASSERT(data->isolate_ == this);
1864
1865 EntryStackItem* item = new EntryStackItem(current_data,
1866 current_isolate,
1867 entry_stack_);
1868 entry_stack_ = item;
1869
1870 SetIsolateThreadLocals(this, data);
1871
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001872 // In case it's the first time some thread enters the isolate.
1873 set_thread_id(data->thread_id());
1874}
1875
1876
1877void Isolate::Exit() {
1878 ASSERT(entry_stack_ != NULL);
1879 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001880 entry_stack_->previous_thread_data->thread_id().Equals(
1881 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001882
1883 if (--entry_stack_->entry_count > 0) return;
1884
1885 ASSERT(CurrentPerIsolateThreadData() != NULL);
1886 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
1887
1888 // Pop the stack.
1889 EntryStackItem* item = entry_stack_;
1890 entry_stack_ = item->previous_item;
1891
1892 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
1893 Isolate* previous_isolate = item->previous_isolate;
1894
1895 delete item;
1896
1897 // Reinit the current thread for the isolate it was running before this one.
1898 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
1899}
1900
1901
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00001902#ifdef DEBUG
1903#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1904const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
1905ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
1906ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
1907#undef ISOLATE_FIELD_OFFSET
1908#endif
1909
1910} } // namespace v8::internal