blob: e42d78ecdcba94ca9355b69b201fdbbf0fcbe092 [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
314void Isolate::EnsureDefaultIsolate() {
315 ScopedLock lock(process_wide_mutex_);
316 if (default_isolate_ == NULL) {
317 isolate_key_ = Thread::CreateThreadLocalKey();
318 thread_id_key_ = Thread::CreateThreadLocalKey();
319 per_isolate_thread_data_key_ = Thread::CreateThreadLocalKey();
320 thread_data_table_ = new Isolate::ThreadDataTable();
321 default_isolate_ = new Isolate();
322 }
323 // Can't use SetIsolateThreadLocals(default_isolate_, NULL) here
324 // becase a non-null thread data may be already set.
325 Thread::SetThreadLocal(isolate_key_, default_isolate_);
326 CHECK(default_isolate_->PreInit());
327}
328
329
330Debugger* Isolate::GetDefaultIsolateDebugger() {
331 EnsureDefaultIsolate();
332 return default_isolate_->debugger();
333}
334
335
336StackGuard* Isolate::GetDefaultIsolateStackGuard() {
337 EnsureDefaultIsolate();
338 return default_isolate_->stack_guard();
339}
340
341
342void Isolate::EnterDefaultIsolate() {
343 EnsureDefaultIsolate();
344 ASSERT(default_isolate_ != NULL);
345
346 PerIsolateThreadData* data = CurrentPerIsolateThreadData();
347 // If not yet in default isolate - enter it.
348 if (data == NULL || data->isolate() != default_isolate_) {
349 default_isolate_->Enter();
350 }
351}
352
353
354Isolate* Isolate::GetDefaultIsolateForLocking() {
355 EnsureDefaultIsolate();
356 return default_isolate_;
357}
358
359
360Isolate::ThreadDataTable::ThreadDataTable()
361 : list_(NULL) {
362}
363
364
365Isolate::PerIsolateThreadData*
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000366 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
367 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000368 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
369 if (data->Matches(isolate, thread_id)) return data;
370 }
371 return NULL;
372}
373
374
375void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
376 if (list_ != NULL) list_->prev_ = data;
377 data->next_ = list_;
378 list_ = data;
379}
380
381
382void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
383 if (list_ == data) list_ = data->next_;
384 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
385 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
386}
387
388
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000389void Isolate::ThreadDataTable::Remove(Isolate* isolate,
390 ThreadId thread_id) {
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000391 PerIsolateThreadData* data = Lookup(isolate, thread_id);
392 if (data != NULL) {
393 Remove(data);
394 }
395}
396
397
398#ifdef DEBUG
399#define TRACE_ISOLATE(tag) \
400 do { \
401 if (FLAG_trace_isolates) { \
402 PrintF("Isolate %p " #tag "\n", reinterpret_cast<void*>(this)); \
403 } \
404 } while (false)
405#else
406#define TRACE_ISOLATE(tag)
407#endif
408
409
410Isolate::Isolate()
411 : state_(UNINITIALIZED),
412 entry_stack_(NULL),
413 stack_trace_nesting_level_(0),
414 incomplete_message_(NULL),
415 preallocated_memory_thread_(NULL),
416 preallocated_message_space_(NULL),
417 bootstrapper_(NULL),
418 runtime_profiler_(NULL),
419 compilation_cache_(NULL),
420 counters_(new Counters()),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000421 code_range_(NULL),
422 break_access_(OS::CreateMutex()),
423 logger_(new Logger()),
424 stats_table_(new StatsTable()),
425 stub_cache_(NULL),
426 deoptimizer_data_(NULL),
427 capture_stack_trace_for_uncaught_exceptions_(false),
428 stack_trace_for_uncaught_exceptions_frame_limit_(0),
429 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
430 transcendental_cache_(NULL),
431 memory_allocator_(NULL),
432 keyed_lookup_cache_(NULL),
433 context_slot_cache_(NULL),
434 descriptor_lookup_cache_(NULL),
435 handle_scope_implementer_(NULL),
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000436 unicode_cache_(NULL),
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000437 in_use_list_(0),
438 free_list_(0),
439 preallocated_storage_preallocated_(false),
440 pc_to_code_cache_(NULL),
441 write_input_buffer_(NULL),
442 global_handles_(NULL),
443 context_switcher_(NULL),
444 thread_manager_(NULL),
445 ast_sentinels_(NULL),
446 string_tracker_(NULL),
447 regexp_stack_(NULL),
448 frame_element_constant_list_(0),
449 result_constant_list_(0) {
450 TRACE_ISOLATE(constructor);
451
452 memset(isolate_addresses_, 0,
453 sizeof(isolate_addresses_[0]) * (k_isolate_address_count + 1));
454
455 heap_.isolate_ = this;
456 zone_.isolate_ = this;
457 stack_guard_.isolate_ = this;
458
lrn@chromium.org7516f052011-03-30 08:52:27 +0000459#if defined(V8_TARGET_ARCH_ARM) && !defined(__arm__) || \
460 defined(V8_TARGET_ARCH_MIPS) && !defined(__mips__)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000461 simulator_initialized_ = false;
462 simulator_i_cache_ = NULL;
463 simulator_redirection_ = NULL;
464#endif
465
466#ifdef DEBUG
467 // heap_histograms_ initializes itself.
468 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
469 memset(code_kind_statistics_, 0,
470 sizeof(code_kind_statistics_[0]) * Code::NUMBER_OF_KINDS);
471#endif
472
473#ifdef ENABLE_DEBUGGER_SUPPORT
474 debug_ = NULL;
475 debugger_ = NULL;
476#endif
477
478#ifdef ENABLE_LOGGING_AND_PROFILING
479 producer_heap_profile_ = NULL;
480#endif
481
482 handle_scope_data_.Initialize();
483
484#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
485 name##_ = (initial_value);
486 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
487#undef ISOLATE_INIT_EXECUTE
488
489#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
490 memset(name##_, 0, sizeof(type) * length);
491 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
492#undef ISOLATE_INIT_ARRAY_EXECUTE
493}
494
495void Isolate::TearDown() {
496 TRACE_ISOLATE(tear_down);
497
498 // Temporarily set this isolate as current so that various parts of
499 // the isolate can access it in their destructors without having a
500 // direct pointer. We don't use Enter/Exit here to avoid
501 // initializing the thread data.
502 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
503 Isolate* saved_isolate = UncheckedCurrent();
504 SetIsolateThreadLocals(this, NULL);
505
506 Deinit();
507
508 if (!IsDefaultIsolate()) {
509 delete this;
510 }
511
512 // Restore the previous current isolate.
513 SetIsolateThreadLocals(saved_isolate, saved_data);
514}
515
516
517void Isolate::Deinit() {
518 if (state_ == INITIALIZED) {
519 TRACE_ISOLATE(deinit);
520
521 if (FLAG_hydrogen_stats) HStatistics::Instance()->Print();
522
523 // We must stop the logger before we tear down other components.
524 logger_->EnsureTickerStopped();
525
526 delete deoptimizer_data_;
527 deoptimizer_data_ = NULL;
528 if (FLAG_preemption) {
529 v8::Locker locker;
530 v8::Locker::StopPreemption();
531 }
532 builtins_.TearDown();
533 bootstrapper_->TearDown();
534
535 // Remove the external reference to the preallocated stack memory.
536 delete preallocated_message_space_;
537 preallocated_message_space_ = NULL;
538 PreallocatedMemoryThreadStop();
539
540 HeapProfiler::TearDown();
541 CpuProfiler::TearDown();
542 if (runtime_profiler_ != NULL) {
543 runtime_profiler_->TearDown();
544 delete runtime_profiler_;
545 runtime_profiler_ = NULL;
546 }
547 heap_.TearDown();
548 logger_->TearDown();
549
550 // The default isolate is re-initializable due to legacy API.
551 state_ = PREINITIALIZED;
552 }
553}
554
555
556void Isolate::SetIsolateThreadLocals(Isolate* isolate,
557 PerIsolateThreadData* data) {
558 Thread::SetThreadLocal(isolate_key_, isolate);
559 Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
560}
561
562
563Isolate::~Isolate() {
564 TRACE_ISOLATE(destructor);
565
566#ifdef ENABLE_LOGGING_AND_PROFILING
567 delete producer_heap_profile_;
568 producer_heap_profile_ = NULL;
569#endif
570
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000571 delete unicode_cache_;
572 unicode_cache_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000573
574 delete regexp_stack_;
575 regexp_stack_ = NULL;
576
577 delete ast_sentinels_;
578 ast_sentinels_ = NULL;
579
580 delete descriptor_lookup_cache_;
581 descriptor_lookup_cache_ = NULL;
582 delete context_slot_cache_;
583 context_slot_cache_ = NULL;
584 delete keyed_lookup_cache_;
585 keyed_lookup_cache_ = NULL;
586
587 delete transcendental_cache_;
588 transcendental_cache_ = NULL;
589 delete stub_cache_;
590 stub_cache_ = NULL;
591 delete stats_table_;
592 stats_table_ = NULL;
593
594 delete logger_;
595 logger_ = NULL;
596
597 delete counters_;
598 counters_ = NULL;
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000599
600 delete handle_scope_implementer_;
601 handle_scope_implementer_ = NULL;
602 delete break_access_;
603 break_access_ = NULL;
604
605 delete compilation_cache_;
606 compilation_cache_ = NULL;
607 delete bootstrapper_;
608 bootstrapper_ = NULL;
609 delete pc_to_code_cache_;
610 pc_to_code_cache_ = NULL;
611 delete write_input_buffer_;
612 write_input_buffer_ = NULL;
613
614 delete context_switcher_;
615 context_switcher_ = NULL;
616 delete thread_manager_;
617 thread_manager_ = NULL;
618
619 delete string_tracker_;
620 string_tracker_ = NULL;
621
622 delete memory_allocator_;
623 memory_allocator_ = NULL;
624 delete code_range_;
625 code_range_ = NULL;
626 delete global_handles_;
627 global_handles_ = NULL;
628
629#ifdef ENABLE_DEBUGGER_SUPPORT
630 delete debugger_;
631 debugger_ = NULL;
632 delete debug_;
633 debug_ = NULL;
634#endif
635}
636
637
638bool Isolate::PreInit() {
639 if (state_ != UNINITIALIZED) return true;
640
641 TRACE_ISOLATE(preinit);
642
643 ASSERT(Isolate::Current() == this);
644
645#ifdef ENABLE_DEBUGGER_SUPPORT
646 debug_ = new Debug(this);
647 debugger_ = new Debugger();
648 debugger_->isolate_ = this;
649#endif
650
651 memory_allocator_ = new MemoryAllocator();
652 memory_allocator_->isolate_ = this;
653 code_range_ = new CodeRange();
654 code_range_->isolate_ = this;
655
656 // Safe after setting Heap::isolate_, initializing StackGuard and
657 // ensuring that Isolate::Current() == this.
658 heap_.SetStackLimits();
659
660#ifdef DEBUG
661 DisallowAllocationFailure disallow_allocation_failure;
662#endif
663
664#define C(name) isolate_addresses_[Isolate::k_##name] = \
665 reinterpret_cast<Address>(name());
666 ISOLATE_ADDRESS_LIST(C)
667 ISOLATE_ADDRESS_LIST_PROF(C)
668#undef C
669
670 string_tracker_ = new StringTracker();
671 string_tracker_->isolate_ = this;
672 thread_manager_ = new ThreadManager();
673 thread_manager_->isolate_ = this;
674 compilation_cache_ = new CompilationCache(this);
675 transcendental_cache_ = new TranscendentalCache();
676 keyed_lookup_cache_ = new KeyedLookupCache();
677 context_slot_cache_ = new ContextSlotCache();
678 descriptor_lookup_cache_ = new DescriptorLookupCache();
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000679 unicode_cache_ = new UnicodeCache();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000680 pc_to_code_cache_ = new PcToCodeCache(this);
681 write_input_buffer_ = new StringInputBuffer();
682 global_handles_ = new GlobalHandles(this);
683 bootstrapper_ = new Bootstrapper();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000684 handle_scope_implementer_ = new HandleScopeImplementer();
685 stub_cache_ = new StubCache(this);
686 ast_sentinels_ = new AstSentinels();
687 regexp_stack_ = new RegExpStack();
688 regexp_stack_->isolate_ = this;
689
690#ifdef ENABLE_LOGGING_AND_PROFILING
691 producer_heap_profile_ = new ProducerHeapProfile();
692 producer_heap_profile_->isolate_ = this;
693#endif
694
695 state_ = PREINITIALIZED;
696 return true;
697}
698
699
700void Isolate::InitializeThreadLocal() {
701 thread_local_top_.Initialize();
702 clear_pending_exception();
703 clear_pending_message();
704 clear_scheduled_exception();
705}
706
707
karlklose@chromium.org44bc7082011-04-11 12:33:05 +0000708void Isolate::PropagatePendingExceptionToExternalTryCatch() {
709 ASSERT(has_pending_exception());
710
711 bool external_caught = IsExternallyCaught();
712 thread_local_top_.external_caught_exception_ = external_caught;
713
714 if (!external_caught) return;
715
716 if (thread_local_top_.pending_exception_ == Failure::OutOfMemoryException()) {
717 // Do not propagate OOM exception: we should kill VM asap.
718 } else if (thread_local_top_.pending_exception_ ==
719 heap()->termination_exception()) {
720 try_catch_handler()->can_continue_ = false;
721 try_catch_handler()->exception_ = heap()->null_value();
722 } else {
723 // At this point all non-object (failure) exceptions have
724 // been dealt with so this shouldn't fail.
725 ASSERT(!pending_exception()->IsFailure());
726 try_catch_handler()->can_continue_ = true;
727 try_catch_handler()->exception_ = pending_exception();
728 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
729 try_catch_handler()->message_ = thread_local_top_.pending_message_obj_;
730 }
731 }
732}
733
734
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000735bool Isolate::Init(Deserializer* des) {
736 ASSERT(state_ != INITIALIZED);
737
738 TRACE_ISOLATE(init);
739
740 bool create_heap_objects = des == NULL;
741
742#ifdef DEBUG
743 // The initialization process does not handle memory exhaustion.
744 DisallowAllocationFailure disallow_allocation_failure;
745#endif
746
747 if (state_ == UNINITIALIZED && !PreInit()) return false;
748
749 // Enable logging before setting up the heap
750 logger_->Setup();
751
752 CpuProfiler::Setup();
753 HeapProfiler::Setup();
754
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000755 // Initialize other runtime facilities
756#if defined(USE_SIMULATOR)
lrn@chromium.org7516f052011-03-30 08:52:27 +0000757#if defined(V8_TARGET_ARCH_ARM) || defined(V8_TARGET_ARCH_MIPS)
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000758 Simulator::Initialize();
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000759#endif
760#endif
761
762 { // NOLINT
763 // Ensure that the thread has a valid stack guard. The v8::Locker object
764 // will ensure this too, but we don't have to use lockers if we are only
765 // using one thread.
766 ExecutionAccess lock(this);
767 stack_guard_.InitThread(lock);
768 }
769
770 // Setup the object heap
771 ASSERT(!heap_.HasBeenSetup());
772 if (!heap_.Setup(create_heap_objects)) {
773 V8::SetFatalError();
774 return false;
775 }
776
777 bootstrapper_->Initialize(create_heap_objects);
778 builtins_.Setup(create_heap_objects);
779
780 InitializeThreadLocal();
781
782 // Only preallocate on the first initialization.
783 if (FLAG_preallocate_message_memory && preallocated_message_space_ == NULL) {
784 // Start the thread which will set aside some memory.
785 PreallocatedMemoryThreadStart();
786 preallocated_message_space_ =
787 new NoAllocationStringAllocator(
788 preallocated_memory_thread_->data(),
789 preallocated_memory_thread_->length());
790 PreallocatedStorageInit(preallocated_memory_thread_->length() / 4);
791 }
792
793 if (FLAG_preemption) {
794 v8::Locker locker;
795 v8::Locker::StartPreemption(100);
796 }
797
798#ifdef ENABLE_DEBUGGER_SUPPORT
799 debug_->Setup(create_heap_objects);
800#endif
801 stub_cache_->Initialize(create_heap_objects);
802
803 // If we are deserializing, read the state into the now-empty heap.
804 if (des != NULL) {
805 des->Deserialize();
806 stub_cache_->Clear();
807 }
808
809 // Deserializing may put strange things in the root array's copy of the
810 // stack guard.
811 heap_.SetStackLimits();
812
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000813 deoptimizer_data_ = new DeoptimizerData;
814 runtime_profiler_ = new RuntimeProfiler(this);
815 runtime_profiler_->Setup();
816
817 // If we are deserializing, log non-function code objects and compiled
818 // functions found in the snapshot.
819 if (des != NULL && FLAG_log_code) {
820 HandleScope scope;
821 LOG(this, LogCodeObjects());
822 LOG(this, LogCompiledFunctions());
823 }
824
825 state_ = INITIALIZED;
826 return true;
827}
828
829
830void Isolate::Enter() {
831 Isolate* current_isolate = NULL;
832 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
833 if (current_data != NULL) {
834 current_isolate = current_data->isolate_;
835 ASSERT(current_isolate != NULL);
836 if (current_isolate == this) {
837 ASSERT(Current() == this);
838 ASSERT(entry_stack_ != NULL);
839 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000840 entry_stack_->previous_thread_data->thread_id().Equals(
841 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000842 // Same thread re-enters the isolate, no need to re-init anything.
843 entry_stack_->entry_count++;
844 return;
845 }
846 }
847
848 // Threads can have default isolate set into TLS as Current but not yet have
849 // PerIsolateThreadData for it, as it requires more advanced phase of the
850 // initialization. For example, a thread might be the one that system used for
851 // static initializers - in this case the default isolate is set in TLS but
852 // the thread did not yet Enter the isolate. If PerisolateThreadData is not
853 // there, use the isolate set in TLS.
854 if (current_isolate == NULL) {
855 current_isolate = Isolate::UncheckedCurrent();
856 }
857
858 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
859 ASSERT(data != NULL);
860 ASSERT(data->isolate_ == this);
861
862 EntryStackItem* item = new EntryStackItem(current_data,
863 current_isolate,
864 entry_stack_);
865 entry_stack_ = item;
866
867 SetIsolateThreadLocals(this, data);
868
869 CHECK(PreInit());
870
871 // In case it's the first time some thread enters the isolate.
872 set_thread_id(data->thread_id());
873}
874
875
876void Isolate::Exit() {
877 ASSERT(entry_stack_ != NULL);
878 ASSERT(entry_stack_->previous_thread_data == NULL ||
ager@chromium.orga9aa5fa2011-04-13 08:46:07 +0000879 entry_stack_->previous_thread_data->thread_id().Equals(
880 ThreadId::Current()));
sgjesse@chromium.orgea88ce92011-03-23 11:19:56 +0000881
882 if (--entry_stack_->entry_count > 0) return;
883
884 ASSERT(CurrentPerIsolateThreadData() != NULL);
885 ASSERT(CurrentPerIsolateThreadData()->isolate_ == this);
886
887 // Pop the stack.
888 EntryStackItem* item = entry_stack_;
889 entry_stack_ = item->previous_item;
890
891 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
892 Isolate* previous_isolate = item->previous_isolate;
893
894 delete item;
895
896 // Reinit the current thread for the isolate it was running before this one.
897 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
898}
899
900
901void Isolate::ResetEagerOptimizingData() {
902 compilation_cache_->ResetEagerOptimizingData();
903}
904
905
906#ifdef DEBUG
907#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
908const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
909ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
910ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
911#undef ISOLATE_FIELD_OFFSET
912#endif
913
914} } // namespace v8::internal