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