blob: b24182b6a0b9478b2bda163d6a1d19b05e43dd34 [file] [log] [blame]
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001// Copyright 2012 the V8 project authors. All rights reserved.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
Steve Block44f0eee2011-05-26 01:26:41 +01004
5#include <stdlib.h>
6
Emily Bernierd0a1eb72015-03-24 16:35:39 -04007#include <fstream> // NOLINT(readability/streams)
8#include <sstream>
9
Ben Murdochb8a8cc12014-11-26 15:28:44 +000010#include "src/v8.h"
Steve Block44f0eee2011-05-26 01:26:41 +010011
Ben Murdochb8a8cc12014-11-26 15:28:44 +000012#include "src/ast.h"
13#include "src/base/platform/platform.h"
14#include "src/base/sys-info.h"
15#include "src/base/utils/random-number-generator.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -040016#include "src/basic-block-profiler.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000017#include "src/bootstrapper.h"
18#include "src/codegen.h"
19#include "src/compilation-cache.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -040020#include "src/compilation-statistics.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000021#include "src/cpu-profiler.h"
22#include "src/debug.h"
23#include "src/deoptimizer.h"
24#include "src/heap/spaces.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000025#include "src/heap-profiler.h"
26#include "src/hydrogen.h"
27#include "src/ic/stub-cache.h"
28#include "src/isolate-inl.h"
29#include "src/lithium-allocator.h"
30#include "src/log.h"
31#include "src/messages.h"
32#include "src/prototype.h"
33#include "src/regexp-stack.h"
34#include "src/runtime-profiler.h"
35#include "src/sampler.h"
36#include "src/scopeinfo.h"
37#include "src/serialize.h"
38#include "src/simulator.h"
39#include "src/version.h"
40#include "src/vm-state-inl.h"
Steve Block44f0eee2011-05-26 01:26:41 +010041
42
43namespace v8 {
44namespace internal {
45
Ben Murdochb8a8cc12014-11-26 15:28:44 +000046base::Atomic32 ThreadId::highest_thread_id_ = 0;
Ben Murdoch8b112d22011-06-08 16:22:53 +010047
48int ThreadId::AllocateThreadId() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000049 int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
Ben Murdoch8b112d22011-06-08 16:22:53 +010050 return new_id;
51}
52
Ben Murdoch257744e2011-11-30 15:57:28 +000053
Ben Murdoch8b112d22011-06-08 16:22:53 +010054int ThreadId::GetCurrentThreadId() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000055 int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
Ben Murdoch8b112d22011-06-08 16:22:53 +010056 if (thread_id == 0) {
57 thread_id = AllocateThreadId();
Ben Murdochb8a8cc12014-11-26 15:28:44 +000058 base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
Ben Murdoch8b112d22011-06-08 16:22:53 +010059 }
60 return thread_id;
61}
Steve Block44f0eee2011-05-26 01:26:41 +010062
Ben Murdoch6d7cb002011-08-04 19:25:22 +010063
Ben Murdoch257744e2011-11-30 15:57:28 +000064ThreadLocalTop::ThreadLocalTop() {
65 InitializeInternal();
66}
67
68
69void ThreadLocalTop::InitializeInternal() {
70 c_entry_fp_ = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -040071 c_function_ = 0;
Ben Murdoch257744e2011-11-30 15:57:28 +000072 handler_ = 0;
73#ifdef USE_SIMULATOR
74 simulator_ = NULL;
75#endif
Ben Murdoch257744e2011-11-30 15:57:28 +000076 js_entry_sp_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000077 external_callback_scope_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000078 current_vm_state_ = EXTERNAL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000079 try_catch_handler_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000080 context_ = NULL;
81 thread_id_ = ThreadId::Invalid();
82 external_caught_exception_ = false;
83 failed_access_check_callback_ = NULL;
84 save_context_ = NULL;
85 catcher_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010086 top_lookup_result_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000087 promise_on_stack_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010088
89 // These members are re-initialized later after deserialization
90 // is complete.
91 pending_exception_ = NULL;
92 has_pending_message_ = false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000093 rethrowing_message_ = false;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010094 pending_message_obj_ = NULL;
95 pending_message_script_ = NULL;
96 scheduled_exception_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000097}
98
99
100void ThreadLocalTop::Initialize() {
101 InitializeInternal();
102#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +0000103 simulator_ = Simulator::current(isolate_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000104#endif
105 thread_id_ = ThreadId::Current();
106}
107
108
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000109void ThreadLocalTop::Free() {
110 // Match unmatched PopPromise calls.
111 while (promise_on_stack_) isolate_->PopPromise();
Ben Murdoch257744e2011-11-30 15:57:28 +0000112}
113
114
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000115base::Thread::LocalStorageKey Isolate::isolate_key_;
116base::Thread::LocalStorageKey Isolate::thread_id_key_;
117base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000118base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER;
Ben Murdoch85b71792012-04-11 18:30:58 +0100119Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000120base::Atomic32 Isolate::isolate_counter_ = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400121#if DEBUG
122base::Atomic32 Isolate::isolate_key_created_ = 0;
123#endif
Steve Block44f0eee2011-05-26 01:26:41 +0100124
125Isolate::PerIsolateThreadData*
126 Isolate::FindOrAllocatePerThreadDataForThisThread() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100127 ThreadId thread_id = ThreadId::Current();
Steve Block44f0eee2011-05-26 01:26:41 +0100128 PerIsolateThreadData* per_thread = NULL;
129 {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000130 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +0100131 per_thread = thread_data_table_->Lookup(this, thread_id);
Steve Block44f0eee2011-05-26 01:26:41 +0100132 if (per_thread == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000133 per_thread = new PerIsolateThreadData(this, thread_id);
134 thread_data_table_->Insert(per_thread);
Steve Block44f0eee2011-05-26 01:26:41 +0100135 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000136 DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
Steve Block44f0eee2011-05-26 01:26:41 +0100137 }
138 return per_thread;
139}
140
141
Ben Murdoch257744e2011-11-30 15:57:28 +0000142Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
143 ThreadId thread_id = ThreadId::Current();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000144 return FindPerThreadDataForThread(thread_id);
145}
146
147
148Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
149 ThreadId thread_id) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000150 PerIsolateThreadData* per_thread = NULL;
151 {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000152 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +0100153 per_thread = thread_data_table_->Lookup(this, thread_id);
Ben Murdoch257744e2011-11-30 15:57:28 +0000154 }
155 return per_thread;
156}
157
158
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000159void Isolate::InitializeOncePerProcess() {
160 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
161 CHECK(thread_data_table_ == NULL);
162 isolate_key_ = base::Thread::CreateThreadLocalKey();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400163#if DEBUG
164 base::NoBarrier_Store(&isolate_key_created_, 1);
165#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000166 thread_id_key_ = base::Thread::CreateThreadLocalKey();
167 per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000168 thread_data_table_ = new Isolate::ThreadDataTable();
Steve Block44f0eee2011-05-26 01:26:41 +0100169}
170
171
Ben Murdoch257744e2011-11-30 15:57:28 +0000172Address Isolate::get_address_from_id(Isolate::AddressId id) {
173 return isolate_addresses_[id];
174}
175
176
177char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
178 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
179 Iterate(v, thread);
180 return thread_storage + sizeof(ThreadLocalTop);
181}
182
183
Ben Murdoch257744e2011-11-30 15:57:28 +0000184void Isolate::IterateThread(ThreadVisitor* v, char* t) {
185 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
186 v->VisitThread(this, thread);
187}
188
189
190void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
191 // Visit the roots from the top for a given thread.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000192 v->VisitPointer(&thread->pending_exception_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000193 v->VisitPointer(&(thread->pending_message_obj_));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000194 v->VisitPointer(bit_cast<Object**>(&(thread->pending_message_script_)));
195 v->VisitPointer(bit_cast<Object**>(&(thread->context_)));
196 v->VisitPointer(&thread->scheduled_exception_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000197
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000198 for (v8::TryCatch* block = thread->try_catch_handler();
Ben Murdoch257744e2011-11-30 15:57:28 +0000199 block != NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000200 block = block->next_) {
201 v->VisitPointer(bit_cast<Object**>(&(block->exception_)));
202 v->VisitPointer(bit_cast<Object**>(&(block->message_obj_)));
203 v->VisitPointer(bit_cast<Object**>(&(block->message_script_)));
Ben Murdoch257744e2011-11-30 15:57:28 +0000204 }
205
206 // Iterate over pointers on native execution stack.
207 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
208 it.frame()->Iterate(v);
209 }
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100210
211 // Iterate pointers in live lookup results.
212 thread->top_lookup_result_->Iterate(v);
Ben Murdoch257744e2011-11-30 15:57:28 +0000213}
214
215
216void Isolate::Iterate(ObjectVisitor* v) {
217 ThreadLocalTop* current_t = thread_local_top();
218 Iterate(v, current_t);
219}
220
221
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000222void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
223 for (DeferredHandles* deferred = deferred_handles_head_;
224 deferred != NULL;
225 deferred = deferred->next_) {
226 deferred->Iterate(visitor);
227 }
228}
229
230
231#ifdef DEBUG
232bool Isolate::IsDeferredHandle(Object** handle) {
233 // Each DeferredHandles instance keeps the handles to one job in the
234 // concurrent recompilation queue, containing a list of blocks. Each block
235 // contains kHandleBlockSize handles except for the first block, which may
236 // not be fully filled.
237 // We iterate through all the blocks to see whether the argument handle
238 // belongs to one of the blocks. If so, it is deferred.
239 for (DeferredHandles* deferred = deferred_handles_head_;
240 deferred != NULL;
241 deferred = deferred->next_) {
242 List<Object**>* blocks = &deferred->blocks_;
243 for (int i = 0; i < blocks->length(); i++) {
244 Object** block_limit = (i == 0) ? deferred->first_block_limit_
245 : blocks->at(i) + kHandleBlockSize;
246 if (blocks->at(i) <= handle && handle < block_limit) return true;
247 }
248 }
249 return false;
250}
251#endif // DEBUG
252
253
Ben Murdoch257744e2011-11-30 15:57:28 +0000254void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000255 thread_local_top()->set_try_catch_handler(that);
Ben Murdoch257744e2011-11-30 15:57:28 +0000256}
257
258
259void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000260 DCHECK(thread_local_top()->try_catch_handler() == that);
261 thread_local_top()->set_try_catch_handler(that->next_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000262 thread_local_top()->catcher_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +0000263}
264
265
266Handle<String> Isolate::StackTraceString() {
267 if (stack_trace_nesting_level_ == 0) {
268 stack_trace_nesting_level_++;
269 HeapStringAllocator allocator;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000270 StringStream::ClearMentionedObjectCache(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000271 StringStream accumulator(&allocator);
272 incomplete_message_ = &accumulator;
273 PrintStack(&accumulator);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000274 Handle<String> stack_trace = accumulator.ToString(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000275 incomplete_message_ = NULL;
276 stack_trace_nesting_level_ = 0;
277 return stack_trace;
278 } else if (stack_trace_nesting_level_ == 1) {
279 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000280 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000281 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000282 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000283 "If you are lucky you may find a partial stack dump on stdout.\n\n");
284 incomplete_message_->OutputToStdOut();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000285 return factory()->empty_string();
Ben Murdoch257744e2011-11-30 15:57:28 +0000286 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000287 base::OS::Abort();
Ben Murdoch257744e2011-11-30 15:57:28 +0000288 // Unreachable
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000289 return factory()->empty_string();
Ben Murdoch257744e2011-11-30 15:57:28 +0000290 }
291}
292
293
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000294void Isolate::PushStackTraceAndDie(unsigned int magic,
295 Object* object,
296 Map* map,
297 unsigned int magic2) {
298 const int kMaxStackTraceSize = 8192;
299 Handle<String> trace = StackTraceString();
300 uint8_t buffer[kMaxStackTraceSize];
301 int length = Min(kMaxStackTraceSize - 1, trace->length());
302 String::WriteToFlat(*trace, buffer, 0, length);
303 buffer[length] = '\0';
304 // TODO(dcarney): convert buffer to utf8?
305 base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2,
306 static_cast<void*>(object), static_cast<void*>(map),
307 reinterpret_cast<char*>(buffer));
308 base::OS::Abort();
309}
310
311
312// Determines whether the given stack frame should be displayed in
313// a stack trace. The caller is the error constructor that asked
314// for the stack trace to be collected. The first time a construct
315// call to this function is encountered it is skipped. The seen_caller
316// in/out parameter is used to remember if the caller has been seen
317// yet.
318static bool IsVisibleInStackTrace(JSFunction* fun,
319 Object* caller,
320 Object* receiver,
321 bool* seen_caller) {
322 if ((fun == caller) && !(*seen_caller)) {
323 *seen_caller = true;
324 return false;
325 }
326 // Skip all frames until we've seen the caller.
327 if (!(*seen_caller)) return false;
328 // Also, skip non-visible built-in functions and any call with the builtins
329 // object as receiver, so as to not reveal either the builtins object or
330 // an internal function.
331 // The --builtins-in-stack-traces command line flag allows including
332 // internal call sites in the stack trace for debugging purposes.
333 if (!FLAG_builtins_in_stack_traces) {
334 if (receiver->IsJSBuiltinsObject()) return false;
335 if (fun->IsBuiltin()) {
336 return fun->shared()->native();
337 } else if (fun->IsFromNativeScript() || fun->IsFromExtensionScript()) {
338 return false;
339 }
340 }
341 return true;
342}
343
344
345Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
346 Handle<Object> caller) {
347 // Get stack trace limit.
348 Handle<Object> error = Object::GetProperty(
349 this, js_builtins_object(), "$Error").ToHandleChecked();
350 if (!error->IsJSObject()) return factory()->undefined_value();
351
352 Handle<String> stackTraceLimit =
353 factory()->InternalizeUtf8String("stackTraceLimit");
354 DCHECK(!stackTraceLimit.is_null());
355 Handle<Object> stack_trace_limit =
356 JSObject::GetDataProperty(Handle<JSObject>::cast(error),
357 stackTraceLimit);
358 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
359 int limit = FastD2IChecked(stack_trace_limit->Number());
360 limit = Max(limit, 0); // Ensure that limit is not negative.
361
362 int initial_size = Min(limit, 10);
363 Handle<FixedArray> elements =
364 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
365
366 // If the caller parameter is a function we skip frames until we're
367 // under it before starting to collect.
368 bool seen_caller = !caller->IsJSFunction();
369 // First element is reserved to store the number of sloppy frames.
370 int cursor = 1;
371 int frames_seen = 0;
372 int sloppy_frames = 0;
373 bool encountered_strict_function = false;
374 for (JavaScriptFrameIterator iter(this);
375 !iter.done() && frames_seen < limit;
376 iter.Advance()) {
377 JavaScriptFrame* frame = iter.frame();
378 // Set initial size to the maximum inlining level + 1 for the outermost
379 // function.
380 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
381 frame->Summarize(&frames);
382 for (int i = frames.length() - 1; i >= 0; i--) {
383 Handle<JSFunction> fun = frames[i].function();
384 Handle<Object> recv = frames[i].receiver();
385 // Filter out internal frames that we do not want to show.
386 if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) continue;
387 // Filter out frames from other security contexts.
388 if (!this->context()->HasSameSecurityTokenAs(fun->context())) continue;
389 if (cursor + 4 > elements->length()) {
390 int new_capacity = JSObject::NewElementsCapacity(elements->length());
391 Handle<FixedArray> new_elements =
392 factory()->NewFixedArrayWithHoles(new_capacity);
393 for (int i = 0; i < cursor; i++) {
394 new_elements->set(i, elements->get(i));
395 }
396 elements = new_elements;
397 }
398 DCHECK(cursor + 4 <= elements->length());
399
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000400 Handle<Code> code = frames[i].code();
401 Handle<Smi> offset(Smi::FromInt(frames[i].offset()), this);
402 // The stack trace API should not expose receivers and function
403 // objects on frames deeper than the top-most one with a strict
404 // mode function. The number of sloppy frames is stored as
405 // first element in the result array.
406 if (!encountered_strict_function) {
407 if (fun->shared()->strict_mode() == STRICT) {
408 encountered_strict_function = true;
409 } else {
410 sloppy_frames++;
411 }
412 }
413 elements->set(cursor++, *recv);
414 elements->set(cursor++, *fun);
415 elements->set(cursor++, *code);
416 elements->set(cursor++, *offset);
417 frames_seen++;
418 }
419 }
420 elements->set(0, Smi::FromInt(sloppy_frames));
421 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
422 result->set_length(Smi::FromInt(cursor));
423 return result;
424}
425
426
427void Isolate::CaptureAndSetDetailedStackTrace(Handle<JSObject> error_object) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100428 if (capture_stack_trace_for_uncaught_exceptions_) {
429 // Capture stack trace for a detailed exception message.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000430 Handle<Name> key = factory()->detailed_stack_trace_symbol();
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100431 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
432 stack_trace_for_uncaught_exceptions_frame_limit_,
433 stack_trace_for_uncaught_exceptions_options_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000434 JSObject::SetProperty(error_object, key, stack_trace, STRICT).Assert();
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100435 }
436}
437
438
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000439void Isolate::CaptureAndSetSimpleStackTrace(Handle<JSObject> error_object,
440 Handle<Object> caller) {
441 // Capture stack trace for simple stack trace string formatting.
442 Handle<Name> key = factory()->stack_trace_symbol();
443 Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
444 JSObject::SetProperty(error_object, key, stack_trace, STRICT).Assert();
445}
446
447
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400448Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
449 Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
450 Handle<Object> stack_trace =
451 JSObject::GetDataProperty(error_object, key_detailed);
452 if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
453
454 if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
455
456 // Try to get details from simple stack trace.
457 Handle<JSArray> detailed_stack_trace =
458 GetDetailedFromSimpleStackTrace(error_object);
459 if (!detailed_stack_trace.is_null()) {
460 // Save the detailed stack since the simple one might be withdrawn later.
461 JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
462 STRICT).Assert();
463 }
464 return detailed_stack_trace;
465}
466
467
468class CaptureStackTraceHelper {
469 public:
470 CaptureStackTraceHelper(Isolate* isolate,
471 StackTrace::StackTraceOptions options)
472 : isolate_(isolate) {
473 if (options & StackTrace::kColumnOffset) {
474 column_key_ =
475 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
476 }
477 if (options & StackTrace::kLineNumber) {
478 line_key_ =
479 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
480 }
481 if (options & StackTrace::kScriptId) {
482 script_id_key_ =
483 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
484 }
485 if (options & StackTrace::kScriptName) {
486 script_name_key_ =
487 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
488 }
489 if (options & StackTrace::kScriptNameOrSourceURL) {
490 script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
491 STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
492 }
493 if (options & StackTrace::kFunctionName) {
494 function_key_ = factory()->InternalizeOneByteString(
495 STATIC_CHAR_VECTOR("functionName"));
496 }
497 if (options & StackTrace::kIsEval) {
498 eval_key_ =
499 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
500 }
501 if (options & StackTrace::kIsConstructor) {
502 constructor_key_ = factory()->InternalizeOneByteString(
503 STATIC_CHAR_VECTOR("isConstructor"));
504 }
505 }
506
507 Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun,
508 Handle<Code> code, Address pc,
509 bool is_constructor) {
510 Handle<JSObject> stack_frame =
511 factory()->NewJSObject(isolate_->object_function());
512
513 Handle<Script> script(Script::cast(fun->shared()->script()));
514
515 if (!line_key_.is_null()) {
516 int script_line_offset = script->line_offset()->value();
517 int position = code->SourcePosition(pc);
518 int line_number = Script::GetLineNumber(script, position);
519 // line_number is already shifted by the script_line_offset.
520 int relative_line_number = line_number - script_line_offset;
521 if (!column_key_.is_null() && relative_line_number >= 0) {
522 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
523 int start = (relative_line_number == 0) ? 0 :
524 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
525 int column_offset = position - start;
526 if (relative_line_number == 0) {
527 // For the case where the code is on the same line as the script
528 // tag.
529 column_offset += script->column_offset()->value();
530 }
531 JSObject::AddProperty(stack_frame, column_key_,
532 handle(Smi::FromInt(column_offset + 1), isolate_),
533 NONE);
534 }
535 JSObject::AddProperty(stack_frame, line_key_,
536 handle(Smi::FromInt(line_number + 1), isolate_),
537 NONE);
538 }
539
540 if (!script_id_key_.is_null()) {
541 JSObject::AddProperty(stack_frame, script_id_key_,
542 handle(script->id(), isolate_), NONE);
543 }
544
545 if (!script_name_key_.is_null()) {
546 JSObject::AddProperty(stack_frame, script_name_key_,
547 handle(script->name(), isolate_), NONE);
548 }
549
550 if (!script_name_or_source_url_key_.is_null()) {
551 Handle<Object> result = Script::GetNameOrSourceURL(script);
552 JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
553 NONE);
554 }
555
556 if (!function_key_.is_null()) {
557 Handle<Object> fun_name(fun->shared()->DebugName(), isolate_);
558 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
559 }
560
561 if (!eval_key_.is_null()) {
562 Handle<Object> is_eval = factory()->ToBoolean(
563 script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
564 JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
565 }
566
567 if (!constructor_key_.is_null()) {
568 Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
569 JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
570 NONE);
571 }
572
573 return stack_frame;
574 }
575
576 private:
577 inline Factory* factory() { return isolate_->factory(); }
578
579 Isolate* isolate_;
580 Handle<String> column_key_;
581 Handle<String> line_key_;
582 Handle<String> script_id_key_;
583 Handle<String> script_name_key_;
584 Handle<String> script_name_or_source_url_key_;
585 Handle<String> function_key_;
586 Handle<String> eval_key_;
587 Handle<String> constructor_key_;
588};
589
590
591Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
592 Handle<JSObject> error_object) {
593 Handle<Name> key = factory()->stack_trace_symbol();
594 Handle<Object> property = JSObject::GetDataProperty(error_object, key);
595 if (!property->IsJSArray()) return Handle<JSArray>();
596 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
597
598 CaptureStackTraceHelper helper(this,
599 stack_trace_for_uncaught_exceptions_options_);
600
601 int frames_seen = 0;
602 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
603 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
604
605 int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
606 if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
607
608 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
609 for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
610 Handle<Object> recv = handle(elements->get(i), this);
611 Handle<JSFunction> fun =
612 handle(JSFunction::cast(elements->get(i + 1)), this);
613 Handle<Code> code = handle(Code::cast(elements->get(i + 2)), this);
614 Handle<Smi> offset = handle(Smi::cast(elements->get(i + 3)), this);
615 Address pc = code->address() + offset->value();
616 bool is_constructor =
617 recv->IsJSObject() &&
618 Handle<JSObject>::cast(recv)->map()->constructor() == *fun;
619
620 Handle<JSObject> stack_frame =
621 helper.NewStackFrameObject(fun, code, pc, is_constructor);
622
623 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
624 frames_seen++;
625 }
626
627 stack_trace->set_length(Smi::FromInt(frames_seen));
628 return stack_trace;
629}
630
631
Ben Murdoch257744e2011-11-30 15:57:28 +0000632Handle<JSArray> Isolate::CaptureCurrentStackTrace(
633 int frame_limit, StackTrace::StackTraceOptions options) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400634 CaptureStackTraceHelper helper(this, options);
635
Ben Murdoch257744e2011-11-30 15:57:28 +0000636 // Ensure no negative values.
637 int limit = Max(frame_limit, 0);
638 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
639
Ben Murdoch257744e2011-11-30 15:57:28 +0000640 StackTraceFrameIterator it(this);
641 int frames_seen = 0;
642 while (!it.done() && (frames_seen < limit)) {
643 JavaScriptFrame* frame = it.frame();
644 // Set initial size to the maximum inlining level + 1 for the outermost
645 // function.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000646 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
Ben Murdoch257744e2011-11-30 15:57:28 +0000647 frame->Summarize(&frames);
648 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000649 Handle<JSFunction> fun = frames[i].function();
650 // Filter frames from other security contexts.
651 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
652 !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
653
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400654 Handle<JSObject> stack_frame = helper.NewStackFrameObject(
655 fun, frames[i].code(), frames[i].pc(), frames[i].is_constructor());
Ben Murdoch257744e2011-11-30 15:57:28 +0000656
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100657 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
Ben Murdoch257744e2011-11-30 15:57:28 +0000658 frames_seen++;
659 }
660 it.Advance();
661 }
662
663 stack_trace->set_length(Smi::FromInt(frames_seen));
664 return stack_trace;
665}
666
667
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000668void Isolate::PrintStack(FILE* out) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000669 if (stack_trace_nesting_level_ == 0) {
670 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000671 StringStream::ClearMentionedObjectCache(this);
672 HeapStringAllocator allocator;
673 StringStream accumulator(&allocator);
Ben Murdoch257744e2011-11-30 15:57:28 +0000674 incomplete_message_ = &accumulator;
675 PrintStack(&accumulator);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000676 accumulator.OutputToFile(out);
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000677 InitializeLoggingAndCounters();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000678 accumulator.Log(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000679 incomplete_message_ = NULL;
680 stack_trace_nesting_level_ = 0;
Ben Murdoch257744e2011-11-30 15:57:28 +0000681 } else if (stack_trace_nesting_level_ == 1) {
682 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000683 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000684 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000685 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000686 "If you are lucky you may find a partial stack dump on stdout.\n\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000687 incomplete_message_->OutputToFile(out);
Ben Murdoch257744e2011-11-30 15:57:28 +0000688 }
689}
690
691
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000692static void PrintFrames(Isolate* isolate,
693 StringStream* accumulator,
Ben Murdoch257744e2011-11-30 15:57:28 +0000694 StackFrame::PrintMode mode) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000695 StackFrameIterator it(isolate);
Ben Murdoch257744e2011-11-30 15:57:28 +0000696 for (int i = 0; !it.done(); it.Advance()) {
697 it.frame()->Print(accumulator, mode, i++);
698 }
699}
700
701
702void Isolate::PrintStack(StringStream* accumulator) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000703 // The MentionedObjectCache is not GC-proof at the moment.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000704 DisallowHeapAllocation no_gc;
705 DCHECK(StringStream::IsMentionedObjectCacheClear(this));
Ben Murdoch257744e2011-11-30 15:57:28 +0000706
707 // Avoid printing anything if there are no frames.
708 if (c_entry_fp(thread_local_top()) == 0) return;
709
710 accumulator->Add(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000711 "\n==== JS stack trace =========================================\n\n");
712 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
Ben Murdoch257744e2011-11-30 15:57:28 +0000713
714 accumulator->Add(
715 "\n==== Details ================================================\n\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000716 PrintFrames(this, accumulator, StackFrame::DETAILS);
Ben Murdoch257744e2011-11-30 15:57:28 +0000717
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000718 accumulator->PrintMentionedObjectCache(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000719 accumulator->Add("=====================\n\n");
720}
721
722
723void Isolate::SetFailedAccessCheckCallback(
724 v8::FailedAccessCheckCallback callback) {
725 thread_local_top()->failed_access_check_callback_ = callback;
726}
727
728
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000729static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
730 Handle<JSObject> receiver) {
731 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
732 if (!constructor->shared()->IsApiFunction()) return NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +0000733
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000734 Object* data_obj =
735 constructor->shared()->get_api_func_data()->access_check_info();
736 if (data_obj == isolate->heap()->undefined_value()) return NULL;
737
738 return AccessCheckInfo::cast(data_obj);
739}
740
741
742void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver,
743 v8::AccessType type) {
744 if (!thread_local_top()->failed_access_check_callback_) {
745 Handle<String> message = factory()->InternalizeUtf8String("no access");
746 Handle<Object> error;
747 ASSIGN_RETURN_ON_EXCEPTION_VALUE(
748 this, error, factory()->NewTypeError(message), /* void */);
749 ScheduleThrow(*error);
750 return;
751 }
752
753 DCHECK(receiver->IsAccessCheckNeeded());
754 DCHECK(context());
Ben Murdoch257744e2011-11-30 15:57:28 +0000755
756 // Get the data object from access check info.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000757 HandleScope scope(this);
758 Handle<Object> data;
759 { DisallowHeapAllocation no_gc;
760 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
761 if (!access_check_info) return;
762 data = handle(access_check_info->data(), this);
763 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000764
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000765 // Leaving JavaScript.
766 VMState<EXTERNAL> state(this);
767 thread_local_top()->failed_access_check_callback_(
768 v8::Utils::ToLocal(receiver),
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100769 type,
770 v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000771}
772
773
774enum MayAccessDecision {
775 YES, NO, UNKNOWN
776};
777
778
779static MayAccessDecision MayAccessPreCheck(Isolate* isolate,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000780 Handle<JSObject> receiver,
Ben Murdoch257744e2011-11-30 15:57:28 +0000781 v8::AccessType type) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000782 DisallowHeapAllocation no_gc;
Ben Murdoch257744e2011-11-30 15:57:28 +0000783 // During bootstrapping, callback functions are not enabled yet.
784 if (isolate->bootstrapper()->IsActive()) return YES;
785
786 if (receiver->IsJSGlobalProxy()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000787 Object* receiver_context = JSGlobalProxy::cast(*receiver)->native_context();
Ben Murdoch257744e2011-11-30 15:57:28 +0000788 if (!receiver_context->IsContext()) return NO;
789
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000790 // Get the native context of current top context.
791 // avoid using Isolate::native_context() because it uses Handle.
792 Context* native_context =
793 isolate->context()->global_object()->native_context();
794 if (receiver_context == native_context) return YES;
Ben Murdoch257744e2011-11-30 15:57:28 +0000795
796 if (Context::cast(receiver_context)->security_token() ==
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000797 native_context->security_token())
Ben Murdoch257744e2011-11-30 15:57:28 +0000798 return YES;
799 }
800
801 return UNKNOWN;
802}
803
804
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400805bool Isolate::IsInternallyUsedPropertyName(Handle<Object> name) {
806 return name.is_identical_to(factory()->hidden_string()) ||
807 name.is_identical_to(factory()->prototype_users_symbol());
808}
809
810
811bool Isolate::IsInternallyUsedPropertyName(Object* name) {
812 return name == heap()->hidden_string() ||
813 name == heap()->prototype_users_symbol();
814}
815
816
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000817bool Isolate::MayNamedAccess(Handle<JSObject> receiver,
818 Handle<Object> key,
Ben Murdoch257744e2011-11-30 15:57:28 +0000819 v8::AccessType type) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000820 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
Ben Murdoch257744e2011-11-30 15:57:28 +0000821
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400822 // Skip checks for internally used properties. Note, we do not
Ben Murdoch257744e2011-11-30 15:57:28 +0000823 // require existence of a context in this case.
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400824 if (IsInternallyUsedPropertyName(key)) return true;
Ben Murdoch257744e2011-11-30 15:57:28 +0000825
826 // Check for compatibility between the security tokens in the
827 // current lexical context and the accessed object.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000828 DCHECK(context());
Ben Murdoch257744e2011-11-30 15:57:28 +0000829
830 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
831 if (decision != UNKNOWN) return decision == YES;
832
Ben Murdoch257744e2011-11-30 15:57:28 +0000833 HandleScope scope(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000834 Handle<Object> data;
835 v8::NamedSecurityCallback callback;
836 { DisallowHeapAllocation no_gc;
837 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
838 if (!access_check_info) return false;
839 Object* fun_obj = access_check_info->named_callback();
840 callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
841 if (!callback) return false;
842 data = handle(access_check_info->data(), this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000843 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000844
845 LOG(this, ApiNamedSecurityCheck(*key));
846
847 // Leaving JavaScript.
848 VMState<EXTERNAL> state(this);
849 return callback(v8::Utils::ToLocal(receiver),
850 v8::Utils::ToLocal(key),
851 type,
852 v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000853}
854
855
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000856bool Isolate::MayIndexedAccess(Handle<JSObject> receiver,
Ben Murdoch257744e2011-11-30 15:57:28 +0000857 uint32_t index,
858 v8::AccessType type) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000859 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
Ben Murdoch257744e2011-11-30 15:57:28 +0000860 // Check for compatibility between the security tokens in the
861 // current lexical context and the accessed object.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000862 DCHECK(context());
Ben Murdoch257744e2011-11-30 15:57:28 +0000863
864 MayAccessDecision decision = MayAccessPreCheck(this, receiver, type);
865 if (decision != UNKNOWN) return decision == YES;
866
Ben Murdoch257744e2011-11-30 15:57:28 +0000867 HandleScope scope(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000868 Handle<Object> data;
869 v8::IndexedSecurityCallback callback;
870 { DisallowHeapAllocation no_gc;
871 // Get named access check callback
872 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
873 if (!access_check_info) return false;
874 Object* fun_obj = access_check_info->indexed_callback();
875 callback = v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
876 if (!callback) return false;
877 data = handle(access_check_info->data(), this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000878 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000879
880 LOG(this, ApiIndexedSecurityCheck(index));
881
882 // Leaving JavaScript.
883 VMState<EXTERNAL> state(this);
884 return callback(
885 v8::Utils::ToLocal(receiver), index, type, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000886}
887
888
889const char* const Isolate::kStackOverflowMessage =
890 "Uncaught RangeError: Maximum call stack size exceeded";
891
892
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000893Object* Isolate::StackOverflow() {
894 HandleScope scope(this);
895 // At this point we cannot create an Error object using its javascript
896 // constructor. Instead, we copy the pre-constructed boilerplate and
897 // attach the stack trace as a hidden property.
898 Handle<String> key = factory()->stack_overflow_string();
899 Handle<JSObject> boilerplate = Handle<JSObject>::cast(
900 Object::GetProperty(js_builtins_object(), key).ToHandleChecked());
901 Handle<JSObject> exception = factory()->CopyJSObject(boilerplate);
Ben Murdoch257744e2011-11-30 15:57:28 +0000902 DoThrow(*exception, NULL);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000903
904 CaptureAndSetSimpleStackTrace(exception, factory()->undefined_value());
905 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000906}
907
908
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000909Object* Isolate::TerminateExecution() {
Ben Murdoch257744e2011-11-30 15:57:28 +0000910 DoThrow(heap_.termination_exception(), NULL);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000911 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000912}
913
914
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000915void Isolate::CancelTerminateExecution() {
916 if (try_catch_handler()) {
917 try_catch_handler()->has_terminated_ = false;
918 }
919 if (has_pending_exception() &&
920 pending_exception() == heap_.termination_exception()) {
921 thread_local_top()->external_caught_exception_ = false;
922 clear_pending_exception();
923 }
924 if (has_scheduled_exception() &&
925 scheduled_exception() == heap_.termination_exception()) {
926 thread_local_top()->external_caught_exception_ = false;
927 clear_scheduled_exception();
928 }
929}
930
931
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400932void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
933 ExecutionAccess access(this);
934 api_interrupts_queue_.push(InterruptEntry(callback, data));
935 stack_guard()->RequestApiInterrupt();
936}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000937
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400938
939void Isolate::InvokeApiInterruptCallbacks() {
940 // Note: callback below should be called outside of execution access lock.
941 while (true) {
942 InterruptEntry entry;
943 {
944 ExecutionAccess access(this);
945 if (api_interrupts_queue_.empty()) return;
946 entry = api_interrupts_queue_.front();
947 api_interrupts_queue_.pop();
948 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000949 VMState<EXTERNAL> state(this);
950 HandleScope handle_scope(this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400951 entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000952 }
953}
954
955
956Object* Isolate::Throw(Object* exception, MessageLocation* location) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000957 DoThrow(exception, location);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000958 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000959}
960
961
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000962Object* Isolate::ReThrow(Object* exception) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000963 bool can_be_caught_externally = false;
964 bool catchable_by_javascript = is_catchable_by_javascript(exception);
965 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
966
967 thread_local_top()->catcher_ = can_be_caught_externally ?
968 try_catch_handler() : NULL;
969
970 // Set the exception being re-thrown.
971 set_pending_exception(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000972 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000973}
974
975
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000976Object* Isolate::ThrowIllegalOperation() {
977 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
978 return Throw(heap_.illegal_access_string());
Ben Murdoch257744e2011-11-30 15:57:28 +0000979}
980
981
982void Isolate::ScheduleThrow(Object* exception) {
983 // When scheduling a throw we first throw the exception to get the
984 // error reporting if it is uncaught before rescheduling it.
985 Throw(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000986 PropagatePendingExceptionToExternalTryCatch();
987 if (has_pending_exception()) {
988 thread_local_top()->scheduled_exception_ = pending_exception();
989 thread_local_top()->external_caught_exception_ = false;
990 clear_pending_exception();
991 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000992}
993
994
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000995void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
996 DCHECK(handler == try_catch_handler());
997 DCHECK(handler->HasCaught());
998 DCHECK(handler->rethrow_);
999 DCHECK(handler->capture_message_);
1000 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
1001 Object* script = reinterpret_cast<Object*>(handler->message_script_);
1002 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
1003 DCHECK(script->IsScript() || script->IsTheHole());
1004 thread_local_top()->pending_message_obj_ = message;
1005 thread_local_top()->pending_message_script_ = script;
1006 thread_local_top()->pending_message_start_pos_ = handler->message_start_pos_;
1007 thread_local_top()->pending_message_end_pos_ = handler->message_end_pos_;
1008}
1009
1010
1011void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1012 DCHECK(has_scheduled_exception());
1013 if (scheduled_exception() == handler->exception_) {
1014 DCHECK(scheduled_exception() != heap()->termination_exception());
1015 clear_scheduled_exception();
1016 }
1017}
1018
1019
1020Object* Isolate::PromoteScheduledException() {
1021 Object* thrown = scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001022 clear_scheduled_exception();
1023 // Re-throw the exception to avoid getting repeated error reporting.
1024 return ReThrow(thrown);
1025}
1026
1027
1028void Isolate::PrintCurrentStackTrace(FILE* out) {
1029 StackTraceFrameIterator it(this);
1030 while (!it.done()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001031 HandleScope scope(this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001032 // Find code position if recorded in relocation info.
1033 JavaScriptFrame* frame = it.frame();
1034 int pos = frame->LookupCode()->SourcePosition(frame->pc());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001035 Handle<Object> pos_obj(Smi::FromInt(pos), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001036 // Fetch function and receiver.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001037 Handle<JSFunction> fun(frame->function());
1038 Handle<Object> recv(frame->receiver(), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001039 // Advance to the next JavaScript frame and determine if the
1040 // current frame is the top-level frame.
1041 it.Advance();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001042 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
Ben Murdoch257744e2011-11-30 15:57:28 +00001043 // Generate and print stack trace line.
1044 Handle<String> line =
1045 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1046 if (line->length() > 0) {
1047 line->PrintOn(out);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001048 PrintF(out, "\n");
Ben Murdoch257744e2011-11-30 15:57:28 +00001049 }
1050 }
1051}
1052
1053
1054void Isolate::ComputeLocation(MessageLocation* target) {
1055 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1056 StackTraceFrameIterator it(this);
1057 if (!it.done()) {
1058 JavaScriptFrame* frame = it.frame();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001059 JSFunction* fun = frame->function();
Ben Murdoch257744e2011-11-30 15:57:28 +00001060 Object* script = fun->shared()->script();
1061 if (script->IsScript() &&
1062 !(Script::cast(script)->source()->IsUndefined())) {
1063 int pos = frame->LookupCode()->SourcePosition(frame->pc());
1064 // Compute the location from the function and the reloc info.
1065 Handle<Script> casted_script(Script::cast(script));
1066 *target = MessageLocation(casted_script, pos, pos + 1);
1067 }
1068 }
1069}
1070
1071
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001072bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1073 Handle<Object> exception) {
1074 *target = MessageLocation(Handle<Script>(heap_.empty_script()), -1, -1);
1075
1076 if (!exception->IsJSObject()) return false;
1077 Handle<Name> key = factory()->stack_trace_symbol();
1078 Handle<Object> property =
1079 JSObject::GetDataProperty(Handle<JSObject>::cast(exception), key);
1080 if (!property->IsJSArray()) return false;
1081 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1082
1083 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1084 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1085
1086 for (int i = 1; i < elements_limit; i += 4) {
1087 Handle<JSFunction> fun =
1088 handle(JSFunction::cast(elements->get(i + 1)), this);
1089 if (fun->IsFromNativeScript()) continue;
1090 Handle<Code> code = handle(Code::cast(elements->get(i + 2)), this);
1091 Handle<Smi> offset = handle(Smi::cast(elements->get(i + 3)), this);
1092 Address pc = code->address() + offset->value();
1093
1094 Object* script = fun->shared()->script();
1095 if (script->IsScript() &&
1096 !(Script::cast(script)->source()->IsUndefined())) {
1097 int pos = code->SourcePosition(pc);
1098 Handle<Script> casted_script(Script::cast(script));
1099 *target = MessageLocation(casted_script, pos, pos + 1);
1100 return true;
1101 }
1102 }
1103 return false;
1104}
1105
1106
Ben Murdoch257744e2011-11-30 15:57:28 +00001107bool Isolate::ShouldReportException(bool* can_be_caught_externally,
1108 bool catchable_by_javascript) {
1109 // Find the top-most try-catch handler.
1110 StackHandler* handler =
1111 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001112 while (handler != NULL && !handler->is_catch()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001113 handler = handler->next();
1114 }
1115
1116 // Get the address of the external handler so we can compare the address to
1117 // determine which one is closer to the top of the stack.
1118 Address external_handler_address =
1119 thread_local_top()->try_catch_handler_address();
1120
1121 // The exception has been externally caught if and only if there is
1122 // an external handler which is on top of the top-most try-catch
1123 // handler.
1124 *can_be_caught_externally = external_handler_address != NULL &&
1125 (handler == NULL || handler->address() > external_handler_address ||
1126 !catchable_by_javascript);
1127
1128 if (*can_be_caught_externally) {
1129 // Only report the exception if the external handler is verbose.
1130 return try_catch_handler()->is_verbose_;
1131 } else {
1132 // Report the exception if it isn't caught by JavaScript code.
1133 return handler == NULL;
1134 }
1135}
1136
1137
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001138// Traverse prototype chain to find out whether the object is derived from
1139// the Error object.
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001140bool Isolate::IsErrorObject(Handle<Object> obj) {
1141 if (!obj->IsJSObject()) return false;
1142
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001143 Handle<String> error_key =
1144 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("$Error"));
1145 Handle<Object> error_constructor = Object::GetProperty(
1146 js_builtins_object(), error_key).ToHandleChecked();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001147
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001148 DisallowHeapAllocation no_gc;
1149 for (PrototypeIterator iter(this, *obj, PrototypeIterator::START_AT_RECEIVER);
1150 !iter.IsAtEnd(); iter.Advance()) {
1151 if (iter.GetCurrent()->IsJSProxy()) return false;
1152 if (JSObject::cast(iter.GetCurrent())->map()->constructor() ==
1153 *error_constructor) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001154 return true;
1155 }
1156 }
1157 return false;
1158}
1159
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001160static int fatal_exception_depth = 0;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001161
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001162
1163Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1164 MessageLocation* location) {
1165 Handle<JSArray> stack_trace_object;
1166 MessageLocation potential_computed_location;
1167 if (capture_stack_trace_for_uncaught_exceptions_) {
1168 if (IsErrorObject(exception)) {
1169 // We fetch the stack trace that corresponds to this error object.
1170 // If the lookup fails, the exception is probably not a valid Error
1171 // object. In that case, we fall through and capture the stack trace
1172 // at this throw site.
1173 stack_trace_object =
1174 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1175 }
1176 if (stack_trace_object.is_null()) {
1177 // Not an error object, we capture stack and location at throw site.
1178 stack_trace_object = CaptureCurrentStackTrace(
1179 stack_trace_for_uncaught_exceptions_frame_limit_,
1180 stack_trace_for_uncaught_exceptions_options_);
1181 }
1182 }
1183 if (!location) {
1184 if (!ComputeLocationFromStackTrace(&potential_computed_location,
1185 exception)) {
1186 ComputeLocation(&potential_computed_location);
1187 }
1188 location = &potential_computed_location;
1189 }
1190
1191 // If the exception argument is a custom object, turn it into a string
1192 // before throwing as uncaught exception. Note that the pending
1193 // exception object to be set later must not be turned into a string.
1194 if (exception->IsJSObject() && !IsErrorObject(exception)) {
1195 MaybeHandle<Object> maybe_exception =
1196 Execution::ToDetailString(this, exception);
1197 if (!maybe_exception.ToHandle(&exception)) {
1198 exception =
1199 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("exception"));
1200 }
1201 }
1202 return MessageHandler::MakeMessageObject(this, "uncaught_exception", location,
1203 HandleVector<Object>(&exception, 1),
1204 stack_trace_object);
1205}
1206
1207
1208void ReportBootstrappingException(Handle<Object> exception,
1209 MessageLocation* location) {
1210 base::OS::PrintError("Exception thrown during bootstrapping\n");
1211 if (location == NULL || location->script().is_null()) return;
1212 // We are bootstrapping and caught an error where the location is set
1213 // and we have a script for the location.
1214 // In this case we could have an extension (or an internal error
1215 // somewhere) and we print out the line number at which the error occured
1216 // to the console for easier debugging.
1217 int line_number =
1218 location->script()->GetLineNumber(location->start_pos()) + 1;
1219 if (exception->IsString() && location->script()->name()->IsString()) {
1220 base::OS::PrintError(
1221 "Extension or internal compilation error: %s in %s at line %d.\n",
1222 String::cast(*exception)->ToCString().get(),
1223 String::cast(location->script()->name())->ToCString().get(),
1224 line_number);
1225 } else if (location->script()->name()->IsString()) {
1226 base::OS::PrintError(
1227 "Extension or internal compilation error in %s at line %d.\n",
1228 String::cast(location->script()->name())->ToCString().get(),
1229 line_number);
1230 } else {
1231 base::OS::PrintError("Extension or internal compilation error.\n");
1232 }
1233#ifdef OBJECT_PRINT
1234 // Since comments and empty lines have been stripped from the source of
1235 // builtins, print the actual source here so that line numbers match.
1236 if (location->script()->source()->IsString()) {
1237 Handle<String> src(String::cast(location->script()->source()));
1238 PrintF("Failing script:\n");
1239 int len = src->length();
1240 int line_number = 1;
1241 PrintF("%5d: ", line_number);
1242 for (int i = 0; i < len; i++) {
1243 uint16_t character = src->Get(i);
1244 PrintF("%c", character);
1245 if (character == '\n' && i < len - 2) {
1246 PrintF("%5d: ", ++line_number);
1247 }
1248 }
1249 }
1250#endif
1251}
1252
1253
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001254void Isolate::DoThrow(Object* exception, MessageLocation* location) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001255 DCHECK(!has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001256
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001257 HandleScope scope(this);
1258 Handle<Object> exception_handle(exception, this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001259
1260 // Determine reporting and whether the exception is caught externally.
1261 bool catchable_by_javascript = is_catchable_by_javascript(exception);
Ben Murdoch257744e2011-11-30 15:57:28 +00001262 bool can_be_caught_externally = false;
1263 bool should_report_exception =
1264 ShouldReportException(&can_be_caught_externally, catchable_by_javascript);
1265 bool report_exception = catchable_by_javascript && should_report_exception;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001266 bool try_catch_needs_message =
1267 can_be_caught_externally && try_catch_handler()->capture_message_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001268 bool rethrowing_message = thread_local_top()->rethrowing_message_;
Ben Murdoch257744e2011-11-30 15:57:28 +00001269
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001270 thread_local_top()->rethrowing_message_ = false;
1271
Ben Murdoch257744e2011-11-30 15:57:28 +00001272 // Notify debugger of exception.
1273 if (catchable_by_javascript) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001274 debug()->OnThrow(exception_handle, report_exception);
Ben Murdoch257744e2011-11-30 15:57:28 +00001275 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001276
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001277 // Generate the message if required.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001278 if (!rethrowing_message && (report_exception || try_catch_needs_message)) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001279 MessageLocation potential_computed_location;
Ben Murdoch257744e2011-11-30 15:57:28 +00001280 if (location == NULL) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001281 // If no location was specified we use a computed one instead.
Ben Murdoch257744e2011-11-30 15:57:28 +00001282 ComputeLocation(&potential_computed_location);
1283 location = &potential_computed_location;
1284 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001285
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001286 if (bootstrapper()->IsActive()) {
1287 // It's not safe to try to make message objects or collect stack traces
1288 // while the bootstrapper is active since the infrastructure may not have
1289 // been properly initialized.
1290 ReportBootstrappingException(exception_handle, location);
1291 } else {
1292 Handle<Object> message_obj = CreateMessage(exception_handle, location);
1293
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001294 thread_local_top()->pending_message_obj_ = *message_obj;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001295 thread_local_top()->pending_message_script_ = *location->script();
1296 thread_local_top()->pending_message_start_pos_ = location->start_pos();
1297 thread_local_top()->pending_message_end_pos_ = location->end_pos();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001298
1299 // If the abort-on-uncaught-exception flag is specified, abort on any
1300 // exception not caught by JavaScript, even when an external handler is
1301 // present. This flag is intended for use by JavaScript developers, so
1302 // print a user-friendly stack trace (not an internal one).
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001303 if (fatal_exception_depth == 0 && FLAG_abort_on_uncaught_exception &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001304 (report_exception || can_be_caught_externally)) {
1305 fatal_exception_depth++;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001306 PrintF(stderr, "%s\n\nFROM\n",
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001307 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1308 PrintCurrentStackTrace(stderr);
1309 base::OS::Abort();
1310 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001311 }
1312 }
1313
1314 // Save the message for reporting if the the exception remains uncaught.
1315 thread_local_top()->has_pending_message_ = report_exception;
Ben Murdoch257744e2011-11-30 15:57:28 +00001316
1317 // Do not forget to clean catcher_ if currently thrown exception cannot
1318 // be caught. If necessary, ReThrow will update the catcher.
1319 thread_local_top()->catcher_ = can_be_caught_externally ?
1320 try_catch_handler() : NULL;
1321
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001322 set_pending_exception(*exception_handle);
Ben Murdoch257744e2011-11-30 15:57:28 +00001323}
1324
1325
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001326bool Isolate::HasExternalTryCatch() {
1327 DCHECK(has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001328
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001329 return (thread_local_top()->catcher_ != NULL) &&
1330 (try_catch_handler() == thread_local_top()->catcher_);
1331}
Ben Murdoch257744e2011-11-30 15:57:28 +00001332
Ben Murdoch257744e2011-11-30 15:57:28 +00001333
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001334bool Isolate::IsFinallyOnTop() {
Ben Murdoch257744e2011-11-30 15:57:28 +00001335 // Get the address of the external handler so we can compare the address to
1336 // determine which one is closer to the top of the stack.
1337 Address external_handler_address =
1338 thread_local_top()->try_catch_handler_address();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001339 DCHECK(external_handler_address != NULL);
Ben Murdoch257744e2011-11-30 15:57:28 +00001340
1341 // The exception has been externally caught if and only if there is
1342 // an external handler which is on top of the top-most try-finally
1343 // handler.
1344 // There should be no try-catch blocks as they would prohibit us from
1345 // finding external catcher in the first place (see catcher_ check above).
1346 //
1347 // Note, that finally clause would rethrow an exception unless it's
1348 // aborted by jumps in control flow like return, break, etc. and we'll
1349 // have another chances to set proper v8::TryCatch.
1350 StackHandler* handler =
1351 StackHandler::FromAddress(Isolate::handler(thread_local_top()));
1352 while (handler != NULL && handler->address() < external_handler_address) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001353 DCHECK(!handler->is_catch());
1354 if (handler->is_finally()) return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001355
1356 handler = handler->next();
1357 }
1358
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001359 return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001360}
1361
1362
1363void Isolate::ReportPendingMessages() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001364 DCHECK(has_pending_exception());
1365 bool can_clear_message = PropagatePendingExceptionToExternalTryCatch();
Ben Murdoch257744e2011-11-30 15:57:28 +00001366
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001367 HandleScope scope(this);
1368 if (thread_local_top_.pending_exception_ == heap()->termination_exception()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001369 // Do nothing: if needed, the exception has been already propagated to
1370 // v8::TryCatch.
1371 } else {
1372 if (thread_local_top_.has_pending_message_) {
1373 thread_local_top_.has_pending_message_ = false;
1374 if (!thread_local_top_.pending_message_obj_->IsTheHole()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001375 HandleScope scope(this);
1376 Handle<Object> message_obj(thread_local_top_.pending_message_obj_,
1377 this);
1378 if (!thread_local_top_.pending_message_script_->IsTheHole()) {
1379 Handle<Script> script(
1380 Script::cast(thread_local_top_.pending_message_script_));
Ben Murdoch257744e2011-11-30 15:57:28 +00001381 int start_pos = thread_local_top_.pending_message_start_pos_;
1382 int end_pos = thread_local_top_.pending_message_end_pos_;
1383 MessageLocation location(script, start_pos, end_pos);
1384 MessageHandler::ReportMessage(this, &location, message_obj);
1385 } else {
1386 MessageHandler::ReportMessage(this, NULL, message_obj);
1387 }
1388 }
1389 }
1390 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001391 if (can_clear_message) clear_pending_message();
Ben Murdoch257744e2011-11-30 15:57:28 +00001392}
1393
1394
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001395MessageLocation Isolate::GetMessageLocation() {
1396 DCHECK(has_pending_exception());
1397
1398 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
1399 thread_local_top_.has_pending_message_ &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001400 !thread_local_top_.pending_message_obj_->IsTheHole()) {
1401 Handle<Script> script(
1402 Script::cast(thread_local_top_.pending_message_script_));
1403 int start_pos = thread_local_top_.pending_message_start_pos_;
1404 int end_pos = thread_local_top_.pending_message_end_pos_;
1405 return MessageLocation(script, start_pos, end_pos);
1406 }
1407
1408 return MessageLocation();
Ben Murdoch257744e2011-11-30 15:57:28 +00001409}
1410
1411
1412bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001413 DCHECK(has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001414 PropagatePendingExceptionToExternalTryCatch();
1415
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001416 bool is_termination_exception =
1417 pending_exception() == heap_.termination_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001418
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001419 // Do not reschedule the exception if this is the bottom call.
1420 bool clear_exception = is_bottom_call;
Ben Murdoch257744e2011-11-30 15:57:28 +00001421
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001422 if (is_termination_exception) {
1423 if (is_bottom_call) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001424 thread_local_top()->external_caught_exception_ = false;
1425 clear_pending_exception();
1426 return false;
1427 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001428 } else if (thread_local_top()->external_caught_exception_) {
1429 // If the exception is externally caught, clear it if there are no
1430 // JavaScript frames on the way to the C++ frame that has the
1431 // external handler.
1432 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1433 Address external_handler_address =
1434 thread_local_top()->try_catch_handler_address();
1435 JavaScriptFrameIterator it(this);
1436 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1437 clear_exception = true;
1438 }
1439 }
1440
1441 // Clear the exception if needed.
1442 if (clear_exception) {
1443 thread_local_top()->external_caught_exception_ = false;
1444 clear_pending_exception();
1445 return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001446 }
1447
1448 // Reschedule the exception.
1449 thread_local_top()->scheduled_exception_ = pending_exception();
1450 clear_pending_exception();
1451 return true;
1452}
1453
1454
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001455void Isolate::PushPromise(Handle<JSObject> promise) {
1456 ThreadLocalTop* tltop = thread_local_top();
1457 PromiseOnStack* prev = tltop->promise_on_stack_;
1458 StackHandler* handler = StackHandler::FromAddress(Isolate::handler(tltop));
1459 Handle<JSObject> global_handle =
1460 Handle<JSObject>::cast(global_handles()->Create(*promise));
1461 tltop->promise_on_stack_ = new PromiseOnStack(handler, global_handle, prev);
1462}
1463
1464
1465void Isolate::PopPromise() {
1466 ThreadLocalTop* tltop = thread_local_top();
1467 if (tltop->promise_on_stack_ == NULL) return;
1468 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
1469 Handle<Object> global_handle = tltop->promise_on_stack_->promise();
1470 delete tltop->promise_on_stack_;
1471 tltop->promise_on_stack_ = prev;
1472 global_handles()->Destroy(global_handle.location());
1473}
1474
1475
1476Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1477 Handle<Object> undefined = factory()->undefined_value();
1478 ThreadLocalTop* tltop = thread_local_top();
1479 if (tltop->promise_on_stack_ == NULL) return undefined;
1480 StackHandler* promise_try = tltop->promise_on_stack_->handler();
1481 // Find the top-most try-catch handler.
1482 StackHandler* handler = StackHandler::FromAddress(Isolate::handler(tltop));
1483 do {
1484 if (handler == promise_try) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001485 return tltop->promise_on_stack_->promise();
1486 }
1487 handler = handler->next();
1488 // Throwing inside a Promise can be intercepted by an inner try-catch, so
1489 // we stop at the first try-catch handler.
1490 } while (handler != NULL && !handler->is_catch());
1491 return undefined;
1492}
1493
1494
Ben Murdoch257744e2011-11-30 15:57:28 +00001495void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1496 bool capture,
1497 int frame_limit,
1498 StackTrace::StackTraceOptions options) {
1499 capture_stack_trace_for_uncaught_exceptions_ = capture;
1500 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1501 stack_trace_for_uncaught_exceptions_options_ = options;
1502}
1503
1504
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001505Handle<Context> Isolate::native_context() {
1506 return handle(context()->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001507}
1508
1509
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001510Handle<Context> Isolate::GetCallingNativeContext() {
1511 JavaScriptFrameIterator it(this);
1512 if (debug_->in_debug_scope()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001513 while (!it.done()) {
1514 JavaScriptFrame* frame = it.frame();
1515 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001516 if (context->native_context() == *debug_->debug_context()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001517 it.Advance();
1518 } else {
1519 break;
1520 }
1521 }
1522 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001523 if (it.done()) return Handle<Context>::null();
1524 JavaScriptFrame* frame = it.frame();
1525 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001526 return Handle<Context>(context->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001527}
1528
1529
1530char* Isolate::ArchiveThread(char* to) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001531 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1532 sizeof(ThreadLocalTop));
Ben Murdoch257744e2011-11-30 15:57:28 +00001533 InitializeThreadLocal();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001534 clear_pending_exception();
1535 clear_pending_message();
1536 clear_scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001537 return to + sizeof(ThreadLocalTop);
1538}
1539
1540
1541char* Isolate::RestoreThread(char* from) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001542 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1543 sizeof(ThreadLocalTop));
1544// This might be just paranoia, but it seems to be needed in case a
1545// thread_local_top_ is restored on a separate OS thread.
Ben Murdoch257744e2011-11-30 15:57:28 +00001546#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +00001547 thread_local_top()->simulator_ = Simulator::current(this);
1548#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001549 DCHECK(context() == NULL || context()->IsContext());
Ben Murdoch257744e2011-11-30 15:57:28 +00001550 return from + sizeof(ThreadLocalTop);
1551}
1552
1553
Steve Block44f0eee2011-05-26 01:26:41 +01001554Isolate::ThreadDataTable::ThreadDataTable()
1555 : list_(NULL) {
1556}
1557
1558
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001559Isolate::ThreadDataTable::~ThreadDataTable() {
1560 // TODO(svenpanne) The assertion below would fire if an embedder does not
1561 // cleanly dispose all Isolates before disposing v8, so we are conservative
1562 // and leave it out for now.
1563 // DCHECK_EQ(NULL, list_);
1564}
1565
1566
1567Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1568#if defined(USE_SIMULATOR)
1569 delete simulator_;
1570#endif
1571}
1572
1573
Steve Block44f0eee2011-05-26 01:26:41 +01001574Isolate::PerIsolateThreadData*
Ben Murdoch8b112d22011-06-08 16:22:53 +01001575 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1576 ThreadId thread_id) {
Steve Block44f0eee2011-05-26 01:26:41 +01001577 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1578 if (data->Matches(isolate, thread_id)) return data;
1579 }
1580 return NULL;
1581}
1582
1583
1584void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1585 if (list_ != NULL) list_->prev_ = data;
1586 data->next_ = list_;
1587 list_ = data;
1588}
1589
1590
1591void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1592 if (list_ == data) list_ = data->next_;
1593 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1594 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001595 delete data;
Steve Block44f0eee2011-05-26 01:26:41 +01001596}
1597
1598
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001599void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1600 PerIsolateThreadData* data = list_;
1601 while (data != NULL) {
1602 PerIsolateThreadData* next = data->next_;
1603 if (data->isolate() == isolate) Remove(data);
1604 data = next;
1605 }
1606}
1607
1608
Steve Block44f0eee2011-05-26 01:26:41 +01001609#ifdef DEBUG
1610#define TRACE_ISOLATE(tag) \
1611 do { \
1612 if (FLAG_trace_isolates) { \
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001613 PrintF("Isolate %p (id %d)" #tag "\n", \
1614 reinterpret_cast<void*>(this), id()); \
Steve Block44f0eee2011-05-26 01:26:41 +01001615 } \
1616 } while (false)
1617#else
1618#define TRACE_ISOLATE(tag)
1619#endif
1620
1621
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001622Isolate::Isolate(bool enable_serializer)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001623 : embedder_data_(),
Steve Block44f0eee2011-05-26 01:26:41 +01001624 entry_stack_(NULL),
1625 stack_trace_nesting_level_(0),
1626 incomplete_message_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001627 bootstrapper_(NULL),
1628 runtime_profiler_(NULL),
1629 compilation_cache_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001630 counters_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001631 code_range_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001632 logger_(NULL),
1633 stats_table_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001634 stub_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001635 code_aging_helper_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001636 deoptimizer_data_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001637 materialized_object_store_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001638 capture_stack_trace_for_uncaught_exceptions_(false),
1639 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1640 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
Steve Block44f0eee2011-05-26 01:26:41 +01001641 memory_allocator_(NULL),
1642 keyed_lookup_cache_(NULL),
1643 context_slot_cache_(NULL),
1644 descriptor_lookup_cache_(NULL),
1645 handle_scope_implementer_(NULL),
Ben Murdoch8b112d22011-06-08 16:22:53 +01001646 unicode_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001647 runtime_zone_(this),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001648 inner_pointer_to_code_cache_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001649 global_handles_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001650 eternal_handles_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001651 thread_manager_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001652 has_installed_extensions_(false),
Steve Block44f0eee2011-05-26 01:26:41 +01001653 string_tracker_(NULL),
1654 regexp_stack_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001655 date_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001656 call_descriptor_data_(NULL),
1657 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1658 // be fixed once the default isolate cleanup is done.
1659 random_number_generator_(NULL),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001660 serializer_enabled_(enable_serializer),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001661 has_fatal_error_(false),
1662 initialized_from_snapshot_(false),
1663 cpu_profiler_(NULL),
1664 heap_profiler_(NULL),
1665 function_entry_hook_(NULL),
1666 deferred_handles_head_(NULL),
1667 optimizing_compiler_thread_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001668 stress_deopt_count_(0),
1669 next_optimization_id_(0),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001670#if TRACE_MAPS
1671 next_unique_sfi_id_(0),
1672#endif
1673 use_counter_callback_(NULL),
1674 basic_block_profiler_(NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001675 {
1676 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1677 CHECK(thread_data_table_);
1678 }
1679 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
Steve Block44f0eee2011-05-26 01:26:41 +01001680 TRACE_ISOLATE(constructor);
1681
1682 memset(isolate_addresses_, 0,
Ben Murdoch589d6972011-11-30 16:04:58 +00001683 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
Steve Block44f0eee2011-05-26 01:26:41 +01001684
1685 heap_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01001686 stack_guard_.isolate_ = this;
1687
Ben Murdoch257744e2011-11-30 15:57:28 +00001688 // ThreadManager is initialized early to support locking an isolate
1689 // before it is entered.
1690 thread_manager_ = new ThreadManager();
1691 thread_manager_->isolate_ = this;
1692
Steve Block44f0eee2011-05-26 01:26:41 +01001693#ifdef DEBUG
1694 // heap_histograms_ initializes itself.
1695 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
Steve Block44f0eee2011-05-26 01:26:41 +01001696#endif
1697
Steve Block44f0eee2011-05-26 01:26:41 +01001698 handle_scope_data_.Initialize();
1699
1700#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1701 name##_ = (initial_value);
1702 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1703#undef ISOLATE_INIT_EXECUTE
1704
1705#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1706 memset(name##_, 0, sizeof(type) * length);
1707 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1708#undef ISOLATE_INIT_ARRAY_EXECUTE
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001709
1710 InitializeLoggingAndCounters();
1711 debug_ = new Debug(this);
Steve Block44f0eee2011-05-26 01:26:41 +01001712}
1713
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001714
Steve Block44f0eee2011-05-26 01:26:41 +01001715void Isolate::TearDown() {
1716 TRACE_ISOLATE(tear_down);
1717
1718 // Temporarily set this isolate as current so that various parts of
1719 // the isolate can access it in their destructors without having a
1720 // direct pointer. We don't use Enter/Exit here to avoid
1721 // initializing the thread data.
1722 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
1723 Isolate* saved_isolate = UncheckedCurrent();
1724 SetIsolateThreadLocals(this, NULL);
1725
1726 Deinit();
1727
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001728 {
1729 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +01001730 thread_data_table_->RemoveAllThreads(this);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001731 }
1732
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001733 if (serialize_partial_snapshot_cache_ != NULL) {
1734 delete[] serialize_partial_snapshot_cache_;
1735 serialize_partial_snapshot_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001736 }
1737
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001738 delete this;
1739
Steve Block44f0eee2011-05-26 01:26:41 +01001740 // Restore the previous current isolate.
1741 SetIsolateThreadLocals(saved_isolate, saved_data);
1742}
1743
1744
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001745void Isolate::GlobalTearDown() {
1746 delete thread_data_table_;
1747 thread_data_table_ = NULL;
1748}
1749
1750
Steve Block44f0eee2011-05-26 01:26:41 +01001751void Isolate::Deinit() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001752 TRACE_ISOLATE(deinit);
Steve Block44f0eee2011-05-26 01:26:41 +01001753
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001754 debug()->Unload();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001755
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001756 FreeThreadResources();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001757
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001758 if (concurrent_recompilation_enabled()) {
1759 optimizing_compiler_thread_->Stop();
1760 delete optimizing_compiler_thread_;
1761 optimizing_compiler_thread_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001762 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001763
1764 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1765 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1766 }
1767
1768 DumpAndResetCompilationStats();
1769
1770 if (FLAG_print_deopt_stress) {
1771 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1772 }
1773
1774 // We must stop the logger before we tear down other components.
1775 Sampler* sampler = logger_->sampler();
1776 if (sampler && sampler->IsActive()) sampler->Stop();
1777
1778 delete deoptimizer_data_;
1779 deoptimizer_data_ = NULL;
1780 builtins_.TearDown();
1781 bootstrapper_->TearDown();
1782
1783 if (runtime_profiler_ != NULL) {
1784 delete runtime_profiler_;
1785 runtime_profiler_ = NULL;
1786 }
1787
1788 delete basic_block_profiler_;
1789 basic_block_profiler_ = NULL;
1790
1791 heap_.TearDown();
1792 logger_->TearDown();
1793
1794 delete heap_profiler_;
1795 heap_profiler_ = NULL;
1796 delete cpu_profiler_;
1797 cpu_profiler_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001798}
1799
1800
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001801void Isolate::PushToPartialSnapshotCache(Object* obj) {
1802 int length = serialize_partial_snapshot_cache_length();
1803 int capacity = serialize_partial_snapshot_cache_capacity();
1804
1805 if (length >= capacity) {
1806 int new_capacity = static_cast<int>((capacity + 10) * 1.2);
1807 Object** new_array = new Object*[new_capacity];
1808 for (int i = 0; i < length; i++) {
1809 new_array[i] = serialize_partial_snapshot_cache()[i];
1810 }
1811 if (capacity != 0) delete[] serialize_partial_snapshot_cache();
1812 set_serialize_partial_snapshot_cache(new_array);
1813 set_serialize_partial_snapshot_cache_capacity(new_capacity);
1814 }
1815
1816 serialize_partial_snapshot_cache()[length] = obj;
1817 set_serialize_partial_snapshot_cache_length(length + 1);
1818}
1819
1820
Steve Block44f0eee2011-05-26 01:26:41 +01001821void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1822 PerIsolateThreadData* data) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001823 base::Thread::SetThreadLocal(isolate_key_, isolate);
1824 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
Steve Block44f0eee2011-05-26 01:26:41 +01001825}
1826
1827
1828Isolate::~Isolate() {
1829 TRACE_ISOLATE(destructor);
1830
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001831 // Has to be called while counters_ are still alive
1832 runtime_zone_.DeleteKeptSegment();
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001833
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001834 // The entry stack must be empty when we get here.
1835 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1836
1837 delete entry_stack_;
1838 entry_stack_ = NULL;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001839
Ben Murdoch8b112d22011-06-08 16:22:53 +01001840 delete unicode_cache_;
1841 unicode_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001842
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001843 delete date_cache_;
1844 date_cache_ = NULL;
1845
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001846 delete[] call_descriptor_data_;
1847 call_descriptor_data_ = NULL;
1848
Steve Block44f0eee2011-05-26 01:26:41 +01001849 delete regexp_stack_;
1850 regexp_stack_ = NULL;
1851
Steve Block44f0eee2011-05-26 01:26:41 +01001852 delete descriptor_lookup_cache_;
1853 descriptor_lookup_cache_ = NULL;
1854 delete context_slot_cache_;
1855 context_slot_cache_ = NULL;
1856 delete keyed_lookup_cache_;
1857 keyed_lookup_cache_ = NULL;
1858
Steve Block44f0eee2011-05-26 01:26:41 +01001859 delete stub_cache_;
1860 stub_cache_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001861 delete code_aging_helper_;
1862 code_aging_helper_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001863 delete stats_table_;
1864 stats_table_ = NULL;
1865
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001866 delete materialized_object_store_;
1867 materialized_object_store_ = NULL;
1868
Steve Block44f0eee2011-05-26 01:26:41 +01001869 delete logger_;
1870 logger_ = NULL;
1871
1872 delete counters_;
1873 counters_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001874
1875 delete handle_scope_implementer_;
1876 handle_scope_implementer_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001877
1878 delete compilation_cache_;
1879 compilation_cache_ = NULL;
1880 delete bootstrapper_;
1881 bootstrapper_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001882 delete inner_pointer_to_code_cache_;
1883 inner_pointer_to_code_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001884
Steve Block44f0eee2011-05-26 01:26:41 +01001885 delete thread_manager_;
1886 thread_manager_ = NULL;
1887
1888 delete string_tracker_;
1889 string_tracker_ = NULL;
1890
1891 delete memory_allocator_;
1892 memory_allocator_ = NULL;
1893 delete code_range_;
1894 code_range_ = NULL;
1895 delete global_handles_;
1896 global_handles_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001897 delete eternal_handles_;
1898 eternal_handles_ = NULL;
1899
1900 delete string_stream_debug_object_cache_;
1901 string_stream_debug_object_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001902
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001903 delete external_reference_table_;
1904 external_reference_table_ = NULL;
1905
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001906 delete random_number_generator_;
1907 random_number_generator_ = NULL;
1908
Steve Block44f0eee2011-05-26 01:26:41 +01001909 delete debug_;
1910 debug_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001911}
1912
1913
Steve Block44f0eee2011-05-26 01:26:41 +01001914void Isolate::InitializeThreadLocal() {
Ben Murdoch257744e2011-11-30 15:57:28 +00001915 thread_local_top_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01001916 thread_local_top_.Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01001917}
1918
1919
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001920bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
1921 DCHECK(has_pending_exception());
Ben Murdoch8b112d22011-06-08 16:22:53 +01001922
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001923 bool has_external_try_catch = HasExternalTryCatch();
1924 if (!has_external_try_catch) {
1925 thread_local_top_.external_caught_exception_ = false;
1926 return true;
1927 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001928
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001929 bool catchable_by_js = is_catchable_by_javascript(pending_exception());
1930 if (catchable_by_js && IsFinallyOnTop()) {
1931 thread_local_top_.external_caught_exception_ = false;
1932 return false;
1933 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01001934
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001935 thread_local_top_.external_caught_exception_ = true;
1936 if (thread_local_top_.pending_exception_ == heap()->termination_exception()) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01001937 try_catch_handler()->can_continue_ = false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001938 try_catch_handler()->has_terminated_ = true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01001939 try_catch_handler()->exception_ = heap()->null_value();
1940 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001941 v8::TryCatch* handler = try_catch_handler();
1942 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
1943 thread_local_top_.pending_message_obj_->IsTheHole());
1944 DCHECK(thread_local_top_.pending_message_script_->IsScript() ||
1945 thread_local_top_.pending_message_script_->IsTheHole());
1946 handler->can_continue_ = true;
1947 handler->has_terminated_ = false;
1948 handler->exception_ = pending_exception();
1949 // Propagate to the external try-catch only if we got an actual message.
1950 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
1951
1952 handler->message_obj_ = thread_local_top_.pending_message_obj_;
1953 handler->message_script_ = thread_local_top_.pending_message_script_;
1954 handler->message_start_pos_ = thread_local_top_.pending_message_start_pos_;
1955 handler->message_end_pos_ = thread_local_top_.pending_message_end_pos_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01001956 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001957 return true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01001958}
1959
1960
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001961void Isolate::InitializeLoggingAndCounters() {
1962 if (logger_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001963 logger_ = new Logger(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001964 }
1965 if (counters_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001966 counters_ = new Counters(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001967 }
1968}
1969
1970
Steve Block44f0eee2011-05-26 01:26:41 +01001971bool Isolate::Init(Deserializer* des) {
Steve Block44f0eee2011-05-26 01:26:41 +01001972 TRACE_ISOLATE(init);
1973
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001974 stress_deopt_count_ = FLAG_deopt_every_n_times;
1975
1976 has_fatal_error_ = false;
1977
1978 if (function_entry_hook() != NULL) {
1979 // When function entry hooking is in effect, we have to create the code
1980 // stubs from scratch to get entry hooks, rather than loading the previously
1981 // generated stubs from disk.
1982 // If this assert fires, the initialization path has regressed.
1983 DCHECK(des == NULL);
1984 }
1985
Steve Block44f0eee2011-05-26 01:26:41 +01001986 // The initialization process does not handle memory exhaustion.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001987 DisallowAllocationFailure disallow_allocation_failure(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001988
1989 memory_allocator_ = new MemoryAllocator(this);
1990 code_range_ = new CodeRange(this);
1991
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001992 // Safe after setting Heap::isolate_, and initializing StackGuard
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001993 heap_.SetStackLimits();
1994
Ben Murdoch589d6972011-11-30 16:04:58 +00001995#define ASSIGN_ELEMENT(CamelName, hacker_name) \
1996 isolate_addresses_[Isolate::k##CamelName##Address] = \
1997 reinterpret_cast<Address>(hacker_name##_address());
1998 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001999#undef ASSIGN_ELEMENT
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002000
2001 string_tracker_ = new StringTracker();
2002 string_tracker_->isolate_ = this;
2003 compilation_cache_ = new CompilationCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002004 keyed_lookup_cache_ = new KeyedLookupCache();
2005 context_slot_cache_ = new ContextSlotCache();
2006 descriptor_lookup_cache_ = new DescriptorLookupCache();
2007 unicode_cache_ = new UnicodeCache();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002008 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002009 global_handles_ = new GlobalHandles(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002010 eternal_handles_ = new EternalHandles();
2011 bootstrapper_ = new Bootstrapper(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002012 handle_scope_implementer_ = new HandleScopeImplementer(this);
2013 stub_cache_ = new StubCache(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002014 materialized_object_store_ = new MaterializedObjectStore(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002015 regexp_stack_ = new RegExpStack();
2016 regexp_stack_->isolate_ = this;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002017 date_cache_ = new DateCache();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002018 call_descriptor_data_ =
2019 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2020 cpu_profiler_ = new CpuProfiler(this);
2021 heap_profiler_ = new HeapProfiler(heap());
Steve Block44f0eee2011-05-26 01:26:41 +01002022
2023 // Enable logging before setting up the heap
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002024 logger_->SetUp(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002025
Steve Block44f0eee2011-05-26 01:26:41 +01002026 // Initialize other runtime facilities
2027#if defined(USE_SIMULATOR)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002028#if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || \
2029 V8_TARGET_ARCH_MIPS || V8_TARGET_ARCH_MIPS64
Ben Murdoch257744e2011-11-30 15:57:28 +00002030 Simulator::Initialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002031#endif
2032#endif
2033
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002034 code_aging_helper_ = new CodeAgingHelper();
2035
Steve Block44f0eee2011-05-26 01:26:41 +01002036 { // NOLINT
2037 // Ensure that the thread has a valid stack guard. The v8::Locker object
2038 // will ensure this too, but we don't have to use lockers if we are only
2039 // using one thread.
2040 ExecutionAccess lock(this);
2041 stack_guard_.InitThread(lock);
2042 }
2043
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002044 // SetUp the object heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002045 DCHECK(!heap_.HasBeenSetUp());
2046 if (!heap_.SetUp()) {
2047 V8::FatalProcessOutOfMemory("heap setup");
Steve Block44f0eee2011-05-26 01:26:41 +01002048 return false;
2049 }
2050
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002051 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2052
2053 const bool create_heap_objects = (des == NULL);
2054 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2055 V8::FatalProcessOutOfMemory("heap object creation");
2056 return false;
2057 }
2058
2059 if (create_heap_objects) {
2060 // Terminate the cache array with the sentinel so we can iterate.
2061 PushToPartialSnapshotCache(heap_.undefined_value());
2062 }
2063
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002064 InitializeThreadLocal();
2065
Steve Block44f0eee2011-05-26 01:26:41 +01002066 bootstrapper_->Initialize(create_heap_objects);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002067 builtins_.SetUp(this, create_heap_objects);
Steve Block44f0eee2011-05-26 01:26:41 +01002068
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002069 if (FLAG_log_internal_timer_events) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002070 set_event_logger(Logger::DefaultEventLoggerSentinel);
Steve Block44f0eee2011-05-26 01:26:41 +01002071 }
2072
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002073 // Set default value if not yet set.
2074 // TODO(yangguo): move this to ResourceConstraints::ConfigureDefaults
2075 // once ResourceConstraints becomes an argument to the Isolate constructor.
2076 if (max_available_threads_ < 1) {
2077 // Choose the default between 1 and 4.
2078 max_available_threads_ =
2079 Max(Min(base::SysInfo::NumberOfProcessors(), 4), 1);
Steve Block44f0eee2011-05-26 01:26:41 +01002080 }
2081
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002082 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2083 PrintF("Concurrent recompilation has been disabled for tracing.\n");
2084 } else if (OptimizingCompilerThread::Enabled(max_available_threads_)) {
2085 optimizing_compiler_thread_ = new OptimizingCompilerThread(this);
2086 optimizing_compiler_thread_->Start();
2087 }
2088
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002089 // Initialize runtime profiler before deserialization, because collections may
2090 // occur, clearing/updating ICs.
2091 runtime_profiler_ = new RuntimeProfiler(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002092
2093 // If we are deserializing, read the state into the now-empty heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002094 if (!create_heap_objects) {
2095 des->Deserialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002096 }
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002097 stub_cache_->Initialize();
2098
2099 // Finish initialization of ThreadLocal after deserialization is done.
2100 clear_pending_exception();
2101 clear_pending_message();
2102 clear_scheduled_exception();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002103
Steve Block44f0eee2011-05-26 01:26:41 +01002104 // Deserializing may put strange things in the root array's copy of the
2105 // stack guard.
2106 heap_.SetStackLimits();
2107
Ben Murdochdb1b4382012-04-26 19:03:50 +01002108 // Quiet the heap NaN if needed on target platform.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002109 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
Ben Murdochdb1b4382012-04-26 19:03:50 +01002110
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002111 if (FLAG_trace_turbo) {
2112 // Create an empty file.
2113 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2114 }
Steve Block44f0eee2011-05-26 01:26:41 +01002115
2116 // If we are deserializing, log non-function code objects and compiled
2117 // functions found in the snapshot.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002118 if (!create_heap_objects &&
2119 (FLAG_log_code ||
2120 FLAG_ll_prof ||
2121 FLAG_perf_jit_prof ||
2122 FLAG_perf_basic_prof ||
2123 logger_->is_logging_code_events())) {
2124 HandleScope scope(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002125 LOG(this, LogCodeObjects());
2126 LOG(this, LogCompiledFunctions());
2127 }
2128
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002129 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2130 Internals::kIsolateEmbedderDataOffset);
2131 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2132 Internals::kIsolateRootsOffset);
2133 CHECK_EQ(static_cast<int>(
2134 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2135 Internals::kAmountOfExternalAllocatedMemoryOffset);
2136 CHECK_EQ(static_cast<int>(OFFSET_OF(
2137 Isolate,
2138 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2139 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2140
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002141 time_millis_at_init_ = base::OS::TimeCurrentMillis();
2142
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002143 heap_.NotifyDeserializationComplete();
2144
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002145 if (!create_heap_objects) {
2146 // Now that the heap is consistent, it's OK to generate the code for the
2147 // deopt entry table that might have been referred to by optimized code in
2148 // the snapshot.
2149 HandleScope scope(this);
2150 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2151 this,
2152 Deoptimizer::LAZY,
2153 kDeoptTableSerializeEntryCount - 1);
2154 }
2155
2156 if (!serializer_enabled()) {
2157 // Ensure that all stubs which need to be generated ahead of time, but
2158 // cannot be serialized into the snapshot have been generated.
2159 HandleScope scope(this);
2160 CodeStub::GenerateFPStubs(this);
2161 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2162 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2163 }
2164
2165 initialized_from_snapshot_ = (des != NULL);
2166
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002167 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2168
Steve Block44f0eee2011-05-26 01:26:41 +01002169 return true;
2170}
2171
2172
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002173// Initialized lazily to allow early
2174// v8::V8::SetAddHistogramSampleFunction calls.
2175StatsTable* Isolate::stats_table() {
2176 if (stats_table_ == NULL) {
2177 stats_table_ = new StatsTable;
2178 }
2179 return stats_table_;
2180}
2181
2182
Steve Block44f0eee2011-05-26 01:26:41 +01002183void Isolate::Enter() {
2184 Isolate* current_isolate = NULL;
2185 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2186 if (current_data != NULL) {
2187 current_isolate = current_data->isolate_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002188 DCHECK(current_isolate != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01002189 if (current_isolate == this) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002190 DCHECK(Current() == this);
2191 DCHECK(entry_stack_ != NULL);
2192 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002193 entry_stack_->previous_thread_data->thread_id().Equals(
2194 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002195 // Same thread re-enters the isolate, no need to re-init anything.
2196 entry_stack_->entry_count++;
2197 return;
2198 }
2199 }
2200
Steve Block44f0eee2011-05-26 01:26:41 +01002201 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002202 DCHECK(data != NULL);
2203 DCHECK(data->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002204
2205 EntryStackItem* item = new EntryStackItem(current_data,
2206 current_isolate,
2207 entry_stack_);
2208 entry_stack_ = item;
2209
2210 SetIsolateThreadLocals(this, data);
2211
Steve Block44f0eee2011-05-26 01:26:41 +01002212 // In case it's the first time some thread enters the isolate.
2213 set_thread_id(data->thread_id());
2214}
2215
2216
2217void Isolate::Exit() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002218 DCHECK(entry_stack_ != NULL);
2219 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002220 entry_stack_->previous_thread_data->thread_id().Equals(
2221 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002222
2223 if (--entry_stack_->entry_count > 0) return;
2224
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002225 DCHECK(CurrentPerIsolateThreadData() != NULL);
2226 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002227
2228 // Pop the stack.
2229 EntryStackItem* item = entry_stack_;
2230 entry_stack_ = item->previous_item;
2231
2232 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2233 Isolate* previous_isolate = item->previous_isolate;
2234
2235 delete item;
2236
2237 // Reinit the current thread for the isolate it was running before this one.
2238 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2239}
2240
2241
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002242void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2243 deferred->next_ = deferred_handles_head_;
2244 if (deferred_handles_head_ != NULL) {
2245 deferred_handles_head_->previous_ = deferred;
2246 }
2247 deferred_handles_head_ = deferred;
2248}
2249
2250
2251void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2252#ifdef DEBUG
2253 // In debug mode assert that the linked list is well-formed.
2254 DeferredHandles* deferred_iterator = deferred;
2255 while (deferred_iterator->previous_ != NULL) {
2256 deferred_iterator = deferred_iterator->previous_;
2257 }
2258 DCHECK(deferred_handles_head_ == deferred_iterator);
2259#endif
2260 if (deferred_handles_head_ == deferred) {
2261 deferred_handles_head_ = deferred_handles_head_->next_;
2262 }
2263 if (deferred->next_ != NULL) {
2264 deferred->next_->previous_ = deferred->previous_;
2265 }
2266 if (deferred->previous_ != NULL) {
2267 deferred->previous_->next_ = deferred->next_;
2268 }
2269}
2270
2271
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002272void Isolate::DumpAndResetCompilationStats() {
2273 if (turbo_statistics() != nullptr) {
2274 OFStream os(stdout);
2275 os << *turbo_statistics() << std::endl;
2276 }
2277 if (hstatistics() != nullptr) hstatistics()->Print();
2278 delete turbo_statistics_;
2279 turbo_statistics_ = nullptr;
2280 delete hstatistics_;
2281 hstatistics_ = nullptr;
2282}
2283
2284
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002285HStatistics* Isolate::GetHStatistics() {
2286 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2287 return hstatistics();
2288}
2289
2290
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002291CompilationStatistics* Isolate::GetTurboStatistics() {
2292 if (turbo_statistics() == NULL)
2293 set_turbo_statistics(new CompilationStatistics());
2294 return turbo_statistics();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002295}
2296
2297
2298HTracer* Isolate::GetHTracer() {
2299 if (htracer() == NULL) set_htracer(new HTracer(id()));
2300 return htracer();
2301}
2302
2303
2304CodeTracer* Isolate::GetCodeTracer() {
2305 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2306 return code_tracer();
2307}
2308
2309
2310Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
2311 Context* native_context = context()->native_context();
2312 Object* maybe_map_array = native_context->js_array_maps();
2313 if (!maybe_map_array->IsUndefined()) {
2314 Object* maybe_transitioned_map =
2315 FixedArray::cast(maybe_map_array)->get(kind);
2316 if (!maybe_transitioned_map->IsUndefined()) {
2317 return Map::cast(maybe_transitioned_map);
2318 }
2319 }
2320 return NULL;
2321}
2322
2323
2324bool Isolate::use_crankshaft() const {
2325 return FLAG_crankshaft &&
2326 !serializer_enabled_ &&
2327 CpuFeatures::SupportsCrankshaft();
2328}
2329
2330
2331bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
2332 Map* root_array_map =
2333 get_initial_js_array_map(GetInitialFastElementsKind());
2334 DCHECK(root_array_map != NULL);
2335 JSObject* initial_array_proto = JSObject::cast(*initial_array_prototype());
2336
2337 // Check that the array prototype hasn't been altered WRT empty elements.
2338 if (root_array_map->prototype() != initial_array_proto) return false;
2339 if (initial_array_proto->elements() != heap()->empty_fixed_array()) {
2340 return false;
2341 }
2342
2343 // Check that the object prototype hasn't been altered WRT empty elements.
2344 JSObject* initial_object_proto = JSObject::cast(*initial_object_prototype());
2345 PrototypeIterator iter(this, initial_array_proto);
2346 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
2347 return false;
2348 }
2349 if (initial_object_proto->elements() != heap()->empty_fixed_array()) {
2350 return false;
2351 }
2352
2353 iter.Advance();
2354 return iter.IsAtEnd();
2355}
2356
2357
2358CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2359 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2360 return &call_descriptor_data_[index];
2361}
2362
2363
2364Object* Isolate::FindCodeObject(Address a) {
2365 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2366}
2367
2368
Steve Block44f0eee2011-05-26 01:26:41 +01002369#ifdef DEBUG
2370#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2371const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2372ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2373ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2374#undef ISOLATE_FIELD_OFFSET
2375#endif
2376
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002377
2378Handle<JSObject> Isolate::GetSymbolRegistry() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002379 if (heap()->symbol_registry()->IsSmi()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002380 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2381 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2382 heap()->set_symbol_registry(*registry);
2383
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002384 static const char* nested[] = {"for", "for_api", "keyFor", "private_api",
2385 "private_intern"};
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002386 for (unsigned i = 0; i < arraysize(nested); ++i) {
2387 Handle<String> name = factory()->InternalizeUtf8String(nested[i]);
2388 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002389 JSObject::NormalizeProperties(obj, KEEP_INOBJECT_PROPERTIES, 8,
2390 "SetupSymbolRegistry");
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002391 JSObject::SetProperty(registry, name, obj, STRICT).Assert();
2392 }
2393 }
2394 return Handle<JSObject>::cast(factory()->symbol_registry());
2395}
2396
2397
2398void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2399 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2400 if (callback == call_completed_callbacks_.at(i)) return;
2401 }
2402 call_completed_callbacks_.Add(callback);
2403}
2404
2405
2406void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2407 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2408 if (callback == call_completed_callbacks_.at(i)) {
2409 call_completed_callbacks_.Remove(i);
2410 }
2411 }
2412}
2413
2414
2415void Isolate::FireCallCompletedCallback() {
2416 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2417 bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2418 if (!has_call_completed_callbacks && !run_microtasks) return;
2419
2420 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2421 if (run_microtasks) RunMicrotasks();
2422 // Fire callbacks. Increase call depth to prevent recursive callbacks.
2423 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2424 reinterpret_cast<v8::Isolate*>(this));
2425 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2426 call_completed_callbacks_.at(i)();
2427 }
2428}
2429
2430
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002431void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2432 promise_reject_callback_ = callback;
2433}
2434
2435
2436void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2437 Handle<Object> value,
2438 v8::PromiseRejectEvent event) {
2439 if (promise_reject_callback_ == NULL) return;
2440 Handle<JSArray> stack_trace;
2441 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2442 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2443 }
2444 promise_reject_callback_(v8::PromiseRejectMessage(
2445 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2446 v8::Utils::StackTraceToLocal(stack_trace)));
2447}
2448
2449
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002450void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2451 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2452 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2453 int num_tasks = pending_microtask_count();
2454 DCHECK(num_tasks <= queue->length());
2455 if (num_tasks == 0) {
2456 queue = factory()->NewFixedArray(8);
2457 heap()->set_microtask_queue(*queue);
2458 } else if (num_tasks == queue->length()) {
2459 queue = FixedArray::CopySize(queue, num_tasks * 2);
2460 heap()->set_microtask_queue(*queue);
2461 }
2462 DCHECK(queue->get(num_tasks)->IsUndefined());
2463 queue->set(num_tasks, *microtask);
2464 set_pending_microtask_count(num_tasks + 1);
2465}
2466
2467
2468void Isolate::RunMicrotasks() {
2469 // %RunMicrotasks may be called in mjsunit tests, which violates
2470 // this assertion, hence the check for --allow-natives-syntax.
2471 // TODO(adamk): However, this also fails some layout tests.
2472 //
2473 // DCHECK(FLAG_allow_natives_syntax ||
2474 // handle_scope_implementer()->CallDepthIsZero());
2475
2476 // Increase call depth to prevent recursive callbacks.
2477 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2478 reinterpret_cast<v8::Isolate*>(this));
2479
2480 while (pending_microtask_count() > 0) {
2481 HandleScope scope(this);
2482 int num_tasks = pending_microtask_count();
2483 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2484 DCHECK(num_tasks <= queue->length());
2485 set_pending_microtask_count(0);
2486 heap()->set_microtask_queue(heap()->empty_fixed_array());
2487
2488 for (int i = 0; i < num_tasks; i++) {
2489 HandleScope scope(this);
2490 Handle<Object> microtask(queue->get(i), this);
2491 if (microtask->IsJSFunction()) {
2492 Handle<JSFunction> microtask_function =
2493 Handle<JSFunction>::cast(microtask);
2494 SaveContext save(this);
2495 set_context(microtask_function->context()->native_context());
2496 MaybeHandle<Object> maybe_exception;
2497 MaybeHandle<Object> result =
2498 Execution::TryCall(microtask_function, factory()->undefined_value(),
2499 0, NULL, &maybe_exception);
2500 // If execution is terminating, just bail out.
2501 Handle<Object> exception;
2502 if (result.is_null() && maybe_exception.is_null()) {
2503 // Clear out any remaining callbacks in the queue.
2504 heap()->set_microtask_queue(heap()->empty_fixed_array());
2505 set_pending_microtask_count(0);
2506 return;
2507 }
2508 } else {
2509 Handle<CallHandlerInfo> callback_info =
2510 Handle<CallHandlerInfo>::cast(microtask);
2511 v8::MicrotaskCallback callback =
2512 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2513 void* data = v8::ToCData<void*>(callback_info->data());
2514 callback(data);
2515 }
2516 }
2517 }
2518}
2519
2520
2521void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2522 DCHECK(!use_counter_callback_);
2523 use_counter_callback_ = callback;
2524}
2525
2526
2527void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
2528 if (use_counter_callback_) {
2529 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2530 }
2531}
2532
2533
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002534BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2535 if (basic_block_profiler_ == NULL) {
2536 basic_block_profiler_ = new BasicBlockProfiler();
2537 }
2538 return basic_block_profiler_;
2539}
2540
2541
2542std::string Isolate::GetTurboCfgFileName() {
2543 if (FLAG_trace_turbo_cfg_file == NULL) {
2544 std::ostringstream os;
2545 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2546 return os.str();
2547 } else {
2548 return FLAG_trace_turbo_cfg_file;
2549 }
2550}
2551
2552
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002553bool StackLimitCheck::JsHasOverflowed() const {
2554 StackGuard* stack_guard = isolate_->stack_guard();
2555#ifdef USE_SIMULATOR
2556 // The simulator uses a separate JS stack.
2557 Address jssp_address = Simulator::current(isolate_)->get_sp();
2558 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
2559 if (jssp < stack_guard->real_jslimit()) return true;
2560#endif // USE_SIMULATOR
2561 return GetCurrentStackPosition() < stack_guard->real_climit();
2562}
2563
2564
2565bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2566 // First check whether the previous scope intercepts.
2567 if (prev_ && prev_->Intercept(flag)) return true;
2568 // Then check whether this scope intercepts.
2569 if ((flag & intercept_mask_)) {
2570 intercepted_flags_ |= flag;
2571 return true;
2572 }
2573 return false;
2574}
2575
Steve Block44f0eee2011-05-26 01:26:41 +01002576} } // namespace v8::internal