blob: 8116f14d30260af9d630e8841d3c1e738bab5a5f [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
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00005#include "src/isolate.h"
6
Steve Block44f0eee2011-05-26 01:26:41 +01007#include <stdlib.h>
8
Emily Bernierd0a1eb72015-03-24 16:35:39 -04009#include <fstream> // NOLINT(readability/streams)
10#include <sstream>
11
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000012#include "src/ast/ast.h"
13#include "src/ast/scopeinfo.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000014#include "src/base/platform/platform.h"
15#include "src/base/sys-info.h"
16#include "src/base/utils/random-number-generator.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -040017#include "src/basic-block-profiler.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000018#include "src/bootstrapper.h"
19#include "src/codegen.h"
20#include "src/compilation-cache.h"
Emily Bernierd0a1eb72015-03-24 16:35:39 -040021#include "src/compilation-statistics.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000022#include "src/crankshaft/hydrogen.h"
23#include "src/debug/debug.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000024#include "src/deoptimizer.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000025#include "src/frames-inl.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000026#include "src/ic/stub-cache.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000027#include "src/interpreter/interpreter.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000028#include "src/isolate-inl.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000029#include "src/log.h"
30#include "src/messages.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000031#include "src/profiler/cpu-profiler.h"
32#include "src/profiler/sampler.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000033#include "src/prototype.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000034#include "src/regexp/regexp-stack.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000035#include "src/runtime-profiler.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000036#include "src/simulator.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000037#include "src/snapshot/serialize.h"
38#include "src/v8.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000039#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;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000085 promise_on_stack_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010086
87 // These members are re-initialized later after deserialization
88 // is complete.
89 pending_exception_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000090 rethrowing_message_ = false;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010091 pending_message_obj_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010092 scheduled_exception_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000093}
94
95
96void ThreadLocalTop::Initialize() {
97 InitializeInternal();
98#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +000099 simulator_ = Simulator::current(isolate_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000100#endif
101 thread_id_ = ThreadId::Current();
102}
103
104
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000105void ThreadLocalTop::Free() {
106 // Match unmatched PopPromise calls.
107 while (promise_on_stack_) isolate_->PopPromise();
Ben Murdoch257744e2011-11-30 15:57:28 +0000108}
109
110
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000111base::Thread::LocalStorageKey Isolate::isolate_key_;
112base::Thread::LocalStorageKey Isolate::thread_id_key_;
113base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000114base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER;
Ben Murdoch85b71792012-04-11 18:30:58 +0100115Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000116base::Atomic32 Isolate::isolate_counter_ = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400117#if DEBUG
118base::Atomic32 Isolate::isolate_key_created_ = 0;
119#endif
Steve Block44f0eee2011-05-26 01:26:41 +0100120
121Isolate::PerIsolateThreadData*
122 Isolate::FindOrAllocatePerThreadDataForThisThread() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100123 ThreadId thread_id = ThreadId::Current();
Steve Block44f0eee2011-05-26 01:26:41 +0100124 PerIsolateThreadData* per_thread = NULL;
125 {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000126 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +0100127 per_thread = thread_data_table_->Lookup(this, thread_id);
Steve Block44f0eee2011-05-26 01:26:41 +0100128 if (per_thread == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000129 per_thread = new PerIsolateThreadData(this, thread_id);
130 thread_data_table_->Insert(per_thread);
Steve Block44f0eee2011-05-26 01:26:41 +0100131 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000132 DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
Steve Block44f0eee2011-05-26 01:26:41 +0100133 }
134 return per_thread;
135}
136
137
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000138void Isolate::DiscardPerThreadDataForThisThread() {
139 int thread_id_int = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
140 if (thread_id_int) {
141 ThreadId thread_id = ThreadId(thread_id_int);
142 DCHECK(!thread_manager_->mutex_owner_.Equals(thread_id));
143 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
144 PerIsolateThreadData* per_thread =
145 thread_data_table_->Lookup(this, thread_id);
146 if (per_thread) {
147 DCHECK(!per_thread->thread_state_);
148 thread_data_table_->Remove(per_thread);
149 }
150 }
151}
152
153
Ben Murdoch257744e2011-11-30 15:57:28 +0000154Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
155 ThreadId thread_id = ThreadId::Current();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000156 return FindPerThreadDataForThread(thread_id);
157}
158
159
160Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
161 ThreadId thread_id) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000162 PerIsolateThreadData* per_thread = NULL;
163 {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000164 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +0100165 per_thread = thread_data_table_->Lookup(this, thread_id);
Ben Murdoch257744e2011-11-30 15:57:28 +0000166 }
167 return per_thread;
168}
169
170
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000171void Isolate::InitializeOncePerProcess() {
172 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
173 CHECK(thread_data_table_ == NULL);
174 isolate_key_ = base::Thread::CreateThreadLocalKey();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400175#if DEBUG
176 base::NoBarrier_Store(&isolate_key_created_, 1);
177#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000178 thread_id_key_ = base::Thread::CreateThreadLocalKey();
179 per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000180 thread_data_table_ = new Isolate::ThreadDataTable();
Steve Block44f0eee2011-05-26 01:26:41 +0100181}
182
183
Ben Murdoch257744e2011-11-30 15:57:28 +0000184Address Isolate::get_address_from_id(Isolate::AddressId id) {
185 return isolate_addresses_[id];
186}
187
188
189char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
190 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
191 Iterate(v, thread);
192 return thread_storage + sizeof(ThreadLocalTop);
193}
194
195
Ben Murdoch257744e2011-11-30 15:57:28 +0000196void Isolate::IterateThread(ThreadVisitor* v, char* t) {
197 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
198 v->VisitThread(this, thread);
199}
200
201
202void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
203 // Visit the roots from the top for a given thread.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000204 v->VisitPointer(&thread->pending_exception_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000205 v->VisitPointer(&(thread->pending_message_obj_));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000206 v->VisitPointer(bit_cast<Object**>(&(thread->context_)));
207 v->VisitPointer(&thread->scheduled_exception_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000208
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000209 for (v8::TryCatch* block = thread->try_catch_handler();
Ben Murdoch257744e2011-11-30 15:57:28 +0000210 block != NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000211 block = block->next_) {
212 v->VisitPointer(bit_cast<Object**>(&(block->exception_)));
213 v->VisitPointer(bit_cast<Object**>(&(block->message_obj_)));
Ben Murdoch257744e2011-11-30 15:57:28 +0000214 }
215
216 // Iterate over pointers on native execution stack.
217 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
218 it.frame()->Iterate(v);
219 }
220}
221
222
223void Isolate::Iterate(ObjectVisitor* v) {
224 ThreadLocalTop* current_t = thread_local_top();
225 Iterate(v, current_t);
226}
227
228
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000229void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
230 for (DeferredHandles* deferred = deferred_handles_head_;
231 deferred != NULL;
232 deferred = deferred->next_) {
233 deferred->Iterate(visitor);
234 }
235}
236
237
238#ifdef DEBUG
239bool Isolate::IsDeferredHandle(Object** handle) {
240 // Each DeferredHandles instance keeps the handles to one job in the
241 // concurrent recompilation queue, containing a list of blocks. Each block
242 // contains kHandleBlockSize handles except for the first block, which may
243 // not be fully filled.
244 // We iterate through all the blocks to see whether the argument handle
245 // belongs to one of the blocks. If so, it is deferred.
246 for (DeferredHandles* deferred = deferred_handles_head_;
247 deferred != NULL;
248 deferred = deferred->next_) {
249 List<Object**>* blocks = &deferred->blocks_;
250 for (int i = 0; i < blocks->length(); i++) {
251 Object** block_limit = (i == 0) ? deferred->first_block_limit_
252 : blocks->at(i) + kHandleBlockSize;
253 if (blocks->at(i) <= handle && handle < block_limit) return true;
254 }
255 }
256 return false;
257}
258#endif // DEBUG
259
260
Ben Murdoch257744e2011-11-30 15:57:28 +0000261void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000262 thread_local_top()->set_try_catch_handler(that);
Ben Murdoch257744e2011-11-30 15:57:28 +0000263}
264
265
266void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000267 DCHECK(thread_local_top()->try_catch_handler() == that);
268 thread_local_top()->set_try_catch_handler(that->next_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000269}
270
271
272Handle<String> Isolate::StackTraceString() {
273 if (stack_trace_nesting_level_ == 0) {
274 stack_trace_nesting_level_++;
275 HeapStringAllocator allocator;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000276 StringStream::ClearMentionedObjectCache(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000277 StringStream accumulator(&allocator);
278 incomplete_message_ = &accumulator;
279 PrintStack(&accumulator);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000280 Handle<String> stack_trace = accumulator.ToString(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000281 incomplete_message_ = NULL;
282 stack_trace_nesting_level_ = 0;
283 return stack_trace;
284 } else if (stack_trace_nesting_level_ == 1) {
285 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000286 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000287 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000288 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000289 "If you are lucky you may find a partial stack dump on stdout.\n\n");
290 incomplete_message_->OutputToStdOut();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000291 return factory()->empty_string();
Ben Murdoch257744e2011-11-30 15:57:28 +0000292 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000293 base::OS::Abort();
Ben Murdoch257744e2011-11-30 15:57:28 +0000294 // Unreachable
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000295 return factory()->empty_string();
Ben Murdoch257744e2011-11-30 15:57:28 +0000296 }
297}
298
299
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000300void Isolate::PushStackTraceAndDie(unsigned int magic, void* ptr1, void* ptr2,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000301 unsigned int magic2) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000302 const int kMaxStackTraceSize = 32 * KB;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000303 Handle<String> trace = StackTraceString();
304 uint8_t buffer[kMaxStackTraceSize];
305 int length = Min(kMaxStackTraceSize - 1, trace->length());
306 String::WriteToFlat(*trace, buffer, 0, length);
307 buffer[length] = '\0';
308 // TODO(dcarney): convert buffer to utf8?
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000309 base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2, ptr1,
310 ptr2, reinterpret_cast<char*>(buffer));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000311 base::OS::Abort();
312}
313
314
315// Determines whether the given stack frame should be displayed in
316// a stack trace. The caller is the error constructor that asked
317// for the stack trace to be collected. The first time a construct
318// call to this function is encountered it is skipped. The seen_caller
319// in/out parameter is used to remember if the caller has been seen
320// yet.
321static bool IsVisibleInStackTrace(JSFunction* fun,
322 Object* caller,
323 Object* receiver,
324 bool* seen_caller) {
325 if ((fun == caller) && !(*seen_caller)) {
326 *seen_caller = true;
327 return false;
328 }
329 // Skip all frames until we've seen the caller.
330 if (!(*seen_caller)) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000331 // Functions defined in native scripts are not visible unless directly
332 // exposed, in which case the native flag is set.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000333 // The --builtins-in-stack-traces command line flag allows including
334 // internal call sites in the stack trace for debugging purposes.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000335 if (!FLAG_builtins_in_stack_traces && fun->shared()->IsBuiltin()) {
336 return fun->shared()->native();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000337 }
338 return true;
339}
340
341
342Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSObject> error_object,
343 Handle<Object> caller) {
344 // Get stack trace limit.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000345 Handle<JSObject> error = error_function();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000346 Handle<String> stackTraceLimit =
347 factory()->InternalizeUtf8String("stackTraceLimit");
348 DCHECK(!stackTraceLimit.is_null());
349 Handle<Object> stack_trace_limit =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000350 JSReceiver::GetDataProperty(error, stackTraceLimit);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000351 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
352 int limit = FastD2IChecked(stack_trace_limit->Number());
353 limit = Max(limit, 0); // Ensure that limit is not negative.
354
355 int initial_size = Min(limit, 10);
356 Handle<FixedArray> elements =
357 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
358
359 // If the caller parameter is a function we skip frames until we're
360 // under it before starting to collect.
361 bool seen_caller = !caller->IsJSFunction();
362 // First element is reserved to store the number of sloppy frames.
363 int cursor = 1;
364 int frames_seen = 0;
365 int sloppy_frames = 0;
366 bool encountered_strict_function = false;
367 for (JavaScriptFrameIterator iter(this);
368 !iter.done() && frames_seen < limit;
369 iter.Advance()) {
370 JavaScriptFrame* frame = iter.frame();
371 // Set initial size to the maximum inlining level + 1 for the outermost
372 // function.
373 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
374 frame->Summarize(&frames);
375 for (int i = frames.length() - 1; i >= 0; i--) {
376 Handle<JSFunction> fun = frames[i].function();
377 Handle<Object> recv = frames[i].receiver();
378 // Filter out internal frames that we do not want to show.
379 if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) continue;
380 // Filter out frames from other security contexts.
381 if (!this->context()->HasSameSecurityTokenAs(fun->context())) continue;
382 if (cursor + 4 > elements->length()) {
383 int new_capacity = JSObject::NewElementsCapacity(elements->length());
384 Handle<FixedArray> new_elements =
385 factory()->NewFixedArrayWithHoles(new_capacity);
386 for (int i = 0; i < cursor; i++) {
387 new_elements->set(i, elements->get(i));
388 }
389 elements = new_elements;
390 }
391 DCHECK(cursor + 4 <= elements->length());
392
Ben Murdoch097c5b22016-05-18 11:27:45 +0100393 Handle<AbstractCode> abstract_code = frames[i].abstract_code();
394
395 Handle<Smi> offset(Smi::FromInt(frames[i].code_offset()), this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000396 // The stack trace API should not expose receivers and function
397 // objects on frames deeper than the top-most one with a strict
398 // mode function. The number of sloppy frames is stored as
399 // first element in the result array.
400 if (!encountered_strict_function) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000401 if (is_strict(fun->shared()->language_mode())) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000402 encountered_strict_function = true;
403 } else {
404 sloppy_frames++;
405 }
406 }
407 elements->set(cursor++, *recv);
408 elements->set(cursor++, *fun);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100409 elements->set(cursor++, *abstract_code);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000410 elements->set(cursor++, *offset);
411 frames_seen++;
412 }
413 }
414 elements->set(0, Smi::FromInt(sloppy_frames));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000415 elements->Shrink(cursor);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000416 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
417 result->set_length(Smi::FromInt(cursor));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000418 // TODO(yangguo): Queue this structured stack trace for preprocessing on GC.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000419 return result;
420}
421
422
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000423MaybeHandle<JSObject> Isolate::CaptureAndSetDetailedStackTrace(
424 Handle<JSObject> error_object) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100425 if (capture_stack_trace_for_uncaught_exceptions_) {
426 // Capture stack trace for a detailed exception message.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000427 Handle<Name> key = factory()->detailed_stack_trace_symbol();
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100428 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
429 stack_trace_for_uncaught_exceptions_frame_limit_,
430 stack_trace_for_uncaught_exceptions_options_);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000431 RETURN_ON_EXCEPTION(
432 this, JSObject::SetProperty(error_object, key, stack_trace, STRICT),
433 JSObject);
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100434 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000435 return error_object;
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100436}
437
438
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000439MaybeHandle<JSObject> Isolate::CaptureAndSetSimpleStackTrace(
440 Handle<JSObject> error_object, Handle<Object> caller) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000441 // 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);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000444 RETURN_ON_EXCEPTION(
445 this, JSObject::SetProperty(error_object, key, stack_trace, STRICT),
446 JSObject);
447 return error_object;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000448}
449
450
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400451Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
452 Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
453 Handle<Object> stack_trace =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000454 JSReceiver::GetDataProperty(error_object, key_detailed);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400455 if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
456
457 if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
458
459 // Try to get details from simple stack trace.
460 Handle<JSArray> detailed_stack_trace =
461 GetDetailedFromSimpleStackTrace(error_object);
462 if (!detailed_stack_trace.is_null()) {
463 // Save the detailed stack since the simple one might be withdrawn later.
464 JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
465 STRICT).Assert();
466 }
467 return detailed_stack_trace;
468}
469
470
471class CaptureStackTraceHelper {
472 public:
473 CaptureStackTraceHelper(Isolate* isolate,
474 StackTrace::StackTraceOptions options)
475 : isolate_(isolate) {
476 if (options & StackTrace::kColumnOffset) {
477 column_key_ =
478 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
479 }
480 if (options & StackTrace::kLineNumber) {
481 line_key_ =
482 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
483 }
484 if (options & StackTrace::kScriptId) {
485 script_id_key_ =
486 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
487 }
488 if (options & StackTrace::kScriptName) {
489 script_name_key_ =
490 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
491 }
492 if (options & StackTrace::kScriptNameOrSourceURL) {
493 script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
494 STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
495 }
496 if (options & StackTrace::kFunctionName) {
497 function_key_ = factory()->InternalizeOneByteString(
498 STATIC_CHAR_VECTOR("functionName"));
499 }
500 if (options & StackTrace::kIsEval) {
501 eval_key_ =
502 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
503 }
504 if (options & StackTrace::kIsConstructor) {
505 constructor_key_ = factory()->InternalizeOneByteString(
506 STATIC_CHAR_VECTOR("isConstructor"));
507 }
508 }
509
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000510 Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun, int position,
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400511 bool is_constructor) {
512 Handle<JSObject> stack_frame =
513 factory()->NewJSObject(isolate_->object_function());
514
515 Handle<Script> script(Script::cast(fun->shared()->script()));
516
517 if (!line_key_.is_null()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000518 int script_line_offset = script->line_offset();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400519 int line_number = Script::GetLineNumber(script, position);
520 // line_number is already shifted by the script_line_offset.
521 int relative_line_number = line_number - script_line_offset;
522 if (!column_key_.is_null() && relative_line_number >= 0) {
523 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
524 int start = (relative_line_number == 0) ? 0 :
525 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
526 int column_offset = position - start;
527 if (relative_line_number == 0) {
528 // For the case where the code is on the same line as the script
529 // tag.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000530 column_offset += script->column_offset();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400531 }
532 JSObject::AddProperty(stack_frame, column_key_,
533 handle(Smi::FromInt(column_offset + 1), isolate_),
534 NONE);
535 }
536 JSObject::AddProperty(stack_frame, line_key_,
537 handle(Smi::FromInt(line_number + 1), isolate_),
538 NONE);
539 }
540
541 if (!script_id_key_.is_null()) {
542 JSObject::AddProperty(stack_frame, script_id_key_,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000543 handle(Smi::FromInt(script->id()), isolate_), NONE);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400544 }
545
546 if (!script_name_key_.is_null()) {
547 JSObject::AddProperty(stack_frame, script_name_key_,
548 handle(script->name(), isolate_), NONE);
549 }
550
551 if (!script_name_or_source_url_key_.is_null()) {
552 Handle<Object> result = Script::GetNameOrSourceURL(script);
553 JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
554 NONE);
555 }
556
557 if (!function_key_.is_null()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000558 Handle<Object> fun_name = JSFunction::GetDebugName(fun);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400559 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
560 }
561
562 if (!eval_key_.is_null()) {
563 Handle<Object> is_eval = factory()->ToBoolean(
564 script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
565 JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
566 }
567
568 if (!constructor_key_.is_null()) {
569 Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
570 JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
571 NONE);
572 }
573
574 return stack_frame;
575 }
576
577 private:
578 inline Factory* factory() { return isolate_->factory(); }
579
580 Isolate* isolate_;
581 Handle<String> column_key_;
582 Handle<String> line_key_;
583 Handle<String> script_id_key_;
584 Handle<String> script_name_key_;
585 Handle<String> script_name_or_source_url_key_;
586 Handle<String> function_key_;
587 Handle<String> eval_key_;
588 Handle<String> constructor_key_;
589};
590
591
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000592int PositionFromStackTrace(Handle<FixedArray> elements, int index) {
593 DisallowHeapAllocation no_gc;
594 Object* maybe_code = elements->get(index + 2);
595 if (maybe_code->IsSmi()) {
596 return Smi::cast(maybe_code)->value();
597 } else {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100598 AbstractCode* abstract_code = AbstractCode::cast(maybe_code);
599 int code_offset = Smi::cast(elements->get(index + 3))->value();
600 return abstract_code->SourcePosition(code_offset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000601 }
602}
603
604
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400605Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
606 Handle<JSObject> error_object) {
607 Handle<Name> key = factory()->stack_trace_symbol();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000608 Handle<Object> property = JSReceiver::GetDataProperty(error_object, key);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400609 if (!property->IsJSArray()) return Handle<JSArray>();
610 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
611
612 CaptureStackTraceHelper helper(this,
613 stack_trace_for_uncaught_exceptions_options_);
614
615 int frames_seen = 0;
616 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
617 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
618
619 int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
620 if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
621
622 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
623 for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
624 Handle<Object> recv = handle(elements->get(i), this);
625 Handle<JSFunction> fun =
626 handle(JSFunction::cast(elements->get(i + 1)), this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400627 bool is_constructor =
628 recv->IsJSObject() &&
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000629 Handle<JSObject>::cast(recv)->map()->GetConstructor() == *fun;
630 int position = PositionFromStackTrace(elements, i);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400631
632 Handle<JSObject> stack_frame =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000633 helper.NewStackFrameObject(fun, position, is_constructor);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400634
635 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
636 frames_seen++;
637 }
638
639 stack_trace->set_length(Smi::FromInt(frames_seen));
640 return stack_trace;
641}
642
643
Ben Murdoch257744e2011-11-30 15:57:28 +0000644Handle<JSArray> Isolate::CaptureCurrentStackTrace(
645 int frame_limit, StackTrace::StackTraceOptions options) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400646 CaptureStackTraceHelper helper(this, options);
647
Ben Murdoch257744e2011-11-30 15:57:28 +0000648 // Ensure no negative values.
649 int limit = Max(frame_limit, 0);
650 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
651
Ben Murdoch257744e2011-11-30 15:57:28 +0000652 StackTraceFrameIterator it(this);
653 int frames_seen = 0;
654 while (!it.done() && (frames_seen < limit)) {
655 JavaScriptFrame* frame = it.frame();
656 // Set initial size to the maximum inlining level + 1 for the outermost
657 // function.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000658 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
Ben Murdoch257744e2011-11-30 15:57:28 +0000659 frame->Summarize(&frames);
660 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000661 Handle<JSFunction> fun = frames[i].function();
662 // Filter frames from other security contexts.
663 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
664 !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100665 int position =
666 frames[i].abstract_code()->SourcePosition(frames[i].code_offset());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000667 Handle<JSObject> stack_frame =
668 helper.NewStackFrameObject(fun, position, frames[i].is_constructor());
Ben Murdoch257744e2011-11-30 15:57:28 +0000669
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100670 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
Ben Murdoch257744e2011-11-30 15:57:28 +0000671 frames_seen++;
672 }
673 it.Advance();
674 }
675
676 stack_trace->set_length(Smi::FromInt(frames_seen));
677 return stack_trace;
678}
679
680
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000681void Isolate::PrintStack(FILE* out, PrintStackMode mode) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000682 if (stack_trace_nesting_level_ == 0) {
683 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000684 StringStream::ClearMentionedObjectCache(this);
685 HeapStringAllocator allocator;
686 StringStream accumulator(&allocator);
Ben Murdoch257744e2011-11-30 15:57:28 +0000687 incomplete_message_ = &accumulator;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000688 PrintStack(&accumulator, mode);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000689 accumulator.OutputToFile(out);
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000690 InitializeLoggingAndCounters();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000691 accumulator.Log(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000692 incomplete_message_ = NULL;
693 stack_trace_nesting_level_ = 0;
Ben Murdoch257744e2011-11-30 15:57:28 +0000694 } else if (stack_trace_nesting_level_ == 1) {
695 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000696 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000697 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000698 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000699 "If you are lucky you may find a partial stack dump on stdout.\n\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000700 incomplete_message_->OutputToFile(out);
Ben Murdoch257744e2011-11-30 15:57:28 +0000701 }
702}
703
704
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000705static void PrintFrames(Isolate* isolate,
706 StringStream* accumulator,
Ben Murdoch257744e2011-11-30 15:57:28 +0000707 StackFrame::PrintMode mode) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000708 StackFrameIterator it(isolate);
Ben Murdoch257744e2011-11-30 15:57:28 +0000709 for (int i = 0; !it.done(); it.Advance()) {
710 it.frame()->Print(accumulator, mode, i++);
711 }
712}
713
714
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000715void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000716 // The MentionedObjectCache is not GC-proof at the moment.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000717 DisallowHeapAllocation no_gc;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000718 DCHECK(accumulator->IsMentionedObjectCacheClear(this));
Ben Murdoch257744e2011-11-30 15:57:28 +0000719
720 // Avoid printing anything if there are no frames.
721 if (c_entry_fp(thread_local_top()) == 0) return;
722
723 accumulator->Add(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000724 "\n==== JS stack trace =========================================\n\n");
725 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000726 if (mode == kPrintStackVerbose) {
727 accumulator->Add(
728 "\n==== Details ================================================\n\n");
729 PrintFrames(this, accumulator, StackFrame::DETAILS);
730 accumulator->PrintMentionedObjectCache(this);
731 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000732 accumulator->Add("=====================\n\n");
733}
734
735
736void Isolate::SetFailedAccessCheckCallback(
737 v8::FailedAccessCheckCallback callback) {
738 thread_local_top()->failed_access_check_callback_ = callback;
739}
740
741
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000742static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
743 Handle<JSObject> receiver) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000744 Object* maybe_constructor = receiver->map()->GetConstructor();
745 if (!maybe_constructor->IsJSFunction()) return NULL;
746 JSFunction* constructor = JSFunction::cast(maybe_constructor);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000747 if (!constructor->shared()->IsApiFunction()) return NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +0000748
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000749 Object* data_obj =
750 constructor->shared()->get_api_func_data()->access_check_info();
751 if (data_obj == isolate->heap()->undefined_value()) return NULL;
752
753 return AccessCheckInfo::cast(data_obj);
754}
755
756
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000757void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000758 if (!thread_local_top()->failed_access_check_callback_) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000759 return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000760 }
761
762 DCHECK(receiver->IsAccessCheckNeeded());
763 DCHECK(context());
Ben Murdoch257744e2011-11-30 15:57:28 +0000764
765 // Get the data object from access check info.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000766 HandleScope scope(this);
767 Handle<Object> data;
768 { DisallowHeapAllocation no_gc;
769 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000770 if (!access_check_info) {
771 AllowHeapAllocation doesnt_matter_anymore;
772 return ScheduleThrow(
773 *factory()->NewTypeError(MessageTemplate::kNoAccess));
774 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000775 data = handle(access_check_info->data(), this);
776 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000777
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000778 // Leaving JavaScript.
779 VMState<EXTERNAL> state(this);
780 thread_local_top()->failed_access_check_callback_(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000781 v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000782}
783
784
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000785bool Isolate::MayAccess(Handle<Context> accessing_context,
786 Handle<JSObject> receiver) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000787 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
Ben Murdoch257744e2011-11-30 15:57:28 +0000788
Ben Murdoch257744e2011-11-30 15:57:28 +0000789 // Check for compatibility between the security tokens in the
790 // current lexical context and the accessed object.
Ben Murdoch257744e2011-11-30 15:57:28 +0000791
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000792 // During bootstrapping, callback functions are not enabled yet.
793 if (bootstrapper()->IsActive()) return true;
794 {
795 DisallowHeapAllocation no_gc;
796
797 if (receiver->IsJSGlobalProxy()) {
798 Object* receiver_context =
799 JSGlobalProxy::cast(*receiver)->native_context();
800 if (!receiver_context->IsContext()) return false;
801
802 // Get the native context of current top context.
803 // avoid using Isolate::native_context() because it uses Handle.
804 Context* native_context =
805 accessing_context->global_object()->native_context();
806 if (receiver_context == native_context) return true;
807
808 if (Context::cast(receiver_context)->security_token() ==
809 native_context->security_token())
810 return true;
811 }
812 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000813
Ben Murdoch257744e2011-11-30 15:57:28 +0000814 HandleScope scope(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000815 Handle<Object> data;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000816 v8::AccessCheckCallback callback = nullptr;
817 v8::NamedSecurityCallback named_callback = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000818 { DisallowHeapAllocation no_gc;
819 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
820 if (!access_check_info) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000821 Object* fun_obj = access_check_info->callback();
822 callback = v8::ToCData<v8::AccessCheckCallback>(fun_obj);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100823 data = handle(access_check_info->data(), this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000824 if (!callback) {
825 fun_obj = access_check_info->named_callback();
826 named_callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
827 if (!named_callback) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000828 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000829 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000830
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000831 LOG(this, ApiSecurityCheck());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000832
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000833 {
834 // Leaving JavaScript.
835 VMState<EXTERNAL> state(this);
836 if (callback) {
837 return callback(v8::Utils::ToLocal(accessing_context),
Ben Murdoch097c5b22016-05-18 11:27:45 +0100838 v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(data));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000839 }
840 Handle<Object> key = factory()->undefined_value();
841 return named_callback(v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(key),
842 v8::ACCESS_HAS, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000843 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000844}
845
846
847const char* const Isolate::kStackOverflowMessage =
848 "Uncaught RangeError: Maximum call stack size exceeded";
849
850
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000851Object* Isolate::StackOverflow() {
852 HandleScope scope(this);
853 // At this point we cannot create an Error object using its javascript
854 // constructor. Instead, we copy the pre-constructed boilerplate and
855 // attach the stack trace as a hidden property.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000856 Handle<Object> exception;
857 if (bootstrapper()->IsActive()) {
858 // There is no boilerplate to use during bootstrapping.
859 exception = factory()->NewStringFromAsciiChecked(
860 MessageTemplate::TemplateString(MessageTemplate::kStackOverflow));
861 } else {
862 Handle<JSObject> boilerplate = stack_overflow_boilerplate();
863 Handle<JSObject> copy = factory()->CopyJSObject(boilerplate);
864 CaptureAndSetSimpleStackTrace(copy, factory()->undefined_value());
865 exception = copy;
866 }
867 Throw(*exception, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000868
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000869#ifdef VERIFY_HEAP
870 if (FLAG_verify_heap && FLAG_stress_compaction) {
871 heap()->CollectAllAvailableGarbage("trigger compaction");
872 }
873#endif // VERIFY_HEAP
874
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000875 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000876}
877
878
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000879Object* Isolate::TerminateExecution() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000880 return Throw(heap_.termination_exception(), nullptr);
Ben Murdoch257744e2011-11-30 15:57:28 +0000881}
882
883
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000884void Isolate::CancelTerminateExecution() {
885 if (try_catch_handler()) {
886 try_catch_handler()->has_terminated_ = false;
887 }
888 if (has_pending_exception() &&
889 pending_exception() == heap_.termination_exception()) {
890 thread_local_top()->external_caught_exception_ = false;
891 clear_pending_exception();
892 }
893 if (has_scheduled_exception() &&
894 scheduled_exception() == heap_.termination_exception()) {
895 thread_local_top()->external_caught_exception_ = false;
896 clear_scheduled_exception();
897 }
898}
899
900
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400901void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
902 ExecutionAccess access(this);
903 api_interrupts_queue_.push(InterruptEntry(callback, data));
904 stack_guard()->RequestApiInterrupt();
905}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000906
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400907
908void Isolate::InvokeApiInterruptCallbacks() {
909 // Note: callback below should be called outside of execution access lock.
910 while (true) {
911 InterruptEntry entry;
912 {
913 ExecutionAccess access(this);
914 if (api_interrupts_queue_.empty()) return;
915 entry = api_interrupts_queue_.front();
916 api_interrupts_queue_.pop();
917 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000918 VMState<EXTERNAL> state(this);
919 HandleScope handle_scope(this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400920 entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000921 }
922}
923
924
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000925void ReportBootstrappingException(Handle<Object> exception,
926 MessageLocation* location) {
927 base::OS::PrintError("Exception thrown during bootstrapping\n");
928 if (location == NULL || location->script().is_null()) return;
929 // We are bootstrapping and caught an error where the location is set
930 // and we have a script for the location.
931 // In this case we could have an extension (or an internal error
932 // somewhere) and we print out the line number at which the error occured
933 // to the console for easier debugging.
934 int line_number =
935 location->script()->GetLineNumber(location->start_pos()) + 1;
936 if (exception->IsString() && location->script()->name()->IsString()) {
937 base::OS::PrintError(
938 "Extension or internal compilation error: %s in %s at line %d.\n",
939 String::cast(*exception)->ToCString().get(),
940 String::cast(location->script()->name())->ToCString().get(),
941 line_number);
942 } else if (location->script()->name()->IsString()) {
943 base::OS::PrintError(
944 "Extension or internal compilation error in %s at line %d.\n",
945 String::cast(location->script()->name())->ToCString().get(),
946 line_number);
947 } else if (exception->IsString()) {
948 base::OS::PrintError("Extension or internal compilation error: %s.\n",
949 String::cast(*exception)->ToCString().get());
950 } else {
951 base::OS::PrintError("Extension or internal compilation error.\n");
952 }
953#ifdef OBJECT_PRINT
954 // Since comments and empty lines have been stripped from the source of
955 // builtins, print the actual source here so that line numbers match.
956 if (location->script()->source()->IsString()) {
957 Handle<String> src(String::cast(location->script()->source()));
958 PrintF("Failing script:");
959 int len = src->length();
960 if (len == 0) {
961 PrintF(" <not available>\n");
962 } else {
963 PrintF("\n");
964 int line_number = 1;
965 PrintF("%5d: ", line_number);
966 for (int i = 0; i < len; i++) {
967 uint16_t character = src->Get(i);
968 PrintF("%c", character);
969 if (character == '\n' && i < len - 2) {
970 PrintF("%5d: ", ++line_number);
971 }
972 }
973 PrintF("\n");
974 }
975 }
976#endif
977}
978
979
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000980Object* Isolate::Throw(Object* exception, MessageLocation* location) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000981 DCHECK(!has_pending_exception());
982
983 HandleScope scope(this);
984 Handle<Object> exception_handle(exception, this);
985
986 // Determine whether a message needs to be created for the given exception
987 // depending on the following criteria:
988 // 1) External v8::TryCatch missing: Always create a message because any
989 // JavaScript handler for a finally-block might re-throw to top-level.
990 // 2) External v8::TryCatch exists: Only create a message if the handler
991 // captures messages or is verbose (which reports despite the catch).
992 // 3) ReThrow from v8::TryCatch: The message from a previous throw still
993 // exists and we preserve it instead of creating a new message.
994 bool requires_message = try_catch_handler() == nullptr ||
995 try_catch_handler()->is_verbose_ ||
996 try_catch_handler()->capture_message_;
997 bool rethrowing_message = thread_local_top()->rethrowing_message_;
998
999 thread_local_top()->rethrowing_message_ = false;
1000
1001 // Notify debugger of exception.
1002 if (is_catchable_by_javascript(exception)) {
1003 debug()->OnThrow(exception_handle);
1004 }
1005
1006 // Generate the message if required.
1007 if (requires_message && !rethrowing_message) {
1008 MessageLocation computed_location;
1009 // If no location was specified we try to use a computed one instead.
1010 if (location == NULL && ComputeLocation(&computed_location)) {
1011 location = &computed_location;
1012 }
1013
1014 if (bootstrapper()->IsActive()) {
1015 // It's not safe to try to make message objects or collect stack traces
1016 // while the bootstrapper is active since the infrastructure may not have
1017 // been properly initialized.
1018 ReportBootstrappingException(exception_handle, location);
1019 } else {
1020 Handle<Object> message_obj = CreateMessage(exception_handle, location);
1021 thread_local_top()->pending_message_obj_ = *message_obj;
1022
1023 // For any exception not caught by JavaScript, even when an external
1024 // handler is present:
1025 // If the abort-on-uncaught-exception flag is specified, and if the
1026 // embedder didn't specify a custom uncaught exception callback,
1027 // or if the custom callback determined that V8 should abort, then
1028 // abort.
1029 if (FLAG_abort_on_uncaught_exception &&
1030 PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT &&
1031 (!abort_on_uncaught_exception_callback_ ||
1032 abort_on_uncaught_exception_callback_(
1033 reinterpret_cast<v8::Isolate*>(this)))) {
1034 // Prevent endless recursion.
1035 FLAG_abort_on_uncaught_exception = false;
1036 // This flag is intended for use by JavaScript developers, so
1037 // print a user-friendly stack trace (not an internal one).
1038 PrintF(stderr, "%s\n\nFROM\n",
1039 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1040 PrintCurrentStackTrace(stderr);
1041 base::OS::Abort();
1042 }
1043 }
1044 }
1045
1046 // Set the exception being thrown.
1047 set_pending_exception(*exception_handle);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001048 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001049}
1050
1051
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001052Object* Isolate::ReThrow(Object* exception) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001053 DCHECK(!has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001054
1055 // Set the exception being re-thrown.
1056 set_pending_exception(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001057 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001058}
1059
1060
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001061Object* Isolate::UnwindAndFindHandler() {
1062 Object* exception = pending_exception();
1063
1064 Code* code = nullptr;
1065 Context* context = nullptr;
1066 intptr_t offset = 0;
1067 Address handler_sp = nullptr;
1068 Address handler_fp = nullptr;
1069
1070 // Special handling of termination exceptions, uncatchable by JavaScript code,
1071 // we unwind the handlers until the top ENTRY handler is found.
1072 bool catchable_by_js = is_catchable_by_javascript(exception);
1073
1074 // Compute handler and stack unwinding information by performing a full walk
1075 // over the stack and dispatching according to the frame type.
1076 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1077 StackFrame* frame = iter.frame();
1078
1079 // For JSEntryStub frames we always have a handler.
1080 if (frame->is_entry() || frame->is_entry_construct()) {
1081 StackHandler* handler = frame->top_handler();
1082
1083 // Restore the next handler.
1084 thread_local_top()->handler_ = handler->next()->address();
1085
1086 // Gather information from the handler.
1087 code = frame->LookupCode();
1088 handler_sp = handler->address() + StackHandlerConstants::kSize;
1089 offset = Smi::cast(code->handler_table()->get(0))->value();
1090 break;
1091 }
1092
1093 // For optimized frames we perform a lookup in the handler table.
1094 if (frame->is_optimized() && catchable_by_js) {
1095 OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
1096 int stack_slots = 0; // Will contain stack slot count of frame.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001097 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, nullptr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001098 if (offset >= 0) {
1099 // Compute the stack pointer from the frame pointer. This ensures that
1100 // argument slots on the stack are dropped as returning would.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001101 Address return_sp = frame->fp() +
1102 StandardFrameConstants::kFixedFrameSizeAboveFp -
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001103 stack_slots * kPointerSize;
1104
1105 // Gather information from the frame.
1106 code = frame->LookupCode();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001107 if (code->marked_for_deoptimization()) {
1108 // If the target code is lazy deoptimized, we jump to the original
1109 // return address, but we make a note that we are throwing, so that
1110 // the deoptimizer can do the right thing.
1111 offset = static_cast<int>(frame->pc() - code->entry());
1112 set_deoptimizer_lazy_throw(true);
1113 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001114 handler_sp = return_sp;
1115 handler_fp = frame->fp();
1116 break;
1117 }
1118 }
1119
Ben Murdoch097c5b22016-05-18 11:27:45 +01001120 // For interpreted frame we perform a range lookup in the handler table.
1121 if (frame->is_interpreted() && catchable_by_js) {
1122 InterpretedFrame* js_frame = static_cast<InterpretedFrame*>(frame);
1123 int context_reg = 0; // Will contain register index holding context.
1124 offset = js_frame->LookupExceptionHandlerInTable(&context_reg, nullptr);
1125 if (offset >= 0) {
1126 // Patch the bytecode offset in the interpreted frame to reflect the
1127 // position of the exception handler. The special builtin below will
1128 // take care of continuing to dispatch at that position. Also restore
1129 // the correct context for the handler from the interpreter register.
1130 context = Context::cast(js_frame->GetInterpreterRegister(context_reg));
1131 js_frame->PatchBytecodeOffset(static_cast<int>(offset));
1132 offset = 0;
1133
1134 // Gather information from the frame.
1135 code = *builtins()->InterpreterEnterBytecodeDispatch();
1136 handler_sp = frame->sp();
1137 handler_fp = frame->fp();
1138 break;
1139 }
1140 }
1141
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001142 // For JavaScript frames we perform a range lookup in the handler table.
1143 if (frame->is_java_script() && catchable_by_js) {
1144 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001145 int stack_depth = 0; // Will contain operand stack depth of handler.
1146 offset = js_frame->LookupExceptionHandlerInTable(&stack_depth, nullptr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001147 if (offset >= 0) {
1148 // Compute the stack pointer from the frame pointer. This ensures that
1149 // operand stack slots are dropped for nested statements. Also restore
1150 // correct context for the handler which is pushed within the try-block.
1151 Address return_sp = frame->fp() -
1152 StandardFrameConstants::kFixedFrameSizeFromFp -
Ben Murdoch097c5b22016-05-18 11:27:45 +01001153 stack_depth * kPointerSize;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001154 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1155 context = Context::cast(Memory::Object_at(return_sp - kPointerSize));
1156
1157 // Gather information from the frame.
1158 code = frame->LookupCode();
1159 handler_sp = return_sp;
1160 handler_fp = frame->fp();
1161 break;
1162 }
1163 }
1164
1165 RemoveMaterializedObjectsOnUnwind(frame);
1166 }
1167
1168 // Handler must exist.
1169 CHECK(code != nullptr);
1170
1171 // Store information to be consumed by the CEntryStub.
1172 thread_local_top()->pending_handler_context_ = context;
1173 thread_local_top()->pending_handler_code_ = code;
1174 thread_local_top()->pending_handler_offset_ = offset;
1175 thread_local_top()->pending_handler_fp_ = handler_fp;
1176 thread_local_top()->pending_handler_sp_ = handler_sp;
1177
1178 // Return and clear pending exception.
1179 clear_pending_exception();
1180 return exception;
1181}
1182
1183
1184Isolate::CatchType Isolate::PredictExceptionCatcher() {
1185 Address external_handler = thread_local_top()->try_catch_handler_address();
1186 Address entry_handler = Isolate::handler(thread_local_top());
1187 if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL;
1188
1189 // Search for an exception handler by performing a full walk over the stack.
1190 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1191 StackFrame* frame = iter.frame();
1192
1193 // For JSEntryStub frames we update the JS_ENTRY handler.
1194 if (frame->is_entry() || frame->is_entry_construct()) {
1195 entry_handler = frame->top_handler()->next()->address();
1196 }
1197
1198 // For JavaScript frames we perform a lookup in the handler table.
1199 if (frame->is_java_script()) {
1200 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001201 HandlerTable::CatchPrediction prediction;
Ben Murdoch097c5b22016-05-18 11:27:45 +01001202 if (js_frame->LookupExceptionHandlerInTable(nullptr, &prediction) > 0) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001203 // We are conservative with our prediction: try-finally is considered
1204 // to always rethrow, to meet the expectation of the debugger.
1205 if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT;
1206 }
1207 }
1208
1209 // The exception has been externally caught if and only if there is an
1210 // external handler which is on top of the top-most JS_ENTRY handler.
1211 if (external_handler != nullptr && !try_catch_handler()->is_verbose_) {
1212 if (entry_handler == nullptr || entry_handler > external_handler) {
1213 return CAUGHT_BY_EXTERNAL;
1214 }
1215 }
1216 }
1217
1218 // Handler not found.
1219 return NOT_CAUGHT;
1220}
1221
1222
1223void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) {
1224 if (frame->is_optimized()) {
1225 bool removed = materialized_object_store_->Remove(frame->fp());
1226 USE(removed);
1227 // If there were any materialized objects, the code should be
1228 // marked for deopt.
1229 DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization());
1230 }
1231}
1232
1233
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001234Object* Isolate::ThrowIllegalOperation() {
1235 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001236 return Throw(heap()->illegal_access_string());
Ben Murdoch257744e2011-11-30 15:57:28 +00001237}
1238
1239
1240void Isolate::ScheduleThrow(Object* exception) {
1241 // When scheduling a throw we first throw the exception to get the
1242 // error reporting if it is uncaught before rescheduling it.
1243 Throw(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001244 PropagatePendingExceptionToExternalTryCatch();
1245 if (has_pending_exception()) {
1246 thread_local_top()->scheduled_exception_ = pending_exception();
1247 thread_local_top()->external_caught_exception_ = false;
1248 clear_pending_exception();
1249 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001250}
1251
1252
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001253void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1254 DCHECK(handler == try_catch_handler());
1255 DCHECK(handler->HasCaught());
1256 DCHECK(handler->rethrow_);
1257 DCHECK(handler->capture_message_);
1258 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001259 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001260 thread_local_top()->pending_message_obj_ = message;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001261}
1262
1263
1264void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1265 DCHECK(has_scheduled_exception());
1266 if (scheduled_exception() == handler->exception_) {
1267 DCHECK(scheduled_exception() != heap()->termination_exception());
1268 clear_scheduled_exception();
1269 }
1270}
1271
1272
1273Object* Isolate::PromoteScheduledException() {
1274 Object* thrown = scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001275 clear_scheduled_exception();
1276 // Re-throw the exception to avoid getting repeated error reporting.
1277 return ReThrow(thrown);
1278}
1279
1280
1281void Isolate::PrintCurrentStackTrace(FILE* out) {
1282 StackTraceFrameIterator it(this);
1283 while (!it.done()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001284 HandleScope scope(this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001285 // Find code position if recorded in relocation info.
1286 JavaScriptFrame* frame = it.frame();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001287 Code* code = frame->LookupCode();
1288 int offset = static_cast<int>(frame->pc() - code->instruction_start());
1289 int pos = frame->LookupCode()->SourcePosition(offset);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001290 Handle<Object> pos_obj(Smi::FromInt(pos), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001291 // Fetch function and receiver.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001292 Handle<JSFunction> fun(frame->function());
1293 Handle<Object> recv(frame->receiver(), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001294 // Advance to the next JavaScript frame and determine if the
1295 // current frame is the top-level frame.
1296 it.Advance();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001297 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
Ben Murdoch257744e2011-11-30 15:57:28 +00001298 // Generate and print stack trace line.
1299 Handle<String> line =
1300 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1301 if (line->length() > 0) {
1302 line->PrintOn(out);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001303 PrintF(out, "\n");
Ben Murdoch257744e2011-11-30 15:57:28 +00001304 }
1305 }
1306}
1307
1308
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001309bool Isolate::ComputeLocation(MessageLocation* target) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001310 StackTraceFrameIterator it(this);
1311 if (!it.done()) {
1312 JavaScriptFrame* frame = it.frame();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001313 JSFunction* fun = frame->function();
Ben Murdoch257744e2011-11-30 15:57:28 +00001314 Object* script = fun->shared()->script();
1315 if (script->IsScript() &&
1316 !(Script::cast(script)->source()->IsUndefined())) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001317 Handle<Script> casted_script(Script::cast(script));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001318 // Compute the location from the function and the relocation info of the
1319 // baseline code. For optimized code this will use the deoptimization
1320 // information to get canonical location information.
1321 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
1322 it.frame()->Summarize(&frames);
1323 FrameSummary& summary = frames.last();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001324 int pos = summary.abstract_code()->SourcePosition(summary.code_offset());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001325 *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1326 return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001327 }
1328 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001329 return false;
1330}
1331
1332
1333bool Isolate::ComputeLocationFromException(MessageLocation* target,
1334 Handle<Object> exception) {
1335 if (!exception->IsJSObject()) return false;
1336
1337 Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1338 Handle<Object> start_pos = JSReceiver::GetDataProperty(
1339 Handle<JSObject>::cast(exception), start_pos_symbol);
1340 if (!start_pos->IsSmi()) return false;
1341 int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1342
1343 Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1344 Handle<Object> end_pos = JSReceiver::GetDataProperty(
1345 Handle<JSObject>::cast(exception), end_pos_symbol);
1346 if (!end_pos->IsSmi()) return false;
1347 int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1348
1349 Handle<Name> script_symbol = factory()->error_script_symbol();
1350 Handle<Object> script = JSReceiver::GetDataProperty(
1351 Handle<JSObject>::cast(exception), script_symbol);
1352 if (!script->IsScript()) return false;
1353
1354 Handle<Script> cast_script(Script::cast(*script));
1355 *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1356 return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001357}
1358
1359
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001360bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1361 Handle<Object> exception) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001362 if (!exception->IsJSObject()) return false;
1363 Handle<Name> key = factory()->stack_trace_symbol();
1364 Handle<Object> property =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001365 JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001366 if (!property->IsJSArray()) return false;
1367 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1368
1369 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1370 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1371
1372 for (int i = 1; i < elements_limit; i += 4) {
1373 Handle<JSFunction> fun =
1374 handle(JSFunction::cast(elements->get(i + 1)), this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001375 if (!fun->shared()->IsSubjectToDebugging()) continue;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001376
1377 Object* script = fun->shared()->script();
1378 if (script->IsScript() &&
1379 !(Script::cast(script)->source()->IsUndefined())) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001380 int pos = PositionFromStackTrace(elements, i);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001381 Handle<Script> casted_script(Script::cast(script));
1382 *target = MessageLocation(casted_script, pos, pos + 1);
1383 return true;
1384 }
1385 }
1386 return false;
1387}
1388
1389
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001390Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1391 MessageLocation* location) {
1392 Handle<JSArray> stack_trace_object;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001393 if (capture_stack_trace_for_uncaught_exceptions_) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001394 if (Object::IsErrorObject(this, exception)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001395 // We fetch the stack trace that corresponds to this error object.
1396 // If the lookup fails, the exception is probably not a valid Error
1397 // object. In that case, we fall through and capture the stack trace
1398 // at this throw site.
1399 stack_trace_object =
1400 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1401 }
1402 if (stack_trace_object.is_null()) {
1403 // Not an error object, we capture stack and location at throw site.
1404 stack_trace_object = CaptureCurrentStackTrace(
1405 stack_trace_for_uncaught_exceptions_frame_limit_,
1406 stack_trace_for_uncaught_exceptions_options_);
1407 }
1408 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001409 MessageLocation computed_location;
1410 if (location == NULL &&
1411 (ComputeLocationFromException(&computed_location, exception) ||
1412 ComputeLocationFromStackTrace(&computed_location, exception) ||
1413 ComputeLocation(&computed_location))) {
1414 location = &computed_location;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001415 }
1416
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001417 return MessageHandler::MakeMessageObject(
1418 this, MessageTemplate::kUncaughtException, location, exception,
1419 stack_trace_object);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001420}
1421
1422
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001423bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) {
1424 DCHECK_NE(heap()->the_hole_value(), exception);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001425
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001426 // For uncatchable exceptions, the JavaScript handler cannot be on top.
1427 if (!is_catchable_by_javascript(exception)) return false;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001428
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001429 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1430 Address entry_handler = Isolate::handler(thread_local_top());
1431 if (entry_handler == nullptr) return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001432
Ben Murdoch257744e2011-11-30 15:57:28 +00001433 // Get the address of the external handler so we can compare the address to
1434 // determine which one is closer to the top of the stack.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001435 Address external_handler = thread_local_top()->try_catch_handler_address();
1436 if (external_handler == nullptr) return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001437
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001438 // The exception has been externally caught if and only if there is an
1439 // external handler which is on top of the top-most JS_ENTRY handler.
Ben Murdoch257744e2011-11-30 15:57:28 +00001440 //
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001441 // Note, that finally clauses would re-throw an exception unless it's aborted
1442 // by jumps in control flow (like return, break, etc.) and we'll have another
1443 // chance to set proper v8::TryCatch later.
1444 return (entry_handler < external_handler);
1445}
Ben Murdoch257744e2011-11-30 15:57:28 +00001446
Ben Murdoch257744e2011-11-30 15:57:28 +00001447
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001448bool Isolate::IsExternalHandlerOnTop(Object* exception) {
1449 DCHECK_NE(heap()->the_hole_value(), exception);
1450
1451 // Get the address of the external handler so we can compare the address to
1452 // determine which one is closer to the top of the stack.
1453 Address external_handler = thread_local_top()->try_catch_handler_address();
1454 if (external_handler == nullptr) return false;
1455
1456 // For uncatchable exceptions, the external handler is always on top.
1457 if (!is_catchable_by_javascript(exception)) return true;
1458
1459 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1460 Address entry_handler = Isolate::handler(thread_local_top());
1461 if (entry_handler == nullptr) return true;
1462
1463 // The exception has been externally caught if and only if there is an
1464 // external handler which is on top of the top-most JS_ENTRY handler.
1465 //
1466 // Note, that finally clauses would re-throw an exception unless it's aborted
1467 // by jumps in control flow (like return, break, etc.) and we'll have another
1468 // chance to set proper v8::TryCatch later.
1469 return (entry_handler > external_handler);
Ben Murdoch257744e2011-11-30 15:57:28 +00001470}
1471
1472
1473void Isolate::ReportPendingMessages() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001474 Object* exception = pending_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001475
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001476 // Try to propagate the exception to an external v8::TryCatch handler. If
1477 // propagation was unsuccessful, then we will get another chance at reporting
1478 // the pending message if the exception is re-thrown.
1479 bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch();
1480 if (!has_been_propagated) return;
1481
1482 // Clear the pending message object early to avoid endless recursion.
1483 Object* message_obj = thread_local_top_.pending_message_obj_;
1484 clear_pending_message();
1485
1486 // For uncatchable exceptions we do nothing. If needed, the exception and the
1487 // message have already been propagated to v8::TryCatch.
1488 if (!is_catchable_by_javascript(exception)) return;
1489
1490 // Determine whether the message needs to be reported to all message handlers
1491 // depending on whether and external v8::TryCatch or an internal JavaScript
1492 // handler is on top.
1493 bool should_report_exception;
1494 if (IsExternalHandlerOnTop(exception)) {
1495 // Only report the exception if the external handler is verbose.
1496 should_report_exception = try_catch_handler()->is_verbose_;
Ben Murdoch257744e2011-11-30 15:57:28 +00001497 } else {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001498 // Report the exception if it isn't caught by JavaScript code.
1499 should_report_exception = !IsJavaScriptHandlerOnTop(exception);
Ben Murdoch257744e2011-11-30 15:57:28 +00001500 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001501
1502 // Actually report the pending message to all message handlers.
1503 if (!message_obj->IsTheHole() && should_report_exception) {
1504 HandleScope scope(this);
1505 Handle<JSMessageObject> message(JSMessageObject::cast(message_obj));
1506 Handle<JSValue> script_wrapper(JSValue::cast(message->script()));
1507 Handle<Script> script(Script::cast(script_wrapper->value()));
1508 int start_pos = message->start_position();
1509 int end_pos = message->end_position();
1510 MessageLocation location(script, start_pos, end_pos);
1511 MessageHandler::ReportMessage(this, &location, message);
1512 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001513}
1514
1515
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001516MessageLocation Isolate::GetMessageLocation() {
1517 DCHECK(has_pending_exception());
1518
1519 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001520 !thread_local_top_.pending_message_obj_->IsTheHole()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001521 Handle<JSMessageObject> message_obj(
1522 JSMessageObject::cast(thread_local_top_.pending_message_obj_));
1523 Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script()));
1524 Handle<Script> script(Script::cast(script_wrapper->value()));
1525 int start_pos = message_obj->start_position();
1526 int end_pos = message_obj->end_position();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001527 return MessageLocation(script, start_pos, end_pos);
1528 }
1529
1530 return MessageLocation();
Ben Murdoch257744e2011-11-30 15:57:28 +00001531}
1532
1533
1534bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001535 DCHECK(has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001536 PropagatePendingExceptionToExternalTryCatch();
1537
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001538 bool is_termination_exception =
1539 pending_exception() == heap_.termination_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001540
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001541 // Do not reschedule the exception if this is the bottom call.
1542 bool clear_exception = is_bottom_call;
Ben Murdoch257744e2011-11-30 15:57:28 +00001543
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001544 if (is_termination_exception) {
1545 if (is_bottom_call) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001546 thread_local_top()->external_caught_exception_ = false;
1547 clear_pending_exception();
1548 return false;
1549 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001550 } else if (thread_local_top()->external_caught_exception_) {
1551 // If the exception is externally caught, clear it if there are no
1552 // JavaScript frames on the way to the C++ frame that has the
1553 // external handler.
1554 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1555 Address external_handler_address =
1556 thread_local_top()->try_catch_handler_address();
1557 JavaScriptFrameIterator it(this);
1558 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1559 clear_exception = true;
1560 }
1561 }
1562
1563 // Clear the exception if needed.
1564 if (clear_exception) {
1565 thread_local_top()->external_caught_exception_ = false;
1566 clear_pending_exception();
1567 return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001568 }
1569
1570 // Reschedule the exception.
1571 thread_local_top()->scheduled_exception_ = pending_exception();
1572 clear_pending_exception();
1573 return true;
1574}
1575
1576
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001577void Isolate::PushPromise(Handle<JSObject> promise,
1578 Handle<JSFunction> function) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001579 ThreadLocalTop* tltop = thread_local_top();
1580 PromiseOnStack* prev = tltop->promise_on_stack_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001581 Handle<JSObject> global_promise =
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001582 Handle<JSObject>::cast(global_handles()->Create(*promise));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001583 Handle<JSFunction> global_function =
1584 Handle<JSFunction>::cast(global_handles()->Create(*function));
1585 tltop->promise_on_stack_ =
1586 new PromiseOnStack(global_function, global_promise, prev);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001587}
1588
1589
1590void Isolate::PopPromise() {
1591 ThreadLocalTop* tltop = thread_local_top();
1592 if (tltop->promise_on_stack_ == NULL) return;
1593 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001594 Handle<Object> global_function = tltop->promise_on_stack_->function();
1595 Handle<Object> global_promise = tltop->promise_on_stack_->promise();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001596 delete tltop->promise_on_stack_;
1597 tltop->promise_on_stack_ = prev;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001598 global_handles()->Destroy(global_function.location());
1599 global_handles()->Destroy(global_promise.location());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001600}
1601
1602
1603Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1604 Handle<Object> undefined = factory()->undefined_value();
1605 ThreadLocalTop* tltop = thread_local_top();
1606 if (tltop->promise_on_stack_ == NULL) return undefined;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001607 Handle<JSFunction> promise_function = tltop->promise_on_stack_->function();
1608 // Find the top-most try-catch or try-finally handler.
1609 if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined;
1610 for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
1611 JavaScriptFrame* frame = it.frame();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001612 if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001613 // Throwing inside a Promise only leads to a reject if not caught by an
1614 // inner try-catch or try-finally.
1615 if (frame->function() == *promise_function) {
1616 return tltop->promise_on_stack_->promise();
1617 }
1618 return undefined;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001619 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001620 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001621 return undefined;
1622}
1623
1624
Ben Murdoch257744e2011-11-30 15:57:28 +00001625void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1626 bool capture,
1627 int frame_limit,
1628 StackTrace::StackTraceOptions options) {
1629 capture_stack_trace_for_uncaught_exceptions_ = capture;
1630 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1631 stack_trace_for_uncaught_exceptions_options_ = options;
1632}
1633
1634
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001635void Isolate::SetAbortOnUncaughtExceptionCallback(
1636 v8::Isolate::AbortOnUncaughtExceptionCallback callback) {
1637 abort_on_uncaught_exception_callback_ = callback;
1638}
1639
1640
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001641Handle<Context> Isolate::native_context() {
1642 return handle(context()->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001643}
1644
1645
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001646Handle<Context> Isolate::GetCallingNativeContext() {
1647 JavaScriptFrameIterator it(this);
1648 if (debug_->in_debug_scope()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001649 while (!it.done()) {
1650 JavaScriptFrame* frame = it.frame();
1651 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001652 if (context->native_context() == *debug_->debug_context()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001653 it.Advance();
1654 } else {
1655 break;
1656 }
1657 }
1658 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001659 if (it.done()) return Handle<Context>::null();
1660 JavaScriptFrame* frame = it.frame();
1661 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001662 return Handle<Context>(context->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001663}
1664
1665
1666char* Isolate::ArchiveThread(char* to) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001667 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1668 sizeof(ThreadLocalTop));
Ben Murdoch257744e2011-11-30 15:57:28 +00001669 InitializeThreadLocal();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001670 clear_pending_exception();
1671 clear_pending_message();
1672 clear_scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001673 return to + sizeof(ThreadLocalTop);
1674}
1675
1676
1677char* Isolate::RestoreThread(char* from) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001678 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1679 sizeof(ThreadLocalTop));
1680// This might be just paranoia, but it seems to be needed in case a
1681// thread_local_top_ is restored on a separate OS thread.
Ben Murdoch257744e2011-11-30 15:57:28 +00001682#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +00001683 thread_local_top()->simulator_ = Simulator::current(this);
1684#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001685 DCHECK(context() == NULL || context()->IsContext());
Ben Murdoch257744e2011-11-30 15:57:28 +00001686 return from + sizeof(ThreadLocalTop);
1687}
1688
1689
Steve Block44f0eee2011-05-26 01:26:41 +01001690Isolate::ThreadDataTable::ThreadDataTable()
1691 : list_(NULL) {
1692}
1693
1694
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001695Isolate::ThreadDataTable::~ThreadDataTable() {
1696 // TODO(svenpanne) The assertion below would fire if an embedder does not
1697 // cleanly dispose all Isolates before disposing v8, so we are conservative
1698 // and leave it out for now.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001699 // DCHECK_NULL(list_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001700}
1701
1702
1703Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1704#if defined(USE_SIMULATOR)
1705 delete simulator_;
1706#endif
1707}
1708
1709
Steve Block44f0eee2011-05-26 01:26:41 +01001710Isolate::PerIsolateThreadData*
Ben Murdoch8b112d22011-06-08 16:22:53 +01001711 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1712 ThreadId thread_id) {
Steve Block44f0eee2011-05-26 01:26:41 +01001713 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1714 if (data->Matches(isolate, thread_id)) return data;
1715 }
1716 return NULL;
1717}
1718
1719
1720void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1721 if (list_ != NULL) list_->prev_ = data;
1722 data->next_ = list_;
1723 list_ = data;
1724}
1725
1726
1727void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1728 if (list_ == data) list_ = data->next_;
1729 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1730 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001731 delete data;
Steve Block44f0eee2011-05-26 01:26:41 +01001732}
1733
1734
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001735void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1736 PerIsolateThreadData* data = list_;
1737 while (data != NULL) {
1738 PerIsolateThreadData* next = data->next_;
1739 if (data->isolate() == isolate) Remove(data);
1740 data = next;
1741 }
1742}
1743
1744
Steve Block44f0eee2011-05-26 01:26:41 +01001745#ifdef DEBUG
1746#define TRACE_ISOLATE(tag) \
1747 do { \
1748 if (FLAG_trace_isolates) { \
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001749 PrintF("Isolate %p (id %d)" #tag "\n", \
1750 reinterpret_cast<void*>(this), id()); \
Steve Block44f0eee2011-05-26 01:26:41 +01001751 } \
1752 } while (false)
1753#else
1754#define TRACE_ISOLATE(tag)
1755#endif
1756
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001757Isolate::Isolate(bool enable_serializer)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001758 : embedder_data_(),
Steve Block44f0eee2011-05-26 01:26:41 +01001759 entry_stack_(NULL),
1760 stack_trace_nesting_level_(0),
1761 incomplete_message_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001762 bootstrapper_(NULL),
1763 runtime_profiler_(NULL),
1764 compilation_cache_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001765 counters_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001766 code_range_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001767 logger_(NULL),
1768 stats_table_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001769 stub_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001770 code_aging_helper_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001771 deoptimizer_data_(NULL),
Ben Murdoch097c5b22016-05-18 11:27:45 +01001772 deoptimizer_lazy_throw_(false),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001773 materialized_object_store_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001774 capture_stack_trace_for_uncaught_exceptions_(false),
1775 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1776 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
Steve Block44f0eee2011-05-26 01:26:41 +01001777 memory_allocator_(NULL),
1778 keyed_lookup_cache_(NULL),
1779 context_slot_cache_(NULL),
1780 descriptor_lookup_cache_(NULL),
1781 handle_scope_implementer_(NULL),
Ben Murdoch8b112d22011-06-08 16:22:53 +01001782 unicode_cache_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001783 inner_pointer_to_code_cache_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001784 global_handles_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001785 eternal_handles_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001786 thread_manager_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001787 has_installed_extensions_(false),
Steve Block44f0eee2011-05-26 01:26:41 +01001788 regexp_stack_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001789 date_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001790 call_descriptor_data_(NULL),
1791 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1792 // be fixed once the default isolate cleanup is done.
1793 random_number_generator_(NULL),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001794 serializer_enabled_(enable_serializer),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001795 has_fatal_error_(false),
1796 initialized_from_snapshot_(false),
1797 cpu_profiler_(NULL),
1798 heap_profiler_(NULL),
1799 function_entry_hook_(NULL),
1800 deferred_handles_head_(NULL),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001801 optimizing_compile_dispatcher_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001802 stress_deopt_count_(0),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001803 virtual_handler_register_(NULL),
1804 virtual_slot_register_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001805 next_optimization_id_(0),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001806 js_calls_from_api_counter_(0),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001807#if TRACE_MAPS
1808 next_unique_sfi_id_(0),
1809#endif
1810 use_counter_callback_(NULL),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001811 basic_block_profiler_(NULL),
1812 cancelable_task_manager_(new CancelableTaskManager()),
1813 abort_on_uncaught_exception_callback_(NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001814 {
1815 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1816 CHECK(thread_data_table_);
1817 }
1818 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
Steve Block44f0eee2011-05-26 01:26:41 +01001819 TRACE_ISOLATE(constructor);
1820
1821 memset(isolate_addresses_, 0,
Ben Murdoch589d6972011-11-30 16:04:58 +00001822 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
Steve Block44f0eee2011-05-26 01:26:41 +01001823
1824 heap_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01001825 stack_guard_.isolate_ = this;
1826
Ben Murdoch257744e2011-11-30 15:57:28 +00001827 // ThreadManager is initialized early to support locking an isolate
1828 // before it is entered.
1829 thread_manager_ = new ThreadManager();
1830 thread_manager_->isolate_ = this;
1831
Steve Block44f0eee2011-05-26 01:26:41 +01001832#ifdef DEBUG
1833 // heap_histograms_ initializes itself.
1834 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
Steve Block44f0eee2011-05-26 01:26:41 +01001835#endif
1836
Steve Block44f0eee2011-05-26 01:26:41 +01001837 handle_scope_data_.Initialize();
1838
1839#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1840 name##_ = (initial_value);
1841 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1842#undef ISOLATE_INIT_EXECUTE
1843
1844#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1845 memset(name##_, 0, sizeof(type) * length);
1846 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1847#undef ISOLATE_INIT_ARRAY_EXECUTE
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001848
1849 InitializeLoggingAndCounters();
1850 debug_ = new Debug(this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001851
1852 init_memcopy_functions(this);
Steve Block44f0eee2011-05-26 01:26:41 +01001853}
1854
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001855
Steve Block44f0eee2011-05-26 01:26:41 +01001856void Isolate::TearDown() {
1857 TRACE_ISOLATE(tear_down);
1858
1859 // Temporarily set this isolate as current so that various parts of
1860 // the isolate can access it in their destructors without having a
1861 // direct pointer. We don't use Enter/Exit here to avoid
1862 // initializing the thread data.
1863 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001864 DCHECK(base::NoBarrier_Load(&isolate_key_created_) == 1);
1865 Isolate* saved_isolate =
1866 reinterpret_cast<Isolate*>(base::Thread::GetThreadLocal(isolate_key_));
Steve Block44f0eee2011-05-26 01:26:41 +01001867 SetIsolateThreadLocals(this, NULL);
1868
1869 Deinit();
1870
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001871 {
1872 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +01001873 thread_data_table_->RemoveAllThreads(this);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001874 }
1875
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001876 delete this;
1877
Steve Block44f0eee2011-05-26 01:26:41 +01001878 // Restore the previous current isolate.
1879 SetIsolateThreadLocals(saved_isolate, saved_data);
1880}
1881
1882
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001883void Isolate::GlobalTearDown() {
1884 delete thread_data_table_;
1885 thread_data_table_ = NULL;
1886}
1887
1888
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001889void Isolate::ClearSerializerData() {
1890 delete external_reference_table_;
1891 external_reference_table_ = NULL;
1892 delete external_reference_map_;
1893 external_reference_map_ = NULL;
1894}
1895
1896
Steve Block44f0eee2011-05-26 01:26:41 +01001897void Isolate::Deinit() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001898 TRACE_ISOLATE(deinit);
Steve Block44f0eee2011-05-26 01:26:41 +01001899
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001900 debug()->Unload();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001901
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001902 FreeThreadResources();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001903
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001904 if (concurrent_recompilation_enabled()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001905 optimizing_compile_dispatcher_->Stop();
1906 delete optimizing_compile_dispatcher_;
1907 optimizing_compile_dispatcher_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001908 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001909
1910 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1911 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1912 }
1913
1914 DumpAndResetCompilationStats();
1915
1916 if (FLAG_print_deopt_stress) {
1917 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1918 }
1919
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001920 if (cpu_profiler_) {
1921 cpu_profiler_->DeleteAllProfiles();
1922 }
1923
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001924 // We must stop the logger before we tear down other components.
1925 Sampler* sampler = logger_->sampler();
1926 if (sampler && sampler->IsActive()) sampler->Stop();
1927
1928 delete deoptimizer_data_;
1929 deoptimizer_data_ = NULL;
1930 builtins_.TearDown();
1931 bootstrapper_->TearDown();
1932
1933 if (runtime_profiler_ != NULL) {
1934 delete runtime_profiler_;
1935 runtime_profiler_ = NULL;
1936 }
1937
1938 delete basic_block_profiler_;
1939 basic_block_profiler_ = NULL;
1940
Ben Murdoch097c5b22016-05-18 11:27:45 +01001941 delete heap_profiler_;
1942 heap_profiler_ = NULL;
1943
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001944 heap_.TearDown();
1945 logger_->TearDown();
1946
Ben Murdoch097c5b22016-05-18 11:27:45 +01001947 delete interpreter_;
1948 interpreter_ = NULL;
1949
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001950 cancelable_task_manager()->CancelAndWait();
1951
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001952 delete cpu_profiler_;
1953 cpu_profiler_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001954
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001955 delete root_index_map_;
1956 root_index_map_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001957
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001958 ClearSerializerData();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001959}
1960
1961
Steve Block44f0eee2011-05-26 01:26:41 +01001962void Isolate::SetIsolateThreadLocals(Isolate* isolate,
1963 PerIsolateThreadData* data) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001964 base::Thread::SetThreadLocal(isolate_key_, isolate);
1965 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
Steve Block44f0eee2011-05-26 01:26:41 +01001966}
1967
1968
1969Isolate::~Isolate() {
1970 TRACE_ISOLATE(destructor);
1971
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001972 // Has to be called while counters_ are still alive
1973 runtime_zone_.DeleteKeptSegment();
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001974
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001975 // The entry stack must be empty when we get here.
1976 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
1977
1978 delete entry_stack_;
1979 entry_stack_ = NULL;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001980
Ben Murdoch8b112d22011-06-08 16:22:53 +01001981 delete unicode_cache_;
1982 unicode_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001983
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001984 delete date_cache_;
1985 date_cache_ = NULL;
1986
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001987 delete[] call_descriptor_data_;
1988 call_descriptor_data_ = NULL;
1989
Steve Block44f0eee2011-05-26 01:26:41 +01001990 delete regexp_stack_;
1991 regexp_stack_ = NULL;
1992
Steve Block44f0eee2011-05-26 01:26:41 +01001993 delete descriptor_lookup_cache_;
1994 descriptor_lookup_cache_ = NULL;
1995 delete context_slot_cache_;
1996 context_slot_cache_ = NULL;
1997 delete keyed_lookup_cache_;
1998 keyed_lookup_cache_ = NULL;
1999
Steve Block44f0eee2011-05-26 01:26:41 +01002000 delete stub_cache_;
2001 stub_cache_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002002 delete code_aging_helper_;
2003 code_aging_helper_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002004 delete stats_table_;
2005 stats_table_ = NULL;
2006
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002007 delete materialized_object_store_;
2008 materialized_object_store_ = NULL;
2009
Steve Block44f0eee2011-05-26 01:26:41 +01002010 delete logger_;
2011 logger_ = NULL;
2012
2013 delete counters_;
2014 counters_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002015
2016 delete handle_scope_implementer_;
2017 handle_scope_implementer_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002018
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002019 delete code_tracer();
2020 set_code_tracer(NULL);
2021
Steve Block44f0eee2011-05-26 01:26:41 +01002022 delete compilation_cache_;
2023 compilation_cache_ = NULL;
2024 delete bootstrapper_;
2025 bootstrapper_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002026 delete inner_pointer_to_code_cache_;
2027 inner_pointer_to_code_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002028
Steve Block44f0eee2011-05-26 01:26:41 +01002029 delete thread_manager_;
2030 thread_manager_ = NULL;
2031
Steve Block44f0eee2011-05-26 01:26:41 +01002032 delete memory_allocator_;
2033 memory_allocator_ = NULL;
2034 delete code_range_;
2035 code_range_ = NULL;
2036 delete global_handles_;
2037 global_handles_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002038 delete eternal_handles_;
2039 eternal_handles_ = NULL;
2040
2041 delete string_stream_debug_object_cache_;
2042 string_stream_debug_object_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002043
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002044 delete random_number_generator_;
2045 random_number_generator_ = NULL;
2046
Steve Block44f0eee2011-05-26 01:26:41 +01002047 delete debug_;
2048 debug_ = NULL;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002049
2050 delete cancelable_task_manager_;
2051 cancelable_task_manager_ = nullptr;
2052
2053#if USE_SIMULATOR
2054 Simulator::TearDown(simulator_i_cache_, simulator_redirection_);
2055 simulator_i_cache_ = nullptr;
2056 simulator_redirection_ = nullptr;
2057#endif
Steve Block44f0eee2011-05-26 01:26:41 +01002058}
2059
2060
Steve Block44f0eee2011-05-26 01:26:41 +01002061void Isolate::InitializeThreadLocal() {
Ben Murdoch257744e2011-11-30 15:57:28 +00002062 thread_local_top_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01002063 thread_local_top_.Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01002064}
2065
2066
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002067bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002068 Object* exception = pending_exception();
Ben Murdoch8b112d22011-06-08 16:22:53 +01002069
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002070 if (IsJavaScriptHandlerOnTop(exception)) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002071 thread_local_top_.external_caught_exception_ = false;
2072 return false;
2073 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01002074
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002075 if (!IsExternalHandlerOnTop(exception)) {
2076 thread_local_top_.external_caught_exception_ = false;
2077 return true;
2078 }
2079
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002080 thread_local_top_.external_caught_exception_ = true;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002081 if (!is_catchable_by_javascript(exception)) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01002082 try_catch_handler()->can_continue_ = false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002083 try_catch_handler()->has_terminated_ = true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002084 try_catch_handler()->exception_ = heap()->null_value();
2085 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002086 v8::TryCatch* handler = try_catch_handler();
2087 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2088 thread_local_top_.pending_message_obj_->IsTheHole());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002089 handler->can_continue_ = true;
2090 handler->has_terminated_ = false;
2091 handler->exception_ = pending_exception();
2092 // Propagate to the external try-catch only if we got an actual message.
2093 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
2094
2095 handler->message_obj_ = thread_local_top_.pending_message_obj_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002096 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002097 return true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002098}
2099
2100
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002101void Isolate::InitializeLoggingAndCounters() {
2102 if (logger_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002103 logger_ = new Logger(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002104 }
2105 if (counters_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002106 counters_ = new Counters(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002107 }
2108}
2109
2110
Steve Block44f0eee2011-05-26 01:26:41 +01002111bool Isolate::Init(Deserializer* des) {
Steve Block44f0eee2011-05-26 01:26:41 +01002112 TRACE_ISOLATE(init);
2113
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002114 stress_deopt_count_ = FLAG_deopt_every_n_times;
2115
2116 has_fatal_error_ = false;
2117
2118 if (function_entry_hook() != NULL) {
2119 // When function entry hooking is in effect, we have to create the code
2120 // stubs from scratch to get entry hooks, rather than loading the previously
2121 // generated stubs from disk.
2122 // If this assert fires, the initialization path has regressed.
2123 DCHECK(des == NULL);
2124 }
2125
Steve Block44f0eee2011-05-26 01:26:41 +01002126 // The initialization process does not handle memory exhaustion.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002127 AlwaysAllocateScope always_allocate(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002128
2129 memory_allocator_ = new MemoryAllocator(this);
2130 code_range_ = new CodeRange(this);
2131
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002132 // Safe after setting Heap::isolate_, and initializing StackGuard
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002133 heap_.SetStackLimits();
2134
Ben Murdoch589d6972011-11-30 16:04:58 +00002135#define ASSIGN_ELEMENT(CamelName, hacker_name) \
2136 isolate_addresses_[Isolate::k##CamelName##Address] = \
2137 reinterpret_cast<Address>(hacker_name##_address());
2138 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002139#undef ASSIGN_ELEMENT
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002140
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002141 compilation_cache_ = new CompilationCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002142 keyed_lookup_cache_ = new KeyedLookupCache();
2143 context_slot_cache_ = new ContextSlotCache();
2144 descriptor_lookup_cache_ = new DescriptorLookupCache();
2145 unicode_cache_ = new UnicodeCache();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002146 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002147 global_handles_ = new GlobalHandles(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002148 eternal_handles_ = new EternalHandles();
2149 bootstrapper_ = new Bootstrapper(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002150 handle_scope_implementer_ = new HandleScopeImplementer(this);
2151 stub_cache_ = new StubCache(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002152 materialized_object_store_ = new MaterializedObjectStore(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002153 regexp_stack_ = new RegExpStack();
2154 regexp_stack_->isolate_ = this;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002155 date_cache_ = new DateCache();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002156 call_descriptor_data_ =
2157 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2158 cpu_profiler_ = new CpuProfiler(this);
2159 heap_profiler_ = new HeapProfiler(heap());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002160 interpreter_ = new interpreter::Interpreter(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002161
2162 // Enable logging before setting up the heap
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002163 logger_->SetUp(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002164
Steve Block44f0eee2011-05-26 01:26:41 +01002165 // Initialize other runtime facilities
2166#if defined(USE_SIMULATOR)
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002167#if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
2168 V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC
Ben Murdoch257744e2011-11-30 15:57:28 +00002169 Simulator::Initialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002170#endif
2171#endif
2172
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002173 code_aging_helper_ = new CodeAgingHelper(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002174
Steve Block44f0eee2011-05-26 01:26:41 +01002175 { // NOLINT
2176 // Ensure that the thread has a valid stack guard. The v8::Locker object
2177 // will ensure this too, but we don't have to use lockers if we are only
2178 // using one thread.
2179 ExecutionAccess lock(this);
2180 stack_guard_.InitThread(lock);
2181 }
2182
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002183 // SetUp the object heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002184 DCHECK(!heap_.HasBeenSetUp());
2185 if (!heap_.SetUp()) {
2186 V8::FatalProcessOutOfMemory("heap setup");
Steve Block44f0eee2011-05-26 01:26:41 +01002187 return false;
2188 }
2189
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002190 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2191
2192 const bool create_heap_objects = (des == NULL);
2193 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2194 V8::FatalProcessOutOfMemory("heap object creation");
2195 return false;
2196 }
2197
2198 if (create_heap_objects) {
2199 // Terminate the cache array with the sentinel so we can iterate.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002200 partial_snapshot_cache_.Add(heap_.undefined_value());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002201 }
2202
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002203 InitializeThreadLocal();
2204
Steve Block44f0eee2011-05-26 01:26:41 +01002205 bootstrapper_->Initialize(create_heap_objects);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002206 builtins_.SetUp(this, create_heap_objects);
Steve Block44f0eee2011-05-26 01:26:41 +01002207
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002208 if (FLAG_log_internal_timer_events) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002209 set_event_logger(Logger::DefaultEventLoggerSentinel);
Steve Block44f0eee2011-05-26 01:26:41 +01002210 }
2211
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002212 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2213 PrintF("Concurrent recompilation has been disabled for tracing.\n");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002214 } else if (OptimizingCompileDispatcher::Enabled()) {
2215 optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002216 }
2217
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002218 // Initialize runtime profiler before deserialization, because collections may
2219 // occur, clearing/updating ICs.
2220 runtime_profiler_ = new RuntimeProfiler(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002221
2222 // If we are deserializing, read the state into the now-empty heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002223 if (!create_heap_objects) {
2224 des->Deserialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002225 }
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002226 stub_cache_->Initialize();
2227
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002228 if (FLAG_ignition) {
2229 interpreter_->Initialize();
2230 }
2231
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002232 // Finish initialization of ThreadLocal after deserialization is done.
2233 clear_pending_exception();
2234 clear_pending_message();
2235 clear_scheduled_exception();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002236
Steve Block44f0eee2011-05-26 01:26:41 +01002237 // Deserializing may put strange things in the root array's copy of the
2238 // stack guard.
2239 heap_.SetStackLimits();
2240
Ben Murdochdb1b4382012-04-26 19:03:50 +01002241 // Quiet the heap NaN if needed on target platform.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002242 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
Ben Murdochdb1b4382012-04-26 19:03:50 +01002243
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002244 if (FLAG_trace_turbo) {
2245 // Create an empty file.
2246 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2247 }
Steve Block44f0eee2011-05-26 01:26:41 +01002248
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002249 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2250 Internals::kIsolateEmbedderDataOffset);
2251 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2252 Internals::kIsolateRootsOffset);
2253 CHECK_EQ(static_cast<int>(
2254 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2255 Internals::kAmountOfExternalAllocatedMemoryOffset);
2256 CHECK_EQ(static_cast<int>(OFFSET_OF(
2257 Isolate,
2258 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2259 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2260
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002261 time_millis_at_init_ = heap_.MonotonicallyIncreasingTimeInMs();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002262
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002263 heap_.NotifyDeserializationComplete();
2264
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002265 if (!create_heap_objects) {
2266 // Now that the heap is consistent, it's OK to generate the code for the
2267 // deopt entry table that might have been referred to by optimized code in
2268 // the snapshot.
2269 HandleScope scope(this);
2270 Deoptimizer::EnsureCodeForDeoptimizationEntry(
2271 this,
2272 Deoptimizer::LAZY,
2273 kDeoptTableSerializeEntryCount - 1);
2274 }
2275
2276 if (!serializer_enabled()) {
2277 // Ensure that all stubs which need to be generated ahead of time, but
2278 // cannot be serialized into the snapshot have been generated.
2279 HandleScope scope(this);
2280 CodeStub::GenerateFPStubs(this);
2281 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2282 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2283 }
2284
2285 initialized_from_snapshot_ = (des != NULL);
2286
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002287 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2288
Steve Block44f0eee2011-05-26 01:26:41 +01002289 return true;
2290}
2291
2292
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002293// Initialized lazily to allow early
2294// v8::V8::SetAddHistogramSampleFunction calls.
2295StatsTable* Isolate::stats_table() {
2296 if (stats_table_ == NULL) {
2297 stats_table_ = new StatsTable;
2298 }
2299 return stats_table_;
2300}
2301
2302
Steve Block44f0eee2011-05-26 01:26:41 +01002303void Isolate::Enter() {
2304 Isolate* current_isolate = NULL;
2305 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2306 if (current_data != NULL) {
2307 current_isolate = current_data->isolate_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002308 DCHECK(current_isolate != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01002309 if (current_isolate == this) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002310 DCHECK(Current() == this);
2311 DCHECK(entry_stack_ != NULL);
2312 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002313 entry_stack_->previous_thread_data->thread_id().Equals(
2314 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002315 // Same thread re-enters the isolate, no need to re-init anything.
2316 entry_stack_->entry_count++;
2317 return;
2318 }
2319 }
2320
Steve Block44f0eee2011-05-26 01:26:41 +01002321 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002322 DCHECK(data != NULL);
2323 DCHECK(data->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002324
2325 EntryStackItem* item = new EntryStackItem(current_data,
2326 current_isolate,
2327 entry_stack_);
2328 entry_stack_ = item;
2329
2330 SetIsolateThreadLocals(this, data);
2331
Steve Block44f0eee2011-05-26 01:26:41 +01002332 // In case it's the first time some thread enters the isolate.
2333 set_thread_id(data->thread_id());
2334}
2335
2336
2337void Isolate::Exit() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002338 DCHECK(entry_stack_ != NULL);
2339 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002340 entry_stack_->previous_thread_data->thread_id().Equals(
2341 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002342
2343 if (--entry_stack_->entry_count > 0) return;
2344
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002345 DCHECK(CurrentPerIsolateThreadData() != NULL);
2346 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002347
2348 // Pop the stack.
2349 EntryStackItem* item = entry_stack_;
2350 entry_stack_ = item->previous_item;
2351
2352 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2353 Isolate* previous_isolate = item->previous_isolate;
2354
2355 delete item;
2356
2357 // Reinit the current thread for the isolate it was running before this one.
2358 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2359}
2360
2361
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002362void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2363 deferred->next_ = deferred_handles_head_;
2364 if (deferred_handles_head_ != NULL) {
2365 deferred_handles_head_->previous_ = deferred;
2366 }
2367 deferred_handles_head_ = deferred;
2368}
2369
2370
2371void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2372#ifdef DEBUG
2373 // In debug mode assert that the linked list is well-formed.
2374 DeferredHandles* deferred_iterator = deferred;
2375 while (deferred_iterator->previous_ != NULL) {
2376 deferred_iterator = deferred_iterator->previous_;
2377 }
2378 DCHECK(deferred_handles_head_ == deferred_iterator);
2379#endif
2380 if (deferred_handles_head_ == deferred) {
2381 deferred_handles_head_ = deferred_handles_head_->next_;
2382 }
2383 if (deferred->next_ != NULL) {
2384 deferred->next_->previous_ = deferred->previous_;
2385 }
2386 if (deferred->previous_ != NULL) {
2387 deferred->previous_->next_ = deferred->next_;
2388 }
2389}
2390
2391
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002392void Isolate::DumpAndResetCompilationStats() {
2393 if (turbo_statistics() != nullptr) {
2394 OFStream os(stdout);
2395 os << *turbo_statistics() << std::endl;
2396 }
2397 if (hstatistics() != nullptr) hstatistics()->Print();
2398 delete turbo_statistics_;
2399 turbo_statistics_ = nullptr;
2400 delete hstatistics_;
2401 hstatistics_ = nullptr;
Ben Murdoch097c5b22016-05-18 11:27:45 +01002402 if (FLAG_runtime_call_stats) {
2403 OFStream os(stdout);
2404 counters()->runtime_call_stats()->Print(os);
2405 counters()->runtime_call_stats()->Reset();
2406 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002407}
2408
2409
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002410HStatistics* Isolate::GetHStatistics() {
2411 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2412 return hstatistics();
2413}
2414
2415
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002416CompilationStatistics* Isolate::GetTurboStatistics() {
2417 if (turbo_statistics() == NULL)
2418 set_turbo_statistics(new CompilationStatistics());
2419 return turbo_statistics();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002420}
2421
2422
2423HTracer* Isolate::GetHTracer() {
2424 if (htracer() == NULL) set_htracer(new HTracer(id()));
2425 return htracer();
2426}
2427
2428
2429CodeTracer* Isolate::GetCodeTracer() {
2430 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2431 return code_tracer();
2432}
2433
2434
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002435Map* Isolate::get_initial_js_array_map(ElementsKind kind, Strength strength) {
2436 if (IsFastElementsKind(kind)) {
2437 DisallowHeapAllocation no_gc;
2438 Object* const initial_js_array_map = context()->native_context()->get(
2439 Context::ArrayMapIndex(kind, strength));
2440 if (!initial_js_array_map->IsUndefined()) {
2441 return Map::cast(initial_js_array_map);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002442 }
2443 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002444 return nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002445}
2446
2447
2448bool Isolate::use_crankshaft() const {
2449 return FLAG_crankshaft &&
2450 !serializer_enabled_ &&
2451 CpuFeatures::SupportsCrankshaft();
2452}
2453
2454
2455bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002456 PropertyCell* no_elements_cell = heap()->array_protector();
2457 bool cell_reports_intact =
2458 no_elements_cell->value()->IsSmi() &&
2459 Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid;
2460
2461#ifdef DEBUG
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002462 Map* root_array_map =
2463 get_initial_js_array_map(GetInitialFastElementsKind());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002464 Context* native_context = context()->native_context();
2465 JSObject* initial_array_proto = JSObject::cast(
2466 native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX));
2467 JSObject* initial_object_proto = JSObject::cast(
2468 native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX));
2469
2470 if (root_array_map == NULL || initial_array_proto == initial_object_proto) {
2471 // We are in the bootstrapping process, and the entire check sequence
2472 // shouldn't be performed.
2473 return cell_reports_intact;
2474 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002475
2476 // Check that the array prototype hasn't been altered WRT empty elements.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002477 if (root_array_map->prototype() != initial_array_proto) {
2478 DCHECK_EQ(false, cell_reports_intact);
2479 return cell_reports_intact;
2480 }
2481
2482 FixedArrayBase* elements = initial_array_proto->elements();
2483 if (elements != heap()->empty_fixed_array() &&
2484 elements != heap()->empty_slow_element_dictionary()) {
2485 DCHECK_EQ(false, cell_reports_intact);
2486 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002487 }
2488
2489 // Check that the object prototype hasn't been altered WRT empty elements.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002490 PrototypeIterator iter(this, initial_array_proto);
2491 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002492 DCHECK_EQ(false, cell_reports_intact);
2493 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002494 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002495
2496 elements = initial_object_proto->elements();
2497 if (elements != heap()->empty_fixed_array() &&
2498 elements != heap()->empty_slow_element_dictionary()) {
2499 DCHECK_EQ(false, cell_reports_intact);
2500 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002501 }
2502
2503 iter.Advance();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002504 if (!iter.IsAtEnd()) {
2505 DCHECK_EQ(false, cell_reports_intact);
2506 return cell_reports_intact;
2507 }
2508
2509#endif
2510
2511 return cell_reports_intact;
2512}
2513
Ben Murdoch097c5b22016-05-18 11:27:45 +01002514bool Isolate::IsArraySpeciesLookupChainIntact() {
2515 if (!FLAG_harmony_species) return true;
2516 // Note: It would be nice to have debug checks to make sure that the
2517 // species protector is accurate, but this would be hard to do for most of
2518 // what the protector stands for:
2519 // - You'd need to traverse the heap to check that no Array instance has
2520 // a constructor property or a modified __proto__
2521 // - To check that Array[Symbol.species] == Array, JS code has to execute,
2522 // but JS cannot be invoked in callstack overflow situations
2523 // All that could be checked reliably is that
2524 // Array.prototype.constructor == Array. Given that limitation, no check is
2525 // done here. In place, there are mjsunit tests harmony/array-species* which
2526 // ensure that behavior is correct in various invalid protector cases.
2527
2528 PropertyCell* species_cell = heap()->species_protector();
2529 return species_cell->value()->IsSmi() &&
2530 Smi::cast(species_cell->value())->value() == kArrayProtectorValid;
2531}
2532
2533void Isolate::InvalidateArraySpeciesProtector() {
2534 if (!FLAG_harmony_species) return;
2535 DCHECK(factory()->species_protector()->value()->IsSmi());
2536 DCHECK(IsArraySpeciesLookupChainIntact());
2537 PropertyCell::SetValueWithInvalidation(
2538 factory()->species_protector(),
2539 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2540 DCHECK(!IsArraySpeciesLookupChainIntact());
2541}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002542
2543void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002544 DisallowHeapAllocation no_gc;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002545 if (IsFastArrayConstructorPrototypeChainIntact() &&
2546 object->map()->is_prototype_map()) {
2547 Object* context = heap()->native_contexts_list();
2548 while (!context->IsUndefined()) {
2549 Context* current_context = Context::cast(context);
2550 if (current_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX) ==
2551 *object ||
2552 current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2553 *object) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002554 CountUsage(v8::Isolate::UseCounterFeature::kArrayProtectorDirtied);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002555 PropertyCell::SetValueWithInvalidation(
2556 factory()->array_protector(),
2557 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2558 break;
2559 }
2560 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2561 }
2562 }
2563}
2564
2565
2566bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) {
2567 if (array->map()->is_prototype_map()) {
2568 Object* context = heap()->native_contexts_list();
2569 while (!context->IsUndefined()) {
2570 Context* current_context = Context::cast(context);
2571 if (current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2572 *array) {
2573 return true;
2574 }
2575 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2576 }
2577 }
2578 return false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002579}
2580
2581
2582CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2583 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2584 return &call_descriptor_data_[index];
2585}
2586
2587
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002588base::RandomNumberGenerator* Isolate::random_number_generator() {
2589 if (random_number_generator_ == NULL) {
2590 if (FLAG_random_seed != 0) {
2591 random_number_generator_ =
2592 new base::RandomNumberGenerator(FLAG_random_seed);
2593 } else {
2594 random_number_generator_ = new base::RandomNumberGenerator();
2595 }
2596 }
2597 return random_number_generator_;
2598}
2599
2600
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002601Object* Isolate::FindCodeObject(Address a) {
2602 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2603}
2604
2605
Steve Block44f0eee2011-05-26 01:26:41 +01002606#ifdef DEBUG
2607#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2608const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2609ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2610ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2611#undef ISOLATE_FIELD_OFFSET
2612#endif
2613
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002614
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002615Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry,
2616 Handle<Map> map, const char* cname) {
2617 Handle<String> name = factory()->InternalizeUtf8String(cname);
2618 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2619 JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0,
2620 "SetupSymbolRegistry");
2621 JSObject::AddProperty(registry, name, obj, NONE);
2622 return obj;
2623}
2624
2625
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002626Handle<JSObject> Isolate::GetSymbolRegistry() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002627 if (heap()->symbol_registry()->IsSmi()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002628 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2629 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2630 heap()->set_symbol_registry(*registry);
2631
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002632 SetUpSubregistry(registry, map, "for");
2633 SetUpSubregistry(registry, map, "for_api");
2634 SetUpSubregistry(registry, map, "keyFor");
2635 SetUpSubregistry(registry, map, "private_api");
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002636 }
2637 return Handle<JSObject>::cast(factory()->symbol_registry());
2638}
2639
2640
Ben Murdoch097c5b22016-05-18 11:27:45 +01002641void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
2642 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2643 if (callback == before_call_entered_callbacks_.at(i)) return;
2644 }
2645 before_call_entered_callbacks_.Add(callback);
2646}
2647
2648
2649void Isolate::RemoveBeforeCallEnteredCallback(
2650 BeforeCallEnteredCallback callback) {
2651 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2652 if (callback == before_call_entered_callbacks_.at(i)) {
2653 before_call_entered_callbacks_.Remove(i);
2654 }
2655 }
2656}
2657
2658
2659void Isolate::FireBeforeCallEnteredCallback() {
2660 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2661 before_call_entered_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this));
2662 }
2663}
2664
2665
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002666void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2667 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2668 if (callback == call_completed_callbacks_.at(i)) return;
2669 }
2670 call_completed_callbacks_.Add(callback);
2671}
2672
2673
2674void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2675 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2676 if (callback == call_completed_callbacks_.at(i)) {
2677 call_completed_callbacks_.Remove(i);
2678 }
2679 }
2680}
2681
2682
2683void Isolate::FireCallCompletedCallback() {
2684 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
2685 bool run_microtasks = autorun_microtasks() && pending_microtask_count();
2686 if (!has_call_completed_callbacks && !run_microtasks) return;
2687
2688 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2689 if (run_microtasks) RunMicrotasks();
2690 // Fire callbacks. Increase call depth to prevent recursive callbacks.
Ben Murdoch097c5b22016-05-18 11:27:45 +01002691 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this);
2692 v8::Isolate::SuppressMicrotaskExecutionScope suppress(isolate);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002693 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002694 call_completed_callbacks_.at(i)(isolate);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002695 }
2696}
2697
2698
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002699void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2700 promise_reject_callback_ = callback;
2701}
2702
2703
2704void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2705 Handle<Object> value,
2706 v8::PromiseRejectEvent event) {
2707 if (promise_reject_callback_ == NULL) return;
2708 Handle<JSArray> stack_trace;
2709 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2710 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2711 }
2712 promise_reject_callback_(v8::PromiseRejectMessage(
2713 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2714 v8::Utils::StackTraceToLocal(stack_trace)));
2715}
2716
2717
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002718void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2719 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2720 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2721 int num_tasks = pending_microtask_count();
2722 DCHECK(num_tasks <= queue->length());
2723 if (num_tasks == 0) {
2724 queue = factory()->NewFixedArray(8);
2725 heap()->set_microtask_queue(*queue);
2726 } else if (num_tasks == queue->length()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002727 queue = factory()->CopyFixedArrayAndGrow(queue, num_tasks);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002728 heap()->set_microtask_queue(*queue);
2729 }
2730 DCHECK(queue->get(num_tasks)->IsUndefined());
2731 queue->set(num_tasks, *microtask);
2732 set_pending_microtask_count(num_tasks + 1);
2733}
2734
2735
2736void Isolate::RunMicrotasks() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002737 // Increase call depth to prevent recursive callbacks.
2738 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2739 reinterpret_cast<v8::Isolate*>(this));
2740
2741 while (pending_microtask_count() > 0) {
2742 HandleScope scope(this);
2743 int num_tasks = pending_microtask_count();
2744 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2745 DCHECK(num_tasks <= queue->length());
2746 set_pending_microtask_count(0);
2747 heap()->set_microtask_queue(heap()->empty_fixed_array());
2748
2749 for (int i = 0; i < num_tasks; i++) {
2750 HandleScope scope(this);
2751 Handle<Object> microtask(queue->get(i), this);
2752 if (microtask->IsJSFunction()) {
2753 Handle<JSFunction> microtask_function =
2754 Handle<JSFunction>::cast(microtask);
2755 SaveContext save(this);
2756 set_context(microtask_function->context()->native_context());
2757 MaybeHandle<Object> maybe_exception;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002758 MaybeHandle<Object> result = Execution::TryCall(
2759 this, microtask_function, factory()->undefined_value(), 0, NULL,
2760 &maybe_exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002761 // If execution is terminating, just bail out.
2762 Handle<Object> exception;
2763 if (result.is_null() && maybe_exception.is_null()) {
2764 // Clear out any remaining callbacks in the queue.
2765 heap()->set_microtask_queue(heap()->empty_fixed_array());
2766 set_pending_microtask_count(0);
2767 return;
2768 }
2769 } else {
2770 Handle<CallHandlerInfo> callback_info =
2771 Handle<CallHandlerInfo>::cast(microtask);
2772 v8::MicrotaskCallback callback =
2773 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2774 void* data = v8::ToCData<void*>(callback_info->data());
2775 callback(data);
2776 }
2777 }
2778 }
2779}
2780
2781
2782void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2783 DCHECK(!use_counter_callback_);
2784 use_counter_callback_ = callback;
2785}
2786
2787
2788void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002789 // The counter callback may cause the embedder to call into V8, which is not
2790 // generally possible during GC.
2791 if (heap_.gc_state() == Heap::NOT_IN_GC) {
2792 if (use_counter_callback_) {
2793 HandleScope handle_scope(this);
2794 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2795 }
2796 } else {
2797 heap_.IncrementDeferredCount(feature);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002798 }
2799}
2800
2801
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002802BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2803 if (basic_block_profiler_ == NULL) {
2804 basic_block_profiler_ = new BasicBlockProfiler();
2805 }
2806 return basic_block_profiler_;
2807}
2808
2809
2810std::string Isolate::GetTurboCfgFileName() {
2811 if (FLAG_trace_turbo_cfg_file == NULL) {
2812 std::ostringstream os;
2813 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2814 return os.str();
2815 } else {
2816 return FLAG_trace_turbo_cfg_file;
2817 }
2818}
2819
2820
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002821// Heap::detached_contexts tracks detached contexts as pairs
2822// (number of GC since the context was detached, the context).
2823void Isolate::AddDetachedContext(Handle<Context> context) {
2824 HandleScope scope(this);
2825 Handle<WeakCell> cell = factory()->NewWeakCell(context);
2826 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2827 int length = detached_contexts->length();
2828 detached_contexts = factory()->CopyFixedArrayAndGrow(detached_contexts, 2);
2829 detached_contexts->set(length, Smi::FromInt(0));
2830 detached_contexts->set(length + 1, *cell);
2831 heap()->set_detached_contexts(*detached_contexts);
2832}
2833
2834
2835void Isolate::CheckDetachedContextsAfterGC() {
2836 HandleScope scope(this);
2837 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2838 int length = detached_contexts->length();
2839 if (length == 0) return;
2840 int new_length = 0;
2841 for (int i = 0; i < length; i += 2) {
2842 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2843 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2844 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2845 if (!cell->cleared()) {
2846 detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2847 detached_contexts->set(new_length + 1, cell);
2848 new_length += 2;
2849 }
2850 counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
2851 }
2852 if (FLAG_trace_detached_contexts) {
2853 PrintF("%d detached contexts are collected out of %d\n",
2854 length - new_length, length);
2855 for (int i = 0; i < new_length; i += 2) {
2856 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2857 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2858 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2859 if (mark_sweeps > 3) {
2860 PrintF("detached context 0x%p\n survived %d GCs (leak?)\n",
2861 static_cast<void*>(cell->value()), mark_sweeps);
2862 }
2863 }
2864 }
2865 if (new_length == 0) {
2866 heap()->set_detached_contexts(heap()->empty_fixed_array());
2867 } else if (new_length < length) {
2868 heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
2869 *detached_contexts, length - new_length);
2870 }
2871}
2872
2873
2874bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002875 StackGuard* stack_guard = isolate_->stack_guard();
2876#ifdef USE_SIMULATOR
2877 // The simulator uses a separate JS stack.
2878 Address jssp_address = Simulator::current(isolate_)->get_sp();
2879 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002880 if (jssp - gap < stack_guard->real_jslimit()) return true;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002881#endif // USE_SIMULATOR
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002882 return GetCurrentStackPosition() - gap < stack_guard->real_climit();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002883}
2884
2885
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002886SaveContext::SaveContext(Isolate* isolate)
2887 : isolate_(isolate), prev_(isolate->save_context()) {
2888 if (isolate->context() != NULL) {
2889 context_ = Handle<Context>(isolate->context());
2890 }
2891 isolate->set_save_context(this);
2892
2893 c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
2894}
2895
2896
2897SaveContext::~SaveContext() {
2898 isolate_->set_context(context_.is_null() ? NULL : *context_);
2899 isolate_->set_save_context(prev_);
2900}
2901
2902
2903#ifdef DEBUG
2904AssertNoContextChange::AssertNoContextChange(Isolate* isolate)
2905 : isolate_(isolate), context_(isolate->context(), isolate) {}
2906#endif // DEBUG
2907
2908
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002909bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2910 // First check whether the previous scope intercepts.
2911 if (prev_ && prev_->Intercept(flag)) return true;
2912 // Then check whether this scope intercepts.
2913 if ((flag & intercept_mask_)) {
2914 intercepted_flags_ |= flag;
2915 return true;
2916 }
2917 return false;
2918}
2919
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002920} // namespace internal
2921} // namespace v8