blob: 82960270b2af1f36d3d1e8a202e568f1a3c2362f [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "bootstrapper.h"
32#include "debug.h"
33#include "execution.h"
Steve Block6ded16b2010-05-10 14:33:55 +010034#include "messages.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000035#include "platform.h"
Steve Blockd0582a62009-12-15 09:54:21 +000036#include "simulator.h"
37#include "string-stream.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000038
39namespace v8 {
40namespace internal {
41
42ThreadLocalTop Top::thread_local_;
43Mutex* Top::break_access_ = OS::CreateMutex();
44
45NoAllocationStringAllocator* preallocated_message_space = NULL;
46
Ben Murdoch3bec4d22010-07-22 14:51:16 +010047bool capture_stack_trace_for_uncaught_exceptions = false;
48int stack_trace_for_uncaught_exceptions_frame_limit = 0;
49StackTrace::StackTraceOptions stack_trace_for_uncaught_exceptions_options =
50 StackTrace::kOverview;
51
Steve Blocka7e24c12009-10-30 11:49:00 +000052Address top_addresses[] = {
53#define C(name) reinterpret_cast<Address>(Top::name()),
54 TOP_ADDRESS_LIST(C)
55 TOP_ADDRESS_LIST_PROF(C)
56#undef C
57 NULL
58};
59
Steve Blockd0582a62009-12-15 09:54:21 +000060
61v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
62 return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
63}
64
65
66void ThreadLocalTop::Initialize() {
67 c_entry_fp_ = 0;
68 handler_ = 0;
69#ifdef ENABLE_LOGGING_AND_PROFILING
70 js_entry_sp_ = 0;
71#endif
72 stack_is_cooked_ = false;
73 try_catch_handler_address_ = NULL;
74 context_ = NULL;
75 int id = ThreadManager::CurrentId();
76 thread_id_ = (id == 0) ? ThreadManager::kInvalidId : id;
77 external_caught_exception_ = false;
78 failed_access_check_callback_ = NULL;
79 save_context_ = NULL;
80 catcher_ = NULL;
81}
82
83
Steve Blocka7e24c12009-10-30 11:49:00 +000084Address Top::get_address_from_id(Top::AddressId id) {
85 return top_addresses[id];
86}
87
Steve Block3ce2e202009-11-05 08:53:23 +000088
Steve Blocka7e24c12009-10-30 11:49:00 +000089char* Top::Iterate(ObjectVisitor* v, char* thread_storage) {
90 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
91 Iterate(v, thread);
92 return thread_storage + sizeof(ThreadLocalTop);
93}
94
95
Steve Block6ded16b2010-05-10 14:33:55 +010096void Top::IterateThread(ThreadVisitor* v) {
97 v->VisitThread(&thread_local_);
98}
99
100
101void Top::IterateThread(ThreadVisitor* v, char* t) {
102 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
103 v->VisitThread(thread);
104}
105
106
Steve Blocka7e24c12009-10-30 11:49:00 +0000107void Top::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
108 v->VisitPointer(&(thread->pending_exception_));
109 v->VisitPointer(&(thread->pending_message_obj_));
Iain Merrick75681382010-08-19 15:07:18 +0100110 v->VisitPointer(BitCast<Object**>(&(thread->pending_message_script_)));
111 v->VisitPointer(BitCast<Object**>(&(thread->context_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000112 v->VisitPointer(&(thread->scheduled_exception_));
113
Steve Blockd0582a62009-12-15 09:54:21 +0000114 for (v8::TryCatch* block = thread->TryCatchHandler();
Steve Blocka7e24c12009-10-30 11:49:00 +0000115 block != NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000116 block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
Iain Merrick75681382010-08-19 15:07:18 +0100117 v->VisitPointer(BitCast<Object**>(&(block->exception_)));
118 v->VisitPointer(BitCast<Object**>(&(block->message_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000119 }
120
121 // Iterate over pointers on native execution stack.
122 for (StackFrameIterator it(thread); !it.done(); it.Advance()) {
123 it.frame()->Iterate(v);
124 }
125}
126
127
128void Top::Iterate(ObjectVisitor* v) {
129 ThreadLocalTop* current_t = &thread_local_;
130 Iterate(v, current_t);
131}
132
133
134void Top::InitializeThreadLocal() {
Steve Blockd0582a62009-12-15 09:54:21 +0000135 thread_local_.Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +0000136 clear_pending_exception();
137 clear_pending_message();
138 clear_scheduled_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +0000139}
140
141
142// Create a dummy thread that will wait forever on a semaphore. The only
143// purpose for this thread is to have some stack area to save essential data
144// into for use by a stacks only core dump (aka minidump).
145class PreallocatedMemoryThread: public Thread {
146 public:
147 PreallocatedMemoryThread() : keep_running_(true) {
148 wait_for_ever_semaphore_ = OS::CreateSemaphore(0);
149 data_ready_semaphore_ = OS::CreateSemaphore(0);
150 }
151
152 // When the thread starts running it will allocate a fixed number of bytes
153 // on the stack and publish the location of this memory for others to use.
154 void Run() {
155 EmbeddedVector<char, 15 * 1024> local_buffer;
156
157 // Initialize the buffer with a known good value.
158 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
159 local_buffer.length());
160
161 // Publish the local buffer and signal its availability.
162 data_ = local_buffer.start();
163 length_ = local_buffer.length();
164 data_ready_semaphore_->Signal();
165
166 while (keep_running_) {
167 // This thread will wait here until the end of time.
168 wait_for_ever_semaphore_->Wait();
169 }
170
171 // Make sure we access the buffer after the wait to remove all possibility
172 // of it being optimized away.
173 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
174 local_buffer.length());
175 }
176
177 static char* data() {
178 if (data_ready_semaphore_ != NULL) {
179 // Initial access is guarded until the data has been published.
180 data_ready_semaphore_->Wait();
181 delete data_ready_semaphore_;
182 data_ready_semaphore_ = NULL;
183 }
184 return data_;
185 }
186
187 static unsigned length() {
188 if (data_ready_semaphore_ != NULL) {
189 // Initial access is guarded until the data has been published.
190 data_ready_semaphore_->Wait();
191 delete data_ready_semaphore_;
192 data_ready_semaphore_ = NULL;
193 }
194 return length_;
195 }
196
197 static void StartThread() {
198 if (the_thread_ != NULL) return;
199
200 the_thread_ = new PreallocatedMemoryThread();
201 the_thread_->Start();
202 }
203
204 // Stop the PreallocatedMemoryThread and release its resources.
205 static void StopThread() {
206 if (the_thread_ == NULL) return;
207
208 the_thread_->keep_running_ = false;
209 wait_for_ever_semaphore_->Signal();
210
211 // Wait for the thread to terminate.
212 the_thread_->Join();
213
214 if (data_ready_semaphore_ != NULL) {
215 delete data_ready_semaphore_;
216 data_ready_semaphore_ = NULL;
217 }
218
219 delete wait_for_ever_semaphore_;
220 wait_for_ever_semaphore_ = NULL;
221
222 // Done with the thread entirely.
223 delete the_thread_;
224 the_thread_ = NULL;
225 }
226
227 private:
228 // Used to make sure that the thread keeps looping even for spurious wakeups.
229 bool keep_running_;
230
231 // The preallocated memory thread singleton.
232 static PreallocatedMemoryThread* the_thread_;
233 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
234 static Semaphore* wait_for_ever_semaphore_;
235 // Semaphore to signal that the data has been initialized.
236 static Semaphore* data_ready_semaphore_;
237
238 // Location and size of the preallocated memory block.
239 static char* data_;
240 static unsigned length_;
241
242 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
243};
244
245PreallocatedMemoryThread* PreallocatedMemoryThread::the_thread_ = NULL;
246Semaphore* PreallocatedMemoryThread::wait_for_ever_semaphore_ = NULL;
247Semaphore* PreallocatedMemoryThread::data_ready_semaphore_ = NULL;
248char* PreallocatedMemoryThread::data_ = NULL;
249unsigned PreallocatedMemoryThread::length_ = 0;
250
251static bool initialized = false;
252
253void Top::Initialize() {
254 CHECK(!initialized);
255
256 InitializeThreadLocal();
257
258 // Only preallocate on the first initialization.
259 if (FLAG_preallocate_message_memory && (preallocated_message_space == NULL)) {
260 // Start the thread which will set aside some memory.
261 PreallocatedMemoryThread::StartThread();
262 preallocated_message_space =
263 new NoAllocationStringAllocator(PreallocatedMemoryThread::data(),
264 PreallocatedMemoryThread::length());
265 PreallocatedStorage::Init(PreallocatedMemoryThread::length() / 4);
266 }
267 initialized = true;
268}
269
270
271void Top::TearDown() {
272 if (initialized) {
273 // Remove the external reference to the preallocated stack memory.
274 if (preallocated_message_space != NULL) {
275 delete preallocated_message_space;
276 preallocated_message_space = NULL;
277 }
278
279 PreallocatedMemoryThread::StopThread();
280 initialized = false;
281 }
282}
283
284
Steve Blocka7e24c12009-10-30 11:49:00 +0000285void Top::RegisterTryCatchHandler(v8::TryCatch* that) {
Steve Blockd0582a62009-12-15 09:54:21 +0000286 // The ARM simulator has a separate JS stack. We therefore register
287 // the C++ try catch handler with the simulator and get back an
288 // address that can be used for comparisons with addresses into the
289 // JS stack. When running without the simulator, the address
290 // returned will be the address of the C++ try catch handler itself.
291 Address address = reinterpret_cast<Address>(
292 SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
293 thread_local_.set_try_catch_handler_address(address);
Steve Blocka7e24c12009-10-30 11:49:00 +0000294}
295
296
297void Top::UnregisterTryCatchHandler(v8::TryCatch* that) {
Steve Blockd0582a62009-12-15 09:54:21 +0000298 ASSERT(thread_local_.TryCatchHandler() == that);
299 thread_local_.set_try_catch_handler_address(
300 reinterpret_cast<Address>(that->next_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000301 thread_local_.catcher_ = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000302 SimulatorStack::UnregisterCTryCatch();
Steve Blocka7e24c12009-10-30 11:49:00 +0000303}
304
305
306void Top::MarkCompactPrologue(bool is_compacting) {
307 MarkCompactPrologue(is_compacting, &thread_local_);
308}
309
310
311void Top::MarkCompactPrologue(bool is_compacting, char* data) {
312 MarkCompactPrologue(is_compacting, reinterpret_cast<ThreadLocalTop*>(data));
313}
314
315
316void Top::MarkCompactPrologue(bool is_compacting, ThreadLocalTop* thread) {
317 if (is_compacting) {
318 StackFrame::CookFramesForThread(thread);
319 }
320}
321
322
323void Top::MarkCompactEpilogue(bool is_compacting, char* data) {
324 MarkCompactEpilogue(is_compacting, reinterpret_cast<ThreadLocalTop*>(data));
325}
326
327
328void Top::MarkCompactEpilogue(bool is_compacting) {
329 MarkCompactEpilogue(is_compacting, &thread_local_);
330}
331
332
333void Top::MarkCompactEpilogue(bool is_compacting, ThreadLocalTop* thread) {
334 if (is_compacting) {
335 StackFrame::UncookFramesForThread(thread);
336 }
337}
338
339
340static int stack_trace_nesting_level = 0;
341static StringStream* incomplete_message = NULL;
342
343
Kristian Monsen25f61362010-05-21 11:50:48 +0100344Handle<String> Top::StackTraceString() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000345 if (stack_trace_nesting_level == 0) {
346 stack_trace_nesting_level++;
347 HeapStringAllocator allocator;
348 StringStream::ClearMentionedObjectCache();
349 StringStream accumulator(&allocator);
350 incomplete_message = &accumulator;
351 PrintStack(&accumulator);
352 Handle<String> stack_trace = accumulator.ToString();
353 incomplete_message = NULL;
354 stack_trace_nesting_level = 0;
355 return stack_trace;
356 } else if (stack_trace_nesting_level == 1) {
357 stack_trace_nesting_level++;
358 OS::PrintError(
359 "\n\nAttempt to print stack while printing stack (double fault)\n");
360 OS::PrintError(
361 "If you are lucky you may find a partial stack dump on stdout.\n\n");
362 incomplete_message->OutputToStdOut();
363 return Factory::empty_symbol();
364 } else {
365 OS::Abort();
366 // Unreachable
367 return Factory::empty_symbol();
368 }
369}
370
371
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100372Handle<JSArray> Top::CaptureCurrentStackTrace(
Kristian Monsen25f61362010-05-21 11:50:48 +0100373 int frame_limit, StackTrace::StackTraceOptions options) {
Kristian Monsen25f61362010-05-21 11:50:48 +0100374 // Ensure no negative values.
375 int limit = Max(frame_limit, 0);
Leon Clarkef7060e22010-06-03 12:02:55 +0100376 Handle<JSArray> stack_trace = Factory::NewJSArray(frame_limit);
Kristian Monsen25f61362010-05-21 11:50:48 +0100377
378 Handle<String> column_key = Factory::LookupAsciiSymbol("column");
379 Handle<String> line_key = Factory::LookupAsciiSymbol("lineNumber");
380 Handle<String> script_key = Factory::LookupAsciiSymbol("scriptName");
381 Handle<String> function_key = Factory::LookupAsciiSymbol("functionName");
382 Handle<String> eval_key = Factory::LookupAsciiSymbol("isEval");
383 Handle<String> constructor_key = Factory::LookupAsciiSymbol("isConstructor");
384
385 StackTraceFrameIterator it;
386 int frames_seen = 0;
387 while (!it.done() && (frames_seen < limit)) {
388 // Create a JSObject to hold the information for the StackFrame.
389 Handle<JSObject> stackFrame = Factory::NewJSObject(object_function());
390
391 JavaScriptFrame* frame = it.frame();
392 JSFunction* fun(JSFunction::cast(frame->function()));
393 Script* script = Script::cast(fun->shared()->script());
394
395 if (options & StackTrace::kLineNumber) {
396 int script_line_offset = script->line_offset()->value();
397 int position = frame->code()->SourcePosition(frame->pc());
398 int line_number = GetScriptLineNumber(Handle<Script>(script), position);
399 // line_number is already shifted by the script_line_offset.
400 int relative_line_number = line_number - script_line_offset;
401 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
402 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
403 int start = (relative_line_number == 0) ? 0 :
404 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
405 int column_offset = position - start;
406 if (relative_line_number == 0) {
407 // For the case where the code is on the same line as the script tag.
408 column_offset += script->column_offset()->value();
409 }
410 SetProperty(stackFrame, column_key,
411 Handle<Smi>(Smi::FromInt(column_offset + 1)), NONE);
412 }
413 SetProperty(stackFrame, line_key,
414 Handle<Smi>(Smi::FromInt(line_number + 1)), NONE);
415 }
416
417 if (options & StackTrace::kScriptName) {
418 Handle<Object> script_name(script->name());
419 SetProperty(stackFrame, script_key, script_name, NONE);
420 }
421
422 if (options & StackTrace::kFunctionName) {
423 Handle<Object> fun_name(fun->shared()->name());
424 if (fun_name->ToBoolean()->IsFalse()) {
425 fun_name = Handle<Object>(fun->shared()->inferred_name());
426 }
427 SetProperty(stackFrame, function_key, fun_name, NONE);
428 }
429
430 if (options & StackTrace::kIsEval) {
431 int type = Smi::cast(script->compilation_type())->value();
432 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
433 Factory::true_value() : Factory::false_value();
434 SetProperty(stackFrame, eval_key, is_eval, NONE);
435 }
436
437 if (options & StackTrace::kIsConstructor) {
438 Handle<Object> is_constructor = (frame->IsConstructor()) ?
439 Factory::true_value() : Factory::false_value();
440 SetProperty(stackFrame, constructor_key, is_constructor, NONE);
441 }
442
Leon Clarkef7060e22010-06-03 12:02:55 +0100443 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stackFrame);
Kristian Monsen25f61362010-05-21 11:50:48 +0100444 frames_seen++;
445 it.Advance();
446 }
447
Leon Clarkef7060e22010-06-03 12:02:55 +0100448 stack_trace->set_length(Smi::FromInt(frames_seen));
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100449 return stack_trace;
Kristian Monsen25f61362010-05-21 11:50:48 +0100450}
451
452
Steve Blocka7e24c12009-10-30 11:49:00 +0000453void Top::PrintStack() {
454 if (stack_trace_nesting_level == 0) {
455 stack_trace_nesting_level++;
456
457 StringAllocator* allocator;
458 if (preallocated_message_space == NULL) {
459 allocator = new HeapStringAllocator();
460 } else {
461 allocator = preallocated_message_space;
462 }
463
464 NativeAllocationChecker allocation_checker(
465 !FLAG_preallocate_message_memory ?
466 NativeAllocationChecker::ALLOW :
467 NativeAllocationChecker::DISALLOW);
468
469 StringStream::ClearMentionedObjectCache();
470 StringStream accumulator(allocator);
471 incomplete_message = &accumulator;
472 PrintStack(&accumulator);
473 accumulator.OutputToStdOut();
474 accumulator.Log();
475 incomplete_message = NULL;
476 stack_trace_nesting_level = 0;
477 if (preallocated_message_space == NULL) {
478 // Remove the HeapStringAllocator created above.
479 delete allocator;
480 }
481 } else if (stack_trace_nesting_level == 1) {
482 stack_trace_nesting_level++;
483 OS::PrintError(
484 "\n\nAttempt to print stack while printing stack (double fault)\n");
485 OS::PrintError(
486 "If you are lucky you may find a partial stack dump on stdout.\n\n");
487 incomplete_message->OutputToStdOut();
488 }
489}
490
491
492static void PrintFrames(StringStream* accumulator,
493 StackFrame::PrintMode mode) {
494 StackFrameIterator it;
495 for (int i = 0; !it.done(); it.Advance()) {
496 it.frame()->Print(accumulator, mode, i++);
497 }
498}
499
500
501void Top::PrintStack(StringStream* accumulator) {
502 // The MentionedObjectCache is not GC-proof at the moment.
503 AssertNoAllocation nogc;
504 ASSERT(StringStream::IsMentionedObjectCacheClear());
505
506 // Avoid printing anything if there are no frames.
507 if (c_entry_fp(GetCurrentThread()) == 0) return;
508
509 accumulator->Add(
510 "\n==== Stack trace ============================================\n\n");
511 PrintFrames(accumulator, StackFrame::OVERVIEW);
512
513 accumulator->Add(
514 "\n==== Details ================================================\n\n");
515 PrintFrames(accumulator, StackFrame::DETAILS);
516
517 accumulator->PrintMentionedObjectCache();
518 accumulator->Add("=====================\n\n");
519}
520
521
522void Top::SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000523 thread_local_.failed_access_check_callback_ = callback;
524}
525
526
527void Top::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
528 if (!thread_local_.failed_access_check_callback_) return;
529
530 ASSERT(receiver->IsAccessCheckNeeded());
531 ASSERT(Top::context());
Steve Blocka7e24c12009-10-30 11:49:00 +0000532
533 // Get the data object from access check info.
534 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +0100535 if (!constructor->shared()->IsApiFunction()) return;
536 Object* data_obj =
537 constructor->shared()->get_api_func_data()->access_check_info();
Steve Blocka7e24c12009-10-30 11:49:00 +0000538 if (data_obj == Heap::undefined_value()) return;
539
540 HandleScope scope;
541 Handle<JSObject> receiver_handle(receiver);
542 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
543 thread_local_.failed_access_check_callback_(
544 v8::Utils::ToLocal(receiver_handle),
545 type,
546 v8::Utils::ToLocal(data));
547}
548
549
550enum MayAccessDecision {
551 YES, NO, UNKNOWN
552};
553
554
555static MayAccessDecision MayAccessPreCheck(JSObject* receiver,
556 v8::AccessType type) {
557 // During bootstrapping, callback functions are not enabled yet.
558 if (Bootstrapper::IsActive()) return YES;
559
560 if (receiver->IsJSGlobalProxy()) {
561 Object* receiver_context = JSGlobalProxy::cast(receiver)->context();
562 if (!receiver_context->IsContext()) return NO;
563
564 // Get the global context of current top context.
565 // avoid using Top::global_context() because it uses Handle.
566 Context* global_context = Top::context()->global()->global_context();
567 if (receiver_context == global_context) return YES;
568
569 if (Context::cast(receiver_context)->security_token() ==
570 global_context->security_token())
571 return YES;
572 }
573
574 return UNKNOWN;
575}
576
577
578bool Top::MayNamedAccess(JSObject* receiver, Object* key, v8::AccessType type) {
579 ASSERT(receiver->IsAccessCheckNeeded());
Steve Block3ce2e202009-11-05 08:53:23 +0000580
581 // The callers of this method are not expecting a GC.
582 AssertNoAllocation no_gc;
583
584 // Skip checks for hidden properties access. Note, we do not
585 // require existence of a context in this case.
586 if (key == Heap::hidden_symbol()) return true;
587
Steve Blocka7e24c12009-10-30 11:49:00 +0000588 // Check for compatibility between the security tokens in the
589 // current lexical context and the accessed object.
590 ASSERT(Top::context());
Steve Blocka7e24c12009-10-30 11:49:00 +0000591
592 MayAccessDecision decision = MayAccessPreCheck(receiver, type);
593 if (decision != UNKNOWN) return decision == YES;
594
595 // Get named access check callback
596 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +0100597 if (!constructor->shared()->IsApiFunction()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000598
Steve Block6ded16b2010-05-10 14:33:55 +0100599 Object* data_obj =
600 constructor->shared()->get_api_func_data()->access_check_info();
Steve Blocka7e24c12009-10-30 11:49:00 +0000601 if (data_obj == Heap::undefined_value()) return false;
602
603 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
604 v8::NamedSecurityCallback callback =
605 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
606
607 if (!callback) return false;
608
609 HandleScope scope;
610 Handle<JSObject> receiver_handle(receiver);
611 Handle<Object> key_handle(key);
612 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
613 LOG(ApiNamedSecurityCheck(key));
614 bool result = false;
615 {
616 // Leaving JavaScript.
617 VMState state(EXTERNAL);
618 result = callback(v8::Utils::ToLocal(receiver_handle),
619 v8::Utils::ToLocal(key_handle),
620 type,
621 v8::Utils::ToLocal(data));
622 }
623 return result;
624}
625
626
627bool Top::MayIndexedAccess(JSObject* receiver,
628 uint32_t index,
629 v8::AccessType type) {
630 ASSERT(receiver->IsAccessCheckNeeded());
631 // Check for compatibility between the security tokens in the
632 // current lexical context and the accessed object.
633 ASSERT(Top::context());
634 // The callers of this method are not expecting a GC.
635 AssertNoAllocation no_gc;
636
637 MayAccessDecision decision = MayAccessPreCheck(receiver, type);
638 if (decision != UNKNOWN) return decision == YES;
639
640 // Get indexed access check callback
641 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +0100642 if (!constructor->shared()->IsApiFunction()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000643
Steve Block6ded16b2010-05-10 14:33:55 +0100644 Object* data_obj =
645 constructor->shared()->get_api_func_data()->access_check_info();
Steve Blocka7e24c12009-10-30 11:49:00 +0000646 if (data_obj == Heap::undefined_value()) return false;
647
648 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
649 v8::IndexedSecurityCallback callback =
650 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
651
652 if (!callback) return false;
653
654 HandleScope scope;
655 Handle<JSObject> receiver_handle(receiver);
656 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
657 LOG(ApiIndexedSecurityCheck(index));
658 bool result = false;
659 {
660 // Leaving JavaScript.
661 VMState state(EXTERNAL);
662 result = callback(v8::Utils::ToLocal(receiver_handle),
663 index,
664 type,
665 v8::Utils::ToLocal(data));
666 }
667 return result;
668}
669
670
671const char* Top::kStackOverflowMessage =
672 "Uncaught RangeError: Maximum call stack size exceeded";
673
674
675Failure* Top::StackOverflow() {
676 HandleScope scope;
677 Handle<String> key = Factory::stack_overflow_symbol();
678 Handle<JSObject> boilerplate =
679 Handle<JSObject>::cast(GetProperty(Top::builtins(), key));
680 Handle<Object> exception = Copy(boilerplate);
681 // TODO(1240995): To avoid having to call JavaScript code to compute
682 // the message for stack overflow exceptions which is very likely to
683 // double fault with another stack overflow exception, we use a
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100684 // precomputed message.
Steve Blocka7e24c12009-10-30 11:49:00 +0000685 DoThrow(*exception, NULL, kStackOverflowMessage);
686 return Failure::Exception();
687}
688
689
690Failure* Top::TerminateExecution() {
691 DoThrow(Heap::termination_exception(), NULL, NULL);
692 return Failure::Exception();
693}
694
695
696Failure* Top::Throw(Object* exception, MessageLocation* location) {
697 DoThrow(exception, location, NULL);
698 return Failure::Exception();
699}
700
701
702Failure* Top::ReThrow(Object* exception, MessageLocation* location) {
703 // Set the exception being re-thrown.
704 set_pending_exception(exception);
705 return Failure::Exception();
706}
707
708
709Failure* Top::ThrowIllegalOperation() {
710 return Throw(Heap::illegal_access_symbol());
711}
712
713
714void Top::ScheduleThrow(Object* exception) {
715 // When scheduling a throw we first throw the exception to get the
716 // error reporting if it is uncaught before rescheduling it.
717 Throw(exception);
718 thread_local_.scheduled_exception_ = pending_exception();
719 thread_local_.external_caught_exception_ = false;
720 clear_pending_exception();
721}
722
723
724Object* Top::PromoteScheduledException() {
725 Object* thrown = scheduled_exception();
726 clear_scheduled_exception();
727 // Re-throw the exception to avoid getting repeated error reporting.
728 return ReThrow(thrown);
729}
730
731
732void Top::PrintCurrentStackTrace(FILE* out) {
733 StackTraceFrameIterator it;
734 while (!it.done()) {
735 HandleScope scope;
736 // Find code position if recorded in relocation info.
737 JavaScriptFrame* frame = it.frame();
738 int pos = frame->code()->SourcePosition(frame->pc());
739 Handle<Object> pos_obj(Smi::FromInt(pos));
740 // Fetch function and receiver.
741 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
742 Handle<Object> recv(frame->receiver());
743 // Advance to the next JavaScript frame and determine if the
744 // current frame is the top-level frame.
745 it.Advance();
746 Handle<Object> is_top_level = it.done()
747 ? Factory::true_value()
748 : Factory::false_value();
749 // Generate and print stack trace line.
750 Handle<String> line =
751 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
752 if (line->length() > 0) {
753 line->PrintOn(out);
754 fprintf(out, "\n");
755 }
756 }
757}
758
759
760void Top::ComputeLocation(MessageLocation* target) {
Andrei Popescu31002712010-02-23 13:46:05 +0000761 *target = MessageLocation(Handle<Script>(Heap::empty_script()), -1, -1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000762 StackTraceFrameIterator it;
763 if (!it.done()) {
764 JavaScriptFrame* frame = it.frame();
765 JSFunction* fun = JSFunction::cast(frame->function());
766 Object* script = fun->shared()->script();
767 if (script->IsScript() &&
768 !(Script::cast(script)->source()->IsUndefined())) {
769 int pos = frame->code()->SourcePosition(frame->pc());
770 // Compute the location from the function and the reloc info.
771 Handle<Script> casted_script(Script::cast(script));
772 *target = MessageLocation(casted_script, pos, pos + 1);
773 }
774 }
775}
776
777
Steve Blocka7e24c12009-10-30 11:49:00 +0000778bool Top::ShouldReturnException(bool* is_caught_externally,
779 bool catchable_by_javascript) {
780 // Find the top-most try-catch handler.
781 StackHandler* handler =
782 StackHandler::FromAddress(Top::handler(Top::GetCurrentThread()));
783 while (handler != NULL && !handler->is_try_catch()) {
784 handler = handler->next();
785 }
786
787 // Get the address of the external handler so we can compare the address to
788 // determine which one is closer to the top of the stack.
Steve Blockd0582a62009-12-15 09:54:21 +0000789 Address external_handler_address = thread_local_.try_catch_handler_address();
Steve Blocka7e24c12009-10-30 11:49:00 +0000790
791 // The exception has been externally caught if and only if there is
792 // an external handler which is on top of the top-most try-catch
793 // handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000794 *is_caught_externally = external_handler_address != NULL &&
795 (handler == NULL || handler->address() > external_handler_address ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000796 !catchable_by_javascript);
797
798 if (*is_caught_externally) {
799 // Only report the exception if the external handler is verbose.
Steve Blockd0582a62009-12-15 09:54:21 +0000800 return thread_local_.TryCatchHandler()->is_verbose_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000801 } else {
802 // Report the exception if it isn't caught by JavaScript code.
803 return handler == NULL;
804 }
805}
806
807
808void Top::DoThrow(Object* exception,
809 MessageLocation* location,
810 const char* message) {
811 ASSERT(!has_pending_exception());
812
813 HandleScope scope;
814 Handle<Object> exception_handle(exception);
815
816 // Determine reporting and whether the exception is caught externally.
817 bool is_caught_externally = false;
818 bool is_out_of_memory = exception == Failure::OutOfMemoryException();
819 bool is_termination_exception = exception == Heap::termination_exception();
820 bool catchable_by_javascript = !is_termination_exception && !is_out_of_memory;
821 bool should_return_exception =
822 ShouldReturnException(&is_caught_externally, catchable_by_javascript);
823 bool report_exception = catchable_by_javascript && should_return_exception;
824
825#ifdef ENABLE_DEBUGGER_SUPPORT
826 // Notify debugger of exception.
827 if (catchable_by_javascript) {
828 Debugger::OnException(exception_handle, report_exception);
829 }
830#endif
831
832 // Generate the message.
833 Handle<Object> message_obj;
834 MessageLocation potential_computed_location;
835 bool try_catch_needs_message =
836 is_caught_externally &&
Steve Blockd0582a62009-12-15 09:54:21 +0000837 thread_local_.TryCatchHandler()->capture_message_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000838 if (report_exception || try_catch_needs_message) {
839 if (location == NULL) {
840 // If no location was specified we use a computed one instead
841 ComputeLocation(&potential_computed_location);
842 location = &potential_computed_location;
843 }
844 if (!Bootstrapper::IsActive()) {
845 // It's not safe to try to make message objects or collect stack
846 // traces while the bootstrapper is active since the infrastructure
847 // may not have been properly initialized.
848 Handle<String> stack_trace;
Kristian Monsen25f61362010-05-21 11:50:48 +0100849 if (FLAG_trace_exception) stack_trace = StackTraceString();
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100850 Handle<JSArray> stack_trace_object;
851 if (report_exception && capture_stack_trace_for_uncaught_exceptions) {
852 stack_trace_object = Top::CaptureCurrentStackTrace(
853 stack_trace_for_uncaught_exceptions_frame_limit,
854 stack_trace_for_uncaught_exceptions_options);
855 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000856 message_obj = MessageHandler::MakeMessageObject("uncaught_exception",
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100857 location, HandleVector<Object>(&exception_handle, 1), stack_trace,
858 stack_trace_object);
Steve Blocka7e24c12009-10-30 11:49:00 +0000859 }
860 }
861
862 // Save the message for reporting if the the exception remains uncaught.
863 thread_local_.has_pending_message_ = report_exception;
864 thread_local_.pending_message_ = message;
865 if (!message_obj.is_null()) {
866 thread_local_.pending_message_obj_ = *message_obj;
867 if (location != NULL) {
868 thread_local_.pending_message_script_ = *location->script();
869 thread_local_.pending_message_start_pos_ = location->start_pos();
870 thread_local_.pending_message_end_pos_ = location->end_pos();
871 }
872 }
873
874 if (is_caught_externally) {
Steve Blockd0582a62009-12-15 09:54:21 +0000875 thread_local_.catcher_ = thread_local_.TryCatchHandler();
Steve Blocka7e24c12009-10-30 11:49:00 +0000876 }
877
878 // NOTE: Notifying the debugger or generating the message
879 // may have caused new exceptions. For now, we just ignore
880 // that and set the pending exception to the original one.
881 set_pending_exception(*exception_handle);
882}
883
884
885void Top::ReportPendingMessages() {
886 ASSERT(has_pending_exception());
887 setup_external_caught();
888 // If the pending exception is OutOfMemoryException set out_of_memory in
889 // the global context. Note: We have to mark the global context here
890 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
891 // set it.
892 bool external_caught = thread_local_.external_caught_exception_;
893 HandleScope scope;
894 if (thread_local_.pending_exception_ == Failure::OutOfMemoryException()) {
895 context()->mark_out_of_memory();
896 } else if (thread_local_.pending_exception_ ==
897 Heap::termination_exception()) {
898 if (external_caught) {
Steve Blockd0582a62009-12-15 09:54:21 +0000899 thread_local_.TryCatchHandler()->can_continue_ = false;
900 thread_local_.TryCatchHandler()->exception_ = Heap::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000901 }
902 } else {
903 Handle<Object> exception(pending_exception());
904 thread_local_.external_caught_exception_ = false;
905 if (external_caught) {
Steve Blockd0582a62009-12-15 09:54:21 +0000906 thread_local_.TryCatchHandler()->can_continue_ = true;
907 thread_local_.TryCatchHandler()->exception_ =
Steve Blocka7e24c12009-10-30 11:49:00 +0000908 thread_local_.pending_exception_;
909 if (!thread_local_.pending_message_obj_->IsTheHole()) {
910 try_catch_handler()->message_ = thread_local_.pending_message_obj_;
911 }
912 }
913 if (thread_local_.has_pending_message_) {
914 thread_local_.has_pending_message_ = false;
915 if (thread_local_.pending_message_ != NULL) {
916 MessageHandler::ReportMessage(thread_local_.pending_message_);
917 } else if (!thread_local_.pending_message_obj_->IsTheHole()) {
918 Handle<Object> message_obj(thread_local_.pending_message_obj_);
919 if (thread_local_.pending_message_script_ != NULL) {
920 Handle<Script> script(thread_local_.pending_message_script_);
921 int start_pos = thread_local_.pending_message_start_pos_;
922 int end_pos = thread_local_.pending_message_end_pos_;
923 MessageLocation location(script, start_pos, end_pos);
924 MessageHandler::ReportMessage(&location, message_obj);
925 } else {
926 MessageHandler::ReportMessage(NULL, message_obj);
927 }
928 }
929 }
930 thread_local_.external_caught_exception_ = external_caught;
931 set_pending_exception(*exception);
932 }
933 clear_pending_message();
934}
935
936
937void Top::TraceException(bool flag) {
938 FLAG_trace_exception = flag;
939}
940
941
942bool Top::OptionalRescheduleException(bool is_bottom_call) {
943 // Allways reschedule out of memory exceptions.
944 if (!is_out_of_memory()) {
945 bool is_termination_exception =
946 pending_exception() == Heap::termination_exception();
947
948 // Do not reschedule the exception if this is the bottom call.
949 bool clear_exception = is_bottom_call;
950
951 if (is_termination_exception) {
952 if (is_bottom_call) {
953 thread_local_.external_caught_exception_ = false;
954 clear_pending_exception();
955 return false;
956 }
957 } else if (thread_local_.external_caught_exception_) {
958 // If the exception is externally caught, clear it if there are no
959 // JavaScript frames on the way to the C++ frame that has the
960 // external handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000961 ASSERT(thread_local_.try_catch_handler_address() != NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000962 Address external_handler_address =
Steve Blockd0582a62009-12-15 09:54:21 +0000963 thread_local_.try_catch_handler_address();
Steve Blocka7e24c12009-10-30 11:49:00 +0000964 JavaScriptFrameIterator it;
965 if (it.done() || (it.frame()->sp() > external_handler_address)) {
966 clear_exception = true;
967 }
968 }
969
970 // Clear the exception if needed.
971 if (clear_exception) {
972 thread_local_.external_caught_exception_ = false;
973 clear_pending_exception();
974 return false;
975 }
976 }
977
978 // Reschedule the exception.
979 thread_local_.scheduled_exception_ = pending_exception();
980 clear_pending_exception();
981 return true;
982}
983
984
Ben Murdoch3bec4d22010-07-22 14:51:16 +0100985void Top::SetCaptureStackTraceForUncaughtExceptions(
986 bool capture,
987 int frame_limit,
988 StackTrace::StackTraceOptions options) {
989 capture_stack_trace_for_uncaught_exceptions = capture;
990 stack_trace_for_uncaught_exceptions_frame_limit = frame_limit;
991 stack_trace_for_uncaught_exceptions_options = options;
992}
993
994
Steve Blocka7e24c12009-10-30 11:49:00 +0000995bool Top::is_out_of_memory() {
996 if (has_pending_exception()) {
997 Object* e = pending_exception();
998 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
999 return true;
1000 }
1001 }
1002 if (has_scheduled_exception()) {
1003 Object* e = scheduled_exception();
1004 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1005 return true;
1006 }
1007 }
1008 return false;
1009}
1010
1011
1012Handle<Context> Top::global_context() {
1013 GlobalObject* global = thread_local_.context_->global();
1014 return Handle<Context>(global->global_context());
1015}
1016
1017
1018Handle<Context> Top::GetCallingGlobalContext() {
1019 JavaScriptFrameIterator it;
Steve Blockd0582a62009-12-15 09:54:21 +00001020#ifdef ENABLE_DEBUGGER_SUPPORT
1021 if (Debug::InDebugger()) {
1022 while (!it.done()) {
1023 JavaScriptFrame* frame = it.frame();
1024 Context* context = Context::cast(frame->context());
1025 if (context->global_context() == *Debug::debug_context()) {
1026 it.Advance();
1027 } else {
1028 break;
1029 }
1030 }
1031 }
1032#endif // ENABLE_DEBUGGER_SUPPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00001033 if (it.done()) return Handle<Context>::null();
1034 JavaScriptFrame* frame = it.frame();
1035 Context* context = Context::cast(frame->context());
1036 return Handle<Context>(context->global_context());
1037}
1038
1039
Steve Blocka7e24c12009-10-30 11:49:00 +00001040char* Top::ArchiveThread(char* to) {
1041 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(thread_local_));
1042 InitializeThreadLocal();
1043 return to + sizeof(thread_local_);
1044}
1045
1046
1047char* Top::RestoreThread(char* from) {
1048 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(thread_local_));
1049 return from + sizeof(thread_local_);
1050}
1051
1052
1053ExecutionAccess::ExecutionAccess() {
1054 Top::break_access_->Lock();
1055}
1056
1057
1058ExecutionAccess::~ExecutionAccess() {
1059 Top::break_access_->Unlock();
1060}
1061
1062
1063} } // namespace v8::internal