blob: 48717021d7f75e8b5eb304ab2eaa14c39ae9e692 [file] [log] [blame]
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +00001// Copyright 2011 the V8 project authors. All rights reserved.
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include <stdlib.h>
29
30#include "v8.h"
31
32#include "ast.h"
33#include "bootstrapper.h"
34#include "codegen.h"
35#include "compilation-cache.h"
36#include "debug.h"
37#include "deoptimizer.h"
38#include "heap-profiler.h"
39#include "hydrogen.h"
40#include "isolate.h"
41#include "lithium-allocator.h"
42#include "log.h"
43#include "regexp-stack.h"
44#include "runtime-profiler.h"
45#include "scanner.h"
46#include "scopeinfo.h"
47#include "serialize.h"
48#include "simulator.h"
49#include "spaces.h"
50#include "stub-cache.h"
51#include "version.h"
52
53
54namespace v8 {
55namespace internal {
56
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +000057Atomic32 ThreadId::highest_thread_id_ = 0;
58
59int ThreadId::AllocateThreadId() {
60 int new_id = NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
61 return new_id;
62}
63
64int ThreadId::GetCurrentThreadId() {
65 int thread_id = Thread::GetThreadLocalInt(Isolate::thread_id_key_);
66 if (thread_id == 0) {
67 thread_id = AllocateThreadId();
68 Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
69 }
70 return thread_id;
71}
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +000072
73// Create a dummy thread that will wait forever on a semaphore. The only
74// purpose for this thread is to have some stack area to save essential data
75// into for use by a stacks only core dump (aka minidump).
76class PreallocatedMemoryThread: public Thread {
77 public:
78 char* data() {
79 if (data_ready_semaphore_ != NULL) {
80 // Initial access is guarded until the data has been published.
81 data_ready_semaphore_->Wait();
82 delete data_ready_semaphore_;
83 data_ready_semaphore_ = NULL;
84 }
85 return data_;
86 }
87
88 unsigned length() {
89 if (data_ready_semaphore_ != NULL) {
90 // Initial access is guarded until the data has been published.
91 data_ready_semaphore_->Wait();
92 delete data_ready_semaphore_;
93 data_ready_semaphore_ = NULL;
94 }
95 return length_;
96 }
97
98 // Stop the PreallocatedMemoryThread and release its resources.
99 void StopThread() {
100 keep_running_ = false;
101 wait_for_ever_semaphore_->Signal();
102
103 // Wait for the thread to terminate.
104 Join();
105
106 if (data_ready_semaphore_ != NULL) {
107 delete data_ready_semaphore_;
108 data_ready_semaphore_ = NULL;
109 }
110
111 delete wait_for_ever_semaphore_;
112 wait_for_ever_semaphore_ = NULL;
113 }
114
115 protected:
116 // When the thread starts running it will allocate a fixed number of bytes
117 // on the stack and publish the location of this memory for others to use.
118 void Run() {
119 EmbeddedVector<char, 15 * 1024> local_buffer;
120
121 // Initialize the buffer with a known good value.
122 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
123 local_buffer.length());
124
125 // Publish the local buffer and signal its availability.
126 data_ = local_buffer.start();
127 length_ = local_buffer.length();
128 data_ready_semaphore_->Signal();
129
130 while (keep_running_) {
131 // This thread will wait here until the end of time.
132 wait_for_ever_semaphore_->Wait();
133 }
134
135 // Make sure we access the buffer after the wait to remove all possibility
136 // of it being optimized away.
137 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
138 local_buffer.length());
139 }
140
141
142 private:
143 explicit PreallocatedMemoryThread(Isolate* isolate)
144 : Thread(isolate, "v8:PreallocMem"),
145 keep_running_(true),
146 wait_for_ever_semaphore_(OS::CreateSemaphore(0)),
147 data_ready_semaphore_(OS::CreateSemaphore(0)),
148 data_(NULL),
149 length_(0) {
150 }
151
152 // Used to make sure that the thread keeps looping even for spurious wakeups.
153 bool keep_running_;
154
155 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
156 Semaphore* wait_for_ever_semaphore_;
157 // Semaphore to signal that the data has been initialized.
158 Semaphore* data_ready_semaphore_;
159
160 // Location and size of the preallocated memory block.
161 char* data_;
162 unsigned length_;
163
164 friend class Isolate;
165
166 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
167};
168
169
170void Isolate::PreallocatedMemoryThreadStart() {
171 if (preallocated_memory_thread_ != NULL) return;
172 preallocated_memory_thread_ = new PreallocatedMemoryThread(this);
173 preallocated_memory_thread_->Start();
174}
175
176
177void Isolate::PreallocatedMemoryThreadStop() {
178 if (preallocated_memory_thread_ == NULL) return;
179 preallocated_memory_thread_->StopThread();
180 // Done with the thread entirely.
181 delete preallocated_memory_thread_;
182 preallocated_memory_thread_ = NULL;
183}
184
185
lrn@chromium.org7516f052011-03-30 08:52:27 +0000186void Isolate::PreallocatedStorageInit(size_t size) {
187 ASSERT(free_list_.next_ == &free_list_);
188 ASSERT(free_list_.previous_ == &free_list_);
189 PreallocatedStorage* free_chunk =
190 reinterpret_cast<PreallocatedStorage*>(new char[size]);
191 free_list_.next_ = free_list_.previous_ = free_chunk;
192 free_chunk->next_ = free_chunk->previous_ = &free_list_;
193 free_chunk->size_ = size - sizeof(PreallocatedStorage);
194 preallocated_storage_preallocated_ = true;
195}
196
197
198void* Isolate::PreallocatedStorageNew(size_t size) {
199 if (!preallocated_storage_preallocated_) {
200 return FreeStoreAllocationPolicy::New(size);
201 }
202 ASSERT(free_list_.next_ != &free_list_);
203 ASSERT(free_list_.previous_ != &free_list_);
204
205 size = (size + kPointerSize - 1) & ~(kPointerSize - 1);
206 // Search for exact fit.
207 for (PreallocatedStorage* storage = free_list_.next_;
208 storage != &free_list_;
209 storage = storage->next_) {
210 if (storage->size_ == size) {
211 storage->Unlink();
212 storage->LinkTo(&in_use_list_);
213 return reinterpret_cast<void*>(storage + 1);
214 }
215 }
216 // Search for first fit.
217 for (PreallocatedStorage* storage = free_list_.next_;
218 storage != &free_list_;
219 storage = storage->next_) {
220 if (storage->size_ >= size + sizeof(PreallocatedStorage)) {
221 storage->Unlink();
222 storage->LinkTo(&in_use_list_);
223 PreallocatedStorage* left_over =
224 reinterpret_cast<PreallocatedStorage*>(
225 reinterpret_cast<char*>(storage + 1) + size);
226 left_over->size_ = storage->size_ - size - sizeof(PreallocatedStorage);
227 ASSERT(size + left_over->size_ + sizeof(PreallocatedStorage) ==
228 storage->size_);
229 storage->size_ = size;
230 left_over->LinkTo(&free_list_);
231 return reinterpret_cast<void*>(storage + 1);
232 }
233 }
234 // Allocation failure.
235 ASSERT(false);
236 return NULL;
237}
238
239
240// We don't attempt to coalesce.
241void Isolate::PreallocatedStorageDelete(void* p) {
242 if (p == NULL) {
243 return;
244 }
245 if (!preallocated_storage_preallocated_) {
246 FreeStoreAllocationPolicy::Delete(p);
247 return;
248 }
249 PreallocatedStorage* storage = reinterpret_cast<PreallocatedStorage*>(p) - 1;
250 ASSERT(storage->next_->previous_ == storage);
251 ASSERT(storage->previous_->next_ == storage);
252 storage->Unlink();
253 storage->LinkTo(&free_list_);
254}
255
256
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000257Isolate* Isolate::default_isolate_ = NULL;
258Thread::LocalStorageKey Isolate::isolate_key_;
259Thread::LocalStorageKey Isolate::thread_id_key_;
260Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
261Mutex* Isolate::process_wide_mutex_ = OS::CreateMutex();
262Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000263
264
265class IsolateInitializer {
266 public:
267 IsolateInitializer() {
268 Isolate::EnsureDefaultIsolate();
269 }
270};
271
272static IsolateInitializer* EnsureDefaultIsolateAllocated() {
273 // TODO(isolates): Use the system threading API to do this once?
274 static IsolateInitializer static_initializer;
275 return &static_initializer;
276}
277
278// This variable only needed to trigger static intialization.
279static IsolateInitializer* static_initializer = EnsureDefaultIsolateAllocated();
280
281
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000282
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000283
284
285Isolate::PerIsolateThreadData* Isolate::AllocatePerIsolateThreadData(
286 ThreadId thread_id) {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000287 ASSERT(!thread_id.Equals(ThreadId::Invalid()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000288 PerIsolateThreadData* per_thread = new PerIsolateThreadData(this, thread_id);
289 {
290 ScopedLock lock(process_wide_mutex_);
291 ASSERT(thread_data_table_->Lookup(this, thread_id) == NULL);
292 thread_data_table_->Insert(per_thread);
293 ASSERT(thread_data_table_->Lookup(this, thread_id) == per_thread);
294 }
295 return per_thread;
296}
297
298
299Isolate::PerIsolateThreadData*
300 Isolate::FindOrAllocatePerThreadDataForThisThread() {
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000301 ThreadId thread_id = ThreadId::Current();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000302 PerIsolateThreadData* per_thread = NULL;
303 {
304 ScopedLock lock(process_wide_mutex_);
305 per_thread = thread_data_table_->Lookup(this, thread_id);
306 if (per_thread == NULL) {
307 per_thread = AllocatePerIsolateThreadData(thread_id);
308 }
309 }
310 return per_thread;
311}
312
313
lrn@chromium.org1c092762011-05-09 09:42:16 +0000314Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
315 ThreadId thread_id = ThreadId::Current();
316 PerIsolateThreadData* per_thread = NULL;
317 {
318 ScopedLock lock(process_wide_mutex_);
319 per_thread = thread_data_table_->Lookup(this, thread_id);
320 }
321 return per_thread;
322}
323
324
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000325void Isolate::EnsureDefaultIsolate() {
326 ScopedLock lock(process_wide_mutex_);
327 if (default_isolate_ == NULL) {
328 isolate_key_ = Thread::CreateThreadLocalKey();
329 thread_id_key_ = Thread::CreateThreadLocalKey();
330 per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
331 thread_data_table_ = new Isolate::ThreadDataTable();
332 default_isolate_ = new Isolate();
333 }
334 // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
335 // becase a non-null thread data may be already set.
lrn@chromium.org1c092762011-05-09 09:42:16 +0000336 if (Thread::GetThreadLocal(isolate_key_) == NULL) {
337 Thread::SetThreadLocal(isolate_key_, default_isolate_);
338 }
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000339 CHECK(default_isolate_->PreInit());
340}
341
342
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000343#ifdef ENABLE_DEBUGGER_SUPPORT
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000344Debugger* Isolate::GetDefaultIsolateDebugger() {
345 EnsureDefaultIsolate();
346 return default_isolate_->debugger();
347}
erik.corry@gmail.com3847bd52011-04-27 10:38:56 +0000348#endif
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000349
350
351StackGuard* Isolate::GetDefaultIsolateStackGuard() {
352 EnsureDefaultIsolate();
353 return default_isolate_->stack_guard();
354}
355
356
357void Isolate::EnterDefaultIsolate() {
358 EnsureDefaultIsolate();
359 ASSERT(default_isolate_ != NULL);
360
361 PerIsolateThreadData* data = CurrentPerIsolateThreadData();
362 // If not yet in default isolate - enter it.
363 if (data == NULL || data->isolate() != default_isolate_) {
364 default_isolate_->Enter();
365 }
366}
367
368
369Isolate* Isolate::GetDefaultIsolateForLocking() {
370 EnsureDefaultIsolate();
371 return default_isolate_;
372}
373
374
375Isolate::ThreadDataTable::ThreadDataTable()
376 : list_(NULL) {
377}
378
379
380Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000381 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
382 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000383 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
384 if (data->Matches(isolate, thread_id)) return data;
385 }
386 return NULL;
387}
388
389
390void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
391 if (list_ != NULL) list_->prev_ = data;
392 data->next_ = list_;
393 list_ = data;
394}
395
396
397void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
398 if (list_ == data) list_ = data->next_;
399 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
400 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
401}
402
403
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000404void Isolate::ThreadDataTable::Remove(Isolate* isolate,
405 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000406 PerIsolateThreadData* data = Lookup(isolate, thread_id);
407 if (data != NULL) {
408 Remove(data);
409 }
410}
411
412
413#ifdef DEBUG
414#define TRACE_ISOLATE(tag) \
415 do { \
416 if (FLAG_trace_isolates) { \
417 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
418 } \
419 } while (false)
420#else
421#define TRACE_ISOLATE(tag)
422#endif
423
424
425Isolate::Isolate()
426 : state_(UNINITIALIZED),
427 entry_stack_(NULL),
428 stack_trace_nesting_level_(0),
429 incomplete_message_(NULL),
430 preallocated_memory_thread_(NULL),
431 preallocated_message_space_(NULL),
432 bootstrapper_(NULL),
433 runtime_profiler_(NULL),
434 compilation_cache_(NULL),
435 counters_(new Counters()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000436 code_range_(NULL),
437 break_access_(OS::CreateMutex()),
438 logger_(new Logger()),
439 stats_table_(new StatsTable()),
440 stub_cache_(NULL),
441 deoptimizer_data_(NULL),
442 capture_stack_trace_for_uncaught_exceptions_(false),
443 stack_trace_for_uncaught_exceptions_frame_limit_(0),
444 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
445 transcendental_cache_(NULL),
446 memory_allocator_(NULL),
447 keyed_lookup_cache_(NULL),
448 context_slot_cache_(NULL),
449 descriptor_lookup_cache_(NULL),
450 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000451 unicode_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000452 in_use_list_(0),
453 free_list_(0),
454 preallocated_storage_preallocated_(false),
455 pc_to_code_cache_(NULL),
456 write_input_buffer_(NULL),
457 global_handles_(NULL),
458 context_switcher_(NULL),
459 thread_manager_(NULL),
460 ast_sentinels_(NULL),
461 string_tracker_(NULL),
462 regexp_stack_(NULL),
463 frame_element_constant_list_(0),
464 result_constant_list_(0) {
465 TRACE_ISOLATE(constructor);
466
467 memset(isolate_addresses_, 0,
468 sizeof(isolate_addresses_[0]) * (k_isolate_address_count + 1));
469
470 heap_.isolate_ = this;
471 zone_.isolate_ = this;
472 stack_guard_.isolate_ = this;
473
lrn@chromium.org1c092762011-05-09 09:42:16 +0000474 // ThreadManager is initialized early to support locking an isolate
475 // before it is entered.
476 thread_manager_ = new ThreadManager();
477 thread_manager_->isolate_ = this;
478
lrn@chromium.org7516f052011-03-30 08:52:27 +0000479#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
480 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000481 simulator_initialized_ = false;
482 simulator_i_cache_ = NULL;
483 simulator_redirection_ = NULL;
484#endif
485
486#ifdef DEBUG
487 // heap_histograms_ initializes itself.
488 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
489 memset(code_kind_statistics_, 0,
490 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
491#endif
492
493#ifdef ENABLE_DEBUGGER_SUPPORT
494 debug_ = NULL;
495 debugger_ = NULL;
496#endif
497
498#ifdef ENABLE_LOGGING_AND_PROFILING
499 producer_heap_profile_ = NULL;
500#endif
501
502 handle_scope_data_.Initialize();
503
504#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
505 name##_ = (initial_value);
506 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
507#undef ISOLATE_INIT_EXECUTE
508
509#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
510 memset(name##_, 0, sizeof(type) * length);
511 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
512#undef ISOLATE_INIT_ARRAY_EXECUTE
513}
514
515void Isolate::TearDown() {
516 TRACE_ISOLATE(tear_down);
517
518 // Temporarily set this isolate as current so that various parts of
519 // the isolate can access it in their destructors without having a
520 // direct pointer. We don't use Enter/Exit here to avoid
521 // initializing the thread data.
522 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
523 Isolate* saved_isolate = UncheckedCurrent();
524 SetIsolateThreadLocals(this, NULL);
525
526 Deinit();
527
528 if (!IsDefaultIsolate()) {
529 delete this;
530 }
531
532 // Restore the previous current isolate.
533 SetIsolateThreadLocals(saved_isolate, saved_data);
534}
535
536
537void Isolate::Deinit() {
538 if (state_ == INITIALIZED) {
539 TRACE_ISOLATE(deinit);
540
541 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
542
543 // We must stop the logger before we tear down other components.
544 logger_->EnsureTickerStopped();
545
546 delete deoptimizer_data_;
547 deoptimizer_data_ = NULL;
548 if (FLAG_preemption) {
549 v8::Locker locker;
550 v8::Locker::StopPreemption();
551 }
552 builtins_.TearDown();
553 bootstrapper_->TearDown();
554
555 // Remove the external reference to the preallocated stack memory.
556 delete preallocated_message_space_;
557 preallocated_message_space_ = NULL;
558 PreallocatedMemoryThreadStop();
559
560 HeapProfiler::TearDown();
561 CpuProfiler::TearDown();
562 if (runtime_profiler_ != NULL) {
563 runtime_profiler_->TearDown();
564 delete runtime_profiler_;
565 runtime_profiler_ = NULL;
566 }
567 heap_.TearDown();
568 logger_->TearDown();
569
570 // The default isolate is re-initializable due to legacy API.
571 state_ = PREINITIALIZED;
572 }
573}
574
575
576void Isolate::SetIsolateThreadLocals(Isolate* isolate,
577 PerIsolateThreadData* data) {
578 Thread::SetThreadLocal(isolate_key_, isolate);
579 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
580}
581
582
583Isolate::~Isolate() {
584 TRACE_ISOLATE(destructor);
585
586#ifdef ENABLE_LOGGING_AND_PROFILING
587 delete producer_heap_profile_;
588 producer_heap_profile_ = NULL;
589#endif
590
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000591 delete unicode_cache_;
592 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000593
594 delete regexp_stack_;
595 regexp_stack_ = NULL;
596
597 delete ast_sentinels_;
598 ast_sentinels_ = NULL;
599
600 delete descriptor_lookup_cache_;
601 descriptor_lookup_cache_ = NULL;
602 delete context_slot_cache_;
603 context_slot_cache_ = NULL;
604 delete keyed_lookup_cache_;
605 keyed_lookup_cache_ = NULL;
606
607 delete transcendental_cache_;
608 transcendental_cache_ = NULL;
609 delete stub_cache_;
610 stub_cache_ = NULL;
611 delete stats_table_;
612 stats_table_ = NULL;
613
614 delete logger_;
615 logger_ = NULL;
616
617 delete counters_;
618 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000619
620 delete handle_scope_implementer_;
621 handle_scope_implementer_ = NULL;
622 delete break_access_;
623 break_access_ = NULL;
624
625 delete compilation_cache_;
626 compilation_cache_ = NULL;
627 delete bootstrapper_;
628 bootstrapper_ = NULL;
629 delete pc_to_code_cache_;
630 pc_to_code_cache_ = NULL;
631 delete write_input_buffer_;
632 write_input_buffer_ = NULL;
633
634 delete context_switcher_;
635 context_switcher_ = NULL;
636 delete thread_manager_;
637 thread_manager_ = NULL;
638
639 delete string_tracker_;
640 string_tracker_ = NULL;
641
642 delete memory_allocator_;
643 memory_allocator_ = NULL;
644 delete code_range_;
645 code_range_ = NULL;
646 delete global_handles_;
647 global_handles_ = NULL;
648
649#ifdef ENABLE_DEBUGGER_SUPPORT
650 delete debugger_;
651 debugger_ = NULL;
652 delete debug_;
653 debug_ = NULL;
654#endif
655}
656
657
658bool Isolate::PreInit() {
659 if (state_ != UNINITIALIZED) return true;
660
661 TRACE_ISOLATE(preinit);
662
663 ASSERT(Isolate::Current() == this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000664#ifdef ENABLE_DEBUGGER_SUPPORT
665 debug_ = new Debug(this);
666 debugger_ = new Debugger();
667 debugger_->isolate_ = this;
668#endif
669
670 memory_allocator_ = new MemoryAllocator();
671 memory_allocator_->isolate_ = this;
672 code_range_ = new CodeRange();
673 code_range_->isolate_ = this;
674
675 // Safe after setting Heap::isolate_, initializing StackGuard and
676 // ensuring that Isolate::Current() == this.
677 heap_.SetStackLimits();
678
679#ifdef DEBUG
680 DisallowAllocationFailure disallow_allocation_failure;
681#endif
682
683#define C(name) isolate_addresses_[Isolate::k_##name] = \
684 reinterpret_cast<Address>(name());
685 ISOLATE_ADDRESS_LIST(C)
686 ISOLATE_ADDRESS_LIST_PROF(C)
687#undef C
688
689 string_tracker_ = new StringTracker();
690 string_tracker_->isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000691 compilation_cache_ = new CompilationCache(this);
692 transcendental_cache_ = new TranscendentalCache();
693 keyed_lookup_cache_ = new KeyedLookupCache();
694 context_slot_cache_ = new ContextSlotCache();
695 descriptor_lookup_cache_ = new DescriptorLookupCache();
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000696 unicode_cache_ = new UnicodeCache();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000697 pc_to_code_cache_ = new PcToCodeCache(this);
698 write_input_buffer_ = new StringInputBuffer();
699 global_handles_ = new GlobalHandles(this);
700 bootstrapper_ = new Bootstrapper();
lrn@chromium.org1c092762011-05-09 09:42:16 +0000701 handle_scope_implementer_ = new HandleScopeImplementer(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000702 stub_cache_ = new StubCache(this);
703 ast_sentinels_ = new AstSentinels();
704 regexp_stack_ = new RegExpStack();
705 regexp_stack_->isolate_ = this;
706
707#ifdef ENABLE_LOGGING_AND_PROFILING
708 producer_heap_profile_ = new ProducerHeapProfile();
709 producer_heap_profile_->isolate_ = this;
710#endif
711
712 state_ = PREINITIALIZED;
713 return true;
714}
715
716
717void Isolate::InitializeThreadLocal() {
lrn@chromium.org1c092762011-05-09 09:42:16 +0000718 thread_local_top_.isolate_ = this;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000719 thread_local_top_.Initialize();
720 clear_pending_exception();
721 clear_pending_message();
722 clear_scheduled_exception();
723}
724
725
karlklose@chromium.org44bc7082011-04-11 12:33:05 +0000726void Isolate::PropagatePendingExceptionToExternalTryCatch() {
727 ASSERT(has_pending_exception());
728
729 bool external_caught = IsExternallyCaught();
730 thread_local_top_.external_caught_exception_ = external_caught;
731
732 if (!external_caught) return;
733
734 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
735 // Do not propagate OOM exception: we should kill VM asap.
736 } else if (thread_local_top_.pending_exception_ ==
737 heap()->termination_exception()) {
738 try_catch_handler()->can_continue_ = false;
739 try_catch_handler()->exception_ = heap()->null_value();
740 } else {
741 // At this point all non-object (failure) exceptions have
742 // been dealt with so this shouldn't fail.
743 ASSERT(!pending_exception()->IsFailure());
744 try_catch_handler()->can_continue_ = true;
745 try_catch_handler()->exception_ = pending_exception();
746 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
747 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
748 }
749 }
750}
751
752
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000753bool Isolate::Init(Deserializer* des) {
754 ASSERT(state_ != INITIALIZED);
755
756 TRACE_ISOLATE(init);
757
758 bool create_heap_objects = des == NULL;
759
760#ifdef DEBUG
761 // The initialization process does not handle memory exhaustion.
762 DisallowAllocationFailure disallow_allocation_failure;
763#endif
764
765 if (state_ == UNINITIALIZED && !PreInit()) return false;
766
767 // Enable logging before setting up the heap
768 logger_->Setup();
769
770 CpuProfiler::Setup();
771 HeapProfiler::Setup();
772
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000773 // Initialize other runtime facilities
774#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +0000775#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
lrn@chromium.org1c092762011-05-09 09:42:16 +0000776 Simulator::Initialize(this);
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000777#endif
778#endif
779
780 { // NOLINT
781 // Ensure that the thread has a valid stack guard. The v8::Locker object
782 // will ensure this too, but we don't have to use lockers if we are only
783 // using one thread.
784 ExecutionAccess lock(this);
785 stack_guard_.InitThread(lock);
786 }
787
788 // Setup the object heap
789 ASSERT(!heap_.HasBeenSetup());
790 if (!heap_.Setup(create_heap_objects)) {
791 V8::SetFatalError();
792 return false;
793 }
794
795 bootstrapper_->Initialize(create_heap_objects);
796 builtins_.Setup(create_heap_objects);
797
798 InitializeThreadLocal();
799
800 // Only preallocate on the first initialization.
801 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
802 // Start the thread which will set aside some memory.
803 PreallocatedMemoryThreadStart();
804 preallocated_message_space_ =
805 new NoAllocationStringAllocator(
806 preallocated_memory_thread_->data(),
807 preallocated_memory_thread_->length());
808 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
809 }
810
811 if (FLAG_preemption) {
812 v8::Locker locker;
813 v8::Locker::StartPreemption(100);
814 }
815
816#ifdef ENABLE_DEBUGGER_SUPPORT
817 debug_->Setup(create_heap_objects);
818#endif
819 stub_cache_->Initialize(create_heap_objects);
820
821 // If we are deserializing, read the state into the now-empty heap.
822 if (des != NULL) {
823 des->Deserialize();
824 stub_cache_->Clear();
825 }
826
827 // Deserializing may put strange things in the root array's copy of the
828 // stack guard.
829 heap_.SetStackLimits();
830
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000831 deoptimizer_data_ = new DeoptimizerData;
832 runtime_profiler_ = new RuntimeProfiler(this);
833 runtime_profiler_->Setup();
834
835 // If we are deserializing, log non-function code objects and compiled
836 // functions found in the snapshot.
sgjesse@chromium.org8e8294a2011-05-02 14:30:53 +0000837 if (des != NULL && (FLAG_log_code || FLAG_ll_prof)) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000838 HandleScope scope;
839 LOG(this, LogCodeObjects());
840 LOG(this, LogCompiledFunctions());
841 }
842
843 state_ = INITIALIZED;
844 return true;
845}
846
847
848void Isolate::Enter() {
849 Isolate* current_isolate = NULL;
850 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
851 if (current_data != NULL) {
852 current_isolate = current_data->isolate_;
853 ASSERT(current_isolate != NULL);
854 if (current_isolate == this) {
855 ASSERT(Current() == this);
856 ASSERT(entry_stack_ != NULL);
857 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000858 entry_stack_->previous_thread_data->thread_id().Equals(
859 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000860 // Same thread re-enters the isolate, no need to re-init anything.
861 entry_stack_->entry_count++;
862 return;
863 }
864 }
865
866 // Threads can have default isolate set into TLS as Current but not yet have
867 // PerIsolateThreadData for it, as it requires more advanced phase of the
868 // initialization. For example, a thread might be the one that system used for
869 // static initializers - in this case the default isolate is set in TLS but
870 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
871 // there, use the isolate set in TLS.
872 if (current_isolate == NULL) {
873 current_isolate = Isolate::UncheckedCurrent();
874 }
875
876 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
877 ASSERT(data != NULL);
878 ASSERT(data->isolate_ == this);
879
880 EntryStackItem* item = new EntryStackItem(current_data,
881 current_isolate,
882 entry_stack_);
883 entry_stack_ = item;
884
885 SetIsolateThreadLocals(this, data);
886
887 CHECK(PreInit());
888
889 // In case it's the first time some thread enters the isolate.
890 set_thread_id(data->thread_id());
891}
892
893
894void Isolate::Exit() {
895 ASSERT(entry_stack_ != NULL);
896 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000897 entry_stack_->previous_thread_data->thread_id().Equals(
898 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000899
900 if (--entry_stack_->entry_count > 0) return;
901
902 ASSERT(CurrentPerIsolateThreadData() != NULL);
903 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
904
905 // Pop the stack.
906 EntryStackItem* item = entry_stack_;
907 entry_stack_ = item->previous_item;
908
909 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
910 Isolate* previous_isolate = item->previous_isolate;
911
912 delete item;
913
914 // Reinit the current thread for the isolate it was running before this one.
915 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
916}
917
918
919void Isolate::ResetEagerOptimizingData() {
920 compilation_cache_->ResetEagerOptimizingData();
921}
922
923
924#ifdef DEBUG
925#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
926const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
927ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
928ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
929#undef ISOLATE_FIELD_OFFSET
930#endif
931
932} } // namespace v8::internal