blob: 87dc1f61ff44f5cbfa32c53230a3a2cc2ddbaa6a [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
47Address top_addresses[] = {
48#define C(name) reinterpret_cast<Address>(Top::name()),
49 TOP_ADDRESS_LIST(C)
50 TOP_ADDRESS_LIST_PROF(C)
51#undef C
52 NULL
53};
54
Steve Blockd0582a62009-12-15 09:54:21 +000055
56v8::TryCatch* ThreadLocalTop::TryCatchHandler() {
57 return TRY_CATCH_FROM_ADDRESS(try_catch_handler_address());
58}
59
60
61void ThreadLocalTop::Initialize() {
62 c_entry_fp_ = 0;
63 handler_ = 0;
64#ifdef ENABLE_LOGGING_AND_PROFILING
65 js_entry_sp_ = 0;
66#endif
67 stack_is_cooked_ = false;
68 try_catch_handler_address_ = NULL;
69 context_ = NULL;
70 int id = ThreadManager::CurrentId();
71 thread_id_ = (id == 0) ? ThreadManager::kInvalidId : id;
72 external_caught_exception_ = false;
73 failed_access_check_callback_ = NULL;
74 save_context_ = NULL;
75 catcher_ = NULL;
76}
77
78
Steve Blocka7e24c12009-10-30 11:49:00 +000079Address Top::get_address_from_id(Top::AddressId id) {
80 return top_addresses[id];
81}
82
Steve Block3ce2e202009-11-05 08:53:23 +000083
Steve Blocka7e24c12009-10-30 11:49:00 +000084char* Top::Iterate(ObjectVisitor* v, char* thread_storage) {
85 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
86 Iterate(v, thread);
87 return thread_storage + sizeof(ThreadLocalTop);
88}
89
90
Steve Block6ded16b2010-05-10 14:33:55 +010091void Top::IterateThread(ThreadVisitor* v) {
92 v->VisitThread(&thread_local_);
93}
94
95
96void Top::IterateThread(ThreadVisitor* v, char* t) {
97 ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
98 v->VisitThread(thread);
99}
100
101
Steve Blocka7e24c12009-10-30 11:49:00 +0000102void Top::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) {
103 v->VisitPointer(&(thread->pending_exception_));
104 v->VisitPointer(&(thread->pending_message_obj_));
105 v->VisitPointer(
Steve Block6ded16b2010-05-10 14:33:55 +0100106 BitCast<Object**, Script**>(&(thread->pending_message_script_)));
107 v->VisitPointer(BitCast<Object**, Context**>(&(thread->context_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000108 v->VisitPointer(&(thread->scheduled_exception_));
109
Steve Blockd0582a62009-12-15 09:54:21 +0000110 for (v8::TryCatch* block = thread->TryCatchHandler();
Steve Blocka7e24c12009-10-30 11:49:00 +0000111 block != NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000112 block = TRY_CATCH_FROM_ADDRESS(block->next_)) {
Steve Block6ded16b2010-05-10 14:33:55 +0100113 v->VisitPointer(BitCast<Object**, void**>(&(block->exception_)));
114 v->VisitPointer(BitCast<Object**, void**>(&(block->message_)));
Steve Blocka7e24c12009-10-30 11:49:00 +0000115 }
116
117 // Iterate over pointers on native execution stack.
118 for (StackFrameIterator it(thread); !it.done(); it.Advance()) {
119 it.frame()->Iterate(v);
120 }
121}
122
123
124void Top::Iterate(ObjectVisitor* v) {
125 ThreadLocalTop* current_t = &thread_local_;
126 Iterate(v, current_t);
127}
128
129
130void Top::InitializeThreadLocal() {
Steve Blockd0582a62009-12-15 09:54:21 +0000131 thread_local_.Initialize();
Steve Blocka7e24c12009-10-30 11:49:00 +0000132 clear_pending_exception();
133 clear_pending_message();
134 clear_scheduled_exception();
Steve Blocka7e24c12009-10-30 11:49:00 +0000135}
136
137
138// Create a dummy thread that will wait forever on a semaphore. The only
139// purpose for this thread is to have some stack area to save essential data
140// into for use by a stacks only core dump (aka minidump).
141class PreallocatedMemoryThread: public Thread {
142 public:
143 PreallocatedMemoryThread() : keep_running_(true) {
144 wait_for_ever_semaphore_ = OS::CreateSemaphore(0);
145 data_ready_semaphore_ = OS::CreateSemaphore(0);
146 }
147
148 // When the thread starts running it will allocate a fixed number of bytes
149 // on the stack and publish the location of this memory for others to use.
150 void Run() {
151 EmbeddedVector<char, 15 * 1024> local_buffer;
152
153 // Initialize the buffer with a known good value.
154 OS::StrNCpy(local_buffer, "Trace data was not generated.\n",
155 local_buffer.length());
156
157 // Publish the local buffer and signal its availability.
158 data_ = local_buffer.start();
159 length_ = local_buffer.length();
160 data_ready_semaphore_->Signal();
161
162 while (keep_running_) {
163 // This thread will wait here until the end of time.
164 wait_for_ever_semaphore_->Wait();
165 }
166
167 // Make sure we access the buffer after the wait to remove all possibility
168 // of it being optimized away.
169 OS::StrNCpy(local_buffer, "PreallocatedMemoryThread shutting down.\n",
170 local_buffer.length());
171 }
172
173 static char* data() {
174 if (data_ready_semaphore_ != NULL) {
175 // Initial access is guarded until the data has been published.
176 data_ready_semaphore_->Wait();
177 delete data_ready_semaphore_;
178 data_ready_semaphore_ = NULL;
179 }
180 return data_;
181 }
182
183 static unsigned length() {
184 if (data_ready_semaphore_ != NULL) {
185 // Initial access is guarded until the data has been published.
186 data_ready_semaphore_->Wait();
187 delete data_ready_semaphore_;
188 data_ready_semaphore_ = NULL;
189 }
190 return length_;
191 }
192
193 static void StartThread() {
194 if (the_thread_ != NULL) return;
195
196 the_thread_ = new PreallocatedMemoryThread();
197 the_thread_->Start();
198 }
199
200 // Stop the PreallocatedMemoryThread and release its resources.
201 static void StopThread() {
202 if (the_thread_ == NULL) return;
203
204 the_thread_->keep_running_ = false;
205 wait_for_ever_semaphore_->Signal();
206
207 // Wait for the thread to terminate.
208 the_thread_->Join();
209
210 if (data_ready_semaphore_ != NULL) {
211 delete data_ready_semaphore_;
212 data_ready_semaphore_ = NULL;
213 }
214
215 delete wait_for_ever_semaphore_;
216 wait_for_ever_semaphore_ = NULL;
217
218 // Done with the thread entirely.
219 delete the_thread_;
220 the_thread_ = NULL;
221 }
222
223 private:
224 // Used to make sure that the thread keeps looping even for spurious wakeups.
225 bool keep_running_;
226
227 // The preallocated memory thread singleton.
228 static PreallocatedMemoryThread* the_thread_;
229 // This semaphore is used by the PreallocatedMemoryThread to wait for ever.
230 static Semaphore* wait_for_ever_semaphore_;
231 // Semaphore to signal that the data has been initialized.
232 static Semaphore* data_ready_semaphore_;
233
234 // Location and size of the preallocated memory block.
235 static char* data_;
236 static unsigned length_;
237
238 DISALLOW_COPY_AND_ASSIGN(PreallocatedMemoryThread);
239};
240
241PreallocatedMemoryThread* PreallocatedMemoryThread::the_thread_ = NULL;
242Semaphore* PreallocatedMemoryThread::wait_for_ever_semaphore_ = NULL;
243Semaphore* PreallocatedMemoryThread::data_ready_semaphore_ = NULL;
244char* PreallocatedMemoryThread::data_ = NULL;
245unsigned PreallocatedMemoryThread::length_ = 0;
246
247static bool initialized = false;
248
249void Top::Initialize() {
250 CHECK(!initialized);
251
252 InitializeThreadLocal();
253
254 // Only preallocate on the first initialization.
255 if (FLAG_preallocate_message_memory && (preallocated_message_space == NULL)) {
256 // Start the thread which will set aside some memory.
257 PreallocatedMemoryThread::StartThread();
258 preallocated_message_space =
259 new NoAllocationStringAllocator(PreallocatedMemoryThread::data(),
260 PreallocatedMemoryThread::length());
261 PreallocatedStorage::Init(PreallocatedMemoryThread::length() / 4);
262 }
263 initialized = true;
264}
265
266
267void Top::TearDown() {
268 if (initialized) {
269 // Remove the external reference to the preallocated stack memory.
270 if (preallocated_message_space != NULL) {
271 delete preallocated_message_space;
272 preallocated_message_space = NULL;
273 }
274
275 PreallocatedMemoryThread::StopThread();
276 initialized = false;
277 }
278}
279
280
Steve Blocka7e24c12009-10-30 11:49:00 +0000281void Top::RegisterTryCatchHandler(v8::TryCatch* that) {
Steve Blockd0582a62009-12-15 09:54:21 +0000282 // The ARM simulator has a separate JS stack. We therefore register
283 // the C++ try catch handler with the simulator and get back an
284 // address that can be used for comparisons with addresses into the
285 // JS stack. When running without the simulator, the address
286 // returned will be the address of the C++ try catch handler itself.
287 Address address = reinterpret_cast<Address>(
288 SimulatorStack::RegisterCTryCatch(reinterpret_cast<uintptr_t>(that)));
289 thread_local_.set_try_catch_handler_address(address);
Steve Blocka7e24c12009-10-30 11:49:00 +0000290}
291
292
293void Top::UnregisterTryCatchHandler(v8::TryCatch* that) {
Steve Blockd0582a62009-12-15 09:54:21 +0000294 ASSERT(thread_local_.TryCatchHandler() == that);
295 thread_local_.set_try_catch_handler_address(
296 reinterpret_cast<Address>(that->next_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000297 thread_local_.catcher_ = NULL;
Steve Blockd0582a62009-12-15 09:54:21 +0000298 SimulatorStack::UnregisterCTryCatch();
Steve Blocka7e24c12009-10-30 11:49:00 +0000299}
300
301
302void Top::MarkCompactPrologue(bool is_compacting) {
303 MarkCompactPrologue(is_compacting, &thread_local_);
304}
305
306
307void Top::MarkCompactPrologue(bool is_compacting, char* data) {
308 MarkCompactPrologue(is_compacting, reinterpret_cast<ThreadLocalTop*>(data));
309}
310
311
312void Top::MarkCompactPrologue(bool is_compacting, ThreadLocalTop* thread) {
313 if (is_compacting) {
314 StackFrame::CookFramesForThread(thread);
315 }
316}
317
318
319void Top::MarkCompactEpilogue(bool is_compacting, char* data) {
320 MarkCompactEpilogue(is_compacting, reinterpret_cast<ThreadLocalTop*>(data));
321}
322
323
324void Top::MarkCompactEpilogue(bool is_compacting) {
325 MarkCompactEpilogue(is_compacting, &thread_local_);
326}
327
328
329void Top::MarkCompactEpilogue(bool is_compacting, ThreadLocalTop* thread) {
330 if (is_compacting) {
331 StackFrame::UncookFramesForThread(thread);
332 }
333}
334
335
336static int stack_trace_nesting_level = 0;
337static StringStream* incomplete_message = NULL;
338
339
Kristian Monsen25f61362010-05-21 11:50:48 +0100340Handle<String> Top::StackTraceString() {
Steve Blocka7e24c12009-10-30 11:49:00 +0000341 if (stack_trace_nesting_level == 0) {
342 stack_trace_nesting_level++;
343 HeapStringAllocator allocator;
344 StringStream::ClearMentionedObjectCache();
345 StringStream accumulator(&allocator);
346 incomplete_message = &accumulator;
347 PrintStack(&accumulator);
348 Handle<String> stack_trace = accumulator.ToString();
349 incomplete_message = NULL;
350 stack_trace_nesting_level = 0;
351 return stack_trace;
352 } else if (stack_trace_nesting_level == 1) {
353 stack_trace_nesting_level++;
354 OS::PrintError(
355 "\n\nAttempt to print stack while printing stack (double fault)\n");
356 OS::PrintError(
357 "If you are lucky you may find a partial stack dump on stdout.\n\n");
358 incomplete_message->OutputToStdOut();
359 return Factory::empty_symbol();
360 } else {
361 OS::Abort();
362 // Unreachable
363 return Factory::empty_symbol();
364 }
365}
366
367
Kristian Monsen25f61362010-05-21 11:50:48 +0100368Local<StackTrace> Top::CaptureCurrentStackTrace(
369 int frame_limit, StackTrace::StackTraceOptions options) {
370 v8::HandleScope scope;
371 // Ensure no negative values.
372 int limit = Max(frame_limit, 0);
373 Handle<JSArray> stackTrace = Factory::NewJSArray(frame_limit);
374 FixedArray* frames = FixedArray::cast(stackTrace->elements());
375
376 Handle<String> column_key = Factory::LookupAsciiSymbol("column");
377 Handle<String> line_key = Factory::LookupAsciiSymbol("lineNumber");
378 Handle<String> script_key = Factory::LookupAsciiSymbol("scriptName");
379 Handle<String> function_key = Factory::LookupAsciiSymbol("functionName");
380 Handle<String> eval_key = Factory::LookupAsciiSymbol("isEval");
381 Handle<String> constructor_key = Factory::LookupAsciiSymbol("isConstructor");
382
383 StackTraceFrameIterator it;
384 int frames_seen = 0;
385 while (!it.done() && (frames_seen < limit)) {
386 // Create a JSObject to hold the information for the StackFrame.
387 Handle<JSObject> stackFrame = Factory::NewJSObject(object_function());
388
389 JavaScriptFrame* frame = it.frame();
390 JSFunction* fun(JSFunction::cast(frame->function()));
391 Script* script = Script::cast(fun->shared()->script());
392
393 if (options & StackTrace::kLineNumber) {
394 int script_line_offset = script->line_offset()->value();
395 int position = frame->code()->SourcePosition(frame->pc());
396 int line_number = GetScriptLineNumber(Handle<Script>(script), position);
397 // line_number is already shifted by the script_line_offset.
398 int relative_line_number = line_number - script_line_offset;
399 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
400 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
401 int start = (relative_line_number == 0) ? 0 :
402 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
403 int column_offset = position - start;
404 if (relative_line_number == 0) {
405 // For the case where the code is on the same line as the script tag.
406 column_offset += script->column_offset()->value();
407 }
408 SetProperty(stackFrame, column_key,
409 Handle<Smi>(Smi::FromInt(column_offset + 1)), NONE);
410 }
411 SetProperty(stackFrame, line_key,
412 Handle<Smi>(Smi::FromInt(line_number + 1)), NONE);
413 }
414
415 if (options & StackTrace::kScriptName) {
416 Handle<Object> script_name(script->name());
417 SetProperty(stackFrame, script_key, script_name, NONE);
418 }
419
420 if (options & StackTrace::kFunctionName) {
421 Handle<Object> fun_name(fun->shared()->name());
422 if (fun_name->ToBoolean()->IsFalse()) {
423 fun_name = Handle<Object>(fun->shared()->inferred_name());
424 }
425 SetProperty(stackFrame, function_key, fun_name, NONE);
426 }
427
428 if (options & StackTrace::kIsEval) {
429 int type = Smi::cast(script->compilation_type())->value();
430 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
431 Factory::true_value() : Factory::false_value();
432 SetProperty(stackFrame, eval_key, is_eval, NONE);
433 }
434
435 if (options & StackTrace::kIsConstructor) {
436 Handle<Object> is_constructor = (frame->IsConstructor()) ?
437 Factory::true_value() : Factory::false_value();
438 SetProperty(stackFrame, constructor_key, is_constructor, NONE);
439 }
440
441 frames->set(frames_seen, *stackFrame);
442 frames_seen++;
443 it.Advance();
444 }
445
446 stackTrace->set_length(Smi::FromInt(frames_seen));
447 return scope.Close(Utils::StackTraceToLocal(stackTrace));
448}
449
450
Steve Blocka7e24c12009-10-30 11:49:00 +0000451void Top::PrintStack() {
452 if (stack_trace_nesting_level == 0) {
453 stack_trace_nesting_level++;
454
455 StringAllocator* allocator;
456 if (preallocated_message_space == NULL) {
457 allocator = new HeapStringAllocator();
458 } else {
459 allocator = preallocated_message_space;
460 }
461
462 NativeAllocationChecker allocation_checker(
463 !FLAG_preallocate_message_memory ?
464 NativeAllocationChecker::ALLOW :
465 NativeAllocationChecker::DISALLOW);
466
467 StringStream::ClearMentionedObjectCache();
468 StringStream accumulator(allocator);
469 incomplete_message = &accumulator;
470 PrintStack(&accumulator);
471 accumulator.OutputToStdOut();
472 accumulator.Log();
473 incomplete_message = NULL;
474 stack_trace_nesting_level = 0;
475 if (preallocated_message_space == NULL) {
476 // Remove the HeapStringAllocator created above.
477 delete allocator;
478 }
479 } else if (stack_trace_nesting_level == 1) {
480 stack_trace_nesting_level++;
481 OS::PrintError(
482 "\n\nAttempt to print stack while printing stack (double fault)\n");
483 OS::PrintError(
484 "If you are lucky you may find a partial stack dump on stdout.\n\n");
485 incomplete_message->OutputToStdOut();
486 }
487}
488
489
490static void PrintFrames(StringStream* accumulator,
491 StackFrame::PrintMode mode) {
492 StackFrameIterator it;
493 for (int i = 0; !it.done(); it.Advance()) {
494 it.frame()->Print(accumulator, mode, i++);
495 }
496}
497
498
499void Top::PrintStack(StringStream* accumulator) {
500 // The MentionedObjectCache is not GC-proof at the moment.
501 AssertNoAllocation nogc;
502 ASSERT(StringStream::IsMentionedObjectCacheClear());
503
504 // Avoid printing anything if there are no frames.
505 if (c_entry_fp(GetCurrentThread()) == 0) return;
506
507 accumulator->Add(
508 "\n==== Stack trace ============================================\n\n");
509 PrintFrames(accumulator, StackFrame::OVERVIEW);
510
511 accumulator->Add(
512 "\n==== Details ================================================\n\n");
513 PrintFrames(accumulator, StackFrame::DETAILS);
514
515 accumulator->PrintMentionedObjectCache();
516 accumulator->Add("=====================\n\n");
517}
518
519
520void Top::SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback) {
521 ASSERT(thread_local_.failed_access_check_callback_ == NULL);
522 thread_local_.failed_access_check_callback_ = callback;
523}
524
525
526void Top::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
527 if (!thread_local_.failed_access_check_callback_) return;
528
529 ASSERT(receiver->IsAccessCheckNeeded());
530 ASSERT(Top::context());
531 // The callers of this method are not expecting a GC.
532 AssertNoAllocation no_gc;
533
534 // Get the data object from access check info.
535 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +0100536 if (!constructor->shared()->IsApiFunction()) return;
537 Object* data_obj =
538 constructor->shared()->get_api_func_data()->access_check_info();
Steve Blocka7e24c12009-10-30 11:49:00 +0000539 if (data_obj == Heap::undefined_value()) return;
540
541 HandleScope scope;
542 Handle<JSObject> receiver_handle(receiver);
543 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
544 thread_local_.failed_access_check_callback_(
545 v8::Utils::ToLocal(receiver_handle),
546 type,
547 v8::Utils::ToLocal(data));
548}
549
550
551enum MayAccessDecision {
552 YES, NO, UNKNOWN
553};
554
555
556static MayAccessDecision MayAccessPreCheck(JSObject* receiver,
557 v8::AccessType type) {
558 // During bootstrapping, callback functions are not enabled yet.
559 if (Bootstrapper::IsActive()) return YES;
560
561 if (receiver->IsJSGlobalProxy()) {
562 Object* receiver_context = JSGlobalProxy::cast(receiver)->context();
563 if (!receiver_context->IsContext()) return NO;
564
565 // Get the global context of current top context.
566 // avoid using Top::global_context() because it uses Handle.
567 Context* global_context = Top::context()->global()->global_context();
568 if (receiver_context == global_context) return YES;
569
570 if (Context::cast(receiver_context)->security_token() ==
571 global_context->security_token())
572 return YES;
573 }
574
575 return UNKNOWN;
576}
577
578
579bool Top::MayNamedAccess(JSObject* receiver, Object* key, v8::AccessType type) {
580 ASSERT(receiver->IsAccessCheckNeeded());
Steve Block3ce2e202009-11-05 08:53:23 +0000581
582 // The callers of this method are not expecting a GC.
583 AssertNoAllocation no_gc;
584
585 // Skip checks for hidden properties access. Note, we do not
586 // require existence of a context in this case.
587 if (key == Heap::hidden_symbol()) return true;
588
Steve Blocka7e24c12009-10-30 11:49:00 +0000589 // Check for compatibility between the security tokens in the
590 // current lexical context and the accessed object.
591 ASSERT(Top::context());
Steve Blocka7e24c12009-10-30 11:49:00 +0000592
593 MayAccessDecision decision = MayAccessPreCheck(receiver, type);
594 if (decision != UNKNOWN) return decision == YES;
595
596 // Get named access check callback
597 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +0100598 if (!constructor->shared()->IsApiFunction()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000599
Steve Block6ded16b2010-05-10 14:33:55 +0100600 Object* data_obj =
601 constructor->shared()->get_api_func_data()->access_check_info();
Steve Blocka7e24c12009-10-30 11:49:00 +0000602 if (data_obj == Heap::undefined_value()) return false;
603
604 Object* fun_obj = AccessCheckInfo::cast(data_obj)->named_callback();
605 v8::NamedSecurityCallback callback =
606 v8::ToCData<v8::NamedSecurityCallback>(fun_obj);
607
608 if (!callback) return false;
609
610 HandleScope scope;
611 Handle<JSObject> receiver_handle(receiver);
612 Handle<Object> key_handle(key);
613 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
614 LOG(ApiNamedSecurityCheck(key));
615 bool result = false;
616 {
617 // Leaving JavaScript.
618 VMState state(EXTERNAL);
619 result = callback(v8::Utils::ToLocal(receiver_handle),
620 v8::Utils::ToLocal(key_handle),
621 type,
622 v8::Utils::ToLocal(data));
623 }
624 return result;
625}
626
627
628bool Top::MayIndexedAccess(JSObject* receiver,
629 uint32_t index,
630 v8::AccessType type) {
631 ASSERT(receiver->IsAccessCheckNeeded());
632 // Check for compatibility between the security tokens in the
633 // current lexical context and the accessed object.
634 ASSERT(Top::context());
635 // The callers of this method are not expecting a GC.
636 AssertNoAllocation no_gc;
637
638 MayAccessDecision decision = MayAccessPreCheck(receiver, type);
639 if (decision != UNKNOWN) return decision == YES;
640
641 // Get indexed access check callback
642 JSFunction* constructor = JSFunction::cast(receiver->map()->constructor());
Steve Block6ded16b2010-05-10 14:33:55 +0100643 if (!constructor->shared()->IsApiFunction()) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000644
Steve Block6ded16b2010-05-10 14:33:55 +0100645 Object* data_obj =
646 constructor->shared()->get_api_func_data()->access_check_info();
Steve Blocka7e24c12009-10-30 11:49:00 +0000647 if (data_obj == Heap::undefined_value()) return false;
648
649 Object* fun_obj = AccessCheckInfo::cast(data_obj)->indexed_callback();
650 v8::IndexedSecurityCallback callback =
651 v8::ToCData<v8::IndexedSecurityCallback>(fun_obj);
652
653 if (!callback) return false;
654
655 HandleScope scope;
656 Handle<JSObject> receiver_handle(receiver);
657 Handle<Object> data(AccessCheckInfo::cast(data_obj)->data());
658 LOG(ApiIndexedSecurityCheck(index));
659 bool result = false;
660 {
661 // Leaving JavaScript.
662 VMState state(EXTERNAL);
663 result = callback(v8::Utils::ToLocal(receiver_handle),
664 index,
665 type,
666 v8::Utils::ToLocal(data));
667 }
668 return result;
669}
670
671
672const char* Top::kStackOverflowMessage =
673 "Uncaught RangeError: Maximum call stack size exceeded";
674
675
676Failure* Top::StackOverflow() {
677 HandleScope scope;
678 Handle<String> key = Factory::stack_overflow_symbol();
679 Handle<JSObject> boilerplate =
680 Handle<JSObject>::cast(GetProperty(Top::builtins(), key));
681 Handle<Object> exception = Copy(boilerplate);
682 // TODO(1240995): To avoid having to call JavaScript code to compute
683 // the message for stack overflow exceptions which is very likely to
684 // double fault with another stack overflow exception, we use a
685 // precomputed message. This is somewhat problematic in that it
686 // doesn't use ReportUncaughtException to determine the location
687 // from where the exception occurred. It should probably be
688 // reworked.
689 DoThrow(*exception, NULL, kStackOverflowMessage);
690 return Failure::Exception();
691}
692
693
694Failure* Top::TerminateExecution() {
695 DoThrow(Heap::termination_exception(), NULL, NULL);
696 return Failure::Exception();
697}
698
699
700Failure* Top::Throw(Object* exception, MessageLocation* location) {
701 DoThrow(exception, location, NULL);
702 return Failure::Exception();
703}
704
705
706Failure* Top::ReThrow(Object* exception, MessageLocation* location) {
707 // Set the exception being re-thrown.
708 set_pending_exception(exception);
709 return Failure::Exception();
710}
711
712
713Failure* Top::ThrowIllegalOperation() {
714 return Throw(Heap::illegal_access_symbol());
715}
716
717
718void Top::ScheduleThrow(Object* exception) {
719 // When scheduling a throw we first throw the exception to get the
720 // error reporting if it is uncaught before rescheduling it.
721 Throw(exception);
722 thread_local_.scheduled_exception_ = pending_exception();
723 thread_local_.external_caught_exception_ = false;
724 clear_pending_exception();
725}
726
727
728Object* Top::PromoteScheduledException() {
729 Object* thrown = scheduled_exception();
730 clear_scheduled_exception();
731 // Re-throw the exception to avoid getting repeated error reporting.
732 return ReThrow(thrown);
733}
734
735
736void Top::PrintCurrentStackTrace(FILE* out) {
737 StackTraceFrameIterator it;
738 while (!it.done()) {
739 HandleScope scope;
740 // Find code position if recorded in relocation info.
741 JavaScriptFrame* frame = it.frame();
742 int pos = frame->code()->SourcePosition(frame->pc());
743 Handle<Object> pos_obj(Smi::FromInt(pos));
744 // Fetch function and receiver.
745 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
746 Handle<Object> recv(frame->receiver());
747 // Advance to the next JavaScript frame and determine if the
748 // current frame is the top-level frame.
749 it.Advance();
750 Handle<Object> is_top_level = it.done()
751 ? Factory::true_value()
752 : Factory::false_value();
753 // Generate and print stack trace line.
754 Handle<String> line =
755 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
756 if (line->length() > 0) {
757 line->PrintOn(out);
758 fprintf(out, "\n");
759 }
760 }
761}
762
763
764void Top::ComputeLocation(MessageLocation* target) {
Andrei Popescu31002712010-02-23 13:46:05 +0000765 *target = MessageLocation(Handle<Script>(Heap::empty_script()), -1, -1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000766 StackTraceFrameIterator it;
767 if (!it.done()) {
768 JavaScriptFrame* frame = it.frame();
769 JSFunction* fun = JSFunction::cast(frame->function());
770 Object* script = fun->shared()->script();
771 if (script->IsScript() &&
772 !(Script::cast(script)->source()->IsUndefined())) {
773 int pos = frame->code()->SourcePosition(frame->pc());
774 // Compute the location from the function and the reloc info.
775 Handle<Script> casted_script(Script::cast(script));
776 *target = MessageLocation(casted_script, pos, pos + 1);
777 }
778 }
779}
780
781
782void Top::ReportUncaughtException(Handle<Object> exception,
783 MessageLocation* location,
784 Handle<String> stack_trace) {
785 Handle<Object> message;
786 if (!Bootstrapper::IsActive()) {
787 // It's not safe to try to make message objects while the bootstrapper
788 // is active since the infrastructure may not have been properly
789 // initialized.
790 message =
791 MessageHandler::MakeMessageObject("uncaught_exception",
792 location,
793 HandleVector<Object>(&exception, 1),
794 stack_trace);
795 }
796 // Report the uncaught exception.
797 MessageHandler::ReportMessage(location, message);
798}
799
800
801bool Top::ShouldReturnException(bool* is_caught_externally,
802 bool catchable_by_javascript) {
803 // Find the top-most try-catch handler.
804 StackHandler* handler =
805 StackHandler::FromAddress(Top::handler(Top::GetCurrentThread()));
806 while (handler != NULL && !handler->is_try_catch()) {
807 handler = handler->next();
808 }
809
810 // Get the address of the external handler so we can compare the address to
811 // determine which one is closer to the top of the stack.
Steve Blockd0582a62009-12-15 09:54:21 +0000812 Address external_handler_address = thread_local_.try_catch_handler_address();
Steve Blocka7e24c12009-10-30 11:49:00 +0000813
814 // The exception has been externally caught if and only if there is
815 // an external handler which is on top of the top-most try-catch
816 // handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000817 *is_caught_externally = external_handler_address != NULL &&
818 (handler == NULL || handler->address() > external_handler_address ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000819 !catchable_by_javascript);
820
821 if (*is_caught_externally) {
822 // Only report the exception if the external handler is verbose.
Steve Blockd0582a62009-12-15 09:54:21 +0000823 return thread_local_.TryCatchHandler()->is_verbose_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000824 } else {
825 // Report the exception if it isn't caught by JavaScript code.
826 return handler == NULL;
827 }
828}
829
830
831void Top::DoThrow(Object* exception,
832 MessageLocation* location,
833 const char* message) {
834 ASSERT(!has_pending_exception());
835
836 HandleScope scope;
837 Handle<Object> exception_handle(exception);
838
839 // Determine reporting and whether the exception is caught externally.
840 bool is_caught_externally = false;
841 bool is_out_of_memory = exception == Failure::OutOfMemoryException();
842 bool is_termination_exception = exception == Heap::termination_exception();
843 bool catchable_by_javascript = !is_termination_exception && !is_out_of_memory;
844 bool should_return_exception =
845 ShouldReturnException(&is_caught_externally, catchable_by_javascript);
846 bool report_exception = catchable_by_javascript && should_return_exception;
847
848#ifdef ENABLE_DEBUGGER_SUPPORT
849 // Notify debugger of exception.
850 if (catchable_by_javascript) {
851 Debugger::OnException(exception_handle, report_exception);
852 }
853#endif
854
855 // Generate the message.
856 Handle<Object> message_obj;
857 MessageLocation potential_computed_location;
858 bool try_catch_needs_message =
859 is_caught_externally &&
Steve Blockd0582a62009-12-15 09:54:21 +0000860 thread_local_.TryCatchHandler()->capture_message_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000861 if (report_exception || try_catch_needs_message) {
862 if (location == NULL) {
863 // If no location was specified we use a computed one instead
864 ComputeLocation(&potential_computed_location);
865 location = &potential_computed_location;
866 }
867 if (!Bootstrapper::IsActive()) {
868 // It's not safe to try to make message objects or collect stack
869 // traces while the bootstrapper is active since the infrastructure
870 // may not have been properly initialized.
871 Handle<String> stack_trace;
Kristian Monsen25f61362010-05-21 11:50:48 +0100872 if (FLAG_trace_exception) stack_trace = StackTraceString();
Steve Blocka7e24c12009-10-30 11:49:00 +0000873 message_obj = MessageHandler::MakeMessageObject("uncaught_exception",
874 location, HandleVector<Object>(&exception_handle, 1), stack_trace);
875 }
876 }
877
878 // Save the message for reporting if the the exception remains uncaught.
879 thread_local_.has_pending_message_ = report_exception;
880 thread_local_.pending_message_ = message;
881 if (!message_obj.is_null()) {
882 thread_local_.pending_message_obj_ = *message_obj;
883 if (location != NULL) {
884 thread_local_.pending_message_script_ = *location->script();
885 thread_local_.pending_message_start_pos_ = location->start_pos();
886 thread_local_.pending_message_end_pos_ = location->end_pos();
887 }
888 }
889
890 if (is_caught_externally) {
Steve Blockd0582a62009-12-15 09:54:21 +0000891 thread_local_.catcher_ = thread_local_.TryCatchHandler();
Steve Blocka7e24c12009-10-30 11:49:00 +0000892 }
893
894 // NOTE: Notifying the debugger or generating the message
895 // may have caused new exceptions. For now, we just ignore
896 // that and set the pending exception to the original one.
897 set_pending_exception(*exception_handle);
898}
899
900
901void Top::ReportPendingMessages() {
902 ASSERT(has_pending_exception());
903 setup_external_caught();
904 // If the pending exception is OutOfMemoryException set out_of_memory in
905 // the global context. Note: We have to mark the global context here
906 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
907 // set it.
908 bool external_caught = thread_local_.external_caught_exception_;
909 HandleScope scope;
910 if (thread_local_.pending_exception_ == Failure::OutOfMemoryException()) {
911 context()->mark_out_of_memory();
912 } else if (thread_local_.pending_exception_ ==
913 Heap::termination_exception()) {
914 if (external_caught) {
Steve Blockd0582a62009-12-15 09:54:21 +0000915 thread_local_.TryCatchHandler()->can_continue_ = false;
916 thread_local_.TryCatchHandler()->exception_ = Heap::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000917 }
918 } else {
919 Handle<Object> exception(pending_exception());
920 thread_local_.external_caught_exception_ = false;
921 if (external_caught) {
Steve Blockd0582a62009-12-15 09:54:21 +0000922 thread_local_.TryCatchHandler()->can_continue_ = true;
923 thread_local_.TryCatchHandler()->exception_ =
Steve Blocka7e24c12009-10-30 11:49:00 +0000924 thread_local_.pending_exception_;
925 if (!thread_local_.pending_message_obj_->IsTheHole()) {
926 try_catch_handler()->message_ = thread_local_.pending_message_obj_;
927 }
928 }
929 if (thread_local_.has_pending_message_) {
930 thread_local_.has_pending_message_ = false;
931 if (thread_local_.pending_message_ != NULL) {
932 MessageHandler::ReportMessage(thread_local_.pending_message_);
933 } else if (!thread_local_.pending_message_obj_->IsTheHole()) {
934 Handle<Object> message_obj(thread_local_.pending_message_obj_);
935 if (thread_local_.pending_message_script_ != NULL) {
936 Handle<Script> script(thread_local_.pending_message_script_);
937 int start_pos = thread_local_.pending_message_start_pos_;
938 int end_pos = thread_local_.pending_message_end_pos_;
939 MessageLocation location(script, start_pos, end_pos);
940 MessageHandler::ReportMessage(&location, message_obj);
941 } else {
942 MessageHandler::ReportMessage(NULL, message_obj);
943 }
944 }
945 }
946 thread_local_.external_caught_exception_ = external_caught;
947 set_pending_exception(*exception);
948 }
949 clear_pending_message();
950}
951
952
953void Top::TraceException(bool flag) {
954 FLAG_trace_exception = flag;
955}
956
957
958bool Top::OptionalRescheduleException(bool is_bottom_call) {
959 // Allways reschedule out of memory exceptions.
960 if (!is_out_of_memory()) {
961 bool is_termination_exception =
962 pending_exception() == Heap::termination_exception();
963
964 // Do not reschedule the exception if this is the bottom call.
965 bool clear_exception = is_bottom_call;
966
967 if (is_termination_exception) {
968 if (is_bottom_call) {
969 thread_local_.external_caught_exception_ = false;
970 clear_pending_exception();
971 return false;
972 }
973 } else if (thread_local_.external_caught_exception_) {
974 // If the exception is externally caught, clear it if there are no
975 // JavaScript frames on the way to the C++ frame that has the
976 // external handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000977 ASSERT(thread_local_.try_catch_handler_address() != NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000978 Address external_handler_address =
Steve Blockd0582a62009-12-15 09:54:21 +0000979 thread_local_.try_catch_handler_address();
Steve Blocka7e24c12009-10-30 11:49:00 +0000980 JavaScriptFrameIterator it;
981 if (it.done() || (it.frame()->sp() > external_handler_address)) {
982 clear_exception = true;
983 }
984 }
985
986 // Clear the exception if needed.
987 if (clear_exception) {
988 thread_local_.external_caught_exception_ = false;
989 clear_pending_exception();
990 return false;
991 }
992 }
993
994 // Reschedule the exception.
995 thread_local_.scheduled_exception_ = pending_exception();
996 clear_pending_exception();
997 return true;
998}
999
1000
1001bool Top::is_out_of_memory() {
1002 if (has_pending_exception()) {
1003 Object* e = pending_exception();
1004 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1005 return true;
1006 }
1007 }
1008 if (has_scheduled_exception()) {
1009 Object* e = scheduled_exception();
1010 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1011 return true;
1012 }
1013 }
1014 return false;
1015}
1016
1017
1018Handle<Context> Top::global_context() {
1019 GlobalObject* global = thread_local_.context_->global();
1020 return Handle<Context>(global->global_context());
1021}
1022
1023
1024Handle<Context> Top::GetCallingGlobalContext() {
1025 JavaScriptFrameIterator it;
Steve Blockd0582a62009-12-15 09:54:21 +00001026#ifdef ENABLE_DEBUGGER_SUPPORT
1027 if (Debug::InDebugger()) {
1028 while (!it.done()) {
1029 JavaScriptFrame* frame = it.frame();
1030 Context* context = Context::cast(frame->context());
1031 if (context->global_context() == *Debug::debug_context()) {
1032 it.Advance();
1033 } else {
1034 break;
1035 }
1036 }
1037 }
1038#endif // ENABLE_DEBUGGER_SUPPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00001039 if (it.done()) return Handle<Context>::null();
1040 JavaScriptFrame* frame = it.frame();
1041 Context* context = Context::cast(frame->context());
1042 return Handle<Context>(context->global_context());
1043}
1044
1045
Steve Blocka7e24c12009-10-30 11:49:00 +00001046char* Top::ArchiveThread(char* to) {
1047 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(thread_local_));
1048 InitializeThreadLocal();
1049 return to + sizeof(thread_local_);
1050}
1051
1052
1053char* Top::RestoreThread(char* from) {
1054 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(thread_local_));
1055 return from + sizeof(thread_local_);
1056}
1057
1058
1059ExecutionAccess::ExecutionAccess() {
1060 Top::break_access_->Lock();
1061}
1062
1063
1064ExecutionAccess::~ExecutionAccess() {
1065 Top::break_access_->Unlock();
1066}
1067
1068
1069} } // namespace v8::internal