Merge remote-tracking branch 'origin/v0.10'
[platform/upstream/nodejs.git] / deps / 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 "allocation-inl.h"
33 #include "ast.h"
34 #include "bootstrapper.h"
35 #include "codegen.h"
36 #include "compilation-cache.h"
37 #include "cpu-profiler.h"
38 #include "debug.h"
39 #include "deoptimizer.h"
40 #include "heap-profiler.h"
41 #include "hydrogen.h"
42 #include "isolate.h"
43 #include "lithium-allocator.h"
44 #include "log.h"
45 #include "marking-thread.h"
46 #include "messages.h"
47 #include "platform.h"
48 #include "regexp-stack.h"
49 #include "runtime-profiler.h"
50 #include "sampler.h"
51 #include "scopeinfo.h"
52 #include "serialize.h"
53 #include "simulator.h"
54 #include "spaces.h"
55 #include "stub-cache.h"
56 #include "sweeper-thread.h"
57 #include "version.h"
58 #include "vm-state-inl.h"
59
60
61 namespace v8 {
62 namespace internal {
63
64 Atomic32 ThreadId::highest_thread_id_ = 0;
65
66 int ThreadId::AllocateThreadId() {
67   int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
68   return new_id;
69 }
70
71
72 int ThreadId::GetCurrentThreadId() {
73   int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
74   if (thread_id == 0) {
75     thread_id = AllocateThreadId();
76     Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
77   }
78   return thread_id;
79 }
80
81
82 ThreadLocalTop::ThreadLocalTop() {
83   InitializeInternal();
84   // This flag may be set using v8::V8::IgnoreOutOfMemoryException()
85   // before an isolate is initialized. The initialize methods below do
86   // not touch it to preserve its value.
87   ignore_out_of_memory_ = false;
88 }
89
90
91 void ThreadLocalTop::InitializeInternal() {
92   c_entry_fp_ = 0;
93   handler_ = 0;
94 #ifdef USE_SIMULATOR
95   simulator_ = NULL;
96 #endif
97   js_entry_sp_ = NULL;
98   external_callback_scope_ = NULL;
99   current_vm_state_ = EXTERNAL;
100   try_catch_handler_address_ = NULL;
101   context_ = NULL;
102   thread_id_ = ThreadId::Invalid();
103   external_caught_exception_ = false;
104   failed_access_check_callback_ = NULL;
105   save_context_ = NULL;
106   catcher_ = NULL;
107   top_lookup_result_ = NULL;
108
109   // These members are re-initialized later after deserialization
110   // is complete.
111   pending_exception_ = NULL;
112   has_pending_message_ = false;
113   rethrowing_message_ = false;
114   pending_message_obj_ = NULL;
115   pending_message_script_ = NULL;
116   scheduled_exception_ = NULL;
117 }
118
119
120 void ThreadLocalTop::Initialize() {
121   InitializeInternal();
122 #ifdef USE_SIMULATOR
123 #if V8_TARGET_ARCH_ARM
124   simulator_ = Simulator::current(isolate_);
125 #elif V8_TARGET_ARCH_MIPS
126   simulator_ = Simulator::current(isolate_);
127 #endif
128 #endif
129   thread_id_ = ThreadId::Current();
130 }
131
132
133 v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
134   return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
135 }
136
137
138 int SystemThreadManager::NumberOfParallelSystemThreads(
139     ParallelSystemComponent type) {
140   int number_of_threads = Min(OS::NumberOfCores(), kMaxThreads);
141   ASSERT(number_of_threads > 0);
142   if (number_of_threads ==  1) {
143     return 0;
144   }
145   if (type == PARALLEL_SWEEPING) {
146     return number_of_threads;
147   } else if (type == CONCURRENT_SWEEPING) {
148     return number_of_threads - 1;
149   } else if (type == PARALLEL_MARKING) {
150     return number_of_threads;
151   }
152   return 1;
153 }
154
155
156 // Create a dummy thread that will wait forever on a semaphore. The only
157 // purpose for this thread is to have some stack area to save essential data
158 // into for use by a stacks only core dump (aka minidump).
159 class PreallocatedMemoryThread: public Thread {
160  public:
161   char* data() {
162     if (data_ready_semaphore_ != NULL) {
163       // Initial access is guarded until the data has been published.
164       data_ready_semaphore_->Wait();
165       delete data_ready_semaphore_;
166       data_ready_semaphore_ = NULL;
167     }
168     return data_;
169   }
170
171   unsigned length() {
172     if (data_ready_semaphore_ != NULL) {
173       // Initial access is guarded until the data has been published.
174       data_ready_semaphore_->Wait();
175       delete data_ready_semaphore_;
176       data_ready_semaphore_ = NULL;
177     }
178     return length_;
179   }
180
181   // Stop the PreallocatedMemoryThread and release its resources.
182   void StopThread() {
183     keep_running_ = false;
184     wait_for_ever_semaphore_->Signal();
185
186     // Wait for the thread to terminate.
187     Join();
188
189     if (data_ready_semaphore_ != NULL) {
190       delete data_ready_semaphore_;
191       data_ready_semaphore_ = NULL;
192     }
193
194     delete wait_for_ever_semaphore_;
195     wait_for_ever_semaphore_ = NULL;
196   }
197
198  protected:
199   // When the thread starts running it will allocate a fixed number of bytes
200   // on the stack and publish the location of this memory for others to use.
201   void Run() {
202     EmbeddedVector<char, 15 * 1024> local_buffer;
203
204     // Initialize the buffer with a known good value.
205     OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
206                 local_buffer.length());
207
208     // Publish the local buffer and signal its availability.
209     data_ = local_buffer.start();
210     length_ = local_buffer.length();
211     data_ready_semaphore_->Signal();
212
213     while (keep_running_) {
214       // This thread will wait here until the end of time.
215       wait_for_ever_semaphore_->Wait();
216     }
217
218     // Make sure we access the buffer after the wait to remove all possibility
219     // of it being optimized away.
220     OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
221                 local_buffer.length());
222   }
223
224
225  private:
226   PreallocatedMemoryThread()
227       : Thread("v8:PreallocMem"),
228         keep_running_(true),
229         wait_for_ever_semaphore_(OS::CreateSemaphore(0)),
230         data_ready_semaphore_(OS::CreateSemaphore(0)),
231         data_(NULL),
232         length_(0) {
233   }
234
235   // Used to make sure that the thread keeps looping even for spurious wakeups.
236   bool keep_running_;
237
238   // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
239   Semaphore* wait_for_ever_semaphore_;
240   // Semaphore to signal that the data has been initialized.
241   Semaphore* data_ready_semaphore_;
242
243   // Location and size of the preallocated memory block.
244   char* data_;
245   unsigned length_;
246
247   friend class Isolate;
248
249   DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
250 };
251
252
253 void Isolate::PreallocatedMemoryThreadStart() {
254   if (preallocated_memory_thread_ != NULL) return;
255   preallocated_memory_thread_ = new PreallocatedMemoryThread();
256   preallocated_memory_thread_->Start();
257 }
258
259
260 void Isolate::PreallocatedMemoryThreadStop() {
261   if (preallocated_memory_thread_ == NULL) return;
262   preallocated_memory_thread_->StopThread();
263   // Done with the thread entirely.
264   delete preallocated_memory_thread_;
265   preallocated_memory_thread_ = NULL;
266 }
267
268
269 void Isolate::PreallocatedStorageInit(size_t size) {
270   ASSERT(free_list_.next_ == &free_list_);
271   ASSERT(free_list_.previous_ == &free_list_);
272   PreallocatedStorage* free_chunk =
273       reinterpret_cast<PreallocatedStorage*>(new char[size]);
274   free_list_.next_ = free_list_.previous_ = free_chunk;
275   free_chunk->next_ = free_chunk->previous_ = &free_list_;
276   free_chunk->size_ = size - sizeof(PreallocatedStorage);
277   preallocated_storage_preallocated_ = true;
278 }
279
280
281 void* Isolate::PreallocatedStorageNew(size_t size) {
282   if (!preallocated_storage_preallocated_) {
283     return FreeStoreAllocationPolicy().New(size);
284   }
285   ASSERT(free_list_.next_ != &free_list_);
286   ASSERT(free_list_.previous_ != &free_list_);
287
288   size = (size + kPointerSize - 1) & ~(kPointerSize - 1);
289   // Search for exact fit.
290   for (PreallocatedStorage* storage = free_list_.next_;
291        storage != &free_list_;
292        storage = storage->next_) {
293     if (storage->size_ == size) {
294       storage->Unlink();
295       storage->LinkTo(&in_use_list_);
296       return reinterpret_cast<void*>(storage + 1);
297     }
298   }
299   // Search for first fit.
300   for (PreallocatedStorage* storage = free_list_.next_;
301        storage != &free_list_;
302        storage = storage->next_) {
303     if (storage->size_ >= size + sizeof(PreallocatedStorage)) {
304       storage->Unlink();
305       storage->LinkTo(&in_use_list_);
306       PreallocatedStorage* left_over =
307           reinterpret_cast<PreallocatedStorage*>(
308               reinterpret_cast<char*>(storage + 1) + size);
309       left_over->size_ = storage->size_ - size - sizeof(PreallocatedStorage);
310       ASSERT(size + left_over->size_ + sizeof(PreallocatedStorage) ==
311              storage->size_);
312       storage->size_ = size;
313       left_over->LinkTo(&free_list_);
314       return reinterpret_cast<void*>(storage + 1);
315     }
316   }
317   // Allocation failure.
318   ASSERT(false);
319   return NULL;
320 }
321
322
323 // We don't attempt to coalesce.
324 void Isolate::PreallocatedStorageDelete(void* p) {
325   if (p == NULL) {
326     return;
327   }
328   if (!preallocated_storage_preallocated_) {
329     FreeStoreAllocationPolicy::Delete(p);
330     return;
331   }
332   PreallocatedStorage* storage = reinterpret_cast<PreallocatedStorage*>(p) - 1;
333   ASSERT(storage->next_->previous_ == storage);
334   ASSERT(storage->previous_->next_ == storage);
335   storage->Unlink();
336   storage->LinkTo(&free_list_);
337 }
338
339 Isolate* Isolate::default_isolate_ = NULL;
340 Thread::LocalStorageKey Isolate::isolate_key_;
341 Thread::LocalStorageKey Isolate::thread_id_key_;
342 Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
343 #ifdef DEBUG
344 Thread::LocalStorageKey PerThreadAssertScopeBase::thread_local_key;
345 #endif  // DEBUG
346 Mutex* Isolate::process_wide_mutex_ = OS::CreateMutex();
347 Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
348 Atomic32 Isolate::isolate_counter_ = 0;
349
350 Isolate::PerIsolateThreadData* Isolate::AllocatePerIsolateThreadData(
351     ThreadId thread_id) {
352   ASSERT(!thread_id.Equals(ThreadId::Invalid()));
353   PerIsolateThreadData* per_thread = new PerIsolateThreadData(this, thread_id);
354   {
355     ScopedLock lock(process_wide_mutex_);
356     ASSERT(thread_data_table_->Lookup(this, thread_id) == NULL);
357     thread_data_table_->Insert(per_thread);
358     ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
359   }
360   return per_thread;
361 }
362
363
364 Isolate::PerIsolateThreadData*
365     Isolate::FindOrAllocatePerThreadDataForThisThread() {
366   ThreadId thread_id = ThreadId::Current();
367   PerIsolateThreadData* per_thread = NULL;
368   {
369     ScopedLock lock(process_wide_mutex_);
370     per_thread = thread_data_table_->Lookup(this, thread_id);
371     if (per_thread == NULL) {
372       per_thread = AllocatePerIsolateThreadData(thread_id);
373     }
374   }
375   return per_thread;
376 }
377
378
379 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
380   ThreadId thread_id = ThreadId::Current();
381   return FindPerThreadDataForThread(thread_id);
382 }
383
384
385 Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
386     ThreadId thread_id) {
387   PerIsolateThreadData* per_thread = NULL;
388   {
389     ScopedLock lock(process_wide_mutex_);
390     per_thread = thread_data_table_->Lookup(this, thread_id);
391   }
392   return per_thread;
393 }
394
395
396 void Isolate::EnsureDefaultIsolate() {
397   ScopedLock lock(process_wide_mutex_);
398   if (default_isolate_ == NULL) {
399     isolate_key_ = Thread::CreateThreadLocalKey();
400     thread_id_key_ = Thread::CreateThreadLocalKey();
401     per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
402 #ifdef DEBUG
403     PerThreadAssertScopeBase::thread_local_key = Thread::CreateThreadLocalKey();
404 #endif  // DEBUG
405     thread_data_table_ = new Isolate::ThreadDataTable();
406     default_isolate_ = new Isolate();
407   }
408   // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
409   // because a non-null thread data may be already set.
410   if (Thread::GetThreadLocal(isolate_key_) == NULL) {
411     Thread::SetThreadLocal(isolate_key_, default_isolate_);
412   }
413 }
414
415 struct StaticInitializer {
416   StaticInitializer() {
417     Isolate::EnsureDefaultIsolate();
418   }
419 } static_initializer;
420
421 #ifdef ENABLE_DEBUGGER_SUPPORT
422 Debugger* Isolate::GetDefaultIsolateDebugger() {
423   EnsureDefaultIsolate();
424   return default_isolate_->debugger();
425 }
426 #endif
427
428
429 StackGuard* Isolate::GetDefaultIsolateStackGuard() {
430   EnsureDefaultIsolate();
431   return default_isolate_->stack_guard();
432 }
433
434
435 void Isolate::EnterDefaultIsolate() {
436   EnsureDefaultIsolate();
437   ASSERT(default_isolate_ != NULL);
438
439   PerIsolateThreadData* data = CurrentPerIsolateThreadData();
440   // If not yet in default isolate - enter it.
441   if (data == NULL || data->isolate() != default_isolate_) {
442     default_isolate_->Enter();
443   }
444 }
445
446
447 v8::Isolate* Isolate::GetDefaultIsolateForLocking() {
448   EnsureDefaultIsolate();
449   return reinterpret_cast<v8::Isolate*>(default_isolate_);
450 }
451
452
453 Address Isolate::get_address_from_id(Isolate::AddressId id) {
454   return isolate_addresses_[id];
455 }
456
457
458 char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
459   ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
460   Iterate(v, thread);
461   return thread_storage + sizeof(ThreadLocalTop);
462 }
463
464
465 void Isolate::IterateThread(ThreadVisitor* v, char* t) {
466   ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
467   v->VisitThread(this, thread);
468 }
469
470
471 void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
472   // Visit the roots from the top for a given thread.
473   Object* pending;
474   // The pending exception can sometimes be a failure.  We can't show
475   // that to the GC, which only understands objects.
476   if (thread->pending_exception_->ToObject(&pending)) {
477     v->VisitPointer(&pending);
478     thread->pending_exception_ = pending;  // In case GC updated it.
479   }
480   v->VisitPointer(&(thread->pending_message_obj_));
481   v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
482   v->VisitPointer(BitCast<Object**>(&(thread->context_)));
483   Object* scheduled;
484   if (thread->scheduled_exception_->ToObject(&scheduled)) {
485     v->VisitPointer(&scheduled);
486     thread->scheduled_exception_ = scheduled;
487   }
488
489   for (v8::TryCatch* block = thread->TryCatchHandler();
490        block != NULL;
491        block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
492     v->VisitPointer(BitCast<Object**>(&(block->exception_)));
493     v->VisitPointer(BitCast<Object**>(&(block->message_obj_)));
494     v->VisitPointer(BitCast<Object**>(&(block->message_script_)));
495   }
496
497   // Iterate over pointers on native execution stack.
498   for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
499     it.frame()->Iterate(v);
500   }
501
502   // Iterate pointers in live lookup results.
503   thread->top_lookup_result_->Iterate(v);
504 }
505
506
507 void Isolate::Iterate(ObjectVisitor* v) {
508   ThreadLocalTop* current_t = thread_local_top();
509   Iterate(v, current_t);
510 }
511
512
513 void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
514   for (DeferredHandles* deferred = deferred_handles_head_;
515        deferred != NULL;
516        deferred = deferred->next_) {
517     deferred->Iterate(visitor);
518   }
519 }
520
521
522 #ifdef DEBUG
523 bool Isolate::IsDeferredHandle(Object** handle) {
524   // Each DeferredHandles instance keeps the handles to one job in the
525   // parallel recompilation queue, containing a list of blocks.  Each block
526   // contains kHandleBlockSize handles except for the first block, which may
527   // not be fully filled.
528   // We iterate through all the blocks to see whether the argument handle
529   // belongs to one of the blocks.  If so, it is deferred.
530   for (DeferredHandles* deferred = deferred_handles_head_;
531        deferred != NULL;
532        deferred = deferred->next_) {
533     List<Object**>* blocks = &deferred->blocks_;
534     for (int i = 0; i < blocks->length(); i++) {
535       Object** block_limit = (i == 0) ? deferred->first_block_limit_
536                                       : blocks->at(i) + kHandleBlockSize;
537       if (blocks->at(i) <= handle && handle < block_limit) return true;
538     }
539   }
540   return false;
541 }
542 #endif  // DEBUG
543
544
545 void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
546   // The ARM simulator has a separate JS stack.  We therefore register
547   // the C++ try catch handler with the simulator and get back an
548   // address that can be used for comparisons with addresses into the
549   // JS stack.  When running without the simulator, the address
550   // returned will be the address of the C++ try catch handler itself.
551   Address address = reinterpret_cast<Address>(
552       SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
553   thread_local_top()->set_try_catch_handler_address(address);
554 }
555
556
557 void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
558   ASSERT(thread_local_top()->TryCatchHandler() == that);
559   thread_local_top()->set_try_catch_handler_address(
560       reinterpret_cast<Address>(that->next_));
561   thread_local_top()->catcher_ = NULL;
562   SimulatorStack::UnregisterCTryCatch();
563 }
564
565
566 Handle<String> Isolate::StackTraceString() {
567   if (stack_trace_nesting_level_ == 0) {
568     stack_trace_nesting_level_++;
569     HeapStringAllocator allocator;
570     StringStream::ClearMentionedObjectCache();
571     StringStream accumulator(&allocator);
572     incomplete_message_ = &accumulator;
573     PrintStack(&accumulator);
574     Handle<String> stack_trace = accumulator.ToString();
575     incomplete_message_ = NULL;
576     stack_trace_nesting_level_ = 0;
577     return stack_trace;
578   } else if (stack_trace_nesting_level_ == 1) {
579     stack_trace_nesting_level_++;
580     OS::PrintError(
581       "\n\nAttempt to print stack while printing stack (double fault)\n");
582     OS::PrintError(
583       "If you are lucky you may find a partial stack dump on stdout.\n\n");
584     incomplete_message_->OutputToStdOut();
585     return factory()->empty_string();
586   } else {
587     OS::Abort();
588     // Unreachable
589     return factory()->empty_string();
590   }
591 }
592
593
594 void Isolate::PushStackTraceAndDie(unsigned int magic,
595                                    Object* object,
596                                    Map* map,
597                                    unsigned int magic2) {
598   const int kMaxStackTraceSize = 8192;
599   Handle<String> trace = StackTraceString();
600   uint8_t buffer[kMaxStackTraceSize];
601   int length = Min(kMaxStackTraceSize - 1, trace->length());
602   String::WriteToFlat(*trace, buffer, 0, length);
603   buffer[length] = '\0';
604   // TODO(dcarney): convert buffer to utf8?
605   OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n",
606                  magic, magic2,
607                  static_cast<void*>(object), static_cast<void*>(map),
608                  reinterpret_cast<char*>(buffer));
609   OS::Abort();
610 }
611
612
613 // Determines whether the given stack frame should be displayed in
614 // a stack trace.  The caller is the error constructor that asked
615 // for the stack trace to be collected.  The first time a construct
616 // call to this function is encountered it is skipped.  The seen_caller
617 // in/out parameter is used to remember if the caller has been seen
618 // yet.
619 static bool IsVisibleInStackTrace(StackFrame* raw_frame,
620                                   Object* caller,
621                                   bool* seen_caller) {
622   // Only display JS frames.
623   if (!raw_frame->is_java_script()) return false;
624   JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
625   JSFunction* fun = frame->function();
626   if ((fun == caller) && !(*seen_caller)) {
627     *seen_caller = true;
628     return false;
629   }
630   // Skip all frames until we've seen the caller.
631   if (!(*seen_caller)) return false;
632   // Also, skip non-visible built-in functions and any call with the builtins
633   // object as receiver, so as to not reveal either the builtins object or
634   // an internal function.
635   // The --builtins-in-stack-traces command line flag allows including
636   // internal call sites in the stack trace for debugging purposes.
637   if (!FLAG_builtins_in_stack_traces) {
638     if (frame->receiver()->IsJSBuiltinsObject() ||
639         (fun->IsBuiltin() && !fun->shared()->native())) {
640       return false;
641     }
642   }
643   return true;
644 }
645
646
647 Handle<JSArray> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
648                                                  Handle<Object> caller,
649                                                  int limit) {
650   limit = Max(limit, 0);  // Ensure that limit is not negative.
651   int initial_size = Min(limit, 10);
652   Handle<FixedArray> elements =
653       factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
654
655   // If the caller parameter is a function we skip frames until we're
656   // under it before starting to collect.
657   bool seen_caller = !caller->IsJSFunction();
658   // First element is reserved to store the number of non-strict frames.
659   int cursor = 1;
660   int frames_seen = 0;
661   int non_strict_frames = 0;
662   bool encountered_strict_function = false;
663   for (StackFrameIterator iter(this);
664        !iter.done() && frames_seen < limit;
665        iter.Advance()) {
666     StackFrame* raw_frame = iter.frame();
667     if (IsVisibleInStackTrace(raw_frame, *caller, &seen_caller)) {
668       frames_seen++;
669       JavaScriptFrame* frame = JavaScriptFrame::cast(raw_frame);
670       // Set initial size to the maximum inlining level + 1 for the outermost
671       // function.
672       List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
673       frame->Summarize(&frames);
674       for (int i = frames.length() - 1; i >= 0; i--) {
675         if (cursor + 4 > elements->length()) {
676           int new_capacity = JSObject::NewElementsCapacity(elements->length());
677           Handle<FixedArray> new_elements =
678               factory()->NewFixedArrayWithHoles(new_capacity);
679           for (int i = 0; i < cursor; i++) {
680             new_elements->set(i, elements->get(i));
681           }
682           elements = new_elements;
683         }
684         ASSERT(cursor + 4 <= elements->length());
685
686         Handle<Object> recv = frames[i].receiver();
687         Handle<JSFunction> fun = frames[i].function();
688         Handle<Code> code = frames[i].code();
689         Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
690         // The stack trace API should not expose receivers and function
691         // objects on frames deeper than the top-most one with a strict
692         // mode function.  The number of non-strict frames is stored as
693         // first element in the result array.
694         if (!encountered_strict_function) {
695           if (!fun->shared()->is_classic_mode()) {
696             encountered_strict_function = true;
697           } else {
698             non_strict_frames++;
699           }
700         }
701         elements->set(cursor++, *recv);
702         elements->set(cursor++, *fun);
703         elements->set(cursor++, *code);
704         elements->set(cursor++, *offset);
705       }
706     }
707   }
708   elements->set(0, Smi::FromInt(non_strict_frames));
709   Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
710   result->set_length(Smi::FromInt(cursor));
711   return result;
712 }
713
714
715 void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
716   if (capture_stack_trace_for_uncaught_exceptions_) {
717     // Capture stack trace for a detailed exception message.
718     Handle<String> key = factory()->hidden_stack_trace_string();
719     Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
720         stack_trace_for_uncaught_exceptions_frame_limit_,
721         stack_trace_for_uncaught_exceptions_options_);
722     JSObject::SetHiddenProperty(error_object, key, stack_trace);
723   }
724 }
725
726
727 Handle<JSArray> Isolate::CaptureCurrentStackTrace(
728     int frame_limit, StackTrace::StackTraceOptions options) {
729   // Ensure no negative values.
730   int limit = Max(frame_limit, 0);
731   Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
732
733   Handle<String> column_key =
734       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("column"));
735   Handle<String> line_key =
736       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("lineNumber"));
737   Handle<String> script_key =
738       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("scriptName"));
739   Handle<String> script_name_or_source_url_key =
740       factory()->InternalizeOneByteString(
741           STATIC_ASCII_VECTOR("scriptNameOrSourceURL"));
742   Handle<String> function_key =
743       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("functionName"));
744   Handle<String> eval_key =
745       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isEval"));
746   Handle<String> constructor_key =
747       factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("isConstructor"));
748
749   StackTraceFrameIterator it(this);
750   int frames_seen = 0;
751   while (!it.done() && (frames_seen < limit)) {
752     JavaScriptFrame* frame = it.frame();
753     // Set initial size to the maximum inlining level + 1 for the outermost
754     // function.
755     List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
756     frame->Summarize(&frames);
757     for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
758       // Create a JSObject to hold the information for the StackFrame.
759       Handle<JSObject> stack_frame = factory()->NewJSObject(object_function());
760
761       Handle<JSFunction> fun = frames[i].function();
762       Handle<Script> script(Script::cast(fun->shared()->script()));
763
764       if (options & StackTrace::kLineNumber) {
765         int script_line_offset = script->line_offset()->value();
766         int position = frames[i].code()->SourcePosition(frames[i].pc());
767         int line_number = GetScriptLineNumber(script, position);
768         // line_number is already shifted by the script_line_offset.
769         int relative_line_number = line_number - script_line_offset;
770         if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
771           Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
772           int start = (relative_line_number == 0) ? 0 :
773               Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
774           int column_offset = position - start;
775           if (relative_line_number == 0) {
776             // For the case where the code is on the same line as the script
777             // tag.
778             column_offset += script->column_offset()->value();
779           }
780           CHECK_NOT_EMPTY_HANDLE(
781               this,
782               JSObject::SetLocalPropertyIgnoreAttributes(
783                   stack_frame, column_key,
784                   Handle<Smi>(Smi::FromInt(column_offset + 1), this), NONE));
785         }
786         CHECK_NOT_EMPTY_HANDLE(
787             this,
788             JSObject::SetLocalPropertyIgnoreAttributes(
789                 stack_frame, line_key,
790                 Handle<Smi>(Smi::FromInt(line_number + 1), this), NONE));
791       }
792
793       if (options & StackTrace::kScriptName) {
794         Handle<Object> script_name(script->name(), this);
795         CHECK_NOT_EMPTY_HANDLE(this,
796                                JSObject::SetLocalPropertyIgnoreAttributes(
797                                    stack_frame, script_key, script_name, NONE));
798       }
799
800       if (options & StackTrace::kScriptNameOrSourceURL) {
801         Handle<Object> result = GetScriptNameOrSourceURL(script);
802         CHECK_NOT_EMPTY_HANDLE(this,
803                                JSObject::SetLocalPropertyIgnoreAttributes(
804                                    stack_frame, script_name_or_source_url_key,
805                                    result, NONE));
806       }
807
808       if (options & StackTrace::kFunctionName) {
809         Handle<Object> fun_name(fun->shared()->name(), this);
810         if (!fun_name->BooleanValue()) {
811           fun_name = Handle<Object>(fun->shared()->inferred_name(), this);
812         }
813         CHECK_NOT_EMPTY_HANDLE(this,
814                                JSObject::SetLocalPropertyIgnoreAttributes(
815                                    stack_frame, function_key, fun_name, NONE));
816       }
817
818       if (options & StackTrace::kIsEval) {
819         int type = Smi::cast(script->compilation_type())->value();
820         Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
821             factory()->true_value() : factory()->false_value();
822         CHECK_NOT_EMPTY_HANDLE(this,
823                                JSObject::SetLocalPropertyIgnoreAttributes(
824                                    stack_frame, eval_key, is_eval, NONE));
825       }
826
827       if (options & StackTrace::kIsConstructor) {
828         Handle<Object> is_constructor = (frames[i].is_constructor()) ?
829             factory()->true_value() : factory()->false_value();
830         CHECK_NOT_EMPTY_HANDLE(this,
831                                JSObject::SetLocalPropertyIgnoreAttributes(
832                                    stack_frame, constructor_key,
833                                    is_constructor, NONE));
834       }
835
836       FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
837       frames_seen++;
838     }
839     it.Advance();
840   }
841
842   stack_trace->set_length(Smi::FromInt(frames_seen));
843   return stack_trace;
844 }
845
846
847 void Isolate::PrintStack(FILE* out) {
848   if (stack_trace_nesting_level_ == 0) {
849     stack_trace_nesting_level_++;
850
851     StringAllocator* allocator;
852     if (preallocated_message_space_ == NULL) {
853       allocator = new HeapStringAllocator();
854     } else {
855       allocator = preallocated_message_space_;
856     }
857
858     StringStream::ClearMentionedObjectCache();
859     StringStream accumulator(allocator);
860     incomplete_message_ = &accumulator;
861     PrintStack(&accumulator);
862     accumulator.OutputToFile(out);
863     InitializeLoggingAndCounters();
864     accumulator.Log();
865     incomplete_message_ = NULL;
866     stack_trace_nesting_level_ = 0;
867     if (preallocated_message_space_ == NULL) {
868       // Remove the HeapStringAllocator created above.
869       delete allocator;
870     }
871   } else if (stack_trace_nesting_level_ == 1) {
872     stack_trace_nesting_level_++;
873     OS::PrintError(
874       "\n\nAttempt to print stack while printing stack (double fault)\n");
875     OS::PrintError(
876       "If you are lucky you may find a partial stack dump on stdout.\n\n");
877     incomplete_message_->OutputToFile(out);
878   }
879 }
880
881
882 static void PrintFrames(Isolate* isolate,
883                         StringStream* accumulator,
884                         StackFrame::PrintMode mode) {
885   StackFrameIterator it(isolate);
886   for (int i = 0; !it.done(); it.Advance()) {
887     it.frame()->Print(accumulator, mode, i++);
888   }
889 }
890
891
892 void Isolate::PrintStack(StringStream* accumulator) {
893   if (!IsInitialized()) {
894     accumulator->Add(
895         "\n==== JS stack trace is not available =======================\n\n");
896     accumulator->Add(
897         "\n==== Isolate for the thread is not initialized =============\n\n");
898     return;
899   }
900   // The MentionedObjectCache is not GC-proof at the moment.
901   DisallowHeapAllocation no_gc;
902   ASSERT(StringStream::IsMentionedObjectCacheClear());
903
904   // Avoid printing anything if there are no frames.
905   if (c_entry_fp(thread_local_top()) == 0) return;
906
907   accumulator->Add(
908       "\n==== JS stack trace =========================================\n\n");
909   PrintFrames(this, accumulator, StackFrame::OVERVIEW);
910
911   accumulator->Add(
912       "\n==== Details ================================================\n\n");
913   PrintFrames(this, accumulator, StackFrame::DETAILS);
914
915   accumulator->PrintMentionedObjectCache();
916   accumulator->Add("=====================\n\n");
917 }
918
919
920 void Isolate::SetFailedAccessCheckCallback(
921     v8::FailedAccessCheckCallback callback) {
922   thread_local_top()->failed_access_check_callback_ = callback;
923 }
924
925
926 void Isolate::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
927   if (!thread_local_top()->failed_access_check_callback_) return;
928
929   ASSERT(receiver->IsAccessCheckNeeded());
930   ASSERT(context());
931
932   // Get the data object from access check info.
933   JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
934   if (!constructor->shared()->IsApiFunction()) return;
935   Object* data_obj =
936       constructor->shared()->get_api_func_data()->access_check_info();
937   if (data_obj == heap_.undefined_value()) return;
938
939   HandleScope scope(this);
940   Handle<JSObject> receiver_handle(receiver);
941   Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
942   { VMState<EXTERNAL> state(this);
943     thread_local_top()->failed_access_check_callback_(
944       v8::Utils::ToLocal(receiver_handle),
945       type,
946       v8::Utils::ToLocal(data));
947   }
948 }
949
950
951 enum MayAccessDecision {
952   YES, NO, UNKNOWN
953 };
954
955
956 static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
957                                            JSObject* receiver,
958                                            v8::AccessType type) {
959   // During bootstrapping, callback functions are not enabled yet.
960   if (isolate->bootstrapper()->IsActive()) return YES;
961
962   if (receiver->IsJSGlobalProxy()) {
963     Object* receiver_context = JSGlobalProxy::cast(receiver)->native_context();
964     if (!receiver_context->IsContext()) return NO;
965
966     // Get the native context of current top context.
967     // avoid using Isolate::native_context() because it uses Handle.
968     Context* native_context =
969         isolate->context()->global_object()->native_context();
970     if (receiver_context == native_context) return YES;
971
972     if (Context::cast(receiver_context)->security_token() ==
973         native_context->security_token())
974       return YES;
975   }
976
977   return UNKNOWN;
978 }
979
980
981 bool Isolate::MayNamedAccess(JSObject* receiver, Object* key,
982                              v8::AccessType type) {
983   ASSERT(receiver->IsAccessCheckNeeded());
984
985   // The callers of this method are not expecting a GC.
986   DisallowHeapAllocation no_gc;
987
988   // Skip checks for hidden properties access.  Note, we do not
989   // require existence of a context in this case.
990   if (key == heap_.hidden_string()) return true;
991
992   // Check for compatibility between the security tokens in the
993   // current lexical context and the accessed object.
994   ASSERT(context());
995
996   MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
997   if (decision != UNKNOWN) return decision == YES;
998
999   // Get named access check callback
1000   JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
1001   if (!constructor->shared()->IsApiFunction()) return false;
1002
1003   Object* data_obj =
1004      constructor->shared()->get_api_func_data()->access_check_info();
1005   if (data_obj == heap_.undefined_value()) return false;
1006
1007   Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
1008   v8::NamedSecurityCallback callback =
1009       v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
1010
1011   if (!callback) return false;
1012
1013   HandleScope scope(this);
1014   Handle<JSObject> receiver_handle(receiver, this);
1015   Handle<Object> key_handle(key, this);
1016   Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
1017   LOG(this, ApiNamedSecurityCheck(key));
1018   bool result = false;
1019   {
1020     // Leaving JavaScript.
1021     VMState<EXTERNAL> state(this);
1022     result = callback(v8::Utils::ToLocal(receiver_handle),
1023                       v8::Utils::ToLocal(key_handle),
1024                       type,
1025                       v8::Utils::ToLocal(data));
1026   }
1027   return result;
1028 }
1029
1030
1031 bool Isolate::MayIndexedAccess(JSObject* receiver,
1032                                uint32_t index,
1033                                v8::AccessType type) {
1034   ASSERT(receiver->IsAccessCheckNeeded());
1035   // Check for compatibility between the security tokens in the
1036   // current lexical context and the accessed object.
1037   ASSERT(context());
1038
1039   MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
1040   if (decision != UNKNOWN) return decision == YES;
1041
1042   // Get indexed access check callback
1043   JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
1044   if (!constructor->shared()->IsApiFunction()) return false;
1045
1046   Object* data_obj =
1047       constructor->shared()->get_api_func_data()->access_check_info();
1048   if (data_obj == heap_.undefined_value()) return false;
1049
1050   Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
1051   v8::IndexedSecurityCallback callback =
1052       v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
1053
1054   if (!callback) return false;
1055
1056   HandleScope scope(this);
1057   Handle<JSObject> receiver_handle(receiver, this);
1058   Handle<Object> data(AccessCheckInfo::cast(data_obj)->data(), this);
1059   LOG(this, ApiIndexedSecurityCheck(index));
1060   bool result = false;
1061   {
1062     // Leaving JavaScript.
1063     VMState<EXTERNAL> state(this);
1064     result = callback(v8::Utils::ToLocal(receiver_handle),
1065                       index,
1066                       type,
1067                       v8::Utils::ToLocal(data));
1068   }
1069   return result;
1070 }
1071
1072
1073 const char* const Isolate::kStackOverflowMessage =
1074   "Uncaught RangeError: Maximum call stack size exceeded";
1075
1076
1077 Failure* Isolate::StackOverflow() {
1078   HandleScope scope(this);
1079   // At this point we cannot create an Error object using its javascript
1080   // constructor.  Instead, we copy the pre-constructed boilerplate and
1081   // attach the stack trace as a hidden property.
1082   Handle<String> key = factory()->stack_overflow_string();
1083   Handle<JSObject> boilerplate =
1084       Handle<JSObject>::cast(GetProperty(this, js_builtins_object(), key));
1085   Handle<JSObject> exception = Copy(boilerplate);
1086   DoThrow(*exception, NULL);
1087
1088   // Get stack trace limit.
1089   Handle<Object> error = GetProperty(js_builtins_object(), "$Error");
1090   if (!error->IsJSObject()) return Failure::Exception();
1091   Handle<Object> stack_trace_limit =
1092       GetProperty(Handle<JSObject>::cast(error), "stackTraceLimit");
1093   if (!stack_trace_limit->IsNumber()) return Failure::Exception();
1094   double dlimit = stack_trace_limit->Number();
1095   int limit = std::isnan(dlimit) ? 0 : static_cast<int>(dlimit);
1096
1097   Handle<JSArray> stack_trace = CaptureSimpleStackTrace(
1098       exception, factory()->undefined_value(), limit);
1099   JSObject::SetHiddenProperty(exception,
1100                               factory()->hidden_stack_trace_string(),
1101                               stack_trace);
1102   return Failure::Exception();
1103 }
1104
1105
1106 Failure* Isolate::TerminateExecution() {
1107   DoThrow(heap_.termination_exception(), NULL);
1108   return Failure::Exception();
1109 }
1110
1111
1112 void Isolate::CancelTerminateExecution() {
1113   if (try_catch_handler()) {
1114     try_catch_handler()->has_terminated_ = false;
1115   }
1116   if (has_pending_exception() &&
1117       pending_exception() == heap_.termination_exception()) {
1118     thread_local_top()->external_caught_exception_ = false;
1119     clear_pending_exception();
1120   }
1121   if (has_scheduled_exception() &&
1122       scheduled_exception() == heap_.termination_exception()) {
1123     thread_local_top()->external_caught_exception_ = false;
1124     clear_scheduled_exception();
1125   }
1126 }
1127
1128
1129 Failure* Isolate::Throw(Object* exception, MessageLocation* location) {
1130   DoThrow(exception, location);
1131   return Failure::Exception();
1132 }
1133
1134
1135 Failure* Isolate::ReThrow(MaybeObject* exception) {
1136   bool can_be_caught_externally = false;
1137   bool catchable_by_javascript = is_catchable_by_javascript(exception);
1138   ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1139
1140   thread_local_top()->catcher_ = can_be_caught_externally ?
1141       try_catch_handler() : NULL;
1142
1143   // Set the exception being re-thrown.
1144   set_pending_exception(exception);
1145   if (exception->IsFailure()) return exception->ToFailureUnchecked();
1146   return Failure::Exception();
1147 }
1148
1149
1150 Failure* Isolate::ThrowIllegalOperation() {
1151   return Throw(heap_.illegal_access_string());
1152 }
1153
1154
1155 void Isolate::ScheduleThrow(Object* exception) {
1156   // When scheduling a throw we first throw the exception to get the
1157   // error reporting if it is uncaught before rescheduling it.
1158   Throw(exception);
1159   PropagatePendingExceptionToExternalTryCatch();
1160   if (has_pending_exception()) {
1161     thread_local_top()->scheduled_exception_ = pending_exception();
1162     thread_local_top()->external_caught_exception_ = false;
1163     clear_pending_exception();
1164   }
1165 }
1166
1167
1168 void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1169   ASSERT(handler == try_catch_handler());
1170   ASSERT(handler->HasCaught());
1171   ASSERT(handler->rethrow_);
1172   ASSERT(handler->capture_message_);
1173   Object* message = reinterpret_cast<Object*>(handler->message_obj_);
1174   Object* script = reinterpret_cast<Object*>(handler->message_script_);
1175   ASSERT(message->IsJSMessageObject() || message->IsTheHole());
1176   ASSERT(script->IsScript() || script->IsTheHole());
1177   thread_local_top()->pending_message_obj_ = message;
1178   thread_local_top()->pending_message_script_ = script;
1179   thread_local_top()->pending_message_start_pos_ = handler->message_start_pos_;
1180   thread_local_top()->pending_message_end_pos_ = handler->message_end_pos_;
1181 }
1182
1183
1184 Failure* Isolate::PromoteScheduledException() {
1185   MaybeObject* thrown = scheduled_exception();
1186   clear_scheduled_exception();
1187   // Re-throw the exception to avoid getting repeated error reporting.
1188   return ReThrow(thrown);
1189 }
1190
1191
1192 void Isolate::PrintCurrentStackTrace(FILE* out) {
1193   StackTraceFrameIterator it(this);
1194   while (!it.done()) {
1195     HandleScope scope(this);
1196     // Find code position if recorded in relocation info.
1197     JavaScriptFrame* frame = it.frame();
1198     int pos = frame->LookupCode()->SourcePosition(frame->pc());
1199     Handle<Object> pos_obj(Smi::FromInt(pos), this);
1200     // Fetch function and receiver.
1201     Handle<JSFunction> fun(frame->function());
1202     Handle<Object> recv(frame->receiver(), this);
1203     // Advance to the next JavaScript frame and determine if the
1204     // current frame is the top-level frame.
1205     it.Advance();
1206     Handle<Object> is_top_level = it.done()
1207         ? factory()->true_value()
1208         : factory()->false_value();
1209     // Generate and print stack trace line.
1210     Handle<String> line =
1211         Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1212     if (line->length() > 0) {
1213       line->PrintOn(out);
1214       PrintF(out, "\n");
1215     }
1216   }
1217 }
1218
1219
1220 void Isolate::ComputeLocation(MessageLocation* target) {
1221   *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1222   StackTraceFrameIterator it(this);
1223   if (!it.done()) {
1224     JavaScriptFrame* frame = it.frame();
1225     JSFunction* fun = frame->function();
1226     Object* script = fun->shared()->script();
1227     if (script->IsScript() &&
1228         !(Script::cast(script)->source()->IsUndefined())) {
1229       int pos = frame->LookupCode()->SourcePosition(frame->pc());
1230       // Compute the location from the function and the reloc info.
1231       Handle<Script> casted_script(Script::cast(script));
1232       *target = MessageLocation(casted_script, pos, pos + 1);
1233     }
1234   }
1235 }
1236
1237
1238 bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1239                                     bool catchable_by_javascript) {
1240   // Find the top-most try-catch handler.
1241   StackHandler* handler =
1242       StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1243   while (handler != NULL && !handler->is_catch()) {
1244     handler = handler->next();
1245   }
1246
1247   // Get the address of the external handler so we can compare the address to
1248   // determine which one is closer to the top of the stack.
1249   Address external_handler_address =
1250       thread_local_top()->try_catch_handler_address();
1251
1252   // The exception has been externally caught if and only if there is
1253   // an external handler which is on top of the top-most try-catch
1254   // handler.
1255   *can_be_caught_externally = external_handler_address != NULL &&
1256       (handler == NULL || handler->address() > external_handler_address ||
1257        !catchable_by_javascript);
1258
1259   if (*can_be_caught_externally) {
1260     // Only report the exception if the external handler is verbose.
1261     return try_catch_handler()->is_verbose_;
1262   } else {
1263     // Report the exception if it isn't caught by JavaScript code.
1264     return handler == NULL;
1265   }
1266 }
1267
1268
1269 bool Isolate::IsErrorObject(Handle<Object> obj) {
1270   if (!obj->IsJSObject()) return false;
1271
1272   String* error_key =
1273       *(factory()->InternalizeOneByteString(STATIC_ASCII_VECTOR("$Error")));
1274   Object* error_constructor =
1275       js_builtins_object()->GetPropertyNoExceptionThrown(error_key);
1276
1277   for (Object* prototype = *obj; !prototype->IsNull();
1278        prototype = prototype->GetPrototype(this)) {
1279     if (!prototype->IsJSObject()) return false;
1280     if (JSObject::cast(prototype)->map()->constructor() == error_constructor) {
1281       return true;
1282     }
1283   }
1284   return false;
1285 }
1286
1287 static int fatal_exception_depth = 0;
1288
1289 void Isolate::DoThrow(Object* exception, MessageLocation* location) {
1290   ASSERT(!has_pending_exception());
1291
1292   HandleScope scope(this);
1293   Handle<Object> exception_handle(exception, this);
1294
1295   // Determine reporting and whether the exception is caught externally.
1296   bool catchable_by_javascript = is_catchable_by_javascript(exception);
1297   bool can_be_caught_externally = false;
1298   bool should_report_exception =
1299       ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1300   bool report_exception = catchable_by_javascript && should_report_exception;
1301   bool try_catch_needs_message =
1302       can_be_caught_externally && try_catch_handler()->capture_message_ &&
1303       !thread_local_top()->rethrowing_message_;
1304   bool bootstrapping = bootstrapper()->IsActive();
1305
1306   thread_local_top()->rethrowing_message_ = false;
1307
1308 #ifdef ENABLE_DEBUGGER_SUPPORT
1309   // Notify debugger of exception.
1310   if (catchable_by_javascript) {
1311     debugger_->OnException(exception_handle, report_exception);
1312   }
1313 #endif
1314
1315   // Generate the message if required.
1316   if (report_exception || try_catch_needs_message) {
1317     MessageLocation potential_computed_location;
1318     if (location == NULL) {
1319       // If no location was specified we use a computed one instead.
1320       ComputeLocation(&potential_computed_location);
1321       location = &potential_computed_location;
1322     }
1323     // It's not safe to try to make message objects or collect stack traces
1324     // while the bootstrapper is active since the infrastructure may not have
1325     // been properly initialized.
1326     if (!bootstrapping) {
1327       Handle<String> stack_trace;
1328       if (FLAG_trace_exception) stack_trace = StackTraceString();
1329       Handle<JSArray> stack_trace_object;
1330       if (capture_stack_trace_for_uncaught_exceptions_) {
1331         if (IsErrorObject(exception_handle)) {
1332           // We fetch the stack trace that corresponds to this error object.
1333           String* key = heap()->hidden_stack_trace_string();
1334           Object* stack_property =
1335               JSObject::cast(*exception_handle)->GetHiddenProperty(key);
1336           // Property lookup may have failed.  In this case it's probably not
1337           // a valid Error object.
1338           if (stack_property->IsJSArray()) {
1339             stack_trace_object = Handle<JSArray>(JSArray::cast(stack_property));
1340           }
1341         }
1342         if (stack_trace_object.is_null()) {
1343           // Not an error object, we capture at throw site.
1344           stack_trace_object = CaptureCurrentStackTrace(
1345               stack_trace_for_uncaught_exceptions_frame_limit_,
1346               stack_trace_for_uncaught_exceptions_options_);
1347         }
1348       }
1349
1350       Handle<Object> exception_arg = exception_handle;
1351       // If the exception argument is a custom object, turn it into a string
1352       // before throwing as uncaught exception.  Note that the pending
1353       // exception object to be set later must not be turned into a string.
1354       if (exception_arg->IsJSObject() && !IsErrorObject(exception_arg)) {
1355         bool failed = false;
1356         exception_arg = Execution::ToDetailString(exception_arg, &failed);
1357         if (failed) {
1358           exception_arg = factory()->InternalizeOneByteString(
1359               STATIC_ASCII_VECTOR("exception"));
1360         }
1361       }
1362       Handle<Object> message_obj = MessageHandler::MakeMessageObject(
1363           this,
1364           "uncaught_exception",
1365           location,
1366           HandleVector<Object>(&exception_arg, 1),
1367           stack_trace,
1368           stack_trace_object);
1369       thread_local_top()->pending_message_obj_ = *message_obj;
1370       if (location != NULL) {
1371         thread_local_top()->pending_message_script_ = *location->script();
1372         thread_local_top()->pending_message_start_pos_ = location->start_pos();
1373         thread_local_top()->pending_message_end_pos_ = location->end_pos();
1374       }
1375
1376       // If the abort-on-uncaught-exception flag is specified, abort on any
1377       // exception not caught by JavaScript, even when an external handler is
1378       // present.  This flag is intended for use by JavaScript developers, so
1379       // print a user-friendly stack trace (not an internal one).
1380       if (fatal_exception_depth == 0 &&
1381           FLAG_abort_on_uncaught_exception &&
1382           (report_exception || can_be_caught_externally)) {
1383         fatal_exception_depth++;
1384         PrintF(stderr,
1385                "%s\n\nFROM\n",
1386                *MessageHandler::GetLocalizedMessage(this, message_obj));
1387         PrintCurrentStackTrace(stderr);
1388         OS::Abort();
1389       }
1390     } else if (location != NULL && !location->script().is_null()) {
1391       // We are bootstrapping and caught an error where the location is set
1392       // and we have a script for the location.
1393       // In this case we could have an extension (or an internal error
1394       // somewhere) and we print out the line number at which the error occured
1395       // to the console for easier debugging.
1396       int line_number = GetScriptLineNumberSafe(location->script(),
1397                                                 location->start_pos());
1398       if (exception->IsString()) {
1399         OS::PrintError(
1400             "Extension or internal compilation error: %s in %s at line %d.\n",
1401             *String::cast(exception)->ToCString(),
1402             *String::cast(location->script()->name())->ToCString(),
1403             line_number + 1);
1404       } else {
1405         OS::PrintError(
1406             "Extension or internal compilation error in %s at line %d.\n",
1407             *String::cast(location->script()->name())->ToCString(),
1408             line_number + 1);
1409       }
1410     }
1411   }
1412
1413   // Save the message for reporting if the the exception remains uncaught.
1414   thread_local_top()->has_pending_message_ = report_exception;
1415
1416   // Do not forget to clean catcher_ if currently thrown exception cannot
1417   // be caught.  If necessary, ReThrow will update the catcher.
1418   thread_local_top()->catcher_ = can_be_caught_externally ?
1419       try_catch_handler() : NULL;
1420
1421   set_pending_exception(*exception_handle);
1422 }
1423
1424
1425 bool Isolate::IsExternallyCaught() {
1426   ASSERT(has_pending_exception());
1427
1428   if ((thread_local_top()->catcher_ == NULL) ||
1429       (try_catch_handler() != thread_local_top()->catcher_)) {
1430     // When throwing the exception, we found no v8::TryCatch
1431     // which should care about this exception.
1432     return false;
1433   }
1434
1435   if (!is_catchable_by_javascript(pending_exception())) {
1436     return true;
1437   }
1438
1439   // Get the address of the external handler so we can compare the address to
1440   // determine which one is closer to the top of the stack.
1441   Address external_handler_address =
1442       thread_local_top()->try_catch_handler_address();
1443   ASSERT(external_handler_address != NULL);
1444
1445   // The exception has been externally caught if and only if there is
1446   // an external handler which is on top of the top-most try-finally
1447   // handler.
1448   // There should be no try-catch blocks as they would prohibit us from
1449   // finding external catcher in the first place (see catcher_ check above).
1450   //
1451   // Note, that finally clause would rethrow an exception unless it's
1452   // aborted by jumps in control flow like return, break, etc. and we'll
1453   // have another chances to set proper v8::TryCatch.
1454   StackHandler* handler =
1455       StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1456   while (handler != NULL && handler->address() < external_handler_address) {
1457     ASSERT(!handler->is_catch());
1458     if (handler->is_finally()) return false;
1459
1460     handler = handler->next();
1461   }
1462
1463   return true;
1464 }
1465
1466
1467 void Isolate::ReportPendingMessages() {
1468   ASSERT(has_pending_exception());
1469   PropagatePendingExceptionToExternalTryCatch();
1470
1471   // If the pending exception is OutOfMemoryException set out_of_memory in
1472   // the native context.  Note: We have to mark the native context here
1473   // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
1474   // set it.
1475   HandleScope scope(this);
1476   if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
1477     context()->mark_out_of_memory();
1478   } else if (thread_local_top_.pending_exception_ ==
1479              heap()->termination_exception()) {
1480     // Do nothing: if needed, the exception has been already propagated to
1481     // v8::TryCatch.
1482   } else {
1483     if (thread_local_top_.has_pending_message_) {
1484       thread_local_top_.has_pending_message_ = false;
1485       if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
1486         HandleScope scope(this);
1487         Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1488                                    this);
1489         if (!thread_local_top_.pending_message_script_->IsTheHole()) {
1490           Handle<Script> script(
1491               Script::cast(thread_local_top_.pending_message_script_));
1492           int start_pos = thread_local_top_.pending_message_start_pos_;
1493           int end_pos = thread_local_top_.pending_message_end_pos_;
1494           MessageLocation location(script, start_pos, end_pos);
1495           MessageHandler::ReportMessage(this, &location, message_obj);
1496         } else {
1497           MessageHandler::ReportMessage(this, NULL, message_obj);
1498         }
1499       }
1500     }
1501   }
1502   clear_pending_message();
1503 }
1504
1505
1506 MessageLocation Isolate::GetMessageLocation() {
1507   ASSERT(has_pending_exception());
1508
1509   if (!thread_local_top_.pending_exception_->IsOutOfMemory() &&
1510       thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1511       thread_local_top_.has_pending_message_ &&
1512       !thread_local_top_.pending_message_obj_->IsTheHole() &&
1513       !thread_local_top_.pending_message_obj_->IsTheHole()) {
1514     Handle<Script> script(
1515         Script::cast(thread_local_top_.pending_message_script_));
1516     int start_pos = thread_local_top_.pending_message_start_pos_;
1517     int end_pos = thread_local_top_.pending_message_end_pos_;
1518     return MessageLocation(script, start_pos, end_pos);
1519   }
1520
1521   return MessageLocation();
1522 }
1523
1524
1525 void Isolate::TraceException(bool flag) {
1526   FLAG_trace_exception = flag;  // TODO(isolates): This is an unfortunate use.
1527 }
1528
1529
1530 bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
1531   ASSERT(has_pending_exception());
1532   PropagatePendingExceptionToExternalTryCatch();
1533
1534   // Always reschedule out of memory exceptions.
1535   if (!is_out_of_memory()) {
1536     bool is_termination_exception =
1537         pending_exception() == heap_.termination_exception();
1538
1539     // Do not reschedule the exception if this is the bottom call.
1540     bool clear_exception = is_bottom_call;
1541
1542     if (is_termination_exception) {
1543       if (is_bottom_call) {
1544         thread_local_top()->external_caught_exception_ = false;
1545         clear_pending_exception();
1546         return false;
1547       }
1548     } else if (thread_local_top()->external_caught_exception_) {
1549       // If the exception is externally caught, clear it if there are no
1550       // JavaScript frames on the way to the C++ frame that has the
1551       // external handler.
1552       ASSERT(thread_local_top()->try_catch_handler_address() != NULL);
1553       Address external_handler_address =
1554           thread_local_top()->try_catch_handler_address();
1555       JavaScriptFrameIterator it(this);
1556       if (it.done() || (it.frame()->sp() > external_handler_address)) {
1557         clear_exception = true;
1558       }
1559     }
1560
1561     // Clear the exception if needed.
1562     if (clear_exception) {
1563       thread_local_top()->external_caught_exception_ = false;
1564       clear_pending_exception();
1565       return false;
1566     }
1567   }
1568
1569   // Reschedule the exception.
1570   thread_local_top()->scheduled_exception_ = pending_exception();
1571   clear_pending_exception();
1572   return true;
1573 }
1574
1575
1576 void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1577       bool capture,
1578       int frame_limit,
1579       StackTrace::StackTraceOptions options) {
1580   capture_stack_trace_for_uncaught_exceptions_ = capture;
1581   stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1582   stack_trace_for_uncaught_exceptions_options_ = options;
1583 }
1584
1585
1586 bool Isolate::is_out_of_memory() {
1587   if (has_pending_exception()) {
1588     MaybeObject* e = pending_exception();
1589     if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1590       return true;
1591     }
1592   }
1593   if (has_scheduled_exception()) {
1594     MaybeObject* e = scheduled_exception();
1595     if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1596       return true;
1597     }
1598   }
1599   return false;
1600 }
1601
1602
1603 Handle<Context> Isolate::native_context() {
1604   return Handle<Context>(context()->global_object()->native_context());
1605 }
1606
1607
1608 Handle<Context> Isolate::global_context() {
1609   return Handle<Context>(context()->global_object()->global_context());
1610 }
1611
1612
1613 Handle<Context> Isolate::GetCallingNativeContext() {
1614   JavaScriptFrameIterator it(this);
1615 #ifdef ENABLE_DEBUGGER_SUPPORT
1616   if (debug_->InDebugger()) {
1617     while (!it.done()) {
1618       JavaScriptFrame* frame = it.frame();
1619       Context* context = Context::cast(frame->context());
1620       if (context->native_context() == *debug_->debug_context()) {
1621         it.Advance();
1622       } else {
1623         break;
1624       }
1625     }
1626   }
1627 #endif  // ENABLE_DEBUGGER_SUPPORT
1628   if (it.done()) return Handle<Context>::null();
1629   JavaScriptFrame* frame = it.frame();
1630   Context* context = Context::cast(frame->context());
1631   return Handle<Context>(context->native_context());
1632 }
1633
1634
1635 char* Isolate::ArchiveThread(char* to) {
1636   OS::MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1637               sizeof(ThreadLocalTop));
1638   InitializeThreadLocal();
1639   clear_pending_exception();
1640   clear_pending_message();
1641   clear_scheduled_exception();
1642   return to + sizeof(ThreadLocalTop);
1643 }
1644
1645
1646 char* Isolate::RestoreThread(char* from) {
1647   OS::MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1648               sizeof(ThreadLocalTop));
1649   // This might be just paranoia, but it seems to be needed in case a
1650   // thread_local_top_ is restored on a separate OS thread.
1651 #ifdef USE_SIMULATOR
1652 #if V8_TARGET_ARCH_ARM
1653   thread_local_top()->simulator_ = Simulator::current(this);
1654 #elif V8_TARGET_ARCH_MIPS
1655   thread_local_top()->simulator_ = Simulator::current(this);
1656 #endif
1657 #endif
1658   ASSERT(context() == NULL || context()->IsContext());
1659   return from + sizeof(ThreadLocalTop);
1660 }
1661
1662
1663 Isolate::ThreadDataTable::ThreadDataTable()
1664     : list_(NULL) {
1665 }
1666
1667
1668 Isolate::ThreadDataTable::~ThreadDataTable() {
1669   // TODO(svenpanne) The assertion below would fire if an embedder does not
1670   // cleanly dispose all Isolates before disposing v8, so we are conservative
1671   // and leave it out for now.
1672   // ASSERT_EQ(NULL, list_);
1673 }
1674
1675
1676 Isolate::PerIsolateThreadData*
1677     Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1678                                      ThreadId thread_id) {
1679   for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1680     if (data->Matches(isolate, thread_id)) return data;
1681   }
1682   return NULL;
1683 }
1684
1685
1686 void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1687   if (list_ != NULL) list_->prev_ = data;
1688   data->next_ = list_;
1689   list_ = data;
1690 }
1691
1692
1693 void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1694   if (list_ == data) list_ = data->next_;
1695   if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1696   if (data->prev_ != NULL) data->prev_->next_ = data->next_;
1697   delete data;
1698 }
1699
1700
1701 void Isolate::ThreadDataTable::Remove(Isolate* isolate,
1702                                       ThreadId thread_id) {
1703   PerIsolateThreadData* data = Lookup(isolate, thread_id);
1704   if (data != NULL) {
1705     Remove(data);
1706   }
1707 }
1708
1709
1710 void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1711   PerIsolateThreadData* data = list_;
1712   while (data != NULL) {
1713     PerIsolateThreadData* next = data->next_;
1714     if (data->isolate() == isolate) Remove(data);
1715     data = next;
1716   }
1717 }
1718
1719
1720 #ifdef DEBUG
1721 #define TRACE_ISOLATE(tag)                                              \
1722   do {                                                                  \
1723     if (FLAG_trace_isolates) {                                          \
1724       PrintF("Isolate %p (id %d)" #tag "\n",                            \
1725              reinterpret_cast<void*>(this), id());                      \
1726     }                                                                   \
1727   } while (false)
1728 #else
1729 #define TRACE_ISOLATE(tag)
1730 #endif
1731
1732
1733 Isolate::Isolate()
1734     : state_(UNINITIALIZED),
1735       embedder_data_(NULL),
1736       entry_stack_(NULL),
1737       stack_trace_nesting_level_(0),
1738       incomplete_message_(NULL),
1739       preallocated_memory_thread_(NULL),
1740       preallocated_message_space_(NULL),
1741       bootstrapper_(NULL),
1742       runtime_profiler_(NULL),
1743       compilation_cache_(NULL),
1744       counters_(NULL),
1745       code_range_(NULL),
1746       // Must be initialized early to allow v8::SetResourceConstraints calls.
1747       break_access_(OS::CreateMutex()),
1748       debugger_initialized_(false),
1749       // Must be initialized early to allow v8::Debug calls.
1750       debugger_access_(OS::CreateMutex()),
1751       logger_(NULL),
1752       stats_table_(NULL),
1753       stub_cache_(NULL),
1754       deoptimizer_data_(NULL),
1755       capture_stack_trace_for_uncaught_exceptions_(false),
1756       stack_trace_for_uncaught_exceptions_frame_limit_(0),
1757       stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
1758       transcendental_cache_(NULL),
1759       memory_allocator_(NULL),
1760       keyed_lookup_cache_(NULL),
1761       context_slot_cache_(NULL),
1762       descriptor_lookup_cache_(NULL),
1763       handle_scope_implementer_(NULL),
1764       unicode_cache_(NULL),
1765       runtime_zone_(this),
1766       in_use_list_(0),
1767       free_list_(0),
1768       preallocated_storage_preallocated_(false),
1769       inner_pointer_to_code_cache_(NULL),
1770       write_iterator_(NULL),
1771       global_handles_(NULL),
1772       context_switcher_(NULL),
1773       thread_manager_(NULL),
1774       fp_stubs_generated_(false),
1775       has_installed_extensions_(false),
1776       string_tracker_(NULL),
1777       regexp_stack_(NULL),
1778       date_cache_(NULL),
1779       code_stub_interface_descriptors_(NULL),
1780       initialized_from_snapshot_(false),
1781       cpu_profiler_(NULL),
1782       heap_profiler_(NULL),
1783       function_entry_hook_(NULL),
1784       deferred_handles_head_(NULL),
1785       optimizing_compiler_thread_(this),
1786       marking_thread_(NULL),
1787       sweeper_thread_(NULL),
1788       callback_table_(NULL),
1789       stress_deopt_count_(0) {
1790   id_ = NoBarrier_AtomicIncrement(&isolate_counter_, 1);
1791   TRACE_ISOLATE(constructor);
1792
1793   memset(isolate_addresses_, 0,
1794       sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
1795
1796   heap_.isolate_ = this;
1797   stack_guard_.isolate_ = this;
1798
1799   // ThreadManager is initialized early to support locking an isolate
1800   // before it is entered.
1801   thread_manager_ = new ThreadManager();
1802   thread_manager_->isolate_ = this;
1803
1804 #if V8_TARGET_ARCH_ARM && !defined(__arm__) || \
1805     V8_TARGET_ARCH_MIPS && !defined(__mips__)
1806   simulator_initialized_ = false;
1807   simulator_i_cache_ = NULL;
1808   simulator_redirection_ = NULL;
1809 #endif
1810
1811 #ifdef DEBUG
1812   // heap_histograms_ initializes itself.
1813   memset(&js_spill_information_, 0, sizeof(js_spill_information_));
1814   memset(code_kind_statistics_, 0,
1815          sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
1816 #endif
1817
1818 #ifdef ENABLE_DEBUGGER_SUPPORT
1819   debug_ = NULL;
1820   debugger_ = NULL;
1821 #endif
1822
1823   handle_scope_data_.Initialize();
1824
1825 #define ISOLATE_INIT_EXECUTE(type, name, initial_value)                        \
1826   name##_ = (initial_value);
1827   ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1828 #undef ISOLATE_INIT_EXECUTE
1829
1830 #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length)                         \
1831   memset(name##_, 0, sizeof(type) * length);
1832   ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1833 #undef ISOLATE_INIT_ARRAY_EXECUTE
1834 }
1835
1836
1837 void Isolate::TearDown() {
1838   TRACE_ISOLATE(tear_down);
1839
1840   // Temporarily set this isolate as current so that various parts of
1841   // the isolate can access it in their destructors without having a
1842   // direct pointer. We don't use Enter/Exit here to avoid
1843   // initializing the thread data.
1844   PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1845   Isolate* saved_isolate = UncheckedCurrent();
1846   SetIsolateThreadLocals(this, NULL);
1847
1848   Deinit();
1849
1850   { ScopedLock lock(process_wide_mutex_);
1851     thread_data_table_->RemoveAllThreads(this);
1852   }
1853
1854   if (serialize_partial_snapshot_cache_ != NULL) {
1855     delete[] serialize_partial_snapshot_cache_;
1856     serialize_partial_snapshot_cache_ = NULL;
1857   }
1858
1859   if (!IsDefaultIsolate()) {
1860     delete this;
1861   }
1862
1863   // Restore the previous current isolate.
1864   SetIsolateThreadLocals(saved_isolate, saved_data);
1865 }
1866
1867
1868 void Isolate::GlobalTearDown() {
1869   delete thread_data_table_;
1870 }
1871
1872
1873 void Isolate::Deinit() {
1874   if (state_ == INITIALIZED) {
1875     TRACE_ISOLATE(deinit);
1876
1877 #ifdef ENABLE_DEBUGGER_SUPPORT
1878     debugger()->UnloadDebugger();
1879 #endif
1880
1881     if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Stop();
1882
1883     if (FLAG_sweeper_threads > 0) {
1884       for (int i = 0; i < FLAG_sweeper_threads; i++) {
1885         sweeper_thread_[i]->Stop();
1886         delete sweeper_thread_[i];
1887       }
1888       delete[] sweeper_thread_;
1889     }
1890
1891     if (FLAG_marking_threads > 0) {
1892       for (int i = 0; i < FLAG_marking_threads; i++) {
1893         marking_thread_[i]->Stop();
1894         delete marking_thread_[i];
1895       }
1896       delete[] marking_thread_;
1897     }
1898
1899     if (FLAG_hydrogen_stats) GetHStatistics()->Print();
1900
1901     if (FLAG_print_deopt_stress) {
1902       PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1903     }
1904
1905     // We must stop the logger before we tear down other components.
1906     Sampler* sampler = logger_->sampler();
1907     if (sampler && sampler->IsActive()) sampler->Stop();
1908
1909     delete deoptimizer_data_;
1910     deoptimizer_data_ = NULL;
1911     if (FLAG_preemption) {
1912       v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
1913       v8::Locker::StopPreemption();
1914     }
1915     builtins_.TearDown();
1916     bootstrapper_->TearDown();
1917
1918     // Remove the external reference to the preallocated stack memory.
1919     delete preallocated_message_space_;
1920     preallocated_message_space_ = NULL;
1921     PreallocatedMemoryThreadStop();
1922
1923     if (runtime_profiler_ != NULL) {
1924       runtime_profiler_->TearDown();
1925       delete runtime_profiler_;
1926       runtime_profiler_ = NULL;
1927     }
1928     heap_.TearDown();
1929     logger_->TearDown();
1930
1931     delete heap_profiler_;
1932     heap_profiler_ = NULL;
1933     delete cpu_profiler_;
1934     cpu_profiler_ = NULL;
1935
1936     // The default isolate is re-initializable due to legacy API.
1937     state_ = UNINITIALIZED;
1938   }
1939 }
1940
1941
1942 void Isolate::PushToPartialSnapshotCache(Object* obj) {
1943   int length = serialize_partial_snapshot_cache_length();
1944   int capacity = serialize_partial_snapshot_cache_capacity();
1945
1946   if (length >= capacity) {
1947     int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1948     Object** new_array = new Object*[new_capacity];
1949     for (int i = 0; i < length; i++) {
1950       new_array[i] = serialize_partial_snapshot_cache()[i];
1951     }
1952     if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1953     set_serialize_partial_snapshot_cache(new_array);
1954     set_serialize_partial_snapshot_cache_capacity(new_capacity);
1955   }
1956
1957   serialize_partial_snapshot_cache()[length] = obj;
1958   set_serialize_partial_snapshot_cache_length(length + 1);
1959 }
1960
1961
1962 void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1963                                      PerIsolateThreadData* data) {
1964   Thread::SetThreadLocal(isolate_key_, isolate);
1965   Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
1966 }
1967
1968
1969 Isolate::~Isolate() {
1970   TRACE_ISOLATE(destructor);
1971
1972   // Has to be called while counters_ are still alive
1973   runtime_zone_.DeleteKeptSegment();
1974
1975   // The entry stack must be empty when we get here,
1976   // except for the default isolate, where it can
1977   // still contain up to one entry stack item
1978   ASSERT(entry_stack_ == NULL || this == default_isolate_);
1979   ASSERT(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1980
1981   delete entry_stack_;
1982   entry_stack_ = NULL;
1983
1984   delete[] assembler_spare_buffer_;
1985   assembler_spare_buffer_ = NULL;
1986
1987   delete unicode_cache_;
1988   unicode_cache_ = NULL;
1989
1990   delete date_cache_;
1991   date_cache_ = NULL;
1992
1993   delete[] code_stub_interface_descriptors_;
1994   code_stub_interface_descriptors_ = NULL;
1995
1996   delete regexp_stack_;
1997   regexp_stack_ = NULL;
1998
1999   delete descriptor_lookup_cache_;
2000   descriptor_lookup_cache_ = NULL;
2001   delete context_slot_cache_;
2002   context_slot_cache_ = NULL;
2003   delete keyed_lookup_cache_;
2004   keyed_lookup_cache_ = NULL;
2005
2006   delete transcendental_cache_;
2007   transcendental_cache_ = NULL;
2008   delete stub_cache_;
2009   stub_cache_ = NULL;
2010   delete stats_table_;
2011   stats_table_ = NULL;
2012
2013   delete logger_;
2014   logger_ = NULL;
2015
2016   delete counters_;
2017   counters_ = NULL;
2018
2019   delete handle_scope_implementer_;
2020   handle_scope_implementer_ = NULL;
2021   delete break_access_;
2022   break_access_ = NULL;
2023   delete debugger_access_;
2024   debugger_access_ = NULL;
2025
2026   delete compilation_cache_;
2027   compilation_cache_ = NULL;
2028   delete bootstrapper_;
2029   bootstrapper_ = NULL;
2030   delete inner_pointer_to_code_cache_;
2031   inner_pointer_to_code_cache_ = NULL;
2032   delete write_iterator_;
2033   write_iterator_ = NULL;
2034
2035   delete context_switcher_;
2036   context_switcher_ = NULL;
2037   delete thread_manager_;
2038   thread_manager_ = NULL;
2039
2040   delete string_tracker_;
2041   string_tracker_ = NULL;
2042
2043   delete memory_allocator_;
2044   memory_allocator_ = NULL;
2045   delete code_range_;
2046   code_range_ = NULL;
2047   delete global_handles_;
2048   global_handles_ = NULL;
2049
2050   delete string_stream_debug_object_cache_;
2051   string_stream_debug_object_cache_ = NULL;
2052
2053   delete external_reference_table_;
2054   external_reference_table_ = NULL;
2055
2056   delete callback_table_;
2057   callback_table_ = NULL;
2058
2059 #ifdef ENABLE_DEBUGGER_SUPPORT
2060   delete debugger_;
2061   debugger_ = NULL;
2062   delete debug_;
2063   debug_ = NULL;
2064 #endif
2065 }
2066
2067
2068 void Isolate::InitializeThreadLocal() {
2069   thread_local_top_.isolate_ = this;
2070   thread_local_top_.Initialize();
2071 }
2072
2073
2074 void Isolate::PropagatePendingExceptionToExternalTryCatch() {
2075   ASSERT(has_pending_exception());
2076
2077   bool external_caught = IsExternallyCaught();
2078   thread_local_top_.external_caught_exception_ = external_caught;
2079
2080   if (!external_caught) return;
2081
2082   if (thread_local_top_.pending_exception_->IsOutOfMemory()) {
2083     // Do not propagate OOM exception: we should kill VM asap.
2084   } else if (thread_local_top_.pending_exception_ ==
2085              heap()->termination_exception()) {
2086     try_catch_handler()->can_continue_ = false;
2087     try_catch_handler()->has_terminated_ = true;
2088     try_catch_handler()->exception_ = heap()->null_value();
2089   } else {
2090     v8::TryCatch* handler = try_catch_handler();
2091     // At this point all non-object (failure) exceptions have
2092     // been dealt with so this shouldn't fail.
2093     ASSERT(!pending_exception()->IsFailure());
2094     ASSERT(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2095            thread_local_top_.pending_message_obj_->IsTheHole());
2096     ASSERT(thread_local_top_.pending_message_script_->IsScript() ||
2097            thread_local_top_.pending_message_script_->IsTheHole());
2098     handler->can_continue_ = true;
2099     handler->has_terminated_ = false;
2100     handler->exception_ = pending_exception();
2101     // Propagate to the external try-catch only if we got an actual message.
2102     if (thread_local_top_.pending_message_obj_->IsTheHole()) return;
2103
2104     handler->message_obj_ = thread_local_top_.pending_message_obj_;
2105     handler->message_script_ = thread_local_top_.pending_message_script_;
2106     handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
2107     handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
2108   }
2109 }
2110
2111
2112 void Isolate::InitializeLoggingAndCounters() {
2113   if (logger_ == NULL) {
2114     logger_ = new Logger(this);
2115   }
2116   if (counters_ == NULL) {
2117     counters_ = new Counters(this);
2118   }
2119 }
2120
2121
2122 void Isolate::InitializeDebugger() {
2123 #ifdef ENABLE_DEBUGGER_SUPPORT
2124   ScopedLock lock(debugger_access_);
2125   if (NoBarrier_Load(&debugger_initialized_)) return;
2126   InitializeLoggingAndCounters();
2127   debug_ = new Debug(this);
2128   debugger_ = new Debugger(this);
2129   Release_Store(&debugger_initialized_, true);
2130 #endif
2131 }
2132
2133
2134 bool Isolate::Init(Deserializer* des) {
2135   ASSERT(state_ != INITIALIZED);
2136   ASSERT(Isolate::Current() == this);
2137   TRACE_ISOLATE(init);
2138
2139   stress_deopt_count_ = FLAG_deopt_every_n_times;
2140
2141   if (function_entry_hook() != NULL) {
2142     // When function entry hooking is in effect, we have to create the code
2143     // stubs from scratch to get entry hooks, rather than loading the previously
2144     // generated stubs from disk.
2145     // If this assert fires, the initialization path has regressed.
2146     ASSERT(des == NULL);
2147   }
2148
2149   // The initialization process does not handle memory exhaustion.
2150   DisallowAllocationFailure disallow_allocation_failure;
2151
2152   InitializeLoggingAndCounters();
2153
2154   InitializeDebugger();
2155
2156   memory_allocator_ = new MemoryAllocator(this);
2157   code_range_ = new CodeRange(this);
2158
2159   // Safe after setting Heap::isolate_, initializing StackGuard and
2160   // ensuring that Isolate::Current() == this.
2161   heap_.SetStackLimits();
2162
2163 #define ASSIGN_ELEMENT(CamelName, hacker_name)                  \
2164   isolate_addresses_[Isolate::k##CamelName##Address] =          \
2165       reinterpret_cast<Address>(hacker_name##_address());
2166   FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
2167 #undef ASSIGN_ELEMENT
2168
2169   string_tracker_ = new StringTracker();
2170   string_tracker_->isolate_ = this;
2171   compilation_cache_ = new CompilationCache(this);
2172   transcendental_cache_ = new TranscendentalCache();
2173   keyed_lookup_cache_ = new KeyedLookupCache();
2174   context_slot_cache_ = new ContextSlotCache();
2175   descriptor_lookup_cache_ = new DescriptorLookupCache();
2176   unicode_cache_ = new UnicodeCache();
2177   inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
2178   write_iterator_ = new ConsStringIteratorOp();
2179   global_handles_ = new GlobalHandles(this);
2180   bootstrapper_ = new Bootstrapper(this);
2181   handle_scope_implementer_ = new HandleScopeImplementer(this);
2182   stub_cache_ = new StubCache(this);
2183   regexp_stack_ = new RegExpStack();
2184   regexp_stack_->isolate_ = this;
2185   date_cache_ = new DateCache();
2186   code_stub_interface_descriptors_ =
2187       new CodeStubInterfaceDescriptor[CodeStub::NUMBER_OF_IDS];
2188   cpu_profiler_ = new CpuProfiler(this);
2189   heap_profiler_ = new HeapProfiler(heap());
2190
2191   // Enable logging before setting up the heap
2192   logger_->SetUp(this);
2193
2194   // Initialize other runtime facilities
2195 #if defined(USE_SIMULATOR)
2196 #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_MIPS
2197   Simulator::Initialize(this);
2198 #endif
2199 #endif
2200
2201   { // NOLINT
2202     // Ensure that the thread has a valid stack guard.  The v8::Locker object
2203     // will ensure this too, but we don't have to use lockers if we are only
2204     // using one thread.
2205     ExecutionAccess lock(this);
2206     stack_guard_.InitThread(lock);
2207   }
2208
2209   // SetUp the object heap.
2210   ASSERT(!heap_.HasBeenSetUp());
2211   if (!heap_.SetUp()) {
2212     V8::FatalProcessOutOfMemory("heap setup");
2213     return false;
2214   }
2215
2216   deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2217
2218   const bool create_heap_objects = (des == NULL);
2219   if (create_heap_objects && !heap_.CreateHeapObjects()) {
2220     V8::FatalProcessOutOfMemory("heap object creation");
2221     return false;
2222   }
2223
2224   if (create_heap_objects) {
2225     // Terminate the cache array with the sentinel so we can iterate.
2226     PushToPartialSnapshotCache(heap_.undefined_value());
2227   }
2228
2229   InitializeThreadLocal();
2230
2231   bootstrapper_->Initialize(create_heap_objects);
2232   builtins_.SetUp(create_heap_objects);
2233
2234   // Only preallocate on the first initialization.
2235   if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
2236     // Start the thread which will set aside some memory.
2237     PreallocatedMemoryThreadStart();
2238     preallocated_message_space_ =
2239         new NoAllocationStringAllocator(
2240             preallocated_memory_thread_->data(),
2241             preallocated_memory_thread_->length());
2242     PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
2243   }
2244
2245   if (FLAG_preemption) {
2246     v8::Locker locker(reinterpret_cast<v8::Isolate*>(this));
2247     v8::Locker::StartPreemption(100);
2248   }
2249
2250 #ifdef ENABLE_DEBUGGER_SUPPORT
2251   debug_->SetUp(create_heap_objects);
2252 #endif
2253
2254   // If we are deserializing, read the state into the now-empty heap.
2255   if (!create_heap_objects) {
2256     des->Deserialize();
2257   }
2258   stub_cache_->Initialize();
2259
2260   // Finish initialization of ThreadLocal after deserialization is done.
2261   clear_pending_exception();
2262   clear_pending_message();
2263   clear_scheduled_exception();
2264
2265   // Deserializing may put strange things in the root array's copy of the
2266   // stack guard.
2267   heap_.SetStackLimits();
2268
2269   // Quiet the heap NaN if needed on target platform.
2270   if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
2271
2272   runtime_profiler_ = new RuntimeProfiler(this);
2273   runtime_profiler_->SetUp();
2274
2275   // If we are deserializing, log non-function code objects and compiled
2276   // functions found in the snapshot.
2277   if (!create_heap_objects &&
2278       (FLAG_log_code || FLAG_ll_prof || logger_->is_logging_code_events())) {
2279     HandleScope scope(this);
2280     LOG(this, LogCodeObjects());
2281     LOG(this, LogCompiledFunctions());
2282   }
2283
2284   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2285            Internals::kIsolateEmbedderDataOffset);
2286   CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2287            Internals::kIsolateRootsOffset);
2288
2289   state_ = INITIALIZED;
2290   time_millis_at_init_ = OS::TimeCurrentMillis();
2291
2292   if (!create_heap_objects) {
2293     // Now that the heap is consistent, it's OK to generate the code for the
2294     // deopt entry table that might have been referred to by optimized code in
2295     // the snapshot.
2296     HandleScope scope(this);
2297     Deoptimizer::EnsureCodeForDeoptimizationEntry(
2298         this,
2299         Deoptimizer::LAZY,
2300         kDeoptTableSerializeEntryCount - 1);
2301   }
2302
2303   if (!Serializer::enabled()) {
2304     // Ensure that all stubs which need to be generated ahead of time, but
2305     // cannot be serialized into the snapshot have been generated.
2306     HandleScope scope(this);
2307     CodeStub::GenerateFPStubs(this);
2308     StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2309     StubFailureTrampolineStub::GenerateAheadOfTime(this);
2310     // TODO(mstarzinger): The following is an ugly hack to make sure the
2311     // interface descriptor is initialized even when stubs have been
2312     // deserialized out of the snapshot without the graph builder.
2313     FastCloneShallowArrayStub stub(FastCloneShallowArrayStub::CLONE_ELEMENTS,
2314                                    DONT_TRACK_ALLOCATION_SITE, 0);
2315     stub.InitializeInterfaceDescriptor(
2316         this, code_stub_interface_descriptor(CodeStub::FastCloneShallowArray));
2317     CompareNilICStub::InitializeForIsolate(this);
2318     ToBooleanStub::InitializeForIsolate(this);
2319     ArrayConstructorStubBase::InstallDescriptors(this);
2320     InternalArrayConstructorStubBase::InstallDescriptors(this);
2321   }
2322
2323   if (FLAG_parallel_recompilation) optimizing_compiler_thread_.Start();
2324
2325   if (FLAG_marking_threads > 0) {
2326     marking_thread_ = new MarkingThread*[FLAG_marking_threads];
2327     for (int i = 0; i < FLAG_marking_threads; i++) {
2328       marking_thread_[i] = new MarkingThread(this);
2329       marking_thread_[i]->Start();
2330     }
2331   }
2332
2333   if (FLAG_sweeper_threads > 0) {
2334     sweeper_thread_ = new SweeperThread*[FLAG_sweeper_threads];
2335     for (int i = 0; i < FLAG_sweeper_threads; i++) {
2336       sweeper_thread_[i] = new SweeperThread(this);
2337       sweeper_thread_[i]->Start();
2338     }
2339   }
2340
2341   initialized_from_snapshot_ = (des != NULL);
2342
2343   return true;
2344 }
2345
2346
2347 // Initialized lazily to allow early
2348 // v8::V8::SetAddHistogramSampleFunction calls.
2349 StatsTable* Isolate::stats_table() {
2350   if (stats_table_ == NULL) {
2351     stats_table_ = new StatsTable;
2352   }
2353   return stats_table_;
2354 }
2355
2356
2357 void Isolate::Enter() {
2358   Isolate* current_isolate = NULL;
2359   PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2360   if (current_data != NULL) {
2361     current_isolate = current_data->isolate_;
2362     ASSERT(current_isolate != NULL);
2363     if (current_isolate == this) {
2364       ASSERT(Current() == this);
2365       ASSERT(entry_stack_ != NULL);
2366       ASSERT(entry_stack_->previous_thread_data == NULL ||
2367              entry_stack_->previous_thread_data->thread_id().Equals(
2368                  ThreadId::Current()));
2369       // Same thread re-enters the isolate, no need to re-init anything.
2370       entry_stack_->entry_count++;
2371       return;
2372     }
2373   }
2374
2375   // Threads can have default isolate set into TLS as Current but not yet have
2376   // PerIsolateThreadData for it, as it requires more advanced phase of the
2377   // initialization. For example, a thread might be the one that system used for
2378   // static initializers - in this case the default isolate is set in TLS but
2379   // the thread did not yet Enter the isolate. If PerisolateThreadData is not
2380   // there, use the isolate set in TLS.
2381   if (current_isolate == NULL) {
2382     current_isolate = Isolate::UncheckedCurrent();
2383   }
2384
2385   PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
2386   ASSERT(data != NULL);
2387   ASSERT(data->isolate_ == this);
2388
2389   EntryStackItem* item = new EntryStackItem(current_data,
2390                                             current_isolate,
2391                                             entry_stack_);
2392   entry_stack_ = item;
2393
2394   SetIsolateThreadLocals(this, data);
2395
2396   // In case it's the first time some thread enters the isolate.
2397   set_thread_id(data->thread_id());
2398 }
2399
2400
2401 void Isolate::Exit() {
2402   ASSERT(entry_stack_ != NULL);
2403   ASSERT(entry_stack_->previous_thread_data == NULL ||
2404          entry_stack_->previous_thread_data->thread_id().Equals(
2405              ThreadId::Current()));
2406
2407   if (--entry_stack_->entry_count > 0) return;
2408
2409   ASSERT(CurrentPerIsolateThreadData() != NULL);
2410   ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
2411
2412   // Pop the stack.
2413   EntryStackItem* item = entry_stack_;
2414   entry_stack_ = item->previous_item;
2415
2416   PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2417   Isolate* previous_isolate = item->previous_isolate;
2418
2419   delete item;
2420
2421   // Reinit the current thread for the isolate it was running before this one.
2422   SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2423 }
2424
2425
2426 void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2427   deferred->next_ = deferred_handles_head_;
2428   if (deferred_handles_head_ != NULL) {
2429     deferred_handles_head_->previous_ = deferred;
2430   }
2431   deferred_handles_head_ = deferred;
2432 }
2433
2434
2435 void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2436 #ifdef DEBUG
2437   // In debug mode assert that the linked list is well-formed.
2438   DeferredHandles* deferred_iterator = deferred;
2439   while (deferred_iterator->previous_ != NULL) {
2440     deferred_iterator = deferred_iterator->previous_;
2441   }
2442   ASSERT(deferred_handles_head_ == deferred_iterator);
2443 #endif
2444   if (deferred_handles_head_ == deferred) {
2445     deferred_handles_head_ = deferred_handles_head_->next_;
2446   }
2447   if (deferred->next_ != NULL) {
2448     deferred->next_->previous_ = deferred->previous_;
2449   }
2450   if (deferred->previous_ != NULL) {
2451     deferred->previous_->next_ = deferred->next_;
2452   }
2453 }
2454
2455
2456 HStatistics* Isolate::GetHStatistics() {
2457   if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2458   return hstatistics();
2459 }
2460
2461
2462 HTracer* Isolate::GetHTracer() {
2463   if (htracer() == NULL) set_htracer(new HTracer(id()));
2464   return htracer();
2465 }
2466
2467
2468 Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2469   Context* native_context = context()->native_context();
2470   Object* maybe_map_array = native_context->js_array_maps();
2471   if (!maybe_map_array->IsUndefined()) {
2472     Object* maybe_transitioned_map =
2473         FixedArray::cast(maybe_map_array)->get(kind);
2474     if (!maybe_transitioned_map->IsUndefined()) {
2475       return Map::cast(maybe_transitioned_map);
2476     }
2477   }
2478   return NULL;
2479 }
2480
2481
2482 bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2483   Map* root_array_map =
2484       get_initial_js_array_map(GetInitialFastElementsKind());
2485   ASSERT(root_array_map != NULL);
2486   JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2487
2488   // Check that the array prototype hasn't been altered WRT empty elements.
2489   if (root_array_map->prototype() != initial_array_proto) return false;
2490   if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2491     return false;
2492   }
2493
2494   // Check that the object prototype hasn't been altered WRT empty elements.
2495   JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2496   Object* root_array_map_proto = initial_array_proto->GetPrototype();
2497   if (root_array_map_proto != initial_object_proto) return false;
2498   if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2499     return false;
2500   }
2501
2502   return initial_object_proto->GetPrototype()->IsNull();
2503 }
2504
2505
2506 CodeStubInterfaceDescriptor*
2507     Isolate::code_stub_interface_descriptor(int index) {
2508   return code_stub_interface_descriptors_ + index;
2509 }
2510
2511
2512 Object* Isolate::FindCodeObject(Address a) {
2513   return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2514 }
2515
2516
2517 #ifdef DEBUG
2518 #define ISOLATE_FIELD_OFFSET(type, name, ignored)                       \
2519 const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2520 ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2521 ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2522 #undef ISOLATE_FIELD_OFFSET
2523 #endif
2524
2525 } }  // namespace v8::internal