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