blob: 9d3511327e63dd8592c2a33f296e6cc0308d748b [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 Murdochda12d292016-06-02 14:46:10 +010025#include "src/external-reference-table.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000026#include "src/frames-inl.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000027#include "src/ic/stub-cache.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000028#include "src/interpreter/interpreter.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000029#include "src/isolate-inl.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000030#include "src/log.h"
31#include "src/messages.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000032#include "src/profiler/cpu-profiler.h"
33#include "src/profiler/sampler.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000034#include "src/prototype.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000035#include "src/regexp/regexp-stack.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000036#include "src/runtime-profiler.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000037#include "src/simulator.h"
Ben Murdochda12d292016-06-02 14:46:10 +010038#include "src/snapshot/deserializer.h"
Ben Murdoch4a90d5f2016-03-22 12:00:34 +000039#include "src/v8.h"
Ben Murdochb8a8cc12014-11-26 15:28:44 +000040#include "src/version.h"
41#include "src/vm-state-inl.h"
Steve Block44f0eee2011-05-26 01:26:41 +010042
43
44namespace v8 {
45namespace internal {
46
Ben Murdochb8a8cc12014-11-26 15:28:44 +000047base::Atomic32 ThreadId::highest_thread_id_ = 0;
Ben Murdoch8b112d22011-06-08 16:22:53 +010048
49int ThreadId::AllocateThreadId() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000050 int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1);
Ben Murdoch8b112d22011-06-08 16:22:53 +010051 return new_id;
52}
53
Ben Murdoch257744e2011-11-30 15:57:28 +000054
Ben Murdoch8b112d22011-06-08 16:22:53 +010055int ThreadId::GetCurrentThreadId() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +000056 int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
Ben Murdoch8b112d22011-06-08 16:22:53 +010057 if (thread_id == 0) {
58 thread_id = AllocateThreadId();
Ben Murdochb8a8cc12014-11-26 15:28:44 +000059 base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id);
Ben Murdoch8b112d22011-06-08 16:22:53 +010060 }
61 return thread_id;
62}
Steve Block44f0eee2011-05-26 01:26:41 +010063
Ben Murdoch6d7cb002011-08-04 19:25:22 +010064
Ben Murdoch257744e2011-11-30 15:57:28 +000065ThreadLocalTop::ThreadLocalTop() {
66 InitializeInternal();
67}
68
69
70void ThreadLocalTop::InitializeInternal() {
71 c_entry_fp_ = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -040072 c_function_ = 0;
Ben Murdoch257744e2011-11-30 15:57:28 +000073 handler_ = 0;
74#ifdef USE_SIMULATOR
75 simulator_ = NULL;
76#endif
Ben Murdoch257744e2011-11-30 15:57:28 +000077 js_entry_sp_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000078 external_callback_scope_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000079 current_vm_state_ = EXTERNAL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000080 try_catch_handler_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000081 context_ = NULL;
82 thread_id_ = ThreadId::Invalid();
83 external_caught_exception_ = false;
84 failed_access_check_callback_ = NULL;
85 save_context_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000086 promise_on_stack_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010087
88 // These members are re-initialized later after deserialization
89 // is complete.
90 pending_exception_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +000091 rethrowing_message_ = false;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010092 pending_message_obj_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +010093 scheduled_exception_ = NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +000094}
95
96
97void ThreadLocalTop::Initialize() {
98 InitializeInternal();
99#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +0000100 simulator_ = Simulator::current(isolate_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000101#endif
102 thread_id_ = ThreadId::Current();
103}
104
105
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000106void ThreadLocalTop::Free() {
107 // Match unmatched PopPromise calls.
108 while (promise_on_stack_) isolate_->PopPromise();
Ben Murdoch257744e2011-11-30 15:57:28 +0000109}
110
111
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000112base::Thread::LocalStorageKey Isolate::isolate_key_;
113base::Thread::LocalStorageKey Isolate::thread_id_key_;
114base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000115base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER;
Ben Murdoch85b71792012-04-11 18:30:58 +0100116Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000117base::Atomic32 Isolate::isolate_counter_ = 0;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400118#if DEBUG
119base::Atomic32 Isolate::isolate_key_created_ = 0;
120#endif
Steve Block44f0eee2011-05-26 01:26:41 +0100121
122Isolate::PerIsolateThreadData*
123 Isolate::FindOrAllocatePerThreadDataForThisThread() {
Ben Murdoch8b112d22011-06-08 16:22:53 +0100124 ThreadId thread_id = ThreadId::Current();
Steve Block44f0eee2011-05-26 01:26:41 +0100125 PerIsolateThreadData* per_thread = NULL;
126 {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000127 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +0100128 per_thread = thread_data_table_->Lookup(this, thread_id);
Steve Block44f0eee2011-05-26 01:26:41 +0100129 if (per_thread == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000130 per_thread = new PerIsolateThreadData(this, thread_id);
131 thread_data_table_->Insert(per_thread);
Steve Block44f0eee2011-05-26 01:26:41 +0100132 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000133 DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread);
Steve Block44f0eee2011-05-26 01:26:41 +0100134 }
135 return per_thread;
136}
137
138
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000139void Isolate::DiscardPerThreadDataForThisThread() {
140 int thread_id_int = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_);
141 if (thread_id_int) {
142 ThreadId thread_id = ThreadId(thread_id_int);
143 DCHECK(!thread_manager_->mutex_owner_.Equals(thread_id));
144 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
145 PerIsolateThreadData* per_thread =
146 thread_data_table_->Lookup(this, thread_id);
147 if (per_thread) {
148 DCHECK(!per_thread->thread_state_);
149 thread_data_table_->Remove(per_thread);
150 }
151 }
152}
153
154
Ben Murdoch257744e2011-11-30 15:57:28 +0000155Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
156 ThreadId thread_id = ThreadId::Current();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000157 return FindPerThreadDataForThread(thread_id);
158}
159
160
161Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
162 ThreadId thread_id) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000163 PerIsolateThreadData* per_thread = NULL;
164 {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000165 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +0100166 per_thread = thread_data_table_->Lookup(this, thread_id);
Ben Murdoch257744e2011-11-30 15:57:28 +0000167 }
168 return per_thread;
169}
170
171
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000172void Isolate::InitializeOncePerProcess() {
173 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
174 CHECK(thread_data_table_ == NULL);
175 isolate_key_ = base::Thread::CreateThreadLocalKey();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400176#if DEBUG
177 base::NoBarrier_Store(&isolate_key_created_, 1);
178#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000179 thread_id_key_ = base::Thread::CreateThreadLocalKey();
180 per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000181 thread_data_table_ = new Isolate::ThreadDataTable();
Steve Block44f0eee2011-05-26 01:26:41 +0100182}
183
184
Ben Murdoch257744e2011-11-30 15:57:28 +0000185Address Isolate::get_address_from_id(Isolate::AddressId id) {
186 return isolate_addresses_[id];
187}
188
189
190char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) {
191 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
192 Iterate(v, thread);
193 return thread_storage + sizeof(ThreadLocalTop);
194}
195
196
Ben Murdoch257744e2011-11-30 15:57:28 +0000197void Isolate::IterateThread(ThreadVisitor* v, char* t) {
198 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
199 v->VisitThread(this, thread);
200}
201
202
203void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
204 // Visit the roots from the top for a given thread.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000205 v->VisitPointer(&thread->pending_exception_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000206 v->VisitPointer(&(thread->pending_message_obj_));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000207 v->VisitPointer(bit_cast<Object**>(&(thread->context_)));
208 v->VisitPointer(&thread->scheduled_exception_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000209
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000210 for (v8::TryCatch* block = thread->try_catch_handler();
Ben Murdoch257744e2011-11-30 15:57:28 +0000211 block != NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000212 block = block->next_) {
213 v->VisitPointer(bit_cast<Object**>(&(block->exception_)));
214 v->VisitPointer(bit_cast<Object**>(&(block->message_obj_)));
Ben Murdoch257744e2011-11-30 15:57:28 +0000215 }
216
217 // Iterate over pointers on native execution stack.
218 for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
219 it.frame()->Iterate(v);
220 }
221}
222
223
224void Isolate::Iterate(ObjectVisitor* v) {
225 ThreadLocalTop* current_t = thread_local_top();
226 Iterate(v, current_t);
227}
228
229
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000230void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) {
231 for (DeferredHandles* deferred = deferred_handles_head_;
232 deferred != NULL;
233 deferred = deferred->next_) {
234 deferred->Iterate(visitor);
235 }
236}
237
238
239#ifdef DEBUG
240bool Isolate::IsDeferredHandle(Object** handle) {
241 // Each DeferredHandles instance keeps the handles to one job in the
242 // concurrent recompilation queue, containing a list of blocks. Each block
243 // contains kHandleBlockSize handles except for the first block, which may
244 // not be fully filled.
245 // We iterate through all the blocks to see whether the argument handle
246 // belongs to one of the blocks. If so, it is deferred.
247 for (DeferredHandles* deferred = deferred_handles_head_;
248 deferred != NULL;
249 deferred = deferred->next_) {
250 List<Object**>* blocks = &deferred->blocks_;
251 for (int i = 0; i < blocks->length(); i++) {
252 Object** block_limit = (i == 0) ? deferred->first_block_limit_
253 : blocks->at(i) + kHandleBlockSize;
254 if (blocks->at(i) <= handle && handle < block_limit) return true;
255 }
256 }
257 return false;
258}
259#endif // DEBUG
260
261
Ben Murdoch257744e2011-11-30 15:57:28 +0000262void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000263 thread_local_top()->set_try_catch_handler(that);
Ben Murdoch257744e2011-11-30 15:57:28 +0000264}
265
266
267void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000268 DCHECK(thread_local_top()->try_catch_handler() == that);
269 thread_local_top()->set_try_catch_handler(that->next_);
Ben Murdoch257744e2011-11-30 15:57:28 +0000270}
271
272
273Handle<String> Isolate::StackTraceString() {
274 if (stack_trace_nesting_level_ == 0) {
275 stack_trace_nesting_level_++;
276 HeapStringAllocator allocator;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000277 StringStream::ClearMentionedObjectCache(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000278 StringStream accumulator(&allocator);
279 incomplete_message_ = &accumulator;
280 PrintStack(&accumulator);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000281 Handle<String> stack_trace = accumulator.ToString(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000282 incomplete_message_ = NULL;
283 stack_trace_nesting_level_ = 0;
284 return stack_trace;
285 } else if (stack_trace_nesting_level_ == 1) {
286 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000287 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000288 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000289 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000290 "If you are lucky you may find a partial stack dump on stdout.\n\n");
291 incomplete_message_->OutputToStdOut();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000292 return factory()->empty_string();
Ben Murdoch257744e2011-11-30 15:57:28 +0000293 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000294 base::OS::Abort();
Ben Murdoch257744e2011-11-30 15:57:28 +0000295 // Unreachable
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000296 return factory()->empty_string();
Ben Murdoch257744e2011-11-30 15:57:28 +0000297 }
298}
299
300
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000301void Isolate::PushStackTraceAndDie(unsigned int magic, void* ptr1, void* ptr2,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000302 unsigned int magic2) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000303 const int kMaxStackTraceSize = 32 * KB;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000304 Handle<String> trace = StackTraceString();
305 uint8_t buffer[kMaxStackTraceSize];
306 int length = Min(kMaxStackTraceSize - 1, trace->length());
307 String::WriteToFlat(*trace, buffer, 0, length);
308 buffer[length] = '\0';
309 // TODO(dcarney): convert buffer to utf8?
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000310 base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2, ptr1,
311 ptr2, reinterpret_cast<char*>(buffer));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000312 base::OS::Abort();
313}
314
315
316// Determines whether the given stack frame should be displayed in
317// a stack trace. The caller is the error constructor that asked
318// for the stack trace to be collected. The first time a construct
319// call to this function is encountered it is skipped. The seen_caller
320// in/out parameter is used to remember if the caller has been seen
321// yet.
322static bool IsVisibleInStackTrace(JSFunction* fun,
323 Object* caller,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000324 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
Ben Murdochda12d292016-06-02 14:46:10 +0100341static Handle<FixedArray> MaybeGrow(Isolate* isolate,
342 Handle<FixedArray> elements,
343 int cur_position, int new_size) {
344 if (new_size > elements->length()) {
345 int new_capacity = JSObject::NewElementsCapacity(elements->length());
346 Handle<FixedArray> new_elements =
347 isolate->factory()->NewFixedArrayWithHoles(new_capacity);
348 for (int i = 0; i < cur_position; i++) {
349 new_elements->set(i, elements->get(i));
350 }
351 elements = new_elements;
352 }
353 DCHECK(new_size <= elements->length());
354 return elements;
355}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000356
Ben Murdochda12d292016-06-02 14:46:10 +0100357Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSReceiver> error_object,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000358 Handle<Object> caller) {
359 // Get stack trace limit.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000360 Handle<JSObject> error = error_function();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000361 Handle<String> stackTraceLimit =
362 factory()->InternalizeUtf8String("stackTraceLimit");
363 DCHECK(!stackTraceLimit.is_null());
364 Handle<Object> stack_trace_limit =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000365 JSReceiver::GetDataProperty(error, stackTraceLimit);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000366 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
367 int limit = FastD2IChecked(stack_trace_limit->Number());
368 limit = Max(limit, 0); // Ensure that limit is not negative.
369
370 int initial_size = Min(limit, 10);
371 Handle<FixedArray> elements =
372 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
373
374 // If the caller parameter is a function we skip frames until we're
375 // under it before starting to collect.
376 bool seen_caller = !caller->IsJSFunction();
377 // First element is reserved to store the number of sloppy frames.
378 int cursor = 1;
379 int frames_seen = 0;
380 int sloppy_frames = 0;
381 bool encountered_strict_function = false;
Ben Murdochda12d292016-06-02 14:46:10 +0100382 for (StackFrameIterator iter(this); !iter.done() && frames_seen < limit;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000383 iter.Advance()) {
Ben Murdochda12d292016-06-02 14:46:10 +0100384 StackFrame* frame = iter.frame();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000385
Ben Murdochda12d292016-06-02 14:46:10 +0100386 switch (frame->type()) {
387 case StackFrame::JAVA_SCRIPT:
388 case StackFrame::OPTIMIZED:
389 case StackFrame::INTERPRETED: {
390 JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame);
391 // Set initial size to the maximum inlining level + 1 for the outermost
392 // function.
393 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
394 js_frame->Summarize(&frames);
395 for (int i = frames.length() - 1; i >= 0; i--) {
396 Handle<JSFunction> fun = frames[i].function();
397 Handle<Object> recv = frames[i].receiver();
398 // Filter out internal frames that we do not want to show.
Ben Murdochc5610432016-08-08 18:44:38 +0100399 if (!IsVisibleInStackTrace(*fun, *caller, &seen_caller)) continue;
Ben Murdochda12d292016-06-02 14:46:10 +0100400 // Filter out frames from other security contexts.
401 if (!this->context()->HasSameSecurityTokenAs(fun->context())) {
402 continue;
403 }
404 elements = MaybeGrow(this, elements, cursor, cursor + 4);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100405
Ben Murdochda12d292016-06-02 14:46:10 +0100406 Handle<AbstractCode> abstract_code = frames[i].abstract_code();
407
408 Handle<Smi> offset(Smi::FromInt(frames[i].code_offset()), this);
409 // The stack trace API should not expose receivers and function
410 // objects on frames deeper than the top-most one with a strict mode
411 // function. The number of sloppy frames is stored as first element in
412 // the result array.
413 if (!encountered_strict_function) {
414 if (is_strict(fun->shared()->language_mode())) {
415 encountered_strict_function = true;
416 } else {
417 sloppy_frames++;
418 }
419 }
420 elements->set(cursor++, *recv);
421 elements->set(cursor++, *fun);
422 elements->set(cursor++, *abstract_code);
423 elements->set(cursor++, *offset);
424 frames_seen++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000425 }
Ben Murdochda12d292016-06-02 14:46:10 +0100426 } break;
427
428 case StackFrame::WASM: {
429 WasmFrame* wasm_frame = WasmFrame::cast(frame);
430 Code* code = wasm_frame->unchecked_code();
431 Handle<AbstractCode> abstract_code =
432 Handle<AbstractCode>(AbstractCode::cast(code));
Ben Murdochc5610432016-08-08 18:44:38 +0100433 int offset =
434 static_cast<int>(wasm_frame->pc() - code->instruction_start());
Ben Murdochda12d292016-06-02 14:46:10 +0100435 elements = MaybeGrow(this, elements, cursor, cursor + 4);
Ben Murdochc5610432016-08-08 18:44:38 +0100436 elements->set(cursor++, wasm_frame->wasm_obj());
437 elements->set(cursor++, Smi::FromInt(wasm_frame->function_index()));
Ben Murdochda12d292016-06-02 14:46:10 +0100438 elements->set(cursor++, *abstract_code);
Ben Murdochc5610432016-08-08 18:44:38 +0100439 elements->set(cursor++, Smi::FromInt(offset));
Ben Murdochda12d292016-06-02 14:46:10 +0100440 frames_seen++;
441 } break;
442
443 default:
444 break;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000445 }
446 }
447 elements->set(0, Smi::FromInt(sloppy_frames));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000448 elements->Shrink(cursor);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000449 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
450 result->set_length(Smi::FromInt(cursor));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000451 // TODO(yangguo): Queue this structured stack trace for preprocessing on GC.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000452 return result;
453}
454
Ben Murdochda12d292016-06-02 14:46:10 +0100455MaybeHandle<JSReceiver> Isolate::CaptureAndSetDetailedStackTrace(
456 Handle<JSReceiver> error_object) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100457 if (capture_stack_trace_for_uncaught_exceptions_) {
458 // Capture stack trace for a detailed exception message.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000459 Handle<Name> key = factory()->detailed_stack_trace_symbol();
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100460 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
461 stack_trace_for_uncaught_exceptions_frame_limit_,
462 stack_trace_for_uncaught_exceptions_options_);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000463 RETURN_ON_EXCEPTION(
Ben Murdochda12d292016-06-02 14:46:10 +0100464 this, JSReceiver::SetProperty(error_object, key, stack_trace, STRICT),
465 JSReceiver);
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100466 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000467 return error_object;
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100468}
469
Ben Murdochda12d292016-06-02 14:46:10 +0100470MaybeHandle<JSReceiver> Isolate::CaptureAndSetSimpleStackTrace(
471 Handle<JSReceiver> error_object, Handle<Object> caller) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000472 // Capture stack trace for simple stack trace string formatting.
473 Handle<Name> key = factory()->stack_trace_symbol();
474 Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000475 RETURN_ON_EXCEPTION(
Ben Murdochda12d292016-06-02 14:46:10 +0100476 this, JSReceiver::SetProperty(error_object, key, stack_trace, STRICT),
477 JSReceiver);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000478 return error_object;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000479}
480
481
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400482Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
483 Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
484 Handle<Object> stack_trace =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000485 JSReceiver::GetDataProperty(error_object, key_detailed);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400486 if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
487
488 if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
489
490 // Try to get details from simple stack trace.
491 Handle<JSArray> detailed_stack_trace =
492 GetDetailedFromSimpleStackTrace(error_object);
493 if (!detailed_stack_trace.is_null()) {
494 // Save the detailed stack since the simple one might be withdrawn later.
495 JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
496 STRICT).Assert();
497 }
498 return detailed_stack_trace;
499}
500
501
502class CaptureStackTraceHelper {
503 public:
504 CaptureStackTraceHelper(Isolate* isolate,
505 StackTrace::StackTraceOptions options)
506 : isolate_(isolate) {
507 if (options & StackTrace::kColumnOffset) {
508 column_key_ =
509 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
510 }
511 if (options & StackTrace::kLineNumber) {
512 line_key_ =
513 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
514 }
515 if (options & StackTrace::kScriptId) {
516 script_id_key_ =
517 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
518 }
519 if (options & StackTrace::kScriptName) {
520 script_name_key_ =
521 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
522 }
523 if (options & StackTrace::kScriptNameOrSourceURL) {
524 script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
525 STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
526 }
527 if (options & StackTrace::kFunctionName) {
528 function_key_ = factory()->InternalizeOneByteString(
529 STATIC_CHAR_VECTOR("functionName"));
530 }
531 if (options & StackTrace::kIsEval) {
532 eval_key_ =
533 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
534 }
535 if (options & StackTrace::kIsConstructor) {
536 constructor_key_ = factory()->InternalizeOneByteString(
537 STATIC_CHAR_VECTOR("isConstructor"));
538 }
539 }
540
Ben Murdochc5610432016-08-08 18:44:38 +0100541 Handle<JSObject> NewStackFrameObject(FrameSummary& summ) {
542 int position = summ.abstract_code()->SourcePosition(summ.code_offset());
543 return NewStackFrameObject(summ.function(), position,
544 summ.is_constructor());
545 }
546
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000547 Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun, int position,
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400548 bool is_constructor) {
549 Handle<JSObject> stack_frame =
550 factory()->NewJSObject(isolate_->object_function());
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400551 Handle<Script> script(Script::cast(fun->shared()->script()));
552
553 if (!line_key_.is_null()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000554 int script_line_offset = script->line_offset();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400555 int line_number = Script::GetLineNumber(script, position);
556 // line_number is already shifted by the script_line_offset.
557 int relative_line_number = line_number - script_line_offset;
558 if (!column_key_.is_null() && relative_line_number >= 0) {
559 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
Ben Murdochc5610432016-08-08 18:44:38 +0100560 int start =
561 (relative_line_number == 0)
562 ? 0
563 : Smi::cast(line_ends->get(relative_line_number - 1))->value() +
564 1;
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400565 int column_offset = position - start;
566 if (relative_line_number == 0) {
Ben Murdochc5610432016-08-08 18:44:38 +0100567 // For the case where the code is on the same line as the script tag.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000568 column_offset += script->column_offset();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400569 }
570 JSObject::AddProperty(stack_frame, column_key_,
571 handle(Smi::FromInt(column_offset + 1), isolate_),
572 NONE);
573 }
574 JSObject::AddProperty(stack_frame, line_key_,
575 handle(Smi::FromInt(line_number + 1), isolate_),
576 NONE);
577 }
578
579 if (!script_id_key_.is_null()) {
580 JSObject::AddProperty(stack_frame, script_id_key_,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000581 handle(Smi::FromInt(script->id()), isolate_), NONE);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400582 }
583
584 if (!script_name_key_.is_null()) {
585 JSObject::AddProperty(stack_frame, script_name_key_,
586 handle(script->name(), isolate_), NONE);
587 }
588
589 if (!script_name_or_source_url_key_.is_null()) {
590 Handle<Object> result = Script::GetNameOrSourceURL(script);
591 JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
592 NONE);
593 }
594
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400595 if (!eval_key_.is_null()) {
596 Handle<Object> is_eval = factory()->ToBoolean(
597 script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
598 JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
599 }
600
Ben Murdochc5610432016-08-08 18:44:38 +0100601 if (!function_key_.is_null()) {
602 Handle<Object> fun_name = JSFunction::GetDebugName(fun);
603 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
604 }
605
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400606 if (!constructor_key_.is_null()) {
607 Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
608 JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
609 NONE);
610 }
Ben Murdochc5610432016-08-08 18:44:38 +0100611 return stack_frame;
612 }
613
614 Handle<JSObject> NewStackFrameObject(WasmFrame* frame) {
615 Handle<JSObject> stack_frame =
616 factory()->NewJSObject(isolate_->object_function());
617
618 if (!function_key_.is_null()) {
619 Handle<Object> fun_name = handle(frame->function_name(), isolate_);
620 if (fun_name->IsUndefined())
621 fun_name = isolate_->factory()->InternalizeUtf8String(
622 Vector<const char>("<WASM>"));
623 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
624 }
625 // Encode the function index as line number.
626 if (!line_key_.is_null()) {
627 JSObject::AddProperty(
628 stack_frame, line_key_,
629 isolate_->factory()->NewNumberFromInt(frame->function_index()), NONE);
630 }
631 // Encode the byte offset as column.
632 if (!column_key_.is_null()) {
633 Code* code = frame->LookupCode();
634 int offset = static_cast<int>(frame->pc() - code->instruction_start());
635 int position = code->SourcePosition(offset);
636 JSObject::AddProperty(stack_frame, column_key_,
637 isolate_->factory()->NewNumberFromInt(position),
638 NONE);
639 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400640
641 return stack_frame;
642 }
643
644 private:
645 inline Factory* factory() { return isolate_->factory(); }
646
647 Isolate* isolate_;
648 Handle<String> column_key_;
649 Handle<String> line_key_;
650 Handle<String> script_id_key_;
651 Handle<String> script_name_key_;
652 Handle<String> script_name_or_source_url_key_;
653 Handle<String> function_key_;
654 Handle<String> eval_key_;
655 Handle<String> constructor_key_;
656};
657
658
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000659int PositionFromStackTrace(Handle<FixedArray> elements, int index) {
660 DisallowHeapAllocation no_gc;
661 Object* maybe_code = elements->get(index + 2);
662 if (maybe_code->IsSmi()) {
663 return Smi::cast(maybe_code)->value();
664 } else {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100665 AbstractCode* abstract_code = AbstractCode::cast(maybe_code);
666 int code_offset = Smi::cast(elements->get(index + 3))->value();
667 return abstract_code->SourcePosition(code_offset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000668 }
669}
670
671
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400672Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
673 Handle<JSObject> error_object) {
674 Handle<Name> key = factory()->stack_trace_symbol();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000675 Handle<Object> property = JSReceiver::GetDataProperty(error_object, key);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400676 if (!property->IsJSArray()) return Handle<JSArray>();
677 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
678
679 CaptureStackTraceHelper helper(this,
680 stack_trace_for_uncaught_exceptions_options_);
681
682 int frames_seen = 0;
683 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
684 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
685
686 int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
687 if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
688
689 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
690 for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
691 Handle<Object> recv = handle(elements->get(i), this);
692 Handle<JSFunction> fun =
693 handle(JSFunction::cast(elements->get(i + 1)), this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400694 bool is_constructor =
695 recv->IsJSObject() &&
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000696 Handle<JSObject>::cast(recv)->map()->GetConstructor() == *fun;
697 int position = PositionFromStackTrace(elements, i);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400698
699 Handle<JSObject> stack_frame =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000700 helper.NewStackFrameObject(fun, position, is_constructor);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400701
702 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
703 frames_seen++;
704 }
705
706 stack_trace->set_length(Smi::FromInt(frames_seen));
707 return stack_trace;
708}
709
710
Ben Murdoch257744e2011-11-30 15:57:28 +0000711Handle<JSArray> Isolate::CaptureCurrentStackTrace(
712 int frame_limit, StackTrace::StackTraceOptions options) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400713 CaptureStackTraceHelper helper(this, options);
714
Ben Murdoch257744e2011-11-30 15:57:28 +0000715 // Ensure no negative values.
716 int limit = Max(frame_limit, 0);
717 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
Ben Murdochc5610432016-08-08 18:44:38 +0100718 Handle<FixedArray> stack_trace_elems(
719 FixedArray::cast(stack_trace->elements()), this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000720
Ben Murdoch257744e2011-11-30 15:57:28 +0000721 int frames_seen = 0;
Ben Murdochc5610432016-08-08 18:44:38 +0100722 for (StackTraceFrameIterator it(this); !it.done() && (frames_seen < limit);
723 it.Advance()) {
724 StandardFrame* frame = it.frame();
725 if (frame->is_java_script()) {
726 // Set initial size to the maximum inlining level + 1 for the outermost
727 // function.
728 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
729 JavaScriptFrame::cast(frame)->Summarize(&frames);
730 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
731 Handle<JSFunction> fun = frames[i].function();
732 // Filter frames from other security contexts.
733 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
734 !this->context()->HasSameSecurityTokenAs(fun->context()))
735 continue;
736 Handle<JSObject> new_frame_obj = helper.NewStackFrameObject(frames[i]);
737 stack_trace_elems->set(frames_seen, *new_frame_obj);
738 frames_seen++;
739 }
740 } else {
741 WasmFrame* wasm_frame = WasmFrame::cast(frame);
742 Handle<JSObject> new_frame_obj = helper.NewStackFrameObject(wasm_frame);
743 stack_trace_elems->set(frames_seen, *new_frame_obj);
Ben Murdoch257744e2011-11-30 15:57:28 +0000744 frames_seen++;
745 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000746 }
747
748 stack_trace->set_length(Smi::FromInt(frames_seen));
749 return stack_trace;
750}
751
752
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000753void Isolate::PrintStack(FILE* out, PrintStackMode mode) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000754 if (stack_trace_nesting_level_ == 0) {
755 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000756 StringStream::ClearMentionedObjectCache(this);
757 HeapStringAllocator allocator;
758 StringStream accumulator(&allocator);
Ben Murdoch257744e2011-11-30 15:57:28 +0000759 incomplete_message_ = &accumulator;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000760 PrintStack(&accumulator, mode);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000761 accumulator.OutputToFile(out);
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000762 InitializeLoggingAndCounters();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000763 accumulator.Log(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000764 incomplete_message_ = NULL;
765 stack_trace_nesting_level_ = 0;
Ben Murdoch257744e2011-11-30 15:57:28 +0000766 } else if (stack_trace_nesting_level_ == 1) {
767 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000768 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000769 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000770 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000771 "If you are lucky you may find a partial stack dump on stdout.\n\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000772 incomplete_message_->OutputToFile(out);
Ben Murdoch257744e2011-11-30 15:57:28 +0000773 }
774}
775
776
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000777static void PrintFrames(Isolate* isolate,
778 StringStream* accumulator,
Ben Murdoch257744e2011-11-30 15:57:28 +0000779 StackFrame::PrintMode mode) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000780 StackFrameIterator it(isolate);
Ben Murdoch257744e2011-11-30 15:57:28 +0000781 for (int i = 0; !it.done(); it.Advance()) {
782 it.frame()->Print(accumulator, mode, i++);
783 }
784}
785
786
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000787void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000788 // The MentionedObjectCache is not GC-proof at the moment.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000789 DisallowHeapAllocation no_gc;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000790 DCHECK(accumulator->IsMentionedObjectCacheClear(this));
Ben Murdoch257744e2011-11-30 15:57:28 +0000791
792 // Avoid printing anything if there are no frames.
793 if (c_entry_fp(thread_local_top()) == 0) return;
794
795 accumulator->Add(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000796 "\n==== JS stack trace =========================================\n\n");
797 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000798 if (mode == kPrintStackVerbose) {
799 accumulator->Add(
800 "\n==== Details ================================================\n\n");
801 PrintFrames(this, accumulator, StackFrame::DETAILS);
802 accumulator->PrintMentionedObjectCache(this);
803 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000804 accumulator->Add("=====================\n\n");
805}
806
807
808void Isolate::SetFailedAccessCheckCallback(
809 v8::FailedAccessCheckCallback callback) {
810 thread_local_top()->failed_access_check_callback_ = callback;
811}
812
813
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000814static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
815 Handle<JSObject> receiver) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000816 Object* maybe_constructor = receiver->map()->GetConstructor();
817 if (!maybe_constructor->IsJSFunction()) return NULL;
818 JSFunction* constructor = JSFunction::cast(maybe_constructor);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000819 if (!constructor->shared()->IsApiFunction()) return NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +0000820
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000821 Object* data_obj =
822 constructor->shared()->get_api_func_data()->access_check_info();
823 if (data_obj == isolate->heap()->undefined_value()) return NULL;
824
825 return AccessCheckInfo::cast(data_obj);
826}
827
828
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000829void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000830 if (!thread_local_top()->failed_access_check_callback_) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000831 return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000832 }
833
834 DCHECK(receiver->IsAccessCheckNeeded());
835 DCHECK(context());
Ben Murdoch257744e2011-11-30 15:57:28 +0000836
837 // Get the data object from access check info.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000838 HandleScope scope(this);
839 Handle<Object> data;
840 { DisallowHeapAllocation no_gc;
841 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000842 if (!access_check_info) {
843 AllowHeapAllocation doesnt_matter_anymore;
844 return ScheduleThrow(
845 *factory()->NewTypeError(MessageTemplate::kNoAccess));
846 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000847 data = handle(access_check_info->data(), this);
848 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000849
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000850 // Leaving JavaScript.
851 VMState<EXTERNAL> state(this);
852 thread_local_top()->failed_access_check_callback_(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000853 v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000854}
855
856
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000857bool Isolate::MayAccess(Handle<Context> accessing_context,
858 Handle<JSObject> receiver) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000859 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
Ben Murdoch257744e2011-11-30 15:57:28 +0000860
Ben Murdoch257744e2011-11-30 15:57:28 +0000861 // Check for compatibility between the security tokens in the
862 // current lexical context and the accessed object.
Ben Murdoch257744e2011-11-30 15:57:28 +0000863
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000864 // During bootstrapping, callback functions are not enabled yet.
865 if (bootstrapper()->IsActive()) return true;
866 {
867 DisallowHeapAllocation no_gc;
868
869 if (receiver->IsJSGlobalProxy()) {
870 Object* receiver_context =
871 JSGlobalProxy::cast(*receiver)->native_context();
872 if (!receiver_context->IsContext()) return false;
873
874 // Get the native context of current top context.
875 // avoid using Isolate::native_context() because it uses Handle.
876 Context* native_context =
877 accessing_context->global_object()->native_context();
878 if (receiver_context == native_context) return true;
879
880 if (Context::cast(receiver_context)->security_token() ==
881 native_context->security_token())
882 return true;
883 }
884 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000885
Ben Murdoch257744e2011-11-30 15:57:28 +0000886 HandleScope scope(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000887 Handle<Object> data;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000888 v8::AccessCheckCallback callback = nullptr;
889 v8::NamedSecurityCallback named_callback = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000890 { DisallowHeapAllocation no_gc;
891 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
892 if (!access_check_info) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000893 Object* fun_obj = access_check_info->callback();
894 callback = v8::ToCData<v8::AccessCheckCallback>(fun_obj);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100895 data = handle(access_check_info->data(), this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000896 if (!callback) {
897 fun_obj = access_check_info->named_callback();
898 named_callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
899 if (!named_callback) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000900 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000901 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000902
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000903 LOG(this, ApiSecurityCheck());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000904
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000905 {
906 // Leaving JavaScript.
907 VMState<EXTERNAL> state(this);
908 if (callback) {
909 return callback(v8::Utils::ToLocal(accessing_context),
Ben Murdoch097c5b22016-05-18 11:27:45 +0100910 v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(data));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000911 }
912 Handle<Object> key = factory()->undefined_value();
913 return named_callback(v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(key),
914 v8::ACCESS_HAS, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000915 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000916}
917
918
919const char* const Isolate::kStackOverflowMessage =
920 "Uncaught RangeError: Maximum call stack size exceeded";
921
922
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000923Object* Isolate::StackOverflow() {
924 HandleScope scope(this);
925 // At this point we cannot create an Error object using its javascript
926 // constructor. Instead, we copy the pre-constructed boilerplate and
927 // attach the stack trace as a hidden property.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000928 Handle<Object> exception;
929 if (bootstrapper()->IsActive()) {
930 // There is no boilerplate to use during bootstrapping.
931 exception = factory()->NewStringFromAsciiChecked(
932 MessageTemplate::TemplateString(MessageTemplate::kStackOverflow));
933 } else {
934 Handle<JSObject> boilerplate = stack_overflow_boilerplate();
935 Handle<JSObject> copy = factory()->CopyJSObject(boilerplate);
936 CaptureAndSetSimpleStackTrace(copy, factory()->undefined_value());
937 exception = copy;
938 }
939 Throw(*exception, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000940
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000941#ifdef VERIFY_HEAP
942 if (FLAG_verify_heap && FLAG_stress_compaction) {
Ben Murdochda12d292016-06-02 14:46:10 +0100943 heap()->CollectAllGarbage(Heap::kNoGCFlags, "trigger compaction");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000944 }
945#endif // VERIFY_HEAP
946
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000947 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000948}
949
950
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000951Object* Isolate::TerminateExecution() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000952 return Throw(heap_.termination_exception(), nullptr);
Ben Murdoch257744e2011-11-30 15:57:28 +0000953}
954
955
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000956void Isolate::CancelTerminateExecution() {
957 if (try_catch_handler()) {
958 try_catch_handler()->has_terminated_ = false;
959 }
960 if (has_pending_exception() &&
961 pending_exception() == heap_.termination_exception()) {
962 thread_local_top()->external_caught_exception_ = false;
963 clear_pending_exception();
964 }
965 if (has_scheduled_exception() &&
966 scheduled_exception() == heap_.termination_exception()) {
967 thread_local_top()->external_caught_exception_ = false;
968 clear_scheduled_exception();
969 }
970}
971
972
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400973void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
974 ExecutionAccess access(this);
975 api_interrupts_queue_.push(InterruptEntry(callback, data));
976 stack_guard()->RequestApiInterrupt();
977}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000978
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400979
980void Isolate::InvokeApiInterruptCallbacks() {
981 // Note: callback below should be called outside of execution access lock.
982 while (true) {
983 InterruptEntry entry;
984 {
985 ExecutionAccess access(this);
986 if (api_interrupts_queue_.empty()) return;
987 entry = api_interrupts_queue_.front();
988 api_interrupts_queue_.pop();
989 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000990 VMState<EXTERNAL> state(this);
991 HandleScope handle_scope(this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400992 entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000993 }
994}
995
996
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000997void ReportBootstrappingException(Handle<Object> exception,
998 MessageLocation* location) {
999 base::OS::PrintError("Exception thrown during bootstrapping\n");
1000 if (location == NULL || location->script().is_null()) return;
1001 // We are bootstrapping and caught an error where the location is set
1002 // and we have a script for the location.
1003 // In this case we could have an extension (or an internal error
1004 // somewhere) and we print out the line number at which the error occured
1005 // to the console for easier debugging.
1006 int line_number =
1007 location->script()->GetLineNumber(location->start_pos()) + 1;
1008 if (exception->IsString() && location->script()->name()->IsString()) {
1009 base::OS::PrintError(
1010 "Extension or internal compilation error: %s in %s at line %d.\n",
1011 String::cast(*exception)->ToCString().get(),
1012 String::cast(location->script()->name())->ToCString().get(),
1013 line_number);
1014 } else if (location->script()->name()->IsString()) {
1015 base::OS::PrintError(
1016 "Extension or internal compilation error in %s at line %d.\n",
1017 String::cast(location->script()->name())->ToCString().get(),
1018 line_number);
1019 } else if (exception->IsString()) {
1020 base::OS::PrintError("Extension or internal compilation error: %s.\n",
1021 String::cast(*exception)->ToCString().get());
1022 } else {
1023 base::OS::PrintError("Extension or internal compilation error.\n");
1024 }
1025#ifdef OBJECT_PRINT
1026 // Since comments and empty lines have been stripped from the source of
1027 // builtins, print the actual source here so that line numbers match.
1028 if (location->script()->source()->IsString()) {
1029 Handle<String> src(String::cast(location->script()->source()));
1030 PrintF("Failing script:");
1031 int len = src->length();
1032 if (len == 0) {
1033 PrintF(" <not available>\n");
1034 } else {
1035 PrintF("\n");
1036 int line_number = 1;
1037 PrintF("%5d: ", line_number);
1038 for (int i = 0; i < len; i++) {
1039 uint16_t character = src->Get(i);
1040 PrintF("%c", character);
1041 if (character == '\n' && i < len - 2) {
1042 PrintF("%5d: ", ++line_number);
1043 }
1044 }
1045 PrintF("\n");
1046 }
1047 }
1048#endif
1049}
1050
1051
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001052Object* Isolate::Throw(Object* exception, MessageLocation* location) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001053 DCHECK(!has_pending_exception());
1054
1055 HandleScope scope(this);
1056 Handle<Object> exception_handle(exception, this);
1057
1058 // Determine whether a message needs to be created for the given exception
1059 // depending on the following criteria:
1060 // 1) External v8::TryCatch missing: Always create a message because any
1061 // JavaScript handler for a finally-block might re-throw to top-level.
1062 // 2) External v8::TryCatch exists: Only create a message if the handler
1063 // captures messages or is verbose (which reports despite the catch).
1064 // 3) ReThrow from v8::TryCatch: The message from a previous throw still
1065 // exists and we preserve it instead of creating a new message.
1066 bool requires_message = try_catch_handler() == nullptr ||
1067 try_catch_handler()->is_verbose_ ||
1068 try_catch_handler()->capture_message_;
1069 bool rethrowing_message = thread_local_top()->rethrowing_message_;
1070
1071 thread_local_top()->rethrowing_message_ = false;
1072
1073 // Notify debugger of exception.
1074 if (is_catchable_by_javascript(exception)) {
1075 debug()->OnThrow(exception_handle);
1076 }
1077
1078 // Generate the message if required.
1079 if (requires_message && !rethrowing_message) {
1080 MessageLocation computed_location;
1081 // If no location was specified we try to use a computed one instead.
1082 if (location == NULL && ComputeLocation(&computed_location)) {
1083 location = &computed_location;
1084 }
1085
1086 if (bootstrapper()->IsActive()) {
1087 // It's not safe to try to make message objects or collect stack traces
1088 // while the bootstrapper is active since the infrastructure may not have
1089 // been properly initialized.
1090 ReportBootstrappingException(exception_handle, location);
1091 } else {
1092 Handle<Object> message_obj = CreateMessage(exception_handle, location);
1093 thread_local_top()->pending_message_obj_ = *message_obj;
1094
1095 // For any exception not caught by JavaScript, even when an external
1096 // handler is present:
1097 // If the abort-on-uncaught-exception flag is specified, and if the
1098 // embedder didn't specify a custom uncaught exception callback,
1099 // or if the custom callback determined that V8 should abort, then
1100 // abort.
1101 if (FLAG_abort_on_uncaught_exception &&
1102 PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT &&
1103 (!abort_on_uncaught_exception_callback_ ||
1104 abort_on_uncaught_exception_callback_(
1105 reinterpret_cast<v8::Isolate*>(this)))) {
1106 // Prevent endless recursion.
1107 FLAG_abort_on_uncaught_exception = false;
1108 // This flag is intended for use by JavaScript developers, so
1109 // print a user-friendly stack trace (not an internal one).
1110 PrintF(stderr, "%s\n\nFROM\n",
1111 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1112 PrintCurrentStackTrace(stderr);
1113 base::OS::Abort();
1114 }
1115 }
1116 }
1117
1118 // Set the exception being thrown.
1119 set_pending_exception(*exception_handle);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001120 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001121}
1122
1123
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001124Object* Isolate::ReThrow(Object* exception) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001125 DCHECK(!has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001126
1127 // Set the exception being re-thrown.
1128 set_pending_exception(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001129 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001130}
1131
1132
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001133Object* Isolate::UnwindAndFindHandler() {
1134 Object* exception = pending_exception();
1135
1136 Code* code = nullptr;
1137 Context* context = nullptr;
1138 intptr_t offset = 0;
1139 Address handler_sp = nullptr;
1140 Address handler_fp = nullptr;
1141
1142 // Special handling of termination exceptions, uncatchable by JavaScript code,
1143 // we unwind the handlers until the top ENTRY handler is found.
1144 bool catchable_by_js = is_catchable_by_javascript(exception);
1145
1146 // Compute handler and stack unwinding information by performing a full walk
1147 // over the stack and dispatching according to the frame type.
1148 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1149 StackFrame* frame = iter.frame();
1150
1151 // For JSEntryStub frames we always have a handler.
1152 if (frame->is_entry() || frame->is_entry_construct()) {
1153 StackHandler* handler = frame->top_handler();
1154
1155 // Restore the next handler.
1156 thread_local_top()->handler_ = handler->next()->address();
1157
1158 // Gather information from the handler.
1159 code = frame->LookupCode();
1160 handler_sp = handler->address() + StackHandlerConstants::kSize;
1161 offset = Smi::cast(code->handler_table()->get(0))->value();
1162 break;
1163 }
1164
1165 // For optimized frames we perform a lookup in the handler table.
1166 if (frame->is_optimized() && catchable_by_js) {
1167 OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
1168 int stack_slots = 0; // Will contain stack slot count of frame.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001169 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, nullptr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001170 if (offset >= 0) {
1171 // Compute the stack pointer from the frame pointer. This ensures that
1172 // argument slots on the stack are dropped as returning would.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001173 Address return_sp = frame->fp() +
1174 StandardFrameConstants::kFixedFrameSizeAboveFp -
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001175 stack_slots * kPointerSize;
1176
1177 // Gather information from the frame.
1178 code = frame->LookupCode();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001179 if (code->marked_for_deoptimization()) {
1180 // If the target code is lazy deoptimized, we jump to the original
1181 // return address, but we make a note that we are throwing, so that
1182 // the deoptimizer can do the right thing.
1183 offset = static_cast<int>(frame->pc() - code->entry());
1184 set_deoptimizer_lazy_throw(true);
1185 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001186 handler_sp = return_sp;
1187 handler_fp = frame->fp();
1188 break;
1189 }
1190 }
1191
Ben Murdoch097c5b22016-05-18 11:27:45 +01001192 // For interpreted frame we perform a range lookup in the handler table.
1193 if (frame->is_interpreted() && catchable_by_js) {
1194 InterpretedFrame* js_frame = static_cast<InterpretedFrame*>(frame);
1195 int context_reg = 0; // Will contain register index holding context.
1196 offset = js_frame->LookupExceptionHandlerInTable(&context_reg, nullptr);
1197 if (offset >= 0) {
1198 // Patch the bytecode offset in the interpreted frame to reflect the
1199 // position of the exception handler. The special builtin below will
1200 // take care of continuing to dispatch at that position. Also restore
1201 // the correct context for the handler from the interpreter register.
Ben Murdochc5610432016-08-08 18:44:38 +01001202 context = Context::cast(js_frame->ReadInterpreterRegister(context_reg));
Ben Murdoch097c5b22016-05-18 11:27:45 +01001203 js_frame->PatchBytecodeOffset(static_cast<int>(offset));
1204 offset = 0;
1205
1206 // Gather information from the frame.
1207 code = *builtins()->InterpreterEnterBytecodeDispatch();
1208 handler_sp = frame->sp();
1209 handler_fp = frame->fp();
1210 break;
1211 }
1212 }
1213
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001214 // For JavaScript frames we perform a range lookup in the handler table.
1215 if (frame->is_java_script() && catchable_by_js) {
1216 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001217 int stack_depth = 0; // Will contain operand stack depth of handler.
1218 offset = js_frame->LookupExceptionHandlerInTable(&stack_depth, nullptr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001219 if (offset >= 0) {
1220 // Compute the stack pointer from the frame pointer. This ensures that
1221 // operand stack slots are dropped for nested statements. Also restore
1222 // correct context for the handler which is pushed within the try-block.
1223 Address return_sp = frame->fp() -
1224 StandardFrameConstants::kFixedFrameSizeFromFp -
Ben Murdoch097c5b22016-05-18 11:27:45 +01001225 stack_depth * kPointerSize;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001226 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1227 context = Context::cast(Memory::Object_at(return_sp - kPointerSize));
1228
1229 // Gather information from the frame.
1230 code = frame->LookupCode();
1231 handler_sp = return_sp;
1232 handler_fp = frame->fp();
1233 break;
1234 }
1235 }
1236
1237 RemoveMaterializedObjectsOnUnwind(frame);
1238 }
1239
1240 // Handler must exist.
1241 CHECK(code != nullptr);
1242
1243 // Store information to be consumed by the CEntryStub.
1244 thread_local_top()->pending_handler_context_ = context;
1245 thread_local_top()->pending_handler_code_ = code;
1246 thread_local_top()->pending_handler_offset_ = offset;
1247 thread_local_top()->pending_handler_fp_ = handler_fp;
1248 thread_local_top()->pending_handler_sp_ = handler_sp;
1249
1250 // Return and clear pending exception.
1251 clear_pending_exception();
1252 return exception;
1253}
1254
1255
1256Isolate::CatchType Isolate::PredictExceptionCatcher() {
1257 Address external_handler = thread_local_top()->try_catch_handler_address();
1258 Address entry_handler = Isolate::handler(thread_local_top());
1259 if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL;
1260
1261 // Search for an exception handler by performing a full walk over the stack.
1262 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1263 StackFrame* frame = iter.frame();
1264
1265 // For JSEntryStub frames we update the JS_ENTRY handler.
1266 if (frame->is_entry() || frame->is_entry_construct()) {
1267 entry_handler = frame->top_handler()->next()->address();
1268 }
1269
1270 // For JavaScript frames we perform a lookup in the handler table.
1271 if (frame->is_java_script()) {
1272 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001273 HandlerTable::CatchPrediction prediction;
Ben Murdoch097c5b22016-05-18 11:27:45 +01001274 if (js_frame->LookupExceptionHandlerInTable(nullptr, &prediction) > 0) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001275 // We are conservative with our prediction: try-finally is considered
1276 // to always rethrow, to meet the expectation of the debugger.
1277 if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT;
1278 }
1279 }
1280
1281 // The exception has been externally caught if and only if there is an
1282 // external handler which is on top of the top-most JS_ENTRY handler.
1283 if (external_handler != nullptr && !try_catch_handler()->is_verbose_) {
1284 if (entry_handler == nullptr || entry_handler > external_handler) {
1285 return CAUGHT_BY_EXTERNAL;
1286 }
1287 }
1288 }
1289
1290 // Handler not found.
1291 return NOT_CAUGHT;
1292}
1293
1294
1295void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) {
1296 if (frame->is_optimized()) {
1297 bool removed = materialized_object_store_->Remove(frame->fp());
1298 USE(removed);
1299 // If there were any materialized objects, the code should be
1300 // marked for deopt.
1301 DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization());
1302 }
1303}
1304
1305
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001306Object* Isolate::ThrowIllegalOperation() {
1307 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001308 return Throw(heap()->illegal_access_string());
Ben Murdoch257744e2011-11-30 15:57:28 +00001309}
1310
1311
1312void Isolate::ScheduleThrow(Object* exception) {
1313 // When scheduling a throw we first throw the exception to get the
1314 // error reporting if it is uncaught before rescheduling it.
1315 Throw(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001316 PropagatePendingExceptionToExternalTryCatch();
1317 if (has_pending_exception()) {
1318 thread_local_top()->scheduled_exception_ = pending_exception();
1319 thread_local_top()->external_caught_exception_ = false;
1320 clear_pending_exception();
1321 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001322}
1323
1324
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001325void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1326 DCHECK(handler == try_catch_handler());
1327 DCHECK(handler->HasCaught());
1328 DCHECK(handler->rethrow_);
1329 DCHECK(handler->capture_message_);
1330 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001331 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001332 thread_local_top()->pending_message_obj_ = message;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001333}
1334
1335
1336void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1337 DCHECK(has_scheduled_exception());
1338 if (scheduled_exception() == handler->exception_) {
1339 DCHECK(scheduled_exception() != heap()->termination_exception());
1340 clear_scheduled_exception();
1341 }
1342}
1343
1344
1345Object* Isolate::PromoteScheduledException() {
1346 Object* thrown = scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001347 clear_scheduled_exception();
1348 // Re-throw the exception to avoid getting repeated error reporting.
1349 return ReThrow(thrown);
1350}
1351
1352
1353void Isolate::PrintCurrentStackTrace(FILE* out) {
1354 StackTraceFrameIterator it(this);
1355 while (!it.done()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001356 HandleScope scope(this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001357 // Find code position if recorded in relocation info.
Ben Murdochc5610432016-08-08 18:44:38 +01001358 StandardFrame* frame = it.frame();
1359 int pos;
1360 if (frame->is_interpreted()) {
1361 InterpretedFrame* iframe = reinterpret_cast<InterpretedFrame*>(frame);
1362 pos = iframe->GetBytecodeArray()->SourcePosition(
1363 iframe->GetBytecodeOffset());
1364 } else if (frame->is_java_script()) {
1365 Code* code = frame->LookupCode();
1366 int offset = static_cast<int>(frame->pc() - code->instruction_start());
1367 pos = frame->LookupCode()->SourcePosition(offset);
1368 } else {
1369 DCHECK(frame->is_wasm());
1370 // TODO(clemensh): include wasm frames here
1371 continue;
1372 }
1373 JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001374 Handle<Object> pos_obj(Smi::FromInt(pos), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001375 // Fetch function and receiver.
Ben Murdochc5610432016-08-08 18:44:38 +01001376 Handle<JSFunction> fun(js_frame->function());
1377 Handle<Object> recv(js_frame->receiver(), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001378 // Advance to the next JavaScript frame and determine if the
1379 // current frame is the top-level frame.
1380 it.Advance();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001381 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
Ben Murdoch257744e2011-11-30 15:57:28 +00001382 // Generate and print stack trace line.
1383 Handle<String> line =
1384 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1385 if (line->length() > 0) {
1386 line->PrintOn(out);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001387 PrintF(out, "\n");
Ben Murdoch257744e2011-11-30 15:57:28 +00001388 }
1389 }
1390}
1391
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001392bool Isolate::ComputeLocation(MessageLocation* target) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001393 StackTraceFrameIterator it(this);
Ben Murdochc5610432016-08-08 18:44:38 +01001394 if (it.done()) return false;
1395 StandardFrame* frame = it.frame();
1396 // TODO(clemensh): handle wasm frames
1397 if (!frame->is_java_script()) return false;
1398 JSFunction* fun = JavaScriptFrame::cast(frame)->function();
1399 Object* script = fun->shared()->script();
1400 if (!script->IsScript() || (Script::cast(script)->source()->IsUndefined())) {
1401 return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001402 }
Ben Murdochc5610432016-08-08 18:44:38 +01001403 Handle<Script> casted_script(Script::cast(script));
1404 // Compute the location from the function and the relocation info of the
1405 // baseline code. For optimized code this will use the deoptimization
1406 // information to get canonical location information.
1407 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
1408 JavaScriptFrame::cast(frame)->Summarize(&frames);
1409 FrameSummary& summary = frames.last();
1410 int pos = summary.abstract_code()->SourcePosition(summary.code_offset());
1411 *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1412 return true;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001413}
1414
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001415bool Isolate::ComputeLocationFromException(MessageLocation* target,
1416 Handle<Object> exception) {
1417 if (!exception->IsJSObject()) return false;
1418
1419 Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1420 Handle<Object> start_pos = JSReceiver::GetDataProperty(
1421 Handle<JSObject>::cast(exception), start_pos_symbol);
1422 if (!start_pos->IsSmi()) return false;
1423 int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1424
1425 Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1426 Handle<Object> end_pos = JSReceiver::GetDataProperty(
1427 Handle<JSObject>::cast(exception), end_pos_symbol);
1428 if (!end_pos->IsSmi()) return false;
1429 int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1430
1431 Handle<Name> script_symbol = factory()->error_script_symbol();
1432 Handle<Object> script = JSReceiver::GetDataProperty(
1433 Handle<JSObject>::cast(exception), script_symbol);
1434 if (!script->IsScript()) return false;
1435
1436 Handle<Script> cast_script(Script::cast(*script));
1437 *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1438 return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001439}
1440
1441
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001442bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1443 Handle<Object> exception) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001444 if (!exception->IsJSObject()) return false;
1445 Handle<Name> key = factory()->stack_trace_symbol();
1446 Handle<Object> property =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001447 JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001448 if (!property->IsJSArray()) return false;
1449 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1450
1451 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1452 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1453
1454 for (int i = 1; i < elements_limit; i += 4) {
Ben Murdochc5610432016-08-08 18:44:38 +01001455 Handle<Object> fun_obj = handle(elements->get(i + 1), this);
1456 if (fun_obj->IsSmi()) {
1457 // TODO(clemensh): handle wasm frames
1458 return false;
1459 }
1460 Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001461 if (!fun->shared()->IsSubjectToDebugging()) continue;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001462
1463 Object* script = fun->shared()->script();
1464 if (script->IsScript() &&
1465 !(Script::cast(script)->source()->IsUndefined())) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001466 int pos = PositionFromStackTrace(elements, i);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001467 Handle<Script> casted_script(Script::cast(script));
1468 *target = MessageLocation(casted_script, pos, pos + 1);
1469 return true;
1470 }
1471 }
1472 return false;
1473}
1474
1475
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001476Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1477 MessageLocation* location) {
1478 Handle<JSArray> stack_trace_object;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001479 if (capture_stack_trace_for_uncaught_exceptions_) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001480 if (Object::IsErrorObject(this, exception)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001481 // We fetch the stack trace that corresponds to this error object.
1482 // If the lookup fails, the exception is probably not a valid Error
1483 // object. In that case, we fall through and capture the stack trace
1484 // at this throw site.
1485 stack_trace_object =
1486 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1487 }
1488 if (stack_trace_object.is_null()) {
1489 // Not an error object, we capture stack and location at throw site.
1490 stack_trace_object = CaptureCurrentStackTrace(
1491 stack_trace_for_uncaught_exceptions_frame_limit_,
1492 stack_trace_for_uncaught_exceptions_options_);
1493 }
1494 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001495 MessageLocation computed_location;
1496 if (location == NULL &&
1497 (ComputeLocationFromException(&computed_location, exception) ||
1498 ComputeLocationFromStackTrace(&computed_location, exception) ||
1499 ComputeLocation(&computed_location))) {
1500 location = &computed_location;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001501 }
1502
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001503 return MessageHandler::MakeMessageObject(
1504 this, MessageTemplate::kUncaughtException, location, exception,
1505 stack_trace_object);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001506}
1507
1508
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001509bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) {
1510 DCHECK_NE(heap()->the_hole_value(), exception);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001511
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001512 // For uncatchable exceptions, the JavaScript handler cannot be on top.
1513 if (!is_catchable_by_javascript(exception)) return false;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001514
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001515 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1516 Address entry_handler = Isolate::handler(thread_local_top());
1517 if (entry_handler == nullptr) return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001518
Ben Murdoch257744e2011-11-30 15:57:28 +00001519 // Get the address of the external handler so we can compare the address to
1520 // determine which one is closer to the top of the stack.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001521 Address external_handler = thread_local_top()->try_catch_handler_address();
1522 if (external_handler == nullptr) return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001523
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001524 // The exception has been externally caught if and only if there is an
1525 // external handler which is on top of the top-most JS_ENTRY handler.
Ben Murdoch257744e2011-11-30 15:57:28 +00001526 //
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001527 // Note, that finally clauses would re-throw an exception unless it's aborted
1528 // by jumps in control flow (like return, break, etc.) and we'll have another
1529 // chance to set proper v8::TryCatch later.
1530 return (entry_handler < external_handler);
1531}
Ben Murdoch257744e2011-11-30 15:57:28 +00001532
Ben Murdoch257744e2011-11-30 15:57:28 +00001533
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001534bool Isolate::IsExternalHandlerOnTop(Object* exception) {
1535 DCHECK_NE(heap()->the_hole_value(), exception);
1536
1537 // Get the address of the external handler so we can compare the address to
1538 // determine which one is closer to the top of the stack.
1539 Address external_handler = thread_local_top()->try_catch_handler_address();
1540 if (external_handler == nullptr) return false;
1541
1542 // For uncatchable exceptions, the external handler is always on top.
1543 if (!is_catchable_by_javascript(exception)) return true;
1544
1545 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1546 Address entry_handler = Isolate::handler(thread_local_top());
1547 if (entry_handler == nullptr) return true;
1548
1549 // The exception has been externally caught if and only if there is an
1550 // external handler which is on top of the top-most JS_ENTRY handler.
1551 //
1552 // Note, that finally clauses would re-throw an exception unless it's aborted
1553 // by jumps in control flow (like return, break, etc.) and we'll have another
1554 // chance to set proper v8::TryCatch later.
1555 return (entry_handler > external_handler);
Ben Murdoch257744e2011-11-30 15:57:28 +00001556}
1557
1558
1559void Isolate::ReportPendingMessages() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001560 Object* exception = pending_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001561
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001562 // Try to propagate the exception to an external v8::TryCatch handler. If
1563 // propagation was unsuccessful, then we will get another chance at reporting
1564 // the pending message if the exception is re-thrown.
1565 bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch();
1566 if (!has_been_propagated) return;
1567
1568 // Clear the pending message object early to avoid endless recursion.
1569 Object* message_obj = thread_local_top_.pending_message_obj_;
1570 clear_pending_message();
1571
1572 // For uncatchable exceptions we do nothing. If needed, the exception and the
1573 // message have already been propagated to v8::TryCatch.
1574 if (!is_catchable_by_javascript(exception)) return;
1575
1576 // Determine whether the message needs to be reported to all message handlers
1577 // depending on whether and external v8::TryCatch or an internal JavaScript
1578 // handler is on top.
1579 bool should_report_exception;
1580 if (IsExternalHandlerOnTop(exception)) {
1581 // Only report the exception if the external handler is verbose.
1582 should_report_exception = try_catch_handler()->is_verbose_;
Ben Murdoch257744e2011-11-30 15:57:28 +00001583 } else {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001584 // Report the exception if it isn't caught by JavaScript code.
1585 should_report_exception = !IsJavaScriptHandlerOnTop(exception);
Ben Murdoch257744e2011-11-30 15:57:28 +00001586 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001587
1588 // Actually report the pending message to all message handlers.
1589 if (!message_obj->IsTheHole() && should_report_exception) {
1590 HandleScope scope(this);
1591 Handle<JSMessageObject> message(JSMessageObject::cast(message_obj));
1592 Handle<JSValue> script_wrapper(JSValue::cast(message->script()));
1593 Handle<Script> script(Script::cast(script_wrapper->value()));
1594 int start_pos = message->start_position();
1595 int end_pos = message->end_position();
1596 MessageLocation location(script, start_pos, end_pos);
1597 MessageHandler::ReportMessage(this, &location, message);
1598 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001599}
1600
1601
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001602MessageLocation Isolate::GetMessageLocation() {
1603 DCHECK(has_pending_exception());
1604
1605 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001606 !thread_local_top_.pending_message_obj_->IsTheHole()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001607 Handle<JSMessageObject> message_obj(
1608 JSMessageObject::cast(thread_local_top_.pending_message_obj_));
1609 Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script()));
1610 Handle<Script> script(Script::cast(script_wrapper->value()));
1611 int start_pos = message_obj->start_position();
1612 int end_pos = message_obj->end_position();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001613 return MessageLocation(script, start_pos, end_pos);
1614 }
1615
1616 return MessageLocation();
Ben Murdoch257744e2011-11-30 15:57:28 +00001617}
1618
1619
1620bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001621 DCHECK(has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001622 PropagatePendingExceptionToExternalTryCatch();
1623
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001624 bool is_termination_exception =
1625 pending_exception() == heap_.termination_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001626
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001627 // Do not reschedule the exception if this is the bottom call.
1628 bool clear_exception = is_bottom_call;
Ben Murdoch257744e2011-11-30 15:57:28 +00001629
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001630 if (is_termination_exception) {
1631 if (is_bottom_call) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001632 thread_local_top()->external_caught_exception_ = false;
1633 clear_pending_exception();
1634 return false;
1635 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001636 } else if (thread_local_top()->external_caught_exception_) {
1637 // If the exception is externally caught, clear it if there are no
1638 // JavaScript frames on the way to the C++ frame that has the
1639 // external handler.
1640 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1641 Address external_handler_address =
1642 thread_local_top()->try_catch_handler_address();
1643 JavaScriptFrameIterator it(this);
1644 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1645 clear_exception = true;
1646 }
1647 }
1648
1649 // Clear the exception if needed.
1650 if (clear_exception) {
1651 thread_local_top()->external_caught_exception_ = false;
1652 clear_pending_exception();
1653 return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001654 }
1655
1656 // Reschedule the exception.
1657 thread_local_top()->scheduled_exception_ = pending_exception();
1658 clear_pending_exception();
1659 return true;
1660}
1661
1662
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001663void Isolate::PushPromise(Handle<JSObject> promise,
1664 Handle<JSFunction> function) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001665 ThreadLocalTop* tltop = thread_local_top();
1666 PromiseOnStack* prev = tltop->promise_on_stack_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001667 Handle<JSObject> global_promise =
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001668 Handle<JSObject>::cast(global_handles()->Create(*promise));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001669 Handle<JSFunction> global_function =
1670 Handle<JSFunction>::cast(global_handles()->Create(*function));
1671 tltop->promise_on_stack_ =
1672 new PromiseOnStack(global_function, global_promise, prev);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001673}
1674
1675
1676void Isolate::PopPromise() {
1677 ThreadLocalTop* tltop = thread_local_top();
1678 if (tltop->promise_on_stack_ == NULL) return;
1679 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001680 Handle<Object> global_function = tltop->promise_on_stack_->function();
1681 Handle<Object> global_promise = tltop->promise_on_stack_->promise();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001682 delete tltop->promise_on_stack_;
1683 tltop->promise_on_stack_ = prev;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001684 global_handles()->Destroy(global_function.location());
1685 global_handles()->Destroy(global_promise.location());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001686}
1687
1688
1689Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1690 Handle<Object> undefined = factory()->undefined_value();
1691 ThreadLocalTop* tltop = thread_local_top();
1692 if (tltop->promise_on_stack_ == NULL) return undefined;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001693 Handle<JSFunction> promise_function = tltop->promise_on_stack_->function();
1694 // Find the top-most try-catch or try-finally handler.
1695 if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined;
1696 for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
1697 JavaScriptFrame* frame = it.frame();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001698 if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001699 // Throwing inside a Promise only leads to a reject if not caught by an
1700 // inner try-catch or try-finally.
1701 if (frame->function() == *promise_function) {
1702 return tltop->promise_on_stack_->promise();
1703 }
1704 return undefined;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001705 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001706 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001707 return undefined;
1708}
1709
1710
Ben Murdoch257744e2011-11-30 15:57:28 +00001711void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1712 bool capture,
1713 int frame_limit,
1714 StackTrace::StackTraceOptions options) {
1715 capture_stack_trace_for_uncaught_exceptions_ = capture;
1716 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1717 stack_trace_for_uncaught_exceptions_options_ = options;
1718}
1719
1720
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001721void Isolate::SetAbortOnUncaughtExceptionCallback(
1722 v8::Isolate::AbortOnUncaughtExceptionCallback callback) {
1723 abort_on_uncaught_exception_callback_ = callback;
1724}
1725
1726
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001727Handle<Context> Isolate::native_context() {
1728 return handle(context()->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001729}
1730
1731
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001732Handle<Context> Isolate::GetCallingNativeContext() {
1733 JavaScriptFrameIterator it(this);
1734 if (debug_->in_debug_scope()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001735 while (!it.done()) {
1736 JavaScriptFrame* frame = it.frame();
1737 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001738 if (context->native_context() == *debug_->debug_context()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001739 it.Advance();
1740 } else {
1741 break;
1742 }
1743 }
1744 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001745 if (it.done()) return Handle<Context>::null();
1746 JavaScriptFrame* frame = it.frame();
1747 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001748 return Handle<Context>(context->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001749}
1750
1751
1752char* Isolate::ArchiveThread(char* to) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001753 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1754 sizeof(ThreadLocalTop));
Ben Murdoch257744e2011-11-30 15:57:28 +00001755 InitializeThreadLocal();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001756 clear_pending_exception();
1757 clear_pending_message();
1758 clear_scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001759 return to + sizeof(ThreadLocalTop);
1760}
1761
1762
1763char* Isolate::RestoreThread(char* from) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001764 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1765 sizeof(ThreadLocalTop));
1766// This might be just paranoia, but it seems to be needed in case a
1767// thread_local_top_ is restored on a separate OS thread.
Ben Murdoch257744e2011-11-30 15:57:28 +00001768#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +00001769 thread_local_top()->simulator_ = Simulator::current(this);
1770#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001771 DCHECK(context() == NULL || context()->IsContext());
Ben Murdoch257744e2011-11-30 15:57:28 +00001772 return from + sizeof(ThreadLocalTop);
1773}
1774
1775
Steve Block44f0eee2011-05-26 01:26:41 +01001776Isolate::ThreadDataTable::ThreadDataTable()
1777 : list_(NULL) {
1778}
1779
1780
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001781Isolate::ThreadDataTable::~ThreadDataTable() {
1782 // TODO(svenpanne) The assertion below would fire if an embedder does not
1783 // cleanly dispose all Isolates before disposing v8, so we are conservative
1784 // and leave it out for now.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001785 // DCHECK_NULL(list_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001786}
1787
1788
1789Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1790#if defined(USE_SIMULATOR)
1791 delete simulator_;
1792#endif
1793}
1794
1795
Steve Block44f0eee2011-05-26 01:26:41 +01001796Isolate::PerIsolateThreadData*
Ben Murdoch8b112d22011-06-08 16:22:53 +01001797 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1798 ThreadId thread_id) {
Steve Block44f0eee2011-05-26 01:26:41 +01001799 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1800 if (data->Matches(isolate, thread_id)) return data;
1801 }
1802 return NULL;
1803}
1804
1805
1806void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1807 if (list_ != NULL) list_->prev_ = data;
1808 data->next_ = list_;
1809 list_ = data;
1810}
1811
1812
1813void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1814 if (list_ == data) list_ = data->next_;
1815 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1816 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001817 delete data;
Steve Block44f0eee2011-05-26 01:26:41 +01001818}
1819
1820
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001821void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1822 PerIsolateThreadData* data = list_;
1823 while (data != NULL) {
1824 PerIsolateThreadData* next = data->next_;
1825 if (data->isolate() == isolate) Remove(data);
1826 data = next;
1827 }
1828}
1829
1830
Steve Block44f0eee2011-05-26 01:26:41 +01001831#ifdef DEBUG
1832#define TRACE_ISOLATE(tag) \
1833 do { \
1834 if (FLAG_trace_isolates) { \
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001835 PrintF("Isolate %p (id %d)" #tag "\n", \
1836 reinterpret_cast<void*>(this), id()); \
Steve Block44f0eee2011-05-26 01:26:41 +01001837 } \
1838 } while (false)
1839#else
1840#define TRACE_ISOLATE(tag)
1841#endif
1842
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001843Isolate::Isolate(bool enable_serializer)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001844 : embedder_data_(),
Steve Block44f0eee2011-05-26 01:26:41 +01001845 entry_stack_(NULL),
1846 stack_trace_nesting_level_(0),
1847 incomplete_message_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001848 bootstrapper_(NULL),
1849 runtime_profiler_(NULL),
1850 compilation_cache_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001851 counters_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001852 logger_(NULL),
1853 stats_table_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001854 stub_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001855 code_aging_helper_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001856 deoptimizer_data_(NULL),
Ben Murdoch097c5b22016-05-18 11:27:45 +01001857 deoptimizer_lazy_throw_(false),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001858 materialized_object_store_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001859 capture_stack_trace_for_uncaught_exceptions_(false),
1860 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1861 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
Steve Block44f0eee2011-05-26 01:26:41 +01001862 keyed_lookup_cache_(NULL),
1863 context_slot_cache_(NULL),
1864 descriptor_lookup_cache_(NULL),
1865 handle_scope_implementer_(NULL),
Ben Murdoch8b112d22011-06-08 16:22:53 +01001866 unicode_cache_(NULL),
Ben Murdochda12d292016-06-02 14:46:10 +01001867 runtime_zone_(&allocator_),
1868 interface_descriptor_zone_(&allocator_),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001869 inner_pointer_to_code_cache_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001870 global_handles_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001871 eternal_handles_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001872 thread_manager_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001873 has_installed_extensions_(false),
Steve Block44f0eee2011-05-26 01:26:41 +01001874 regexp_stack_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001875 date_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001876 call_descriptor_data_(NULL),
1877 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1878 // be fixed once the default isolate cleanup is done.
1879 random_number_generator_(NULL),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001880 serializer_enabled_(enable_serializer),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001881 has_fatal_error_(false),
1882 initialized_from_snapshot_(false),
Ben Murdochda12d292016-06-02 14:46:10 +01001883 is_tail_call_elimination_enabled_(true),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001884 cpu_profiler_(NULL),
1885 heap_profiler_(NULL),
1886 function_entry_hook_(NULL),
1887 deferred_handles_head_(NULL),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001888 optimizing_compile_dispatcher_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001889 stress_deopt_count_(0),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001890 virtual_handler_register_(NULL),
1891 virtual_slot_register_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001892 next_optimization_id_(0),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001893 js_calls_from_api_counter_(0),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001894#if TRACE_MAPS
1895 next_unique_sfi_id_(0),
1896#endif
Ben Murdochc5610432016-08-08 18:44:38 +01001897 is_running_microtasks_(false),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001898 use_counter_callback_(NULL),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001899 basic_block_profiler_(NULL),
1900 cancelable_task_manager_(new CancelableTaskManager()),
1901 abort_on_uncaught_exception_callback_(NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001902 {
1903 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1904 CHECK(thread_data_table_);
1905 }
1906 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
Steve Block44f0eee2011-05-26 01:26:41 +01001907 TRACE_ISOLATE(constructor);
1908
1909 memset(isolate_addresses_, 0,
Ben Murdoch589d6972011-11-30 16:04:58 +00001910 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
Steve Block44f0eee2011-05-26 01:26:41 +01001911
1912 heap_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01001913 stack_guard_.isolate_ = this;
1914
Ben Murdoch257744e2011-11-30 15:57:28 +00001915 // ThreadManager is initialized early to support locking an isolate
1916 // before it is entered.
1917 thread_manager_ = new ThreadManager();
1918 thread_manager_->isolate_ = this;
1919
Steve Block44f0eee2011-05-26 01:26:41 +01001920#ifdef DEBUG
1921 // heap_histograms_ initializes itself.
1922 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
Steve Block44f0eee2011-05-26 01:26:41 +01001923#endif
1924
Steve Block44f0eee2011-05-26 01:26:41 +01001925 handle_scope_data_.Initialize();
1926
1927#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1928 name##_ = (initial_value);
1929 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1930#undef ISOLATE_INIT_EXECUTE
1931
1932#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1933 memset(name##_, 0, sizeof(type) * length);
1934 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1935#undef ISOLATE_INIT_ARRAY_EXECUTE
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001936
1937 InitializeLoggingAndCounters();
1938 debug_ = new Debug(this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001939
1940 init_memcopy_functions(this);
Steve Block44f0eee2011-05-26 01:26:41 +01001941}
1942
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001943
Steve Block44f0eee2011-05-26 01:26:41 +01001944void Isolate::TearDown() {
1945 TRACE_ISOLATE(tear_down);
1946
1947 // Temporarily set this isolate as current so that various parts of
1948 // the isolate can access it in their destructors without having a
1949 // direct pointer. We don't use Enter/Exit here to avoid
1950 // initializing the thread data.
1951 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001952 DCHECK(base::NoBarrier_Load(&isolate_key_created_) == 1);
1953 Isolate* saved_isolate =
1954 reinterpret_cast<Isolate*>(base::Thread::GetThreadLocal(isolate_key_));
Steve Block44f0eee2011-05-26 01:26:41 +01001955 SetIsolateThreadLocals(this, NULL);
1956
1957 Deinit();
1958
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001959 {
1960 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +01001961 thread_data_table_->RemoveAllThreads(this);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001962 }
1963
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001964 delete this;
1965
Steve Block44f0eee2011-05-26 01:26:41 +01001966 // Restore the previous current isolate.
1967 SetIsolateThreadLocals(saved_isolate, saved_data);
1968}
1969
1970
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001971void Isolate::GlobalTearDown() {
1972 delete thread_data_table_;
1973 thread_data_table_ = NULL;
1974}
1975
1976
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001977void Isolate::ClearSerializerData() {
1978 delete external_reference_table_;
1979 external_reference_table_ = NULL;
1980 delete external_reference_map_;
1981 external_reference_map_ = NULL;
1982}
1983
1984
Steve Block44f0eee2011-05-26 01:26:41 +01001985void Isolate::Deinit() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001986 TRACE_ISOLATE(deinit);
Steve Block44f0eee2011-05-26 01:26:41 +01001987
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001988 debug()->Unload();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001989
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001990 FreeThreadResources();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001991
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001992 if (concurrent_recompilation_enabled()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001993 optimizing_compile_dispatcher_->Stop();
1994 delete optimizing_compile_dispatcher_;
1995 optimizing_compile_dispatcher_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001996 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001997
1998 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1999 heap_.mark_compact_collector()->EnsureSweepingCompleted();
2000 }
2001
2002 DumpAndResetCompilationStats();
2003
2004 if (FLAG_print_deopt_stress) {
2005 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
2006 }
2007
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002008 if (cpu_profiler_) {
2009 cpu_profiler_->DeleteAllProfiles();
2010 }
2011
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002012 // We must stop the logger before we tear down other components.
2013 Sampler* sampler = logger_->sampler();
2014 if (sampler && sampler->IsActive()) sampler->Stop();
2015
2016 delete deoptimizer_data_;
2017 deoptimizer_data_ = NULL;
2018 builtins_.TearDown();
2019 bootstrapper_->TearDown();
2020
2021 if (runtime_profiler_ != NULL) {
2022 delete runtime_profiler_;
2023 runtime_profiler_ = NULL;
2024 }
2025
2026 delete basic_block_profiler_;
2027 basic_block_profiler_ = NULL;
2028
Ben Murdoch097c5b22016-05-18 11:27:45 +01002029 delete heap_profiler_;
2030 heap_profiler_ = NULL;
2031
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002032 heap_.TearDown();
2033 logger_->TearDown();
2034
Ben Murdoch097c5b22016-05-18 11:27:45 +01002035 delete interpreter_;
2036 interpreter_ = NULL;
2037
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002038 cancelable_task_manager()->CancelAndWait();
2039
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002040 delete cpu_profiler_;
2041 cpu_profiler_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002042
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002043 delete root_index_map_;
2044 root_index_map_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002045
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002046 ClearSerializerData();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002047}
2048
2049
Steve Block44f0eee2011-05-26 01:26:41 +01002050void Isolate::SetIsolateThreadLocals(Isolate* isolate,
2051 PerIsolateThreadData* data) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002052 base::Thread::SetThreadLocal(isolate_key_, isolate);
2053 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
Steve Block44f0eee2011-05-26 01:26:41 +01002054}
2055
2056
2057Isolate::~Isolate() {
2058 TRACE_ISOLATE(destructor);
2059
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002060 // Has to be called while counters_ are still alive
2061 runtime_zone_.DeleteKeptSegment();
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002062
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002063 // The entry stack must be empty when we get here.
2064 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
2065
2066 delete entry_stack_;
2067 entry_stack_ = NULL;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002068
Ben Murdoch8b112d22011-06-08 16:22:53 +01002069 delete unicode_cache_;
2070 unicode_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002071
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002072 delete date_cache_;
2073 date_cache_ = NULL;
2074
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002075 delete[] call_descriptor_data_;
2076 call_descriptor_data_ = NULL;
2077
Steve Block44f0eee2011-05-26 01:26:41 +01002078 delete regexp_stack_;
2079 regexp_stack_ = NULL;
2080
Steve Block44f0eee2011-05-26 01:26:41 +01002081 delete descriptor_lookup_cache_;
2082 descriptor_lookup_cache_ = NULL;
2083 delete context_slot_cache_;
2084 context_slot_cache_ = NULL;
2085 delete keyed_lookup_cache_;
2086 keyed_lookup_cache_ = NULL;
2087
Steve Block44f0eee2011-05-26 01:26:41 +01002088 delete stub_cache_;
2089 stub_cache_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002090 delete code_aging_helper_;
2091 code_aging_helper_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002092 delete stats_table_;
2093 stats_table_ = NULL;
2094
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002095 delete materialized_object_store_;
2096 materialized_object_store_ = NULL;
2097
Steve Block44f0eee2011-05-26 01:26:41 +01002098 delete logger_;
2099 logger_ = NULL;
2100
2101 delete counters_;
2102 counters_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002103
2104 delete handle_scope_implementer_;
2105 handle_scope_implementer_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002106
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002107 delete code_tracer();
2108 set_code_tracer(NULL);
2109
Steve Block44f0eee2011-05-26 01:26:41 +01002110 delete compilation_cache_;
2111 compilation_cache_ = NULL;
2112 delete bootstrapper_;
2113 bootstrapper_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002114 delete inner_pointer_to_code_cache_;
2115 inner_pointer_to_code_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002116
Steve Block44f0eee2011-05-26 01:26:41 +01002117 delete thread_manager_;
2118 thread_manager_ = NULL;
2119
Steve Block44f0eee2011-05-26 01:26:41 +01002120 delete global_handles_;
2121 global_handles_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002122 delete eternal_handles_;
2123 eternal_handles_ = NULL;
2124
2125 delete string_stream_debug_object_cache_;
2126 string_stream_debug_object_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002127
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002128 delete random_number_generator_;
2129 random_number_generator_ = NULL;
2130
Steve Block44f0eee2011-05-26 01:26:41 +01002131 delete debug_;
2132 debug_ = NULL;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002133
2134 delete cancelable_task_manager_;
2135 cancelable_task_manager_ = nullptr;
2136
2137#if USE_SIMULATOR
2138 Simulator::TearDown(simulator_i_cache_, simulator_redirection_);
2139 simulator_i_cache_ = nullptr;
2140 simulator_redirection_ = nullptr;
2141#endif
Steve Block44f0eee2011-05-26 01:26:41 +01002142}
2143
2144
Steve Block44f0eee2011-05-26 01:26:41 +01002145void Isolate::InitializeThreadLocal() {
Ben Murdoch257744e2011-11-30 15:57:28 +00002146 thread_local_top_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01002147 thread_local_top_.Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01002148}
2149
2150
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002151bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002152 Object* exception = pending_exception();
Ben Murdoch8b112d22011-06-08 16:22:53 +01002153
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002154 if (IsJavaScriptHandlerOnTop(exception)) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002155 thread_local_top_.external_caught_exception_ = false;
2156 return false;
2157 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01002158
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002159 if (!IsExternalHandlerOnTop(exception)) {
2160 thread_local_top_.external_caught_exception_ = false;
2161 return true;
2162 }
2163
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002164 thread_local_top_.external_caught_exception_ = true;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002165 if (!is_catchable_by_javascript(exception)) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01002166 try_catch_handler()->can_continue_ = false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002167 try_catch_handler()->has_terminated_ = true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002168 try_catch_handler()->exception_ = heap()->null_value();
2169 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002170 v8::TryCatch* handler = try_catch_handler();
2171 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2172 thread_local_top_.pending_message_obj_->IsTheHole());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002173 handler->can_continue_ = true;
2174 handler->has_terminated_ = false;
2175 handler->exception_ = pending_exception();
2176 // Propagate to the external try-catch only if we got an actual message.
2177 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
2178
2179 handler->message_obj_ = thread_local_top_.pending_message_obj_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002180 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002181 return true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002182}
2183
2184
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002185void Isolate::InitializeLoggingAndCounters() {
2186 if (logger_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002187 logger_ = new Logger(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002188 }
2189 if (counters_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002190 counters_ = new Counters(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002191 }
2192}
2193
2194
Steve Block44f0eee2011-05-26 01:26:41 +01002195bool Isolate::Init(Deserializer* des) {
Steve Block44f0eee2011-05-26 01:26:41 +01002196 TRACE_ISOLATE(init);
2197
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002198 stress_deopt_count_ = FLAG_deopt_every_n_times;
2199
2200 has_fatal_error_ = false;
2201
2202 if (function_entry_hook() != NULL) {
2203 // When function entry hooking is in effect, we have to create the code
2204 // stubs from scratch to get entry hooks, rather than loading the previously
2205 // generated stubs from disk.
2206 // If this assert fires, the initialization path has regressed.
2207 DCHECK(des == NULL);
2208 }
2209
Steve Block44f0eee2011-05-26 01:26:41 +01002210 // The initialization process does not handle memory exhaustion.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002211 AlwaysAllocateScope always_allocate(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002212
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002213 // Safe after setting Heap::isolate_, and initializing StackGuard
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002214 heap_.SetStackLimits();
2215
Ben Murdoch589d6972011-11-30 16:04:58 +00002216#define ASSIGN_ELEMENT(CamelName, hacker_name) \
2217 isolate_addresses_[Isolate::k##CamelName##Address] = \
2218 reinterpret_cast<Address>(hacker_name##_address());
2219 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002220#undef ASSIGN_ELEMENT
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002221
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002222 compilation_cache_ = new CompilationCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002223 keyed_lookup_cache_ = new KeyedLookupCache();
2224 context_slot_cache_ = new ContextSlotCache();
2225 descriptor_lookup_cache_ = new DescriptorLookupCache();
2226 unicode_cache_ = new UnicodeCache();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002227 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002228 global_handles_ = new GlobalHandles(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002229 eternal_handles_ = new EternalHandles();
2230 bootstrapper_ = new Bootstrapper(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002231 handle_scope_implementer_ = new HandleScopeImplementer(this);
2232 stub_cache_ = new StubCache(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002233 materialized_object_store_ = new MaterializedObjectStore(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002234 regexp_stack_ = new RegExpStack();
2235 regexp_stack_->isolate_ = this;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002236 date_cache_ = new DateCache();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002237 call_descriptor_data_ =
2238 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2239 cpu_profiler_ = new CpuProfiler(this);
2240 heap_profiler_ = new HeapProfiler(heap());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002241 interpreter_ = new interpreter::Interpreter(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002242
2243 // Enable logging before setting up the heap
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002244 logger_->SetUp(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002245
Steve Block44f0eee2011-05-26 01:26:41 +01002246 // Initialize other runtime facilities
2247#if defined(USE_SIMULATOR)
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002248#if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
Ben Murdochda12d292016-06-02 14:46:10 +01002249 V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_S390
Ben Murdoch257744e2011-11-30 15:57:28 +00002250 Simulator::Initialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002251#endif
2252#endif
2253
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002254 code_aging_helper_ = new CodeAgingHelper(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002255
Steve Block44f0eee2011-05-26 01:26:41 +01002256 { // NOLINT
2257 // Ensure that the thread has a valid stack guard. The v8::Locker object
2258 // will ensure this too, but we don't have to use lockers if we are only
2259 // using one thread.
2260 ExecutionAccess lock(this);
2261 stack_guard_.InitThread(lock);
2262 }
2263
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002264 // SetUp the object heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002265 DCHECK(!heap_.HasBeenSetUp());
2266 if (!heap_.SetUp()) {
2267 V8::FatalProcessOutOfMemory("heap setup");
Steve Block44f0eee2011-05-26 01:26:41 +01002268 return false;
2269 }
2270
Ben Murdochc5610432016-08-08 18:44:38 +01002271 deoptimizer_data_ = new DeoptimizerData(heap()->memory_allocator());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002272
2273 const bool create_heap_objects = (des == NULL);
2274 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2275 V8::FatalProcessOutOfMemory("heap object creation");
2276 return false;
2277 }
2278
2279 if (create_heap_objects) {
Ben Murdochda12d292016-06-02 14:46:10 +01002280 // Terminate the partial snapshot cache so we can iterate.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002281 partial_snapshot_cache_.Add(heap_.undefined_value());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002282 }
2283
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002284 InitializeThreadLocal();
2285
Steve Block44f0eee2011-05-26 01:26:41 +01002286 bootstrapper_->Initialize(create_heap_objects);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002287 builtins_.SetUp(this, create_heap_objects);
Steve Block44f0eee2011-05-26 01:26:41 +01002288
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002289 if (FLAG_log_internal_timer_events) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002290 set_event_logger(Logger::DefaultEventLoggerSentinel);
Steve Block44f0eee2011-05-26 01:26:41 +01002291 }
2292
Ben Murdochc5610432016-08-08 18:44:38 +01002293 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs || FLAG_trace_turbo ||
2294 FLAG_trace_turbo_graph) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002295 PrintF("Concurrent recompilation has been disabled for tracing.\n");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002296 } else if (OptimizingCompileDispatcher::Enabled()) {
2297 optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002298 }
2299
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002300 // Initialize runtime profiler before deserialization, because collections may
2301 // occur, clearing/updating ICs.
2302 runtime_profiler_ = new RuntimeProfiler(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002303
2304 // If we are deserializing, read the state into the now-empty heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002305 if (!create_heap_objects) {
2306 des->Deserialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002307 }
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002308 stub_cache_->Initialize();
Ben Murdochc5610432016-08-08 18:44:38 +01002309 if (FLAG_ignition || serializer_enabled()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002310 interpreter_->Initialize();
2311 }
2312
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002313 // Finish initialization of ThreadLocal after deserialization is done.
2314 clear_pending_exception();
2315 clear_pending_message();
2316 clear_scheduled_exception();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002317
Steve Block44f0eee2011-05-26 01:26:41 +01002318 // Deserializing may put strange things in the root array's copy of the
2319 // stack guard.
2320 heap_.SetStackLimits();
2321
Ben Murdochdb1b4382012-04-26 19:03:50 +01002322 // Quiet the heap NaN if needed on target platform.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002323 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
Ben Murdochdb1b4382012-04-26 19:03:50 +01002324
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002325 if (FLAG_trace_turbo) {
2326 // Create an empty file.
2327 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2328 }
Steve Block44f0eee2011-05-26 01:26:41 +01002329
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002330 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2331 Internals::kIsolateEmbedderDataOffset);
2332 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2333 Internals::kIsolateRootsOffset);
2334 CHECK_EQ(static_cast<int>(
2335 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2336 Internals::kAmountOfExternalAllocatedMemoryOffset);
2337 CHECK_EQ(static_cast<int>(OFFSET_OF(
2338 Isolate,
2339 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2340 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2341
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002342 time_millis_at_init_ = heap_.MonotonicallyIncreasingTimeInMs();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002343
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002344 heap_.NotifyDeserializationComplete();
2345
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002346 if (!create_heap_objects) {
2347 // Now that the heap is consistent, it's OK to generate the code for the
2348 // deopt entry table that might have been referred to by optimized code in
2349 // the snapshot.
2350 HandleScope scope(this);
2351 Deoptimizer::EnsureCodeForDeoptimizationEntry(
Ben Murdochda12d292016-06-02 14:46:10 +01002352 this, Deoptimizer::LAZY,
2353 ExternalReferenceTable::kDeoptTableSerializeEntryCount - 1);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002354 }
2355
2356 if (!serializer_enabled()) {
2357 // Ensure that all stubs which need to be generated ahead of time, but
2358 // cannot be serialized into the snapshot have been generated.
2359 HandleScope scope(this);
2360 CodeStub::GenerateFPStubs(this);
2361 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2362 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2363 }
2364
2365 initialized_from_snapshot_ = (des != NULL);
2366
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002367 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2368
Steve Block44f0eee2011-05-26 01:26:41 +01002369 return true;
2370}
2371
2372
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002373// Initialized lazily to allow early
2374// v8::V8::SetAddHistogramSampleFunction calls.
2375StatsTable* Isolate::stats_table() {
2376 if (stats_table_ == NULL) {
2377 stats_table_ = new StatsTable;
2378 }
2379 return stats_table_;
2380}
2381
2382
Steve Block44f0eee2011-05-26 01:26:41 +01002383void Isolate::Enter() {
2384 Isolate* current_isolate = NULL;
2385 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2386 if (current_data != NULL) {
2387 current_isolate = current_data->isolate_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002388 DCHECK(current_isolate != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01002389 if (current_isolate == this) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002390 DCHECK(Current() == this);
2391 DCHECK(entry_stack_ != NULL);
2392 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002393 entry_stack_->previous_thread_data->thread_id().Equals(
2394 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002395 // Same thread re-enters the isolate, no need to re-init anything.
2396 entry_stack_->entry_count++;
2397 return;
2398 }
2399 }
2400
Steve Block44f0eee2011-05-26 01:26:41 +01002401 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002402 DCHECK(data != NULL);
2403 DCHECK(data->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002404
2405 EntryStackItem* item = new EntryStackItem(current_data,
2406 current_isolate,
2407 entry_stack_);
2408 entry_stack_ = item;
2409
2410 SetIsolateThreadLocals(this, data);
2411
Steve Block44f0eee2011-05-26 01:26:41 +01002412 // In case it's the first time some thread enters the isolate.
2413 set_thread_id(data->thread_id());
2414}
2415
2416
2417void Isolate::Exit() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002418 DCHECK(entry_stack_ != NULL);
2419 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002420 entry_stack_->previous_thread_data->thread_id().Equals(
2421 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002422
2423 if (--entry_stack_->entry_count > 0) return;
2424
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002425 DCHECK(CurrentPerIsolateThreadData() != NULL);
2426 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002427
2428 // Pop the stack.
2429 EntryStackItem* item = entry_stack_;
2430 entry_stack_ = item->previous_item;
2431
2432 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2433 Isolate* previous_isolate = item->previous_isolate;
2434
2435 delete item;
2436
2437 // Reinit the current thread for the isolate it was running before this one.
2438 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2439}
2440
2441
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002442void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2443 deferred->next_ = deferred_handles_head_;
2444 if (deferred_handles_head_ != NULL) {
2445 deferred_handles_head_->previous_ = deferred;
2446 }
2447 deferred_handles_head_ = deferred;
2448}
2449
2450
2451void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2452#ifdef DEBUG
2453 // In debug mode assert that the linked list is well-formed.
2454 DeferredHandles* deferred_iterator = deferred;
2455 while (deferred_iterator->previous_ != NULL) {
2456 deferred_iterator = deferred_iterator->previous_;
2457 }
2458 DCHECK(deferred_handles_head_ == deferred_iterator);
2459#endif
2460 if (deferred_handles_head_ == deferred) {
2461 deferred_handles_head_ = deferred_handles_head_->next_;
2462 }
2463 if (deferred->next_ != NULL) {
2464 deferred->next_->previous_ = deferred->previous_;
2465 }
2466 if (deferred->previous_ != NULL) {
2467 deferred->previous_->next_ = deferred->next_;
2468 }
2469}
2470
2471
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002472void Isolate::DumpAndResetCompilationStats() {
2473 if (turbo_statistics() != nullptr) {
2474 OFStream os(stdout);
2475 os << *turbo_statistics() << std::endl;
2476 }
2477 if (hstatistics() != nullptr) hstatistics()->Print();
2478 delete turbo_statistics_;
2479 turbo_statistics_ = nullptr;
2480 delete hstatistics_;
2481 hstatistics_ = nullptr;
Ben Murdoch097c5b22016-05-18 11:27:45 +01002482 if (FLAG_runtime_call_stats) {
2483 OFStream os(stdout);
2484 counters()->runtime_call_stats()->Print(os);
2485 counters()->runtime_call_stats()->Reset();
2486 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002487}
2488
2489
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002490HStatistics* Isolate::GetHStatistics() {
2491 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2492 return hstatistics();
2493}
2494
2495
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002496CompilationStatistics* Isolate::GetTurboStatistics() {
2497 if (turbo_statistics() == NULL)
2498 set_turbo_statistics(new CompilationStatistics());
2499 return turbo_statistics();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002500}
2501
2502
2503HTracer* Isolate::GetHTracer() {
2504 if (htracer() == NULL) set_htracer(new HTracer(id()));
2505 return htracer();
2506}
2507
2508
2509CodeTracer* Isolate::GetCodeTracer() {
2510 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2511 return code_tracer();
2512}
2513
Ben Murdochda12d292016-06-02 14:46:10 +01002514Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002515 if (IsFastElementsKind(kind)) {
2516 DisallowHeapAllocation no_gc;
Ben Murdochda12d292016-06-02 14:46:10 +01002517 Object* const initial_js_array_map =
2518 context()->native_context()->get(Context::ArrayMapIndex(kind));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002519 if (!initial_js_array_map->IsUndefined()) {
2520 return Map::cast(initial_js_array_map);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002521 }
2522 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002523 return nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002524}
2525
2526
2527bool Isolate::use_crankshaft() const {
2528 return FLAG_crankshaft &&
2529 !serializer_enabled_ &&
2530 CpuFeatures::SupportsCrankshaft();
2531}
2532
Ben Murdochc5610432016-08-08 18:44:38 +01002533bool Isolate::IsArrayOrObjectPrototype(Object* object) {
2534 Object* context = heap()->native_contexts_list();
2535 while (context != heap()->undefined_value()) {
2536 Context* current_context = Context::cast(context);
2537 if (current_context->initial_object_prototype() == object ||
2538 current_context->initial_array_prototype() == object) {
2539 return true;
2540 }
2541 context = current_context->next_context_link();
2542 }
2543 return false;
2544}
2545
2546bool Isolate::IsInAnyContext(Object* object, uint32_t index) {
2547 DisallowHeapAllocation no_gc;
2548 Object* context = heap()->native_contexts_list();
2549 while (context != heap()->undefined_value()) {
2550 Context* current_context = Context::cast(context);
2551 if (current_context->get(index) == object) {
2552 return true;
2553 }
2554 context = current_context->next_context_link();
2555 }
2556 return false;
2557}
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002558
2559bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002560 PropertyCell* no_elements_cell = heap()->array_protector();
2561 bool cell_reports_intact =
2562 no_elements_cell->value()->IsSmi() &&
2563 Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid;
2564
2565#ifdef DEBUG
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002566 Map* root_array_map =
2567 get_initial_js_array_map(GetInitialFastElementsKind());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002568 Context* native_context = context()->native_context();
2569 JSObject* initial_array_proto = JSObject::cast(
2570 native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX));
2571 JSObject* initial_object_proto = JSObject::cast(
2572 native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX));
2573
2574 if (root_array_map == NULL || initial_array_proto == initial_object_proto) {
2575 // We are in the bootstrapping process, and the entire check sequence
2576 // shouldn't be performed.
2577 return cell_reports_intact;
2578 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002579
2580 // Check that the array prototype hasn't been altered WRT empty elements.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002581 if (root_array_map->prototype() != initial_array_proto) {
2582 DCHECK_EQ(false, cell_reports_intact);
2583 return cell_reports_intact;
2584 }
2585
2586 FixedArrayBase* elements = initial_array_proto->elements();
2587 if (elements != heap()->empty_fixed_array() &&
2588 elements != heap()->empty_slow_element_dictionary()) {
2589 DCHECK_EQ(false, cell_reports_intact);
2590 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002591 }
2592
2593 // Check that the object prototype hasn't been altered WRT empty elements.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002594 PrototypeIterator iter(this, initial_array_proto);
2595 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002596 DCHECK_EQ(false, cell_reports_intact);
2597 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002598 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002599
2600 elements = initial_object_proto->elements();
2601 if (elements != heap()->empty_fixed_array() &&
2602 elements != heap()->empty_slow_element_dictionary()) {
2603 DCHECK_EQ(false, cell_reports_intact);
2604 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002605 }
2606
2607 iter.Advance();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002608 if (!iter.IsAtEnd()) {
2609 DCHECK_EQ(false, cell_reports_intact);
2610 return cell_reports_intact;
2611 }
2612
2613#endif
2614
2615 return cell_reports_intact;
2616}
2617
Ben Murdochc5610432016-08-08 18:44:38 +01002618bool Isolate::IsIsConcatSpreadableLookupChainIntact() {
2619 Cell* is_concat_spreadable_cell = heap()->is_concat_spreadable_protector();
2620 bool is_is_concat_spreadable_set =
2621 Smi::cast(is_concat_spreadable_cell->value())->value() ==
2622 kArrayProtectorInvalid;
2623#ifdef DEBUG
2624 Map* root_array_map = get_initial_js_array_map(GetInitialFastElementsKind());
2625 if (root_array_map == NULL) {
2626 // Ignore the value of is_concat_spreadable during bootstrap.
2627 return !is_is_concat_spreadable_set;
2628 }
2629 Handle<Object> array_prototype(array_function()->prototype(), this);
2630 Handle<Symbol> key = factory()->is_concat_spreadable_symbol();
2631 Handle<Object> value;
2632 LookupIterator it(array_prototype, key);
2633 if (it.IsFound() && !JSReceiver::GetDataProperty(&it)->IsUndefined()) {
2634 // TODO(cbruni): Currently we do not revert if we unset the
2635 // @@isConcatSpreadable property on Array.prototype or Object.prototype
2636 // hence the reverse implication doesn't hold.
2637 DCHECK(is_is_concat_spreadable_set);
2638 return false;
2639 }
2640#endif // DEBUG
2641
2642 return !is_is_concat_spreadable_set;
Ben Murdoch097c5b22016-05-18 11:27:45 +01002643}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002644
2645void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002646 DisallowHeapAllocation no_gc;
Ben Murdochc5610432016-08-08 18:44:38 +01002647 if (!object->map()->is_prototype_map()) return;
2648 if (!IsFastArrayConstructorPrototypeChainIntact()) return;
2649 if (!IsArrayOrObjectPrototype(*object)) return;
2650 PropertyCell::SetValueWithInvalidation(
2651 factory()->array_protector(),
2652 handle(Smi::FromInt(kArrayProtectorInvalid), this));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002653}
2654
Ben Murdochc5610432016-08-08 18:44:38 +01002655void Isolate::InvalidateHasInstanceProtector() {
2656 DCHECK(factory()->has_instance_protector()->value()->IsSmi());
2657 DCHECK(IsHasInstanceLookupChainIntact());
2658 PropertyCell::SetValueWithInvalidation(
2659 factory()->has_instance_protector(),
2660 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2661 DCHECK(!IsHasInstanceLookupChainIntact());
2662}
2663
2664void Isolate::InvalidateIsConcatSpreadableProtector() {
2665 DCHECK(factory()->is_concat_spreadable_protector()->value()->IsSmi());
2666 DCHECK(IsIsConcatSpreadableLookupChainIntact());
2667 factory()->is_concat_spreadable_protector()->set_value(
2668 Smi::FromInt(kArrayProtectorInvalid));
2669 DCHECK(!IsIsConcatSpreadableLookupChainIntact());
2670}
2671
2672void Isolate::InvalidateArraySpeciesProtector() {
2673 if (!FLAG_harmony_species) return;
2674 DCHECK(factory()->species_protector()->value()->IsSmi());
2675 DCHECK(IsArraySpeciesLookupChainIntact());
2676 factory()->species_protector()->set_value(
2677 Smi::FromInt(kArrayProtectorInvalid));
2678 DCHECK(!IsArraySpeciesLookupChainIntact());
2679}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002680
2681bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) {
Ben Murdochc5610432016-08-08 18:44:38 +01002682 DisallowHeapAllocation no_gc;
2683 return IsInAnyContext(*array, Context::INITIAL_ARRAY_PROTOTYPE_INDEX);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002684}
2685
2686
2687CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2688 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2689 return &call_descriptor_data_[index];
2690}
2691
2692
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002693base::RandomNumberGenerator* Isolate::random_number_generator() {
2694 if (random_number_generator_ == NULL) {
2695 if (FLAG_random_seed != 0) {
2696 random_number_generator_ =
2697 new base::RandomNumberGenerator(FLAG_random_seed);
2698 } else {
2699 random_number_generator_ = new base::RandomNumberGenerator();
2700 }
2701 }
2702 return random_number_generator_;
2703}
2704
2705
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002706Object* Isolate::FindCodeObject(Address a) {
2707 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2708}
2709
2710
Steve Block44f0eee2011-05-26 01:26:41 +01002711#ifdef DEBUG
2712#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2713const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2714ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2715ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2716#undef ISOLATE_FIELD_OFFSET
2717#endif
2718
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002719
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002720Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry,
2721 Handle<Map> map, const char* cname) {
2722 Handle<String> name = factory()->InternalizeUtf8String(cname);
2723 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2724 JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0,
2725 "SetupSymbolRegistry");
2726 JSObject::AddProperty(registry, name, obj, NONE);
2727 return obj;
2728}
2729
2730
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002731Handle<JSObject> Isolate::GetSymbolRegistry() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002732 if (heap()->symbol_registry()->IsSmi()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002733 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2734 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2735 heap()->set_symbol_registry(*registry);
2736
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002737 SetUpSubregistry(registry, map, "for");
2738 SetUpSubregistry(registry, map, "for_api");
2739 SetUpSubregistry(registry, map, "keyFor");
2740 SetUpSubregistry(registry, map, "private_api");
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002741 }
2742 return Handle<JSObject>::cast(factory()->symbol_registry());
2743}
2744
2745
Ben Murdoch097c5b22016-05-18 11:27:45 +01002746void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
2747 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2748 if (callback == before_call_entered_callbacks_.at(i)) return;
2749 }
2750 before_call_entered_callbacks_.Add(callback);
2751}
2752
2753
2754void Isolate::RemoveBeforeCallEnteredCallback(
2755 BeforeCallEnteredCallback callback) {
2756 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2757 if (callback == before_call_entered_callbacks_.at(i)) {
2758 before_call_entered_callbacks_.Remove(i);
2759 }
2760 }
2761}
2762
2763
2764void Isolate::FireBeforeCallEnteredCallback() {
2765 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2766 before_call_entered_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this));
2767 }
2768}
2769
2770
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002771void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2772 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2773 if (callback == call_completed_callbacks_.at(i)) return;
2774 }
2775 call_completed_callbacks_.Add(callback);
2776}
2777
2778
2779void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2780 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2781 if (callback == call_completed_callbacks_.at(i)) {
2782 call_completed_callbacks_.Remove(i);
2783 }
2784 }
2785}
2786
2787
2788void Isolate::FireCallCompletedCallback() {
2789 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
Ben Murdochda12d292016-06-02 14:46:10 +01002790 bool run_microtasks =
2791 pending_microtask_count() &&
2792 !handle_scope_implementer()->HasMicrotasksSuppressions() &&
2793 handle_scope_implementer()->microtasks_policy() ==
2794 v8::MicrotasksPolicy::kAuto;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002795 if (!has_call_completed_callbacks && !run_microtasks) return;
2796
2797 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2798 if (run_microtasks) RunMicrotasks();
2799 // Fire callbacks. Increase call depth to prevent recursive callbacks.
Ben Murdoch097c5b22016-05-18 11:27:45 +01002800 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this);
2801 v8::Isolate::SuppressMicrotaskExecutionScope suppress(isolate);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002802 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002803 call_completed_callbacks_.at(i)(isolate);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002804 }
2805}
2806
2807
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002808void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2809 promise_reject_callback_ = callback;
2810}
2811
2812
2813void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2814 Handle<Object> value,
2815 v8::PromiseRejectEvent event) {
2816 if (promise_reject_callback_ == NULL) return;
2817 Handle<JSArray> stack_trace;
2818 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2819 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2820 }
2821 promise_reject_callback_(v8::PromiseRejectMessage(
2822 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2823 v8::Utils::StackTraceToLocal(stack_trace)));
2824}
2825
2826
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002827void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2828 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2829 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2830 int num_tasks = pending_microtask_count();
2831 DCHECK(num_tasks <= queue->length());
2832 if (num_tasks == 0) {
2833 queue = factory()->NewFixedArray(8);
2834 heap()->set_microtask_queue(*queue);
2835 } else if (num_tasks == queue->length()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002836 queue = factory()->CopyFixedArrayAndGrow(queue, num_tasks);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002837 heap()->set_microtask_queue(*queue);
2838 }
2839 DCHECK(queue->get(num_tasks)->IsUndefined());
2840 queue->set(num_tasks, *microtask);
2841 set_pending_microtask_count(num_tasks + 1);
2842}
2843
2844
2845void Isolate::RunMicrotasks() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002846 // Increase call depth to prevent recursive callbacks.
2847 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2848 reinterpret_cast<v8::Isolate*>(this));
Ben Murdochc5610432016-08-08 18:44:38 +01002849 is_running_microtasks_ = true;
Ben Murdochda12d292016-06-02 14:46:10 +01002850 RunMicrotasksInternal();
Ben Murdochc5610432016-08-08 18:44:38 +01002851 is_running_microtasks_ = false;
Ben Murdochda12d292016-06-02 14:46:10 +01002852 FireMicrotasksCompletedCallback();
2853}
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002854
Ben Murdochda12d292016-06-02 14:46:10 +01002855
2856void Isolate::RunMicrotasksInternal() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002857 while (pending_microtask_count() > 0) {
2858 HandleScope scope(this);
2859 int num_tasks = pending_microtask_count();
2860 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2861 DCHECK(num_tasks <= queue->length());
2862 set_pending_microtask_count(0);
2863 heap()->set_microtask_queue(heap()->empty_fixed_array());
2864
Ben Murdochda12d292016-06-02 14:46:10 +01002865 Isolate* isolate = this;
2866 FOR_WITH_HANDLE_SCOPE(isolate, int, i = 0, i, i < num_tasks, i++, {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002867 Handle<Object> microtask(queue->get(i), this);
2868 if (microtask->IsJSFunction()) {
2869 Handle<JSFunction> microtask_function =
2870 Handle<JSFunction>::cast(microtask);
2871 SaveContext save(this);
2872 set_context(microtask_function->context()->native_context());
2873 MaybeHandle<Object> maybe_exception;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002874 MaybeHandle<Object> result = Execution::TryCall(
2875 this, microtask_function, factory()->undefined_value(), 0, NULL,
2876 &maybe_exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002877 // If execution is terminating, just bail out.
2878 Handle<Object> exception;
2879 if (result.is_null() && maybe_exception.is_null()) {
2880 // Clear out any remaining callbacks in the queue.
2881 heap()->set_microtask_queue(heap()->empty_fixed_array());
2882 set_pending_microtask_count(0);
2883 return;
2884 }
2885 } else {
2886 Handle<CallHandlerInfo> callback_info =
2887 Handle<CallHandlerInfo>::cast(microtask);
2888 v8::MicrotaskCallback callback =
2889 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2890 void* data = v8::ToCData<void*>(callback_info->data());
2891 callback(data);
2892 }
Ben Murdochda12d292016-06-02 14:46:10 +01002893 });
2894 }
2895}
2896
2897
2898void Isolate::AddMicrotasksCompletedCallback(
2899 MicrotasksCompletedCallback callback) {
2900 for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) {
2901 if (callback == microtasks_completed_callbacks_.at(i)) return;
2902 }
2903 microtasks_completed_callbacks_.Add(callback);
2904}
2905
2906
2907void Isolate::RemoveMicrotasksCompletedCallback(
2908 MicrotasksCompletedCallback callback) {
2909 for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) {
2910 if (callback == microtasks_completed_callbacks_.at(i)) {
2911 microtasks_completed_callbacks_.Remove(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002912 }
2913 }
2914}
2915
2916
Ben Murdochda12d292016-06-02 14:46:10 +01002917void Isolate::FireMicrotasksCompletedCallback() {
2918 for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) {
2919 microtasks_completed_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this));
2920 }
2921}
2922
2923
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002924void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2925 DCHECK(!use_counter_callback_);
2926 use_counter_callback_ = callback;
2927}
2928
2929
2930void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002931 // The counter callback may cause the embedder to call into V8, which is not
2932 // generally possible during GC.
2933 if (heap_.gc_state() == Heap::NOT_IN_GC) {
2934 if (use_counter_callback_) {
2935 HandleScope handle_scope(this);
2936 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2937 }
2938 } else {
2939 heap_.IncrementDeferredCount(feature);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002940 }
2941}
2942
2943
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002944BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2945 if (basic_block_profiler_ == NULL) {
2946 basic_block_profiler_ = new BasicBlockProfiler();
2947 }
2948 return basic_block_profiler_;
2949}
2950
2951
2952std::string Isolate::GetTurboCfgFileName() {
2953 if (FLAG_trace_turbo_cfg_file == NULL) {
2954 std::ostringstream os;
2955 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2956 return os.str();
2957 } else {
2958 return FLAG_trace_turbo_cfg_file;
2959 }
2960}
2961
Ben Murdochda12d292016-06-02 14:46:10 +01002962void Isolate::SetTailCallEliminationEnabled(bool enabled) {
2963 if (is_tail_call_elimination_enabled_ == enabled) return;
2964 is_tail_call_elimination_enabled_ = enabled;
2965 // TODO(ishell): Introduce DependencyGroup::kTailCallChangedGroup to
2966 // deoptimize only those functions that are affected by the change of this
2967 // flag.
2968 internal::Deoptimizer::DeoptimizeAll(this);
2969}
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002970
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002971// Heap::detached_contexts tracks detached contexts as pairs
2972// (number of GC since the context was detached, the context).
2973void Isolate::AddDetachedContext(Handle<Context> context) {
2974 HandleScope scope(this);
2975 Handle<WeakCell> cell = factory()->NewWeakCell(context);
2976 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2977 int length = detached_contexts->length();
2978 detached_contexts = factory()->CopyFixedArrayAndGrow(detached_contexts, 2);
2979 detached_contexts->set(length, Smi::FromInt(0));
2980 detached_contexts->set(length + 1, *cell);
2981 heap()->set_detached_contexts(*detached_contexts);
2982}
2983
2984
2985void Isolate::CheckDetachedContextsAfterGC() {
2986 HandleScope scope(this);
2987 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2988 int length = detached_contexts->length();
2989 if (length == 0) return;
2990 int new_length = 0;
2991 for (int i = 0; i < length; i += 2) {
2992 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2993 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2994 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2995 if (!cell->cleared()) {
2996 detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2997 detached_contexts->set(new_length + 1, cell);
2998 new_length += 2;
2999 }
3000 counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
3001 }
3002 if (FLAG_trace_detached_contexts) {
3003 PrintF("%d detached contexts are collected out of %d\n",
3004 length - new_length, length);
3005 for (int i = 0; i < new_length; i += 2) {
3006 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
3007 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
3008 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
3009 if (mark_sweeps > 3) {
Ben Murdochc5610432016-08-08 18:44:38 +01003010 PrintF("detached context %p\n survived %d GCs (leak?)\n",
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003011 static_cast<void*>(cell->value()), mark_sweeps);
3012 }
3013 }
3014 }
3015 if (new_length == 0) {
3016 heap()->set_detached_contexts(heap()->empty_fixed_array());
3017 } else if (new_length < length) {
3018 heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
3019 *detached_contexts, length - new_length);
3020 }
3021}
3022
3023
3024bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00003025 StackGuard* stack_guard = isolate_->stack_guard();
3026#ifdef USE_SIMULATOR
3027 // The simulator uses a separate JS stack.
3028 Address jssp_address = Simulator::current(isolate_)->get_sp();
3029 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003030 if (jssp - gap < stack_guard->real_jslimit()) return true;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00003031#endif // USE_SIMULATOR
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003032 return GetCurrentStackPosition() - gap < stack_guard->real_climit();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00003033}
3034
3035
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003036SaveContext::SaveContext(Isolate* isolate)
3037 : isolate_(isolate), prev_(isolate->save_context()) {
3038 if (isolate->context() != NULL) {
3039 context_ = Handle<Context>(isolate->context());
3040 }
3041 isolate->set_save_context(this);
3042
3043 c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
3044}
3045
3046
3047SaveContext::~SaveContext() {
3048 isolate_->set_context(context_.is_null() ? NULL : *context_);
3049 isolate_->set_save_context(prev_);
3050}
3051
3052
3053#ifdef DEBUG
3054AssertNoContextChange::AssertNoContextChange(Isolate* isolate)
3055 : isolate_(isolate), context_(isolate->context(), isolate) {}
3056#endif // DEBUG
3057
3058
Ben Murdochb8a8cc12014-11-26 15:28:44 +00003059bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
3060 // First check whether the previous scope intercepts.
3061 if (prev_ && prev_->Intercept(flag)) return true;
3062 // Then check whether this scope intercepts.
3063 if ((flag & intercept_mask_)) {
3064 intercepted_flags_ |= flag;
3065 return true;
3066 }
3067 return false;
3068}
3069
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00003070} // namespace internal
3071} // namespace v8