blob: c9f01118c5ed85e1b011caeeebe15a2737e1fbdc [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,
324 Object* receiver,
325 bool* seen_caller) {
326 if ((fun == caller) && !(*seen_caller)) {
327 *seen_caller = true;
328 return false;
329 }
330 // Skip all frames until we've seen the caller.
331 if (!(*seen_caller)) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000332 // Functions defined in native scripts are not visible unless directly
333 // exposed, in which case the native flag is set.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000334 // The --builtins-in-stack-traces command line flag allows including
335 // internal call sites in the stack trace for debugging purposes.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000336 if (!FLAG_builtins_in_stack_traces && fun->shared()->IsBuiltin()) {
337 return fun->shared()->native();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000338 }
339 return true;
340}
341
Ben Murdochda12d292016-06-02 14:46:10 +0100342static Handle<FixedArray> MaybeGrow(Isolate* isolate,
343 Handle<FixedArray> elements,
344 int cur_position, int new_size) {
345 if (new_size > elements->length()) {
346 int new_capacity = JSObject::NewElementsCapacity(elements->length());
347 Handle<FixedArray> new_elements =
348 isolate->factory()->NewFixedArrayWithHoles(new_capacity);
349 for (int i = 0; i < cur_position; i++) {
350 new_elements->set(i, elements->get(i));
351 }
352 elements = new_elements;
353 }
354 DCHECK(new_size <= elements->length());
355 return elements;
356}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000357
Ben Murdochda12d292016-06-02 14:46:10 +0100358Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSReceiver> error_object,
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000359 Handle<Object> caller) {
360 // Get stack trace limit.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000361 Handle<JSObject> error = error_function();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000362 Handle<String> stackTraceLimit =
363 factory()->InternalizeUtf8String("stackTraceLimit");
364 DCHECK(!stackTraceLimit.is_null());
365 Handle<Object> stack_trace_limit =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000366 JSReceiver::GetDataProperty(error, stackTraceLimit);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000367 if (!stack_trace_limit->IsNumber()) return factory()->undefined_value();
368 int limit = FastD2IChecked(stack_trace_limit->Number());
369 limit = Max(limit, 0); // Ensure that limit is not negative.
370
371 int initial_size = Min(limit, 10);
372 Handle<FixedArray> elements =
373 factory()->NewFixedArrayWithHoles(initial_size * 4 + 1);
374
375 // If the caller parameter is a function we skip frames until we're
376 // under it before starting to collect.
377 bool seen_caller = !caller->IsJSFunction();
378 // First element is reserved to store the number of sloppy frames.
379 int cursor = 1;
380 int frames_seen = 0;
381 int sloppy_frames = 0;
382 bool encountered_strict_function = false;
Ben Murdochda12d292016-06-02 14:46:10 +0100383 for (StackFrameIterator iter(this); !iter.done() && frames_seen < limit;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000384 iter.Advance()) {
Ben Murdochda12d292016-06-02 14:46:10 +0100385 StackFrame* frame = iter.frame();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000386
Ben Murdochda12d292016-06-02 14:46:10 +0100387 switch (frame->type()) {
388 case StackFrame::JAVA_SCRIPT:
389 case StackFrame::OPTIMIZED:
390 case StackFrame::INTERPRETED: {
391 JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame);
392 // Set initial size to the maximum inlining level + 1 for the outermost
393 // function.
394 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
395 js_frame->Summarize(&frames);
396 for (int i = frames.length() - 1; i >= 0; i--) {
397 Handle<JSFunction> fun = frames[i].function();
398 Handle<Object> recv = frames[i].receiver();
399 // Filter out internal frames that we do not want to show.
400 if (!IsVisibleInStackTrace(*fun, *caller, *recv, &seen_caller)) {
401 continue;
402 }
403 // Filter out frames from other security contexts.
404 if (!this->context()->HasSameSecurityTokenAs(fun->context())) {
405 continue;
406 }
407 elements = MaybeGrow(this, elements, cursor, cursor + 4);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100408
Ben Murdochda12d292016-06-02 14:46:10 +0100409 Handle<AbstractCode> abstract_code = frames[i].abstract_code();
410
411 Handle<Smi> offset(Smi::FromInt(frames[i].code_offset()), this);
412 // The stack trace API should not expose receivers and function
413 // objects on frames deeper than the top-most one with a strict mode
414 // function. The number of sloppy frames is stored as first element in
415 // the result array.
416 if (!encountered_strict_function) {
417 if (is_strict(fun->shared()->language_mode())) {
418 encountered_strict_function = true;
419 } else {
420 sloppy_frames++;
421 }
422 }
423 elements->set(cursor++, *recv);
424 elements->set(cursor++, *fun);
425 elements->set(cursor++, *abstract_code);
426 elements->set(cursor++, *offset);
427 frames_seen++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000428 }
Ben Murdochda12d292016-06-02 14:46:10 +0100429 } break;
430
431 case StackFrame::WASM: {
432 WasmFrame* wasm_frame = WasmFrame::cast(frame);
433 Code* code = wasm_frame->unchecked_code();
434 Handle<AbstractCode> abstract_code =
435 Handle<AbstractCode>(AbstractCode::cast(code));
436 Handle<JSFunction> fun = factory()->NewFunction(
437 factory()->NewStringFromAsciiChecked("<WASM>"));
438 elements = MaybeGrow(this, elements, cursor, cursor + 4);
439 // TODO(jfb) Pass module object.
440 elements->set(cursor++, *factory()->undefined_value());
441 elements->set(cursor++, *fun);
442 elements->set(cursor++, *abstract_code);
443 elements->set(cursor++, Internals::IntToSmi(0));
444 frames_seen++;
445 } break;
446
447 default:
448 break;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000449 }
450 }
451 elements->set(0, Smi::FromInt(sloppy_frames));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000452 elements->Shrink(cursor);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000453 Handle<JSArray> result = factory()->NewJSArrayWithElements(elements);
454 result->set_length(Smi::FromInt(cursor));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000455 // TODO(yangguo): Queue this structured stack trace for preprocessing on GC.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000456 return result;
457}
458
Ben Murdochda12d292016-06-02 14:46:10 +0100459MaybeHandle<JSReceiver> Isolate::CaptureAndSetDetailedStackTrace(
460 Handle<JSReceiver> error_object) {
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100461 if (capture_stack_trace_for_uncaught_exceptions_) {
462 // Capture stack trace for a detailed exception message.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000463 Handle<Name> key = factory()->detailed_stack_trace_symbol();
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100464 Handle<JSArray> stack_trace = CaptureCurrentStackTrace(
465 stack_trace_for_uncaught_exceptions_frame_limit_,
466 stack_trace_for_uncaught_exceptions_options_);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000467 RETURN_ON_EXCEPTION(
Ben Murdochda12d292016-06-02 14:46:10 +0100468 this, JSReceiver::SetProperty(error_object, key, stack_trace, STRICT),
469 JSReceiver);
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100470 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000471 return error_object;
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100472}
473
Ben Murdochda12d292016-06-02 14:46:10 +0100474MaybeHandle<JSReceiver> Isolate::CaptureAndSetSimpleStackTrace(
475 Handle<JSReceiver> error_object, Handle<Object> caller) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000476 // Capture stack trace for simple stack trace string formatting.
477 Handle<Name> key = factory()->stack_trace_symbol();
478 Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000479 RETURN_ON_EXCEPTION(
Ben Murdochda12d292016-06-02 14:46:10 +0100480 this, JSReceiver::SetProperty(error_object, key, stack_trace, STRICT),
481 JSReceiver);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000482 return error_object;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000483}
484
485
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400486Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) {
487 Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol();
488 Handle<Object> stack_trace =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000489 JSReceiver::GetDataProperty(error_object, key_detailed);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400490 if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace);
491
492 if (!capture_stack_trace_for_uncaught_exceptions_) return Handle<JSArray>();
493
494 // Try to get details from simple stack trace.
495 Handle<JSArray> detailed_stack_trace =
496 GetDetailedFromSimpleStackTrace(error_object);
497 if (!detailed_stack_trace.is_null()) {
498 // Save the detailed stack since the simple one might be withdrawn later.
499 JSObject::SetProperty(error_object, key_detailed, detailed_stack_trace,
500 STRICT).Assert();
501 }
502 return detailed_stack_trace;
503}
504
505
506class CaptureStackTraceHelper {
507 public:
508 CaptureStackTraceHelper(Isolate* isolate,
509 StackTrace::StackTraceOptions options)
510 : isolate_(isolate) {
511 if (options & StackTrace::kColumnOffset) {
512 column_key_ =
513 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column"));
514 }
515 if (options & StackTrace::kLineNumber) {
516 line_key_ =
517 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber"));
518 }
519 if (options & StackTrace::kScriptId) {
520 script_id_key_ =
521 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId"));
522 }
523 if (options & StackTrace::kScriptName) {
524 script_name_key_ =
525 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName"));
526 }
527 if (options & StackTrace::kScriptNameOrSourceURL) {
528 script_name_or_source_url_key_ = factory()->InternalizeOneByteString(
529 STATIC_CHAR_VECTOR("scriptNameOrSourceURL"));
530 }
531 if (options & StackTrace::kFunctionName) {
532 function_key_ = factory()->InternalizeOneByteString(
533 STATIC_CHAR_VECTOR("functionName"));
534 }
535 if (options & StackTrace::kIsEval) {
536 eval_key_ =
537 factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval"));
538 }
539 if (options & StackTrace::kIsConstructor) {
540 constructor_key_ = factory()->InternalizeOneByteString(
541 STATIC_CHAR_VECTOR("isConstructor"));
542 }
543 }
544
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000545 Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun, int position,
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400546 bool is_constructor) {
547 Handle<JSObject> stack_frame =
548 factory()->NewJSObject(isolate_->object_function());
549
550 Handle<Script> script(Script::cast(fun->shared()->script()));
551
552 if (!line_key_.is_null()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000553 int script_line_offset = script->line_offset();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400554 int line_number = Script::GetLineNumber(script, position);
555 // line_number is already shifted by the script_line_offset.
556 int relative_line_number = line_number - script_line_offset;
557 if (!column_key_.is_null() && relative_line_number >= 0) {
558 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
559 int start = (relative_line_number == 0) ? 0 :
560 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
561 int column_offset = position - start;
562 if (relative_line_number == 0) {
563 // For the case where the code is on the same line as the script
564 // tag.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000565 column_offset += script->column_offset();
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400566 }
567 JSObject::AddProperty(stack_frame, column_key_,
568 handle(Smi::FromInt(column_offset + 1), isolate_),
569 NONE);
570 }
571 JSObject::AddProperty(stack_frame, line_key_,
572 handle(Smi::FromInt(line_number + 1), isolate_),
573 NONE);
574 }
575
576 if (!script_id_key_.is_null()) {
577 JSObject::AddProperty(stack_frame, script_id_key_,
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000578 handle(Smi::FromInt(script->id()), isolate_), NONE);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400579 }
580
581 if (!script_name_key_.is_null()) {
582 JSObject::AddProperty(stack_frame, script_name_key_,
583 handle(script->name(), isolate_), NONE);
584 }
585
586 if (!script_name_or_source_url_key_.is_null()) {
587 Handle<Object> result = Script::GetNameOrSourceURL(script);
588 JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result,
589 NONE);
590 }
591
592 if (!function_key_.is_null()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000593 Handle<Object> fun_name = JSFunction::GetDebugName(fun);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400594 JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE);
595 }
596
597 if (!eval_key_.is_null()) {
598 Handle<Object> is_eval = factory()->ToBoolean(
599 script->compilation_type() == Script::COMPILATION_TYPE_EVAL);
600 JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE);
601 }
602
603 if (!constructor_key_.is_null()) {
604 Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor);
605 JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj,
606 NONE);
607 }
608
609 return stack_frame;
610 }
611
612 private:
613 inline Factory* factory() { return isolate_->factory(); }
614
615 Isolate* isolate_;
616 Handle<String> column_key_;
617 Handle<String> line_key_;
618 Handle<String> script_id_key_;
619 Handle<String> script_name_key_;
620 Handle<String> script_name_or_source_url_key_;
621 Handle<String> function_key_;
622 Handle<String> eval_key_;
623 Handle<String> constructor_key_;
624};
625
626
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000627int PositionFromStackTrace(Handle<FixedArray> elements, int index) {
628 DisallowHeapAllocation no_gc;
629 Object* maybe_code = elements->get(index + 2);
630 if (maybe_code->IsSmi()) {
631 return Smi::cast(maybe_code)->value();
632 } else {
Ben Murdoch097c5b22016-05-18 11:27:45 +0100633 AbstractCode* abstract_code = AbstractCode::cast(maybe_code);
634 int code_offset = Smi::cast(elements->get(index + 3))->value();
635 return abstract_code->SourcePosition(code_offset);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000636 }
637}
638
639
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400640Handle<JSArray> Isolate::GetDetailedFromSimpleStackTrace(
641 Handle<JSObject> error_object) {
642 Handle<Name> key = factory()->stack_trace_symbol();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000643 Handle<Object> property = JSReceiver::GetDataProperty(error_object, key);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400644 if (!property->IsJSArray()) return Handle<JSArray>();
645 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
646
647 CaptureStackTraceHelper helper(this,
648 stack_trace_for_uncaught_exceptions_options_);
649
650 int frames_seen = 0;
651 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
652 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
653
654 int frame_limit = stack_trace_for_uncaught_exceptions_frame_limit_;
655 if (frame_limit < 0) frame_limit = (elements_limit - 1) / 4;
656
657 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
658 for (int i = 1; i < elements_limit && frames_seen < frame_limit; i += 4) {
659 Handle<Object> recv = handle(elements->get(i), this);
660 Handle<JSFunction> fun =
661 handle(JSFunction::cast(elements->get(i + 1)), this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400662 bool is_constructor =
663 recv->IsJSObject() &&
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000664 Handle<JSObject>::cast(recv)->map()->GetConstructor() == *fun;
665 int position = PositionFromStackTrace(elements, i);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400666
667 Handle<JSObject> stack_frame =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000668 helper.NewStackFrameObject(fun, position, is_constructor);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400669
670 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
671 frames_seen++;
672 }
673
674 stack_trace->set_length(Smi::FromInt(frames_seen));
675 return stack_trace;
676}
677
678
Ben Murdoch257744e2011-11-30 15:57:28 +0000679Handle<JSArray> Isolate::CaptureCurrentStackTrace(
680 int frame_limit, StackTrace::StackTraceOptions options) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400681 CaptureStackTraceHelper helper(this, options);
682
Ben Murdoch257744e2011-11-30 15:57:28 +0000683 // Ensure no negative values.
684 int limit = Max(frame_limit, 0);
685 Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit);
686
Ben Murdoch257744e2011-11-30 15:57:28 +0000687 StackTraceFrameIterator it(this);
688 int frames_seen = 0;
689 while (!it.done() && (frames_seen < limit)) {
690 JavaScriptFrame* frame = it.frame();
691 // Set initial size to the maximum inlining level + 1 for the outermost
692 // function.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000693 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
Ben Murdoch257744e2011-11-30 15:57:28 +0000694 frame->Summarize(&frames);
695 for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000696 Handle<JSFunction> fun = frames[i].function();
697 // Filter frames from other security contexts.
698 if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
699 !this->context()->HasSameSecurityTokenAs(fun->context())) continue;
Ben Murdoch097c5b22016-05-18 11:27:45 +0100700 int position =
701 frames[i].abstract_code()->SourcePosition(frames[i].code_offset());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000702 Handle<JSObject> stack_frame =
703 helper.NewStackFrameObject(fun, position, frames[i].is_constructor());
Ben Murdoch257744e2011-11-30 15:57:28 +0000704
Ben Murdoch3ef787d2012-04-12 10:51:47 +0100705 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stack_frame);
Ben Murdoch257744e2011-11-30 15:57:28 +0000706 frames_seen++;
707 }
708 it.Advance();
709 }
710
711 stack_trace->set_length(Smi::FromInt(frames_seen));
712 return stack_trace;
713}
714
715
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000716void Isolate::PrintStack(FILE* out, PrintStackMode mode) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000717 if (stack_trace_nesting_level_ == 0) {
718 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000719 StringStream::ClearMentionedObjectCache(this);
720 HeapStringAllocator allocator;
721 StringStream accumulator(&allocator);
Ben Murdoch257744e2011-11-30 15:57:28 +0000722 incomplete_message_ = &accumulator;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000723 PrintStack(&accumulator, mode);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000724 accumulator.OutputToFile(out);
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000725 InitializeLoggingAndCounters();
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000726 accumulator.Log(this);
Ben Murdoch257744e2011-11-30 15:57:28 +0000727 incomplete_message_ = NULL;
728 stack_trace_nesting_level_ = 0;
Ben Murdoch257744e2011-11-30 15:57:28 +0000729 } else if (stack_trace_nesting_level_ == 1) {
730 stack_trace_nesting_level_++;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000731 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000732 "\n\nAttempt to print stack while printing stack (double fault)\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000733 base::OS::PrintError(
Ben Murdoch257744e2011-11-30 15:57:28 +0000734 "If you are lucky you may find a partial stack dump on stdout.\n\n");
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000735 incomplete_message_->OutputToFile(out);
Ben Murdoch257744e2011-11-30 15:57:28 +0000736 }
737}
738
739
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000740static void PrintFrames(Isolate* isolate,
741 StringStream* accumulator,
Ben Murdoch257744e2011-11-30 15:57:28 +0000742 StackFrame::PrintMode mode) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000743 StackFrameIterator it(isolate);
Ben Murdoch257744e2011-11-30 15:57:28 +0000744 for (int i = 0; !it.done(); it.Advance()) {
745 it.frame()->Print(accumulator, mode, i++);
746 }
747}
748
749
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000750void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) {
Ben Murdoch257744e2011-11-30 15:57:28 +0000751 // The MentionedObjectCache is not GC-proof at the moment.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000752 DisallowHeapAllocation no_gc;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000753 DCHECK(accumulator->IsMentionedObjectCacheClear(this));
Ben Murdoch257744e2011-11-30 15:57:28 +0000754
755 // Avoid printing anything if there are no frames.
756 if (c_entry_fp(thread_local_top()) == 0) return;
757
758 accumulator->Add(
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000759 "\n==== JS stack trace =========================================\n\n");
760 PrintFrames(this, accumulator, StackFrame::OVERVIEW);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000761 if (mode == kPrintStackVerbose) {
762 accumulator->Add(
763 "\n==== Details ================================================\n\n");
764 PrintFrames(this, accumulator, StackFrame::DETAILS);
765 accumulator->PrintMentionedObjectCache(this);
766 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000767 accumulator->Add("=====================\n\n");
768}
769
770
771void Isolate::SetFailedAccessCheckCallback(
772 v8::FailedAccessCheckCallback callback) {
773 thread_local_top()->failed_access_check_callback_ = callback;
774}
775
776
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000777static inline AccessCheckInfo* GetAccessCheckInfo(Isolate* isolate,
778 Handle<JSObject> receiver) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000779 Object* maybe_constructor = receiver->map()->GetConstructor();
780 if (!maybe_constructor->IsJSFunction()) return NULL;
781 JSFunction* constructor = JSFunction::cast(maybe_constructor);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000782 if (!constructor->shared()->IsApiFunction()) return NULL;
Ben Murdoch257744e2011-11-30 15:57:28 +0000783
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000784 Object* data_obj =
785 constructor->shared()->get_api_func_data()->access_check_info();
786 if (data_obj == isolate->heap()->undefined_value()) return NULL;
787
788 return AccessCheckInfo::cast(data_obj);
789}
790
791
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000792void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000793 if (!thread_local_top()->failed_access_check_callback_) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000794 return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess));
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000795 }
796
797 DCHECK(receiver->IsAccessCheckNeeded());
798 DCHECK(context());
Ben Murdoch257744e2011-11-30 15:57:28 +0000799
800 // Get the data object from access check info.
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000801 HandleScope scope(this);
802 Handle<Object> data;
803 { DisallowHeapAllocation no_gc;
804 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000805 if (!access_check_info) {
806 AllowHeapAllocation doesnt_matter_anymore;
807 return ScheduleThrow(
808 *factory()->NewTypeError(MessageTemplate::kNoAccess));
809 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000810 data = handle(access_check_info->data(), this);
811 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000812
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000813 // Leaving JavaScript.
814 VMState<EXTERNAL> state(this);
815 thread_local_top()->failed_access_check_callback_(
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000816 v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000817}
818
819
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000820bool Isolate::MayAccess(Handle<Context> accessing_context,
821 Handle<JSObject> receiver) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000822 DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
Ben Murdoch257744e2011-11-30 15:57:28 +0000823
Ben Murdoch257744e2011-11-30 15:57:28 +0000824 // Check for compatibility between the security tokens in the
825 // current lexical context and the accessed object.
Ben Murdoch257744e2011-11-30 15:57:28 +0000826
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000827 // During bootstrapping, callback functions are not enabled yet.
828 if (bootstrapper()->IsActive()) return true;
829 {
830 DisallowHeapAllocation no_gc;
831
832 if (receiver->IsJSGlobalProxy()) {
833 Object* receiver_context =
834 JSGlobalProxy::cast(*receiver)->native_context();
835 if (!receiver_context->IsContext()) return false;
836
837 // Get the native context of current top context.
838 // avoid using Isolate::native_context() because it uses Handle.
839 Context* native_context =
840 accessing_context->global_object()->native_context();
841 if (receiver_context == native_context) return true;
842
843 if (Context::cast(receiver_context)->security_token() ==
844 native_context->security_token())
845 return true;
846 }
847 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000848
Ben Murdoch257744e2011-11-30 15:57:28 +0000849 HandleScope scope(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000850 Handle<Object> data;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000851 v8::AccessCheckCallback callback = nullptr;
852 v8::NamedSecurityCallback named_callback = nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000853 { DisallowHeapAllocation no_gc;
854 AccessCheckInfo* access_check_info = GetAccessCheckInfo(this, receiver);
855 if (!access_check_info) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000856 Object* fun_obj = access_check_info->callback();
857 callback = v8::ToCData<v8::AccessCheckCallback>(fun_obj);
Ben Murdoch097c5b22016-05-18 11:27:45 +0100858 data = handle(access_check_info->data(), this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000859 if (!callback) {
860 fun_obj = access_check_info->named_callback();
861 named_callback = v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
862 if (!named_callback) return false;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000863 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000864 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000865
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000866 LOG(this, ApiSecurityCheck());
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000867
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000868 {
869 // Leaving JavaScript.
870 VMState<EXTERNAL> state(this);
871 if (callback) {
872 return callback(v8::Utils::ToLocal(accessing_context),
Ben Murdoch097c5b22016-05-18 11:27:45 +0100873 v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(data));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000874 }
875 Handle<Object> key = factory()->undefined_value();
876 return named_callback(v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(key),
877 v8::ACCESS_HAS, v8::Utils::ToLocal(data));
Ben Murdoch257744e2011-11-30 15:57:28 +0000878 }
Ben Murdoch257744e2011-11-30 15:57:28 +0000879}
880
881
882const char* const Isolate::kStackOverflowMessage =
883 "Uncaught RangeError: Maximum call stack size exceeded";
884
885
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000886Object* Isolate::StackOverflow() {
887 HandleScope scope(this);
888 // At this point we cannot create an Error object using its javascript
889 // constructor. Instead, we copy the pre-constructed boilerplate and
890 // attach the stack trace as a hidden property.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000891 Handle<Object> exception;
892 if (bootstrapper()->IsActive()) {
893 // There is no boilerplate to use during bootstrapping.
894 exception = factory()->NewStringFromAsciiChecked(
895 MessageTemplate::TemplateString(MessageTemplate::kStackOverflow));
896 } else {
897 Handle<JSObject> boilerplate = stack_overflow_boilerplate();
898 Handle<JSObject> copy = factory()->CopyJSObject(boilerplate);
899 CaptureAndSetSimpleStackTrace(copy, factory()->undefined_value());
900 exception = copy;
901 }
902 Throw(*exception, nullptr);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000903
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000904#ifdef VERIFY_HEAP
905 if (FLAG_verify_heap && FLAG_stress_compaction) {
Ben Murdochda12d292016-06-02 14:46:10 +0100906 heap()->CollectAllGarbage(Heap::kNoGCFlags, "trigger compaction");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000907 }
908#endif // VERIFY_HEAP
909
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000910 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +0000911}
912
913
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000914Object* Isolate::TerminateExecution() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000915 return Throw(heap_.termination_exception(), nullptr);
Ben Murdoch257744e2011-11-30 15:57:28 +0000916}
917
918
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000919void Isolate::CancelTerminateExecution() {
920 if (try_catch_handler()) {
921 try_catch_handler()->has_terminated_ = false;
922 }
923 if (has_pending_exception() &&
924 pending_exception() == heap_.termination_exception()) {
925 thread_local_top()->external_caught_exception_ = false;
926 clear_pending_exception();
927 }
928 if (has_scheduled_exception() &&
929 scheduled_exception() == heap_.termination_exception()) {
930 thread_local_top()->external_caught_exception_ = false;
931 clear_scheduled_exception();
932 }
933}
934
935
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400936void Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
937 ExecutionAccess access(this);
938 api_interrupts_queue_.push(InterruptEntry(callback, data));
939 stack_guard()->RequestApiInterrupt();
940}
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000941
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400942
943void Isolate::InvokeApiInterruptCallbacks() {
944 // Note: callback below should be called outside of execution access lock.
945 while (true) {
946 InterruptEntry entry;
947 {
948 ExecutionAccess access(this);
949 if (api_interrupts_queue_.empty()) return;
950 entry = api_interrupts_queue_.front();
951 api_interrupts_queue_.pop();
952 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000953 VMState<EXTERNAL> state(this);
954 HandleScope handle_scope(this);
Emily Bernierd0a1eb72015-03-24 16:35:39 -0400955 entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
Ben Murdochb8a8cc12014-11-26 15:28:44 +0000956 }
957}
958
959
Ben Murdoch4a90d5f2016-03-22 12:00:34 +0000960void ReportBootstrappingException(Handle<Object> exception,
961 MessageLocation* location) {
962 base::OS::PrintError("Exception thrown during bootstrapping\n");
963 if (location == NULL || location->script().is_null()) return;
964 // We are bootstrapping and caught an error where the location is set
965 // and we have a script for the location.
966 // In this case we could have an extension (or an internal error
967 // somewhere) and we print out the line number at which the error occured
968 // to the console for easier debugging.
969 int line_number =
970 location->script()->GetLineNumber(location->start_pos()) + 1;
971 if (exception->IsString() && location->script()->name()->IsString()) {
972 base::OS::PrintError(
973 "Extension or internal compilation error: %s in %s at line %d.\n",
974 String::cast(*exception)->ToCString().get(),
975 String::cast(location->script()->name())->ToCString().get(),
976 line_number);
977 } else if (location->script()->name()->IsString()) {
978 base::OS::PrintError(
979 "Extension or internal compilation error in %s at line %d.\n",
980 String::cast(location->script()->name())->ToCString().get(),
981 line_number);
982 } else if (exception->IsString()) {
983 base::OS::PrintError("Extension or internal compilation error: %s.\n",
984 String::cast(*exception)->ToCString().get());
985 } else {
986 base::OS::PrintError("Extension or internal compilation error.\n");
987 }
988#ifdef OBJECT_PRINT
989 // Since comments and empty lines have been stripped from the source of
990 // builtins, print the actual source here so that line numbers match.
991 if (location->script()->source()->IsString()) {
992 Handle<String> src(String::cast(location->script()->source()));
993 PrintF("Failing script:");
994 int len = src->length();
995 if (len == 0) {
996 PrintF(" <not available>\n");
997 } else {
998 PrintF("\n");
999 int line_number = 1;
1000 PrintF("%5d: ", line_number);
1001 for (int i = 0; i < len; i++) {
1002 uint16_t character = src->Get(i);
1003 PrintF("%c", character);
1004 if (character == '\n' && i < len - 2) {
1005 PrintF("%5d: ", ++line_number);
1006 }
1007 }
1008 PrintF("\n");
1009 }
1010 }
1011#endif
1012}
1013
1014
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001015Object* Isolate::Throw(Object* exception, MessageLocation* location) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001016 DCHECK(!has_pending_exception());
1017
1018 HandleScope scope(this);
1019 Handle<Object> exception_handle(exception, this);
1020
1021 // Determine whether a message needs to be created for the given exception
1022 // depending on the following criteria:
1023 // 1) External v8::TryCatch missing: Always create a message because any
1024 // JavaScript handler for a finally-block might re-throw to top-level.
1025 // 2) External v8::TryCatch exists: Only create a message if the handler
1026 // captures messages or is verbose (which reports despite the catch).
1027 // 3) ReThrow from v8::TryCatch: The message from a previous throw still
1028 // exists and we preserve it instead of creating a new message.
1029 bool requires_message = try_catch_handler() == nullptr ||
1030 try_catch_handler()->is_verbose_ ||
1031 try_catch_handler()->capture_message_;
1032 bool rethrowing_message = thread_local_top()->rethrowing_message_;
1033
1034 thread_local_top()->rethrowing_message_ = false;
1035
1036 // Notify debugger of exception.
1037 if (is_catchable_by_javascript(exception)) {
1038 debug()->OnThrow(exception_handle);
1039 }
1040
1041 // Generate the message if required.
1042 if (requires_message && !rethrowing_message) {
1043 MessageLocation computed_location;
1044 // If no location was specified we try to use a computed one instead.
1045 if (location == NULL && ComputeLocation(&computed_location)) {
1046 location = &computed_location;
1047 }
1048
1049 if (bootstrapper()->IsActive()) {
1050 // It's not safe to try to make message objects or collect stack traces
1051 // while the bootstrapper is active since the infrastructure may not have
1052 // been properly initialized.
1053 ReportBootstrappingException(exception_handle, location);
1054 } else {
1055 Handle<Object> message_obj = CreateMessage(exception_handle, location);
1056 thread_local_top()->pending_message_obj_ = *message_obj;
1057
1058 // For any exception not caught by JavaScript, even when an external
1059 // handler is present:
1060 // If the abort-on-uncaught-exception flag is specified, and if the
1061 // embedder didn't specify a custom uncaught exception callback,
1062 // or if the custom callback determined that V8 should abort, then
1063 // abort.
1064 if (FLAG_abort_on_uncaught_exception &&
1065 PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT &&
1066 (!abort_on_uncaught_exception_callback_ ||
1067 abort_on_uncaught_exception_callback_(
1068 reinterpret_cast<v8::Isolate*>(this)))) {
1069 // Prevent endless recursion.
1070 FLAG_abort_on_uncaught_exception = false;
1071 // This flag is intended for use by JavaScript developers, so
1072 // print a user-friendly stack trace (not an internal one).
1073 PrintF(stderr, "%s\n\nFROM\n",
1074 MessageHandler::GetLocalizedMessage(this, message_obj).get());
1075 PrintCurrentStackTrace(stderr);
1076 base::OS::Abort();
1077 }
1078 }
1079 }
1080
1081 // Set the exception being thrown.
1082 set_pending_exception(*exception_handle);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001083 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001084}
1085
1086
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001087Object* Isolate::ReThrow(Object* exception) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001088 DCHECK(!has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001089
1090 // Set the exception being re-thrown.
1091 set_pending_exception(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001092 return heap()->exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001093}
1094
1095
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001096Object* Isolate::UnwindAndFindHandler() {
1097 Object* exception = pending_exception();
1098
1099 Code* code = nullptr;
1100 Context* context = nullptr;
1101 intptr_t offset = 0;
1102 Address handler_sp = nullptr;
1103 Address handler_fp = nullptr;
1104
1105 // Special handling of termination exceptions, uncatchable by JavaScript code,
1106 // we unwind the handlers until the top ENTRY handler is found.
1107 bool catchable_by_js = is_catchable_by_javascript(exception);
1108
1109 // Compute handler and stack unwinding information by performing a full walk
1110 // over the stack and dispatching according to the frame type.
1111 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1112 StackFrame* frame = iter.frame();
1113
1114 // For JSEntryStub frames we always have a handler.
1115 if (frame->is_entry() || frame->is_entry_construct()) {
1116 StackHandler* handler = frame->top_handler();
1117
1118 // Restore the next handler.
1119 thread_local_top()->handler_ = handler->next()->address();
1120
1121 // Gather information from the handler.
1122 code = frame->LookupCode();
1123 handler_sp = handler->address() + StackHandlerConstants::kSize;
1124 offset = Smi::cast(code->handler_table()->get(0))->value();
1125 break;
1126 }
1127
1128 // For optimized frames we perform a lookup in the handler table.
1129 if (frame->is_optimized() && catchable_by_js) {
1130 OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
1131 int stack_slots = 0; // Will contain stack slot count of frame.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001132 offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, nullptr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001133 if (offset >= 0) {
1134 // Compute the stack pointer from the frame pointer. This ensures that
1135 // argument slots on the stack are dropped as returning would.
Ben Murdoch097c5b22016-05-18 11:27:45 +01001136 Address return_sp = frame->fp() +
1137 StandardFrameConstants::kFixedFrameSizeAboveFp -
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001138 stack_slots * kPointerSize;
1139
1140 // Gather information from the frame.
1141 code = frame->LookupCode();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001142 if (code->marked_for_deoptimization()) {
1143 // If the target code is lazy deoptimized, we jump to the original
1144 // return address, but we make a note that we are throwing, so that
1145 // the deoptimizer can do the right thing.
1146 offset = static_cast<int>(frame->pc() - code->entry());
1147 set_deoptimizer_lazy_throw(true);
1148 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001149 handler_sp = return_sp;
1150 handler_fp = frame->fp();
1151 break;
1152 }
1153 }
1154
Ben Murdoch097c5b22016-05-18 11:27:45 +01001155 // For interpreted frame we perform a range lookup in the handler table.
1156 if (frame->is_interpreted() && catchable_by_js) {
1157 InterpretedFrame* js_frame = static_cast<InterpretedFrame*>(frame);
1158 int context_reg = 0; // Will contain register index holding context.
1159 offset = js_frame->LookupExceptionHandlerInTable(&context_reg, nullptr);
1160 if (offset >= 0) {
1161 // Patch the bytecode offset in the interpreted frame to reflect the
1162 // position of the exception handler. The special builtin below will
1163 // take care of continuing to dispatch at that position. Also restore
1164 // the correct context for the handler from the interpreter register.
1165 context = Context::cast(js_frame->GetInterpreterRegister(context_reg));
1166 js_frame->PatchBytecodeOffset(static_cast<int>(offset));
1167 offset = 0;
1168
1169 // Gather information from the frame.
1170 code = *builtins()->InterpreterEnterBytecodeDispatch();
1171 handler_sp = frame->sp();
1172 handler_fp = frame->fp();
1173 break;
1174 }
1175 }
1176
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001177 // For JavaScript frames we perform a range lookup in the handler table.
1178 if (frame->is_java_script() && catchable_by_js) {
1179 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
Ben Murdoch097c5b22016-05-18 11:27:45 +01001180 int stack_depth = 0; // Will contain operand stack depth of handler.
1181 offset = js_frame->LookupExceptionHandlerInTable(&stack_depth, nullptr);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001182 if (offset >= 0) {
1183 // Compute the stack pointer from the frame pointer. This ensures that
1184 // operand stack slots are dropped for nested statements. Also restore
1185 // correct context for the handler which is pushed within the try-block.
1186 Address return_sp = frame->fp() -
1187 StandardFrameConstants::kFixedFrameSizeFromFp -
Ben Murdoch097c5b22016-05-18 11:27:45 +01001188 stack_depth * kPointerSize;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001189 STATIC_ASSERT(TryBlockConstant::kElementCount == 1);
1190 context = Context::cast(Memory::Object_at(return_sp - kPointerSize));
1191
1192 // Gather information from the frame.
1193 code = frame->LookupCode();
1194 handler_sp = return_sp;
1195 handler_fp = frame->fp();
1196 break;
1197 }
1198 }
1199
1200 RemoveMaterializedObjectsOnUnwind(frame);
1201 }
1202
1203 // Handler must exist.
1204 CHECK(code != nullptr);
1205
1206 // Store information to be consumed by the CEntryStub.
1207 thread_local_top()->pending_handler_context_ = context;
1208 thread_local_top()->pending_handler_code_ = code;
1209 thread_local_top()->pending_handler_offset_ = offset;
1210 thread_local_top()->pending_handler_fp_ = handler_fp;
1211 thread_local_top()->pending_handler_sp_ = handler_sp;
1212
1213 // Return and clear pending exception.
1214 clear_pending_exception();
1215 return exception;
1216}
1217
1218
1219Isolate::CatchType Isolate::PredictExceptionCatcher() {
1220 Address external_handler = thread_local_top()->try_catch_handler_address();
1221 Address entry_handler = Isolate::handler(thread_local_top());
1222 if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL;
1223
1224 // Search for an exception handler by performing a full walk over the stack.
1225 for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
1226 StackFrame* frame = iter.frame();
1227
1228 // For JSEntryStub frames we update the JS_ENTRY handler.
1229 if (frame->is_entry() || frame->is_entry_construct()) {
1230 entry_handler = frame->top_handler()->next()->address();
1231 }
1232
1233 // For JavaScript frames we perform a lookup in the handler table.
1234 if (frame->is_java_script()) {
1235 JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001236 HandlerTable::CatchPrediction prediction;
Ben Murdoch097c5b22016-05-18 11:27:45 +01001237 if (js_frame->LookupExceptionHandlerInTable(nullptr, &prediction) > 0) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001238 // We are conservative with our prediction: try-finally is considered
1239 // to always rethrow, to meet the expectation of the debugger.
1240 if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT;
1241 }
1242 }
1243
1244 // The exception has been externally caught if and only if there is an
1245 // external handler which is on top of the top-most JS_ENTRY handler.
1246 if (external_handler != nullptr && !try_catch_handler()->is_verbose_) {
1247 if (entry_handler == nullptr || entry_handler > external_handler) {
1248 return CAUGHT_BY_EXTERNAL;
1249 }
1250 }
1251 }
1252
1253 // Handler not found.
1254 return NOT_CAUGHT;
1255}
1256
1257
1258void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) {
1259 if (frame->is_optimized()) {
1260 bool removed = materialized_object_store_->Remove(frame->fp());
1261 USE(removed);
1262 // If there were any materialized objects, the code should be
1263 // marked for deopt.
1264 DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization());
1265 }
1266}
1267
1268
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001269Object* Isolate::ThrowIllegalOperation() {
1270 if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001271 return Throw(heap()->illegal_access_string());
Ben Murdoch257744e2011-11-30 15:57:28 +00001272}
1273
1274
1275void Isolate::ScheduleThrow(Object* exception) {
1276 // When scheduling a throw we first throw the exception to get the
1277 // error reporting if it is uncaught before rescheduling it.
1278 Throw(exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001279 PropagatePendingExceptionToExternalTryCatch();
1280 if (has_pending_exception()) {
1281 thread_local_top()->scheduled_exception_ = pending_exception();
1282 thread_local_top()->external_caught_exception_ = false;
1283 clear_pending_exception();
1284 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001285}
1286
1287
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001288void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
1289 DCHECK(handler == try_catch_handler());
1290 DCHECK(handler->HasCaught());
1291 DCHECK(handler->rethrow_);
1292 DCHECK(handler->capture_message_);
1293 Object* message = reinterpret_cast<Object*>(handler->message_obj_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001294 DCHECK(message->IsJSMessageObject() || message->IsTheHole());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001295 thread_local_top()->pending_message_obj_ = message;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001296}
1297
1298
1299void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
1300 DCHECK(has_scheduled_exception());
1301 if (scheduled_exception() == handler->exception_) {
1302 DCHECK(scheduled_exception() != heap()->termination_exception());
1303 clear_scheduled_exception();
1304 }
1305}
1306
1307
1308Object* Isolate::PromoteScheduledException() {
1309 Object* thrown = scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001310 clear_scheduled_exception();
1311 // Re-throw the exception to avoid getting repeated error reporting.
1312 return ReThrow(thrown);
1313}
1314
1315
1316void Isolate::PrintCurrentStackTrace(FILE* out) {
1317 StackTraceFrameIterator it(this);
1318 while (!it.done()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001319 HandleScope scope(this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001320 // Find code position if recorded in relocation info.
1321 JavaScriptFrame* frame = it.frame();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001322 Code* code = frame->LookupCode();
1323 int offset = static_cast<int>(frame->pc() - code->instruction_start());
1324 int pos = frame->LookupCode()->SourcePosition(offset);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001325 Handle<Object> pos_obj(Smi::FromInt(pos), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001326 // Fetch function and receiver.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001327 Handle<JSFunction> fun(frame->function());
1328 Handle<Object> recv(frame->receiver(), this);
Ben Murdoch257744e2011-11-30 15:57:28 +00001329 // Advance to the next JavaScript frame and determine if the
1330 // current frame is the top-level frame.
1331 it.Advance();
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001332 Handle<Object> is_top_level = factory()->ToBoolean(it.done());
Ben Murdoch257744e2011-11-30 15:57:28 +00001333 // Generate and print stack trace line.
1334 Handle<String> line =
1335 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
1336 if (line->length() > 0) {
1337 line->PrintOn(out);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001338 PrintF(out, "\n");
Ben Murdoch257744e2011-11-30 15:57:28 +00001339 }
1340 }
1341}
1342
1343
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001344bool Isolate::ComputeLocation(MessageLocation* target) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001345 StackTraceFrameIterator it(this);
1346 if (!it.done()) {
1347 JavaScriptFrame* frame = it.frame();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001348 JSFunction* fun = frame->function();
Ben Murdoch257744e2011-11-30 15:57:28 +00001349 Object* script = fun->shared()->script();
1350 if (script->IsScript() &&
1351 !(Script::cast(script)->source()->IsUndefined())) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001352 Handle<Script> casted_script(Script::cast(script));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001353 // Compute the location from the function and the relocation info of the
1354 // baseline code. For optimized code this will use the deoptimization
1355 // information to get canonical location information.
1356 List<FrameSummary> frames(FLAG_max_inlining_levels + 1);
1357 it.frame()->Summarize(&frames);
1358 FrameSummary& summary = frames.last();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001359 int pos = summary.abstract_code()->SourcePosition(summary.code_offset());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001360 *target = MessageLocation(casted_script, pos, pos + 1, handle(fun));
1361 return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001362 }
1363 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001364 return false;
1365}
1366
1367
1368bool Isolate::ComputeLocationFromException(MessageLocation* target,
1369 Handle<Object> exception) {
1370 if (!exception->IsJSObject()) return false;
1371
1372 Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
1373 Handle<Object> start_pos = JSReceiver::GetDataProperty(
1374 Handle<JSObject>::cast(exception), start_pos_symbol);
1375 if (!start_pos->IsSmi()) return false;
1376 int start_pos_value = Handle<Smi>::cast(start_pos)->value();
1377
1378 Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
1379 Handle<Object> end_pos = JSReceiver::GetDataProperty(
1380 Handle<JSObject>::cast(exception), end_pos_symbol);
1381 if (!end_pos->IsSmi()) return false;
1382 int end_pos_value = Handle<Smi>::cast(end_pos)->value();
1383
1384 Handle<Name> script_symbol = factory()->error_script_symbol();
1385 Handle<Object> script = JSReceiver::GetDataProperty(
1386 Handle<JSObject>::cast(exception), script_symbol);
1387 if (!script->IsScript()) return false;
1388
1389 Handle<Script> cast_script(Script::cast(*script));
1390 *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
1391 return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001392}
1393
1394
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001395bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target,
1396 Handle<Object> exception) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001397 if (!exception->IsJSObject()) return false;
1398 Handle<Name> key = factory()->stack_trace_symbol();
1399 Handle<Object> property =
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001400 JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001401 if (!property->IsJSArray()) return false;
1402 Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property);
1403
1404 Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements()));
1405 int elements_limit = Smi::cast(simple_stack_trace->length())->value();
1406
1407 for (int i = 1; i < elements_limit; i += 4) {
1408 Handle<JSFunction> fun =
1409 handle(JSFunction::cast(elements->get(i + 1)), this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001410 if (!fun->shared()->IsSubjectToDebugging()) continue;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001411
1412 Object* script = fun->shared()->script();
1413 if (script->IsScript() &&
1414 !(Script::cast(script)->source()->IsUndefined())) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001415 int pos = PositionFromStackTrace(elements, i);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001416 Handle<Script> casted_script(Script::cast(script));
1417 *target = MessageLocation(casted_script, pos, pos + 1);
1418 return true;
1419 }
1420 }
1421 return false;
1422}
1423
1424
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001425Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
1426 MessageLocation* location) {
1427 Handle<JSArray> stack_trace_object;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001428 if (capture_stack_trace_for_uncaught_exceptions_) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001429 if (Object::IsErrorObject(this, exception)) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001430 // We fetch the stack trace that corresponds to this error object.
1431 // If the lookup fails, the exception is probably not a valid Error
1432 // object. In that case, we fall through and capture the stack trace
1433 // at this throw site.
1434 stack_trace_object =
1435 GetDetailedStackTrace(Handle<JSObject>::cast(exception));
1436 }
1437 if (stack_trace_object.is_null()) {
1438 // Not an error object, we capture stack and location at throw site.
1439 stack_trace_object = CaptureCurrentStackTrace(
1440 stack_trace_for_uncaught_exceptions_frame_limit_,
1441 stack_trace_for_uncaught_exceptions_options_);
1442 }
1443 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001444 MessageLocation computed_location;
1445 if (location == NULL &&
1446 (ComputeLocationFromException(&computed_location, exception) ||
1447 ComputeLocationFromStackTrace(&computed_location, exception) ||
1448 ComputeLocation(&computed_location))) {
1449 location = &computed_location;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001450 }
1451
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001452 return MessageHandler::MakeMessageObject(
1453 this, MessageTemplate::kUncaughtException, location, exception,
1454 stack_trace_object);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001455}
1456
1457
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001458bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) {
1459 DCHECK_NE(heap()->the_hole_value(), exception);
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001460
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001461 // For uncatchable exceptions, the JavaScript handler cannot be on top.
1462 if (!is_catchable_by_javascript(exception)) return false;
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001463
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001464 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1465 Address entry_handler = Isolate::handler(thread_local_top());
1466 if (entry_handler == nullptr) return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001467
Ben Murdoch257744e2011-11-30 15:57:28 +00001468 // Get the address of the external handler so we can compare the address to
1469 // determine which one is closer to the top of the stack.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001470 Address external_handler = thread_local_top()->try_catch_handler_address();
1471 if (external_handler == nullptr) return true;
Ben Murdoch257744e2011-11-30 15:57:28 +00001472
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001473 // The exception has been externally caught if and only if there is an
1474 // external handler which is on top of the top-most JS_ENTRY handler.
Ben Murdoch257744e2011-11-30 15:57:28 +00001475 //
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001476 // Note, that finally clauses would re-throw an exception unless it's aborted
1477 // by jumps in control flow (like return, break, etc.) and we'll have another
1478 // chance to set proper v8::TryCatch later.
1479 return (entry_handler < external_handler);
1480}
Ben Murdoch257744e2011-11-30 15:57:28 +00001481
Ben Murdoch257744e2011-11-30 15:57:28 +00001482
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001483bool Isolate::IsExternalHandlerOnTop(Object* exception) {
1484 DCHECK_NE(heap()->the_hole_value(), exception);
1485
1486 // Get the address of the external handler so we can compare the address to
1487 // determine which one is closer to the top of the stack.
1488 Address external_handler = thread_local_top()->try_catch_handler_address();
1489 if (external_handler == nullptr) return false;
1490
1491 // For uncatchable exceptions, the external handler is always on top.
1492 if (!is_catchable_by_javascript(exception)) return true;
1493
1494 // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist.
1495 Address entry_handler = Isolate::handler(thread_local_top());
1496 if (entry_handler == nullptr) return true;
1497
1498 // The exception has been externally caught if and only if there is an
1499 // external handler which is on top of the top-most JS_ENTRY handler.
1500 //
1501 // Note, that finally clauses would re-throw an exception unless it's aborted
1502 // by jumps in control flow (like return, break, etc.) and we'll have another
1503 // chance to set proper v8::TryCatch later.
1504 return (entry_handler > external_handler);
Ben Murdoch257744e2011-11-30 15:57:28 +00001505}
1506
1507
1508void Isolate::ReportPendingMessages() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001509 Object* exception = pending_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001510
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001511 // Try to propagate the exception to an external v8::TryCatch handler. If
1512 // propagation was unsuccessful, then we will get another chance at reporting
1513 // the pending message if the exception is re-thrown.
1514 bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch();
1515 if (!has_been_propagated) return;
1516
1517 // Clear the pending message object early to avoid endless recursion.
1518 Object* message_obj = thread_local_top_.pending_message_obj_;
1519 clear_pending_message();
1520
1521 // For uncatchable exceptions we do nothing. If needed, the exception and the
1522 // message have already been propagated to v8::TryCatch.
1523 if (!is_catchable_by_javascript(exception)) return;
1524
1525 // Determine whether the message needs to be reported to all message handlers
1526 // depending on whether and external v8::TryCatch or an internal JavaScript
1527 // handler is on top.
1528 bool should_report_exception;
1529 if (IsExternalHandlerOnTop(exception)) {
1530 // Only report the exception if the external handler is verbose.
1531 should_report_exception = try_catch_handler()->is_verbose_;
Ben Murdoch257744e2011-11-30 15:57:28 +00001532 } else {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001533 // Report the exception if it isn't caught by JavaScript code.
1534 should_report_exception = !IsJavaScriptHandlerOnTop(exception);
Ben Murdoch257744e2011-11-30 15:57:28 +00001535 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001536
1537 // Actually report the pending message to all message handlers.
1538 if (!message_obj->IsTheHole() && should_report_exception) {
1539 HandleScope scope(this);
1540 Handle<JSMessageObject> message(JSMessageObject::cast(message_obj));
1541 Handle<JSValue> script_wrapper(JSValue::cast(message->script()));
1542 Handle<Script> script(Script::cast(script_wrapper->value()));
1543 int start_pos = message->start_position();
1544 int end_pos = message->end_position();
1545 MessageLocation location(script, start_pos, end_pos);
1546 MessageHandler::ReportMessage(this, &location, message);
1547 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001548}
1549
1550
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001551MessageLocation Isolate::GetMessageLocation() {
1552 DCHECK(has_pending_exception());
1553
1554 if (thread_local_top_.pending_exception_ != heap()->termination_exception() &&
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001555 !thread_local_top_.pending_message_obj_->IsTheHole()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001556 Handle<JSMessageObject> message_obj(
1557 JSMessageObject::cast(thread_local_top_.pending_message_obj_));
1558 Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script()));
1559 Handle<Script> script(Script::cast(script_wrapper->value()));
1560 int start_pos = message_obj->start_position();
1561 int end_pos = message_obj->end_position();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001562 return MessageLocation(script, start_pos, end_pos);
1563 }
1564
1565 return MessageLocation();
Ben Murdoch257744e2011-11-30 15:57:28 +00001566}
1567
1568
1569bool Isolate::OptionalRescheduleException(bool is_bottom_call) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001570 DCHECK(has_pending_exception());
Ben Murdoch257744e2011-11-30 15:57:28 +00001571 PropagatePendingExceptionToExternalTryCatch();
1572
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001573 bool is_termination_exception =
1574 pending_exception() == heap_.termination_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001575
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001576 // Do not reschedule the exception if this is the bottom call.
1577 bool clear_exception = is_bottom_call;
Ben Murdoch257744e2011-11-30 15:57:28 +00001578
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001579 if (is_termination_exception) {
1580 if (is_bottom_call) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001581 thread_local_top()->external_caught_exception_ = false;
1582 clear_pending_exception();
1583 return false;
1584 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001585 } else if (thread_local_top()->external_caught_exception_) {
1586 // If the exception is externally caught, clear it if there are no
1587 // JavaScript frames on the way to the C++ frame that has the
1588 // external handler.
1589 DCHECK(thread_local_top()->try_catch_handler_address() != NULL);
1590 Address external_handler_address =
1591 thread_local_top()->try_catch_handler_address();
1592 JavaScriptFrameIterator it(this);
1593 if (it.done() || (it.frame()->sp() > external_handler_address)) {
1594 clear_exception = true;
1595 }
1596 }
1597
1598 // Clear the exception if needed.
1599 if (clear_exception) {
1600 thread_local_top()->external_caught_exception_ = false;
1601 clear_pending_exception();
1602 return false;
Ben Murdoch257744e2011-11-30 15:57:28 +00001603 }
1604
1605 // Reschedule the exception.
1606 thread_local_top()->scheduled_exception_ = pending_exception();
1607 clear_pending_exception();
1608 return true;
1609}
1610
1611
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001612void Isolate::PushPromise(Handle<JSObject> promise,
1613 Handle<JSFunction> function) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001614 ThreadLocalTop* tltop = thread_local_top();
1615 PromiseOnStack* prev = tltop->promise_on_stack_;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001616 Handle<JSObject> global_promise =
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001617 Handle<JSObject>::cast(global_handles()->Create(*promise));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001618 Handle<JSFunction> global_function =
1619 Handle<JSFunction>::cast(global_handles()->Create(*function));
1620 tltop->promise_on_stack_ =
1621 new PromiseOnStack(global_function, global_promise, prev);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001622}
1623
1624
1625void Isolate::PopPromise() {
1626 ThreadLocalTop* tltop = thread_local_top();
1627 if (tltop->promise_on_stack_ == NULL) return;
1628 PromiseOnStack* prev = tltop->promise_on_stack_->prev();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001629 Handle<Object> global_function = tltop->promise_on_stack_->function();
1630 Handle<Object> global_promise = tltop->promise_on_stack_->promise();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001631 delete tltop->promise_on_stack_;
1632 tltop->promise_on_stack_ = prev;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001633 global_handles()->Destroy(global_function.location());
1634 global_handles()->Destroy(global_promise.location());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001635}
1636
1637
1638Handle<Object> Isolate::GetPromiseOnStackOnThrow() {
1639 Handle<Object> undefined = factory()->undefined_value();
1640 ThreadLocalTop* tltop = thread_local_top();
1641 if (tltop->promise_on_stack_ == NULL) return undefined;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001642 Handle<JSFunction> promise_function = tltop->promise_on_stack_->function();
1643 // Find the top-most try-catch or try-finally handler.
1644 if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined;
1645 for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
1646 JavaScriptFrame* frame = it.frame();
Ben Murdoch097c5b22016-05-18 11:27:45 +01001647 if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001648 // Throwing inside a Promise only leads to a reject if not caught by an
1649 // inner try-catch or try-finally.
1650 if (frame->function() == *promise_function) {
1651 return tltop->promise_on_stack_->promise();
1652 }
1653 return undefined;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001654 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001655 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001656 return undefined;
1657}
1658
1659
Ben Murdoch257744e2011-11-30 15:57:28 +00001660void Isolate::SetCaptureStackTraceForUncaughtExceptions(
1661 bool capture,
1662 int frame_limit,
1663 StackTrace::StackTraceOptions options) {
1664 capture_stack_trace_for_uncaught_exceptions_ = capture;
1665 stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
1666 stack_trace_for_uncaught_exceptions_options_ = options;
1667}
1668
1669
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001670void Isolate::SetAbortOnUncaughtExceptionCallback(
1671 v8::Isolate::AbortOnUncaughtExceptionCallback callback) {
1672 abort_on_uncaught_exception_callback_ = callback;
1673}
1674
1675
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001676Handle<Context> Isolate::native_context() {
1677 return handle(context()->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001678}
1679
1680
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001681Handle<Context> Isolate::GetCallingNativeContext() {
1682 JavaScriptFrameIterator it(this);
1683 if (debug_->in_debug_scope()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001684 while (!it.done()) {
1685 JavaScriptFrame* frame = it.frame();
1686 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001687 if (context->native_context() == *debug_->debug_context()) {
Ben Murdoch257744e2011-11-30 15:57:28 +00001688 it.Advance();
1689 } else {
1690 break;
1691 }
1692 }
1693 }
Ben Murdoch257744e2011-11-30 15:57:28 +00001694 if (it.done()) return Handle<Context>::null();
1695 JavaScriptFrame* frame = it.frame();
1696 Context* context = Context::cast(frame->context());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001697 return Handle<Context>(context->native_context());
Ben Murdoch257744e2011-11-30 15:57:28 +00001698}
1699
1700
1701char* Isolate::ArchiveThread(char* to) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001702 MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
1703 sizeof(ThreadLocalTop));
Ben Murdoch257744e2011-11-30 15:57:28 +00001704 InitializeThreadLocal();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001705 clear_pending_exception();
1706 clear_pending_message();
1707 clear_scheduled_exception();
Ben Murdoch257744e2011-11-30 15:57:28 +00001708 return to + sizeof(ThreadLocalTop);
1709}
1710
1711
1712char* Isolate::RestoreThread(char* from) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001713 MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
1714 sizeof(ThreadLocalTop));
1715// This might be just paranoia, but it seems to be needed in case a
1716// thread_local_top_ is restored on a separate OS thread.
Ben Murdoch257744e2011-11-30 15:57:28 +00001717#ifdef USE_SIMULATOR
Ben Murdoch257744e2011-11-30 15:57:28 +00001718 thread_local_top()->simulator_ = Simulator::current(this);
1719#endif
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001720 DCHECK(context() == NULL || context()->IsContext());
Ben Murdoch257744e2011-11-30 15:57:28 +00001721 return from + sizeof(ThreadLocalTop);
1722}
1723
1724
Steve Block44f0eee2011-05-26 01:26:41 +01001725Isolate::ThreadDataTable::ThreadDataTable()
1726 : list_(NULL) {
1727}
1728
1729
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001730Isolate::ThreadDataTable::~ThreadDataTable() {
1731 // TODO(svenpanne) The assertion below would fire if an embedder does not
1732 // cleanly dispose all Isolates before disposing v8, so we are conservative
1733 // and leave it out for now.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001734 // DCHECK_NULL(list_);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001735}
1736
1737
1738Isolate::PerIsolateThreadData::~PerIsolateThreadData() {
1739#if defined(USE_SIMULATOR)
1740 delete simulator_;
1741#endif
1742}
1743
1744
Steve Block44f0eee2011-05-26 01:26:41 +01001745Isolate::PerIsolateThreadData*
Ben Murdoch8b112d22011-06-08 16:22:53 +01001746 Isolate::ThreadDataTable::Lookup(Isolate* isolate,
1747 ThreadId thread_id) {
Steve Block44f0eee2011-05-26 01:26:41 +01001748 for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) {
1749 if (data->Matches(isolate, thread_id)) return data;
1750 }
1751 return NULL;
1752}
1753
1754
1755void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
1756 if (list_ != NULL) list_->prev_ = data;
1757 data->next_ = list_;
1758 list_ = data;
1759}
1760
1761
1762void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
1763 if (list_ == data) list_ = data->next_;
1764 if (data->next_ != NULL) data->next_->prev_ = data->prev_;
1765 if (data->prev_ != NULL) data->prev_->next_ = data->next_;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001766 delete data;
Steve Block44f0eee2011-05-26 01:26:41 +01001767}
1768
1769
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001770void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) {
1771 PerIsolateThreadData* data = list_;
1772 while (data != NULL) {
1773 PerIsolateThreadData* next = data->next_;
1774 if (data->isolate() == isolate) Remove(data);
1775 data = next;
1776 }
1777}
1778
1779
Steve Block44f0eee2011-05-26 01:26:41 +01001780#ifdef DEBUG
1781#define TRACE_ISOLATE(tag) \
1782 do { \
1783 if (FLAG_trace_isolates) { \
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001784 PrintF("Isolate %p (id %d)" #tag "\n", \
1785 reinterpret_cast<void*>(this), id()); \
Steve Block44f0eee2011-05-26 01:26:41 +01001786 } \
1787 } while (false)
1788#else
1789#define TRACE_ISOLATE(tag)
1790#endif
1791
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001792Isolate::Isolate(bool enable_serializer)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001793 : embedder_data_(),
Steve Block44f0eee2011-05-26 01:26:41 +01001794 entry_stack_(NULL),
1795 stack_trace_nesting_level_(0),
1796 incomplete_message_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001797 bootstrapper_(NULL),
1798 runtime_profiler_(NULL),
1799 compilation_cache_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001800 counters_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001801 code_range_(NULL),
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001802 logger_(NULL),
1803 stats_table_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001804 stub_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001805 code_aging_helper_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001806 deoptimizer_data_(NULL),
Ben Murdoch097c5b22016-05-18 11:27:45 +01001807 deoptimizer_lazy_throw_(false),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001808 materialized_object_store_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001809 capture_stack_trace_for_uncaught_exceptions_(false),
1810 stack_trace_for_uncaught_exceptions_frame_limit_(0),
1811 stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview),
Steve Block44f0eee2011-05-26 01:26:41 +01001812 memory_allocator_(NULL),
1813 keyed_lookup_cache_(NULL),
1814 context_slot_cache_(NULL),
1815 descriptor_lookup_cache_(NULL),
1816 handle_scope_implementer_(NULL),
Ben Murdoch8b112d22011-06-08 16:22:53 +01001817 unicode_cache_(NULL),
Ben Murdochda12d292016-06-02 14:46:10 +01001818 runtime_zone_(&allocator_),
1819 interface_descriptor_zone_(&allocator_),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001820 inner_pointer_to_code_cache_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001821 global_handles_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001822 eternal_handles_(NULL),
Steve Block44f0eee2011-05-26 01:26:41 +01001823 thread_manager_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001824 has_installed_extensions_(false),
Steve Block44f0eee2011-05-26 01:26:41 +01001825 regexp_stack_(NULL),
Ben Murdoch3ef787d2012-04-12 10:51:47 +01001826 date_cache_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001827 call_descriptor_data_(NULL),
1828 // TODO(bmeurer) Initialized lazily because it depends on flags; can
1829 // be fixed once the default isolate cleanup is done.
1830 random_number_generator_(NULL),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001831 serializer_enabled_(enable_serializer),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001832 has_fatal_error_(false),
1833 initialized_from_snapshot_(false),
Ben Murdochda12d292016-06-02 14:46:10 +01001834 is_tail_call_elimination_enabled_(true),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001835 cpu_profiler_(NULL),
1836 heap_profiler_(NULL),
1837 function_entry_hook_(NULL),
1838 deferred_handles_head_(NULL),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001839 optimizing_compile_dispatcher_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001840 stress_deopt_count_(0),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001841 virtual_handler_register_(NULL),
1842 virtual_slot_register_(NULL),
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001843 next_optimization_id_(0),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001844 js_calls_from_api_counter_(0),
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001845#if TRACE_MAPS
1846 next_unique_sfi_id_(0),
1847#endif
1848 use_counter_callback_(NULL),
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001849 basic_block_profiler_(NULL),
1850 cancelable_task_manager_(new CancelableTaskManager()),
1851 abort_on_uncaught_exception_callback_(NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001852 {
1853 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
1854 CHECK(thread_data_table_);
1855 }
1856 id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1);
Steve Block44f0eee2011-05-26 01:26:41 +01001857 TRACE_ISOLATE(constructor);
1858
1859 memset(isolate_addresses_, 0,
Ben Murdoch589d6972011-11-30 16:04:58 +00001860 sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1));
Steve Block44f0eee2011-05-26 01:26:41 +01001861
1862 heap_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01001863 stack_guard_.isolate_ = this;
1864
Ben Murdoch257744e2011-11-30 15:57:28 +00001865 // ThreadManager is initialized early to support locking an isolate
1866 // before it is entered.
1867 thread_manager_ = new ThreadManager();
1868 thread_manager_->isolate_ = this;
1869
Steve Block44f0eee2011-05-26 01:26:41 +01001870#ifdef DEBUG
1871 // heap_histograms_ initializes itself.
1872 memset(&js_spill_information_, 0, sizeof(js_spill_information_));
Steve Block44f0eee2011-05-26 01:26:41 +01001873#endif
1874
Steve Block44f0eee2011-05-26 01:26:41 +01001875 handle_scope_data_.Initialize();
1876
1877#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
1878 name##_ = (initial_value);
1879 ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
1880#undef ISOLATE_INIT_EXECUTE
1881
1882#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
1883 memset(name##_, 0, sizeof(type) * length);
1884 ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
1885#undef ISOLATE_INIT_ARRAY_EXECUTE
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001886
1887 InitializeLoggingAndCounters();
1888 debug_ = new Debug(this);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001889
1890 init_memcopy_functions(this);
Steve Block44f0eee2011-05-26 01:26:41 +01001891}
1892
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001893
Steve Block44f0eee2011-05-26 01:26:41 +01001894void Isolate::TearDown() {
1895 TRACE_ISOLATE(tear_down);
1896
1897 // Temporarily set this isolate as current so that various parts of
1898 // the isolate can access it in their destructors without having a
1899 // direct pointer. We don't use Enter/Exit here to avoid
1900 // initializing the thread data.
1901 PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001902 DCHECK(base::NoBarrier_Load(&isolate_key_created_) == 1);
1903 Isolate* saved_isolate =
1904 reinterpret_cast<Isolate*>(base::Thread::GetThreadLocal(isolate_key_));
Steve Block44f0eee2011-05-26 01:26:41 +01001905 SetIsolateThreadLocals(this, NULL);
1906
1907 Deinit();
1908
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001909 {
1910 base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer());
Ben Murdoch85b71792012-04-11 18:30:58 +01001911 thread_data_table_->RemoveAllThreads(this);
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001912 }
1913
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001914 delete this;
1915
Steve Block44f0eee2011-05-26 01:26:41 +01001916 // Restore the previous current isolate.
1917 SetIsolateThreadLocals(saved_isolate, saved_data);
1918}
1919
1920
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001921void Isolate::GlobalTearDown() {
1922 delete thread_data_table_;
1923 thread_data_table_ = NULL;
1924}
1925
1926
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001927void Isolate::ClearSerializerData() {
1928 delete external_reference_table_;
1929 external_reference_table_ = NULL;
1930 delete external_reference_map_;
1931 external_reference_map_ = NULL;
1932}
1933
1934
Steve Block44f0eee2011-05-26 01:26:41 +01001935void Isolate::Deinit() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001936 TRACE_ISOLATE(deinit);
Steve Block44f0eee2011-05-26 01:26:41 +01001937
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001938 debug()->Unload();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001939
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001940 FreeThreadResources();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001941
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001942 if (concurrent_recompilation_enabled()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001943 optimizing_compile_dispatcher_->Stop();
1944 delete optimizing_compile_dispatcher_;
1945 optimizing_compile_dispatcher_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001946 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001947
1948 if (heap_.mark_compact_collector()->sweeping_in_progress()) {
1949 heap_.mark_compact_collector()->EnsureSweepingCompleted();
1950 }
1951
1952 DumpAndResetCompilationStats();
1953
1954 if (FLAG_print_deopt_stress) {
1955 PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
1956 }
1957
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001958 if (cpu_profiler_) {
1959 cpu_profiler_->DeleteAllProfiles();
1960 }
1961
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001962 // We must stop the logger before we tear down other components.
1963 Sampler* sampler = logger_->sampler();
1964 if (sampler && sampler->IsActive()) sampler->Stop();
1965
1966 delete deoptimizer_data_;
1967 deoptimizer_data_ = NULL;
1968 builtins_.TearDown();
1969 bootstrapper_->TearDown();
1970
1971 if (runtime_profiler_ != NULL) {
1972 delete runtime_profiler_;
1973 runtime_profiler_ = NULL;
1974 }
1975
1976 delete basic_block_profiler_;
1977 basic_block_profiler_ = NULL;
1978
Ben Murdoch097c5b22016-05-18 11:27:45 +01001979 delete heap_profiler_;
1980 heap_profiler_ = NULL;
1981
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001982 heap_.TearDown();
1983 logger_->TearDown();
1984
Ben Murdoch097c5b22016-05-18 11:27:45 +01001985 delete interpreter_;
1986 interpreter_ = NULL;
1987
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001988 cancelable_task_manager()->CancelAndWait();
1989
Emily Bernierd0a1eb72015-03-24 16:35:39 -04001990 delete cpu_profiler_;
1991 cpu_profiler_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001992
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001993 delete root_index_map_;
1994 root_index_map_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01001995
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00001996 ClearSerializerData();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00001997}
1998
1999
Steve Block44f0eee2011-05-26 01:26:41 +01002000void Isolate::SetIsolateThreadLocals(Isolate* isolate,
2001 PerIsolateThreadData* data) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002002 base::Thread::SetThreadLocal(isolate_key_, isolate);
2003 base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
Steve Block44f0eee2011-05-26 01:26:41 +01002004}
2005
2006
2007Isolate::~Isolate() {
2008 TRACE_ISOLATE(destructor);
2009
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002010 // Has to be called while counters_ are still alive
2011 runtime_zone_.DeleteKeptSegment();
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002012
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002013 // The entry stack must be empty when we get here.
2014 DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL);
2015
2016 delete entry_stack_;
2017 entry_stack_ = NULL;
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002018
Ben Murdoch8b112d22011-06-08 16:22:53 +01002019 delete unicode_cache_;
2020 unicode_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002021
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002022 delete date_cache_;
2023 date_cache_ = NULL;
2024
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002025 delete[] call_descriptor_data_;
2026 call_descriptor_data_ = NULL;
2027
Steve Block44f0eee2011-05-26 01:26:41 +01002028 delete regexp_stack_;
2029 regexp_stack_ = NULL;
2030
Steve Block44f0eee2011-05-26 01:26:41 +01002031 delete descriptor_lookup_cache_;
2032 descriptor_lookup_cache_ = NULL;
2033 delete context_slot_cache_;
2034 context_slot_cache_ = NULL;
2035 delete keyed_lookup_cache_;
2036 keyed_lookup_cache_ = NULL;
2037
Steve Block44f0eee2011-05-26 01:26:41 +01002038 delete stub_cache_;
2039 stub_cache_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002040 delete code_aging_helper_;
2041 code_aging_helper_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002042 delete stats_table_;
2043 stats_table_ = NULL;
2044
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002045 delete materialized_object_store_;
2046 materialized_object_store_ = NULL;
2047
Steve Block44f0eee2011-05-26 01:26:41 +01002048 delete logger_;
2049 logger_ = NULL;
2050
2051 delete counters_;
2052 counters_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002053
2054 delete handle_scope_implementer_;
2055 handle_scope_implementer_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002056
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002057 delete code_tracer();
2058 set_code_tracer(NULL);
2059
Steve Block44f0eee2011-05-26 01:26:41 +01002060 delete compilation_cache_;
2061 compilation_cache_ = NULL;
2062 delete bootstrapper_;
2063 bootstrapper_ = NULL;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002064 delete inner_pointer_to_code_cache_;
2065 inner_pointer_to_code_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002066
Steve Block44f0eee2011-05-26 01:26:41 +01002067 delete thread_manager_;
2068 thread_manager_ = NULL;
2069
Steve Block44f0eee2011-05-26 01:26:41 +01002070 delete memory_allocator_;
2071 memory_allocator_ = NULL;
2072 delete code_range_;
2073 code_range_ = NULL;
2074 delete global_handles_;
2075 global_handles_ = NULL;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002076 delete eternal_handles_;
2077 eternal_handles_ = NULL;
2078
2079 delete string_stream_debug_object_cache_;
2080 string_stream_debug_object_cache_ = NULL;
Steve Block44f0eee2011-05-26 01:26:41 +01002081
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002082 delete random_number_generator_;
2083 random_number_generator_ = NULL;
2084
Steve Block44f0eee2011-05-26 01:26:41 +01002085 delete debug_;
2086 debug_ = NULL;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002087
2088 delete cancelable_task_manager_;
2089 cancelable_task_manager_ = nullptr;
2090
2091#if USE_SIMULATOR
2092 Simulator::TearDown(simulator_i_cache_, simulator_redirection_);
2093 simulator_i_cache_ = nullptr;
2094 simulator_redirection_ = nullptr;
2095#endif
Steve Block44f0eee2011-05-26 01:26:41 +01002096}
2097
2098
Steve Block44f0eee2011-05-26 01:26:41 +01002099void Isolate::InitializeThreadLocal() {
Ben Murdoch257744e2011-11-30 15:57:28 +00002100 thread_local_top_.isolate_ = this;
Steve Block44f0eee2011-05-26 01:26:41 +01002101 thread_local_top_.Initialize();
Steve Block44f0eee2011-05-26 01:26:41 +01002102}
2103
2104
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002105bool Isolate::PropagatePendingExceptionToExternalTryCatch() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002106 Object* exception = pending_exception();
Ben Murdoch8b112d22011-06-08 16:22:53 +01002107
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002108 if (IsJavaScriptHandlerOnTop(exception)) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002109 thread_local_top_.external_caught_exception_ = false;
2110 return false;
2111 }
Ben Murdoch8b112d22011-06-08 16:22:53 +01002112
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002113 if (!IsExternalHandlerOnTop(exception)) {
2114 thread_local_top_.external_caught_exception_ = false;
2115 return true;
2116 }
2117
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002118 thread_local_top_.external_caught_exception_ = true;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002119 if (!is_catchable_by_javascript(exception)) {
Ben Murdoch8b112d22011-06-08 16:22:53 +01002120 try_catch_handler()->can_continue_ = false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002121 try_catch_handler()->has_terminated_ = true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002122 try_catch_handler()->exception_ = heap()->null_value();
2123 } else {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002124 v8::TryCatch* handler = try_catch_handler();
2125 DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() ||
2126 thread_local_top_.pending_message_obj_->IsTheHole());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002127 handler->can_continue_ = true;
2128 handler->has_terminated_ = false;
2129 handler->exception_ = pending_exception();
2130 // Propagate to the external try-catch only if we got an actual message.
2131 if (thread_local_top_.pending_message_obj_->IsTheHole()) return true;
2132
2133 handler->message_obj_ = thread_local_top_.pending_message_obj_;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002134 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002135 return true;
Ben Murdoch8b112d22011-06-08 16:22:53 +01002136}
2137
2138
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002139void Isolate::InitializeLoggingAndCounters() {
2140 if (logger_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002141 logger_ = new Logger(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002142 }
2143 if (counters_ == NULL) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002144 counters_ = new Counters(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002145 }
2146}
2147
2148
Steve Block44f0eee2011-05-26 01:26:41 +01002149bool Isolate::Init(Deserializer* des) {
Steve Block44f0eee2011-05-26 01:26:41 +01002150 TRACE_ISOLATE(init);
2151
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002152 stress_deopt_count_ = FLAG_deopt_every_n_times;
2153
2154 has_fatal_error_ = false;
2155
2156 if (function_entry_hook() != NULL) {
2157 // When function entry hooking is in effect, we have to create the code
2158 // stubs from scratch to get entry hooks, rather than loading the previously
2159 // generated stubs from disk.
2160 // If this assert fires, the initialization path has regressed.
2161 DCHECK(des == NULL);
2162 }
2163
Steve Block44f0eee2011-05-26 01:26:41 +01002164 // The initialization process does not handle memory exhaustion.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002165 AlwaysAllocateScope always_allocate(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002166
2167 memory_allocator_ = new MemoryAllocator(this);
2168 code_range_ = new CodeRange(this);
2169
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002170 // Safe after setting Heap::isolate_, and initializing StackGuard
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002171 heap_.SetStackLimits();
2172
Ben Murdoch589d6972011-11-30 16:04:58 +00002173#define ASSIGN_ELEMENT(CamelName, hacker_name) \
2174 isolate_addresses_[Isolate::k##CamelName##Address] = \
2175 reinterpret_cast<Address>(hacker_name##_address());
2176 FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002177#undef ASSIGN_ELEMENT
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002178
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002179 compilation_cache_ = new CompilationCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002180 keyed_lookup_cache_ = new KeyedLookupCache();
2181 context_slot_cache_ = new ContextSlotCache();
2182 descriptor_lookup_cache_ = new DescriptorLookupCache();
2183 unicode_cache_ = new UnicodeCache();
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002184 inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002185 global_handles_ = new GlobalHandles(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002186 eternal_handles_ = new EternalHandles();
2187 bootstrapper_ = new Bootstrapper(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002188 handle_scope_implementer_ = new HandleScopeImplementer(this);
2189 stub_cache_ = new StubCache(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002190 materialized_object_store_ = new MaterializedObjectStore(this);
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002191 regexp_stack_ = new RegExpStack();
2192 regexp_stack_->isolate_ = this;
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002193 date_cache_ = new DateCache();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002194 call_descriptor_data_ =
2195 new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS];
2196 cpu_profiler_ = new CpuProfiler(this);
2197 heap_profiler_ = new HeapProfiler(heap());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002198 interpreter_ = new interpreter::Interpreter(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002199
2200 // Enable logging before setting up the heap
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002201 logger_->SetUp(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002202
Steve Block44f0eee2011-05-26 01:26:41 +01002203 // Initialize other runtime facilities
2204#if defined(USE_SIMULATOR)
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002205#if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \
Ben Murdochda12d292016-06-02 14:46:10 +01002206 V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_S390
Ben Murdoch257744e2011-11-30 15:57:28 +00002207 Simulator::Initialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002208#endif
2209#endif
2210
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002211 code_aging_helper_ = new CodeAgingHelper(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002212
Steve Block44f0eee2011-05-26 01:26:41 +01002213 { // NOLINT
2214 // Ensure that the thread has a valid stack guard. The v8::Locker object
2215 // will ensure this too, but we don't have to use lockers if we are only
2216 // using one thread.
2217 ExecutionAccess lock(this);
2218 stack_guard_.InitThread(lock);
2219 }
2220
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002221 // SetUp the object heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002222 DCHECK(!heap_.HasBeenSetUp());
2223 if (!heap_.SetUp()) {
2224 V8::FatalProcessOutOfMemory("heap setup");
Steve Block44f0eee2011-05-26 01:26:41 +01002225 return false;
2226 }
2227
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002228 deoptimizer_data_ = new DeoptimizerData(memory_allocator_);
2229
2230 const bool create_heap_objects = (des == NULL);
2231 if (create_heap_objects && !heap_.CreateHeapObjects()) {
2232 V8::FatalProcessOutOfMemory("heap object creation");
2233 return false;
2234 }
2235
2236 if (create_heap_objects) {
Ben Murdochda12d292016-06-02 14:46:10 +01002237 // Terminate the partial snapshot cache so we can iterate.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002238 partial_snapshot_cache_.Add(heap_.undefined_value());
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002239 }
2240
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00002241 InitializeThreadLocal();
2242
Steve Block44f0eee2011-05-26 01:26:41 +01002243 bootstrapper_->Initialize(create_heap_objects);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002244 builtins_.SetUp(this, create_heap_objects);
Steve Block44f0eee2011-05-26 01:26:41 +01002245
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002246 if (FLAG_log_internal_timer_events) {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002247 set_event_logger(Logger::DefaultEventLoggerSentinel);
Steve Block44f0eee2011-05-26 01:26:41 +01002248 }
2249
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002250 if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs) {
2251 PrintF("Concurrent recompilation has been disabled for tracing.\n");
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002252 } else if (OptimizingCompileDispatcher::Enabled()) {
2253 optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002254 }
2255
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002256 // Initialize runtime profiler before deserialization, because collections may
2257 // occur, clearing/updating ICs.
2258 runtime_profiler_ = new RuntimeProfiler(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002259
2260 // If we are deserializing, read the state into the now-empty heap.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002261 if (!create_heap_objects) {
2262 des->Deserialize(this);
Steve Block44f0eee2011-05-26 01:26:41 +01002263 }
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002264 stub_cache_->Initialize();
2265
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002266 if (FLAG_ignition) {
2267 interpreter_->Initialize();
2268 }
2269
Ben Murdoch3ef787d2012-04-12 10:51:47 +01002270 // Finish initialization of ThreadLocal after deserialization is done.
2271 clear_pending_exception();
2272 clear_pending_message();
2273 clear_scheduled_exception();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002274
Steve Block44f0eee2011-05-26 01:26:41 +01002275 // Deserializing may put strange things in the root array's copy of the
2276 // stack guard.
2277 heap_.SetStackLimits();
2278
Ben Murdochdb1b4382012-04-26 19:03:50 +01002279 // Quiet the heap NaN if needed on target platform.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002280 if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value());
Ben Murdochdb1b4382012-04-26 19:03:50 +01002281
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002282 if (FLAG_trace_turbo) {
2283 // Create an empty file.
2284 std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc);
2285 }
Steve Block44f0eee2011-05-26 01:26:41 +01002286
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002287 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)),
2288 Internals::kIsolateEmbedderDataOffset);
2289 CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)),
2290 Internals::kIsolateRootsOffset);
2291 CHECK_EQ(static_cast<int>(
2292 OFFSET_OF(Isolate, heap_.amount_of_external_allocated_memory_)),
2293 Internals::kAmountOfExternalAllocatedMemoryOffset);
2294 CHECK_EQ(static_cast<int>(OFFSET_OF(
2295 Isolate,
2296 heap_.amount_of_external_allocated_memory_at_last_global_gc_)),
2297 Internals::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
2298
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002299 time_millis_at_init_ = heap_.MonotonicallyIncreasingTimeInMs();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002300
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002301 heap_.NotifyDeserializationComplete();
2302
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002303 if (!create_heap_objects) {
2304 // Now that the heap is consistent, it's OK to generate the code for the
2305 // deopt entry table that might have been referred to by optimized code in
2306 // the snapshot.
2307 HandleScope scope(this);
2308 Deoptimizer::EnsureCodeForDeoptimizationEntry(
Ben Murdochda12d292016-06-02 14:46:10 +01002309 this, Deoptimizer::LAZY,
2310 ExternalReferenceTable::kDeoptTableSerializeEntryCount - 1);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002311 }
2312
2313 if (!serializer_enabled()) {
2314 // Ensure that all stubs which need to be generated ahead of time, but
2315 // cannot be serialized into the snapshot have been generated.
2316 HandleScope scope(this);
2317 CodeStub::GenerateFPStubs(this);
2318 StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this);
2319 StubFailureTrampolineStub::GenerateAheadOfTime(this);
2320 }
2321
2322 initialized_from_snapshot_ = (des != NULL);
2323
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002324 if (!FLAG_inline_new) heap_.DisableInlineAllocation();
2325
Steve Block44f0eee2011-05-26 01:26:41 +01002326 return true;
2327}
2328
2329
Ben Murdoch69a99ed2011-11-30 16:03:39 +00002330// Initialized lazily to allow early
2331// v8::V8::SetAddHistogramSampleFunction calls.
2332StatsTable* Isolate::stats_table() {
2333 if (stats_table_ == NULL) {
2334 stats_table_ = new StatsTable;
2335 }
2336 return stats_table_;
2337}
2338
2339
Steve Block44f0eee2011-05-26 01:26:41 +01002340void Isolate::Enter() {
2341 Isolate* current_isolate = NULL;
2342 PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
2343 if (current_data != NULL) {
2344 current_isolate = current_data->isolate_;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002345 DCHECK(current_isolate != NULL);
Steve Block44f0eee2011-05-26 01:26:41 +01002346 if (current_isolate == this) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002347 DCHECK(Current() == this);
2348 DCHECK(entry_stack_ != NULL);
2349 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002350 entry_stack_->previous_thread_data->thread_id().Equals(
2351 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002352 // Same thread re-enters the isolate, no need to re-init anything.
2353 entry_stack_->entry_count++;
2354 return;
2355 }
2356 }
2357
Steve Block44f0eee2011-05-26 01:26:41 +01002358 PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002359 DCHECK(data != NULL);
2360 DCHECK(data->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002361
2362 EntryStackItem* item = new EntryStackItem(current_data,
2363 current_isolate,
2364 entry_stack_);
2365 entry_stack_ = item;
2366
2367 SetIsolateThreadLocals(this, data);
2368
Steve Block44f0eee2011-05-26 01:26:41 +01002369 // In case it's the first time some thread enters the isolate.
2370 set_thread_id(data->thread_id());
2371}
2372
2373
2374void Isolate::Exit() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002375 DCHECK(entry_stack_ != NULL);
2376 DCHECK(entry_stack_->previous_thread_data == NULL ||
Ben Murdoch8b112d22011-06-08 16:22:53 +01002377 entry_stack_->previous_thread_data->thread_id().Equals(
2378 ThreadId::Current()));
Steve Block44f0eee2011-05-26 01:26:41 +01002379
2380 if (--entry_stack_->entry_count > 0) return;
2381
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002382 DCHECK(CurrentPerIsolateThreadData() != NULL);
2383 DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
Steve Block44f0eee2011-05-26 01:26:41 +01002384
2385 // Pop the stack.
2386 EntryStackItem* item = entry_stack_;
2387 entry_stack_ = item->previous_item;
2388
2389 PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
2390 Isolate* previous_isolate = item->previous_isolate;
2391
2392 delete item;
2393
2394 // Reinit the current thread for the isolate it was running before this one.
2395 SetIsolateThreadLocals(previous_isolate, previous_thread_data);
2396}
2397
2398
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002399void Isolate::LinkDeferredHandles(DeferredHandles* deferred) {
2400 deferred->next_ = deferred_handles_head_;
2401 if (deferred_handles_head_ != NULL) {
2402 deferred_handles_head_->previous_ = deferred;
2403 }
2404 deferred_handles_head_ = deferred;
2405}
2406
2407
2408void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) {
2409#ifdef DEBUG
2410 // In debug mode assert that the linked list is well-formed.
2411 DeferredHandles* deferred_iterator = deferred;
2412 while (deferred_iterator->previous_ != NULL) {
2413 deferred_iterator = deferred_iterator->previous_;
2414 }
2415 DCHECK(deferred_handles_head_ == deferred_iterator);
2416#endif
2417 if (deferred_handles_head_ == deferred) {
2418 deferred_handles_head_ = deferred_handles_head_->next_;
2419 }
2420 if (deferred->next_ != NULL) {
2421 deferred->next_->previous_ = deferred->previous_;
2422 }
2423 if (deferred->previous_ != NULL) {
2424 deferred->previous_->next_ = deferred->next_;
2425 }
2426}
2427
2428
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002429void Isolate::DumpAndResetCompilationStats() {
2430 if (turbo_statistics() != nullptr) {
2431 OFStream os(stdout);
2432 os << *turbo_statistics() << std::endl;
2433 }
2434 if (hstatistics() != nullptr) hstatistics()->Print();
2435 delete turbo_statistics_;
2436 turbo_statistics_ = nullptr;
2437 delete hstatistics_;
2438 hstatistics_ = nullptr;
Ben Murdoch097c5b22016-05-18 11:27:45 +01002439 if (FLAG_runtime_call_stats) {
2440 OFStream os(stdout);
2441 counters()->runtime_call_stats()->Print(os);
2442 counters()->runtime_call_stats()->Reset();
2443 }
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002444}
2445
2446
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002447HStatistics* Isolate::GetHStatistics() {
2448 if (hstatistics() == NULL) set_hstatistics(new HStatistics());
2449 return hstatistics();
2450}
2451
2452
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002453CompilationStatistics* Isolate::GetTurboStatistics() {
2454 if (turbo_statistics() == NULL)
2455 set_turbo_statistics(new CompilationStatistics());
2456 return turbo_statistics();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002457}
2458
2459
2460HTracer* Isolate::GetHTracer() {
2461 if (htracer() == NULL) set_htracer(new HTracer(id()));
2462 return htracer();
2463}
2464
2465
2466CodeTracer* Isolate::GetCodeTracer() {
2467 if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id()));
2468 return code_tracer();
2469}
2470
Ben Murdochda12d292016-06-02 14:46:10 +01002471Map* Isolate::get_initial_js_array_map(ElementsKind kind) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002472 if (IsFastElementsKind(kind)) {
2473 DisallowHeapAllocation no_gc;
Ben Murdochda12d292016-06-02 14:46:10 +01002474 Object* const initial_js_array_map =
2475 context()->native_context()->get(Context::ArrayMapIndex(kind));
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002476 if (!initial_js_array_map->IsUndefined()) {
2477 return Map::cast(initial_js_array_map);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002478 }
2479 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002480 return nullptr;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002481}
2482
2483
2484bool Isolate::use_crankshaft() const {
2485 return FLAG_crankshaft &&
2486 !serializer_enabled_ &&
2487 CpuFeatures::SupportsCrankshaft();
2488}
2489
2490
2491bool Isolate::IsFastArrayConstructorPrototypeChainIntact() {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002492 PropertyCell* no_elements_cell = heap()->array_protector();
2493 bool cell_reports_intact =
2494 no_elements_cell->value()->IsSmi() &&
2495 Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid;
2496
2497#ifdef DEBUG
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002498 Map* root_array_map =
2499 get_initial_js_array_map(GetInitialFastElementsKind());
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002500 Context* native_context = context()->native_context();
2501 JSObject* initial_array_proto = JSObject::cast(
2502 native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX));
2503 JSObject* initial_object_proto = JSObject::cast(
2504 native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX));
2505
2506 if (root_array_map == NULL || initial_array_proto == initial_object_proto) {
2507 // We are in the bootstrapping process, and the entire check sequence
2508 // shouldn't be performed.
2509 return cell_reports_intact;
2510 }
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002511
2512 // Check that the array prototype hasn't been altered WRT empty elements.
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002513 if (root_array_map->prototype() != initial_array_proto) {
2514 DCHECK_EQ(false, cell_reports_intact);
2515 return cell_reports_intact;
2516 }
2517
2518 FixedArrayBase* elements = initial_array_proto->elements();
2519 if (elements != heap()->empty_fixed_array() &&
2520 elements != heap()->empty_slow_element_dictionary()) {
2521 DCHECK_EQ(false, cell_reports_intact);
2522 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002523 }
2524
2525 // Check that the object prototype hasn't been altered WRT empty elements.
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002526 PrototypeIterator iter(this, initial_array_proto);
2527 if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002528 DCHECK_EQ(false, cell_reports_intact);
2529 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002530 }
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002531
2532 elements = initial_object_proto->elements();
2533 if (elements != heap()->empty_fixed_array() &&
2534 elements != heap()->empty_slow_element_dictionary()) {
2535 DCHECK_EQ(false, cell_reports_intact);
2536 return cell_reports_intact;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002537 }
2538
2539 iter.Advance();
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002540 if (!iter.IsAtEnd()) {
2541 DCHECK_EQ(false, cell_reports_intact);
2542 return cell_reports_intact;
2543 }
2544
2545#endif
2546
2547 return cell_reports_intact;
2548}
2549
Ben Murdoch097c5b22016-05-18 11:27:45 +01002550void Isolate::InvalidateArraySpeciesProtector() {
2551 if (!FLAG_harmony_species) return;
2552 DCHECK(factory()->species_protector()->value()->IsSmi());
2553 DCHECK(IsArraySpeciesLookupChainIntact());
2554 PropertyCell::SetValueWithInvalidation(
2555 factory()->species_protector(),
2556 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2557 DCHECK(!IsArraySpeciesLookupChainIntact());
2558}
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002559
2560void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002561 DisallowHeapAllocation no_gc;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002562 if (IsFastArrayConstructorPrototypeChainIntact() &&
2563 object->map()->is_prototype_map()) {
2564 Object* context = heap()->native_contexts_list();
2565 while (!context->IsUndefined()) {
2566 Context* current_context = Context::cast(context);
2567 if (current_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX) ==
2568 *object ||
2569 current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2570 *object) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002571 CountUsage(v8::Isolate::UseCounterFeature::kArrayProtectorDirtied);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002572 PropertyCell::SetValueWithInvalidation(
2573 factory()->array_protector(),
2574 handle(Smi::FromInt(kArrayProtectorInvalid), this));
2575 break;
2576 }
2577 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2578 }
2579 }
2580}
2581
2582
2583bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) {
2584 if (array->map()->is_prototype_map()) {
2585 Object* context = heap()->native_contexts_list();
2586 while (!context->IsUndefined()) {
2587 Context* current_context = Context::cast(context);
2588 if (current_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX) ==
2589 *array) {
2590 return true;
2591 }
2592 context = current_context->get(Context::NEXT_CONTEXT_LINK);
2593 }
2594 }
2595 return false;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002596}
2597
2598
2599CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) {
2600 DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS);
2601 return &call_descriptor_data_[index];
2602}
2603
2604
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002605base::RandomNumberGenerator* Isolate::random_number_generator() {
2606 if (random_number_generator_ == NULL) {
2607 if (FLAG_random_seed != 0) {
2608 random_number_generator_ =
2609 new base::RandomNumberGenerator(FLAG_random_seed);
2610 } else {
2611 random_number_generator_ = new base::RandomNumberGenerator();
2612 }
2613 }
2614 return random_number_generator_;
2615}
2616
2617
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002618Object* Isolate::FindCodeObject(Address a) {
2619 return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a);
2620}
2621
2622
Steve Block44f0eee2011-05-26 01:26:41 +01002623#ifdef DEBUG
2624#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
2625const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
2626ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
2627ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
2628#undef ISOLATE_FIELD_OFFSET
2629#endif
2630
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002631
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002632Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry,
2633 Handle<Map> map, const char* cname) {
2634 Handle<String> name = factory()->InternalizeUtf8String(cname);
2635 Handle<JSObject> obj = factory()->NewJSObjectFromMap(map);
2636 JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0,
2637 "SetupSymbolRegistry");
2638 JSObject::AddProperty(registry, name, obj, NONE);
2639 return obj;
2640}
2641
2642
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002643Handle<JSObject> Isolate::GetSymbolRegistry() {
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002644 if (heap()->symbol_registry()->IsSmi()) {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002645 Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize);
2646 Handle<JSObject> registry = factory()->NewJSObjectFromMap(map);
2647 heap()->set_symbol_registry(*registry);
2648
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002649 SetUpSubregistry(registry, map, "for");
2650 SetUpSubregistry(registry, map, "for_api");
2651 SetUpSubregistry(registry, map, "keyFor");
2652 SetUpSubregistry(registry, map, "private_api");
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002653 }
2654 return Handle<JSObject>::cast(factory()->symbol_registry());
2655}
2656
2657
Ben Murdoch097c5b22016-05-18 11:27:45 +01002658void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
2659 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2660 if (callback == before_call_entered_callbacks_.at(i)) return;
2661 }
2662 before_call_entered_callbacks_.Add(callback);
2663}
2664
2665
2666void Isolate::RemoveBeforeCallEnteredCallback(
2667 BeforeCallEnteredCallback callback) {
2668 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2669 if (callback == before_call_entered_callbacks_.at(i)) {
2670 before_call_entered_callbacks_.Remove(i);
2671 }
2672 }
2673}
2674
2675
2676void Isolate::FireBeforeCallEnteredCallback() {
2677 for (int i = 0; i < before_call_entered_callbacks_.length(); i++) {
2678 before_call_entered_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this));
2679 }
2680}
2681
2682
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002683void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
2684 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2685 if (callback == call_completed_callbacks_.at(i)) return;
2686 }
2687 call_completed_callbacks_.Add(callback);
2688}
2689
2690
2691void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
2692 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
2693 if (callback == call_completed_callbacks_.at(i)) {
2694 call_completed_callbacks_.Remove(i);
2695 }
2696 }
2697}
2698
2699
2700void Isolate::FireCallCompletedCallback() {
2701 bool has_call_completed_callbacks = !call_completed_callbacks_.is_empty();
Ben Murdochda12d292016-06-02 14:46:10 +01002702 bool run_microtasks =
2703 pending_microtask_count() &&
2704 !handle_scope_implementer()->HasMicrotasksSuppressions() &&
2705 handle_scope_implementer()->microtasks_policy() ==
2706 v8::MicrotasksPolicy::kAuto;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002707 if (!has_call_completed_callbacks && !run_microtasks) return;
2708
2709 if (!handle_scope_implementer()->CallDepthIsZero()) return;
2710 if (run_microtasks) RunMicrotasks();
2711 // Fire callbacks. Increase call depth to prevent recursive callbacks.
Ben Murdoch097c5b22016-05-18 11:27:45 +01002712 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this);
2713 v8::Isolate::SuppressMicrotaskExecutionScope suppress(isolate);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002714 for (int i = 0; i < call_completed_callbacks_.length(); i++) {
Ben Murdoch097c5b22016-05-18 11:27:45 +01002715 call_completed_callbacks_.at(i)(isolate);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002716 }
2717}
2718
2719
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002720void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
2721 promise_reject_callback_ = callback;
2722}
2723
2724
2725void Isolate::ReportPromiseReject(Handle<JSObject> promise,
2726 Handle<Object> value,
2727 v8::PromiseRejectEvent event) {
2728 if (promise_reject_callback_ == NULL) return;
2729 Handle<JSArray> stack_trace;
2730 if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) {
2731 stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value));
2732 }
2733 promise_reject_callback_(v8::PromiseRejectMessage(
2734 v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value),
2735 v8::Utils::StackTraceToLocal(stack_trace)));
2736}
2737
2738
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002739void Isolate::EnqueueMicrotask(Handle<Object> microtask) {
2740 DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo());
2741 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2742 int num_tasks = pending_microtask_count();
2743 DCHECK(num_tasks <= queue->length());
2744 if (num_tasks == 0) {
2745 queue = factory()->NewFixedArray(8);
2746 heap()->set_microtask_queue(*queue);
2747 } else if (num_tasks == queue->length()) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002748 queue = factory()->CopyFixedArrayAndGrow(queue, num_tasks);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002749 heap()->set_microtask_queue(*queue);
2750 }
2751 DCHECK(queue->get(num_tasks)->IsUndefined());
2752 queue->set(num_tasks, *microtask);
2753 set_pending_microtask_count(num_tasks + 1);
2754}
2755
2756
2757void Isolate::RunMicrotasks() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002758 // Increase call depth to prevent recursive callbacks.
2759 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
2760 reinterpret_cast<v8::Isolate*>(this));
Ben Murdochda12d292016-06-02 14:46:10 +01002761 RunMicrotasksInternal();
2762 FireMicrotasksCompletedCallback();
2763}
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002764
Ben Murdochda12d292016-06-02 14:46:10 +01002765
2766void Isolate::RunMicrotasksInternal() {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002767 while (pending_microtask_count() > 0) {
2768 HandleScope scope(this);
2769 int num_tasks = pending_microtask_count();
2770 Handle<FixedArray> queue(heap()->microtask_queue(), this);
2771 DCHECK(num_tasks <= queue->length());
2772 set_pending_microtask_count(0);
2773 heap()->set_microtask_queue(heap()->empty_fixed_array());
2774
Ben Murdochda12d292016-06-02 14:46:10 +01002775 Isolate* isolate = this;
2776 FOR_WITH_HANDLE_SCOPE(isolate, int, i = 0, i, i < num_tasks, i++, {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002777 Handle<Object> microtask(queue->get(i), this);
2778 if (microtask->IsJSFunction()) {
2779 Handle<JSFunction> microtask_function =
2780 Handle<JSFunction>::cast(microtask);
2781 SaveContext save(this);
2782 set_context(microtask_function->context()->native_context());
2783 MaybeHandle<Object> maybe_exception;
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002784 MaybeHandle<Object> result = Execution::TryCall(
2785 this, microtask_function, factory()->undefined_value(), 0, NULL,
2786 &maybe_exception);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002787 // If execution is terminating, just bail out.
2788 Handle<Object> exception;
2789 if (result.is_null() && maybe_exception.is_null()) {
2790 // Clear out any remaining callbacks in the queue.
2791 heap()->set_microtask_queue(heap()->empty_fixed_array());
2792 set_pending_microtask_count(0);
2793 return;
2794 }
2795 } else {
2796 Handle<CallHandlerInfo> callback_info =
2797 Handle<CallHandlerInfo>::cast(microtask);
2798 v8::MicrotaskCallback callback =
2799 v8::ToCData<v8::MicrotaskCallback>(callback_info->callback());
2800 void* data = v8::ToCData<void*>(callback_info->data());
2801 callback(data);
2802 }
Ben Murdochda12d292016-06-02 14:46:10 +01002803 });
2804 }
2805}
2806
2807
2808void Isolate::AddMicrotasksCompletedCallback(
2809 MicrotasksCompletedCallback callback) {
2810 for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) {
2811 if (callback == microtasks_completed_callbacks_.at(i)) return;
2812 }
2813 microtasks_completed_callbacks_.Add(callback);
2814}
2815
2816
2817void Isolate::RemoveMicrotasksCompletedCallback(
2818 MicrotasksCompletedCallback callback) {
2819 for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) {
2820 if (callback == microtasks_completed_callbacks_.at(i)) {
2821 microtasks_completed_callbacks_.Remove(i);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002822 }
2823 }
2824}
2825
2826
Ben Murdochda12d292016-06-02 14:46:10 +01002827void Isolate::FireMicrotasksCompletedCallback() {
2828 for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) {
2829 microtasks_completed_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this));
2830 }
2831}
2832
2833
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002834void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
2835 DCHECK(!use_counter_callback_);
2836 use_counter_callback_ = callback;
2837}
2838
2839
2840void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002841 // The counter callback may cause the embedder to call into V8, which is not
2842 // generally possible during GC.
2843 if (heap_.gc_state() == Heap::NOT_IN_GC) {
2844 if (use_counter_callback_) {
2845 HandleScope handle_scope(this);
2846 use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
2847 }
2848 } else {
2849 heap_.IncrementDeferredCount(feature);
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002850 }
2851}
2852
2853
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002854BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() {
2855 if (basic_block_profiler_ == NULL) {
2856 basic_block_profiler_ = new BasicBlockProfiler();
2857 }
2858 return basic_block_profiler_;
2859}
2860
2861
2862std::string Isolate::GetTurboCfgFileName() {
2863 if (FLAG_trace_turbo_cfg_file == NULL) {
2864 std::ostringstream os;
2865 os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg";
2866 return os.str();
2867 } else {
2868 return FLAG_trace_turbo_cfg_file;
2869 }
2870}
2871
Ben Murdochda12d292016-06-02 14:46:10 +01002872void Isolate::SetTailCallEliminationEnabled(bool enabled) {
2873 if (is_tail_call_elimination_enabled_ == enabled) return;
2874 is_tail_call_elimination_enabled_ = enabled;
2875 // TODO(ishell): Introduce DependencyGroup::kTailCallChangedGroup to
2876 // deoptimize only those functions that are affected by the change of this
2877 // flag.
2878 internal::Deoptimizer::DeoptimizeAll(this);
2879}
Emily Bernierd0a1eb72015-03-24 16:35:39 -04002880
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002881// Heap::detached_contexts tracks detached contexts as pairs
2882// (number of GC since the context was detached, the context).
2883void Isolate::AddDetachedContext(Handle<Context> context) {
2884 HandleScope scope(this);
2885 Handle<WeakCell> cell = factory()->NewWeakCell(context);
2886 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2887 int length = detached_contexts->length();
2888 detached_contexts = factory()->CopyFixedArrayAndGrow(detached_contexts, 2);
2889 detached_contexts->set(length, Smi::FromInt(0));
2890 detached_contexts->set(length + 1, *cell);
2891 heap()->set_detached_contexts(*detached_contexts);
2892}
2893
2894
2895void Isolate::CheckDetachedContextsAfterGC() {
2896 HandleScope scope(this);
2897 Handle<FixedArray> detached_contexts(heap()->detached_contexts());
2898 int length = detached_contexts->length();
2899 if (length == 0) return;
2900 int new_length = 0;
2901 for (int i = 0; i < length; i += 2) {
2902 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2903 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2904 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2905 if (!cell->cleared()) {
2906 detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1));
2907 detached_contexts->set(new_length + 1, cell);
2908 new_length += 2;
2909 }
2910 counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1);
2911 }
2912 if (FLAG_trace_detached_contexts) {
2913 PrintF("%d detached contexts are collected out of %d\n",
2914 length - new_length, length);
2915 for (int i = 0; i < new_length; i += 2) {
2916 int mark_sweeps = Smi::cast(detached_contexts->get(i))->value();
2917 DCHECK(detached_contexts->get(i + 1)->IsWeakCell());
2918 WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1));
2919 if (mark_sweeps > 3) {
2920 PrintF("detached context 0x%p\n survived %d GCs (leak?)\n",
2921 static_cast<void*>(cell->value()), mark_sweeps);
2922 }
2923 }
2924 }
2925 if (new_length == 0) {
2926 heap()->set_detached_contexts(heap()->empty_fixed_array());
2927 } else if (new_length < length) {
2928 heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>(
2929 *detached_contexts, length - new_length);
2930 }
2931}
2932
2933
2934bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const {
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002935 StackGuard* stack_guard = isolate_->stack_guard();
2936#ifdef USE_SIMULATOR
2937 // The simulator uses a separate JS stack.
2938 Address jssp_address = Simulator::current(isolate_)->get_sp();
2939 uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address);
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002940 if (jssp - gap < stack_guard->real_jslimit()) return true;
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002941#endif // USE_SIMULATOR
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002942 return GetCurrentStackPosition() - gap < stack_guard->real_climit();
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002943}
2944
2945
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002946SaveContext::SaveContext(Isolate* isolate)
2947 : isolate_(isolate), prev_(isolate->save_context()) {
2948 if (isolate->context() != NULL) {
2949 context_ = Handle<Context>(isolate->context());
2950 }
2951 isolate->set_save_context(this);
2952
2953 c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
2954}
2955
2956
2957SaveContext::~SaveContext() {
2958 isolate_->set_context(context_.is_null() ? NULL : *context_);
2959 isolate_->set_save_context(prev_);
2960}
2961
2962
2963#ifdef DEBUG
2964AssertNoContextChange::AssertNoContextChange(Isolate* isolate)
2965 : isolate_(isolate), context_(isolate->context(), isolate) {}
2966#endif // DEBUG
2967
2968
Ben Murdochb8a8cc12014-11-26 15:28:44 +00002969bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) {
2970 // First check whether the previous scope intercepts.
2971 if (prev_ && prev_->Intercept(flag)) return true;
2972 // Then check whether this scope intercepts.
2973 if ((flag & intercept_mask_)) {
2974 intercepted_flags_ |= flag;
2975 return true;
2976 }
2977 return false;
2978}
2979
Ben Murdoch4a90d5f2016-03-22 12:00:34 +00002980} // namespace internal
2981} // namespace v8