blob: 516ec67496216110c798b077659623dba8cf9e32 [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);
Leon Clarkef7060e22010-06-03 12:02:55 +0100373 Handle<JSArray> stack_trace = Factory::NewJSArray(frame_limit);
Kristian Monsen25f61362010-05-21 11:50:48 +0100374
375 Handle<String> column_key = Factory::LookupAsciiSymbol("column");
376 Handle<String> line_key = Factory::LookupAsciiSymbol("lineNumber");
377 Handle<String> script_key = Factory::LookupAsciiSymbol("scriptName");
378 Handle<String> function_key = Factory::LookupAsciiSymbol("functionName");
379 Handle<String> eval_key = Factory::LookupAsciiSymbol("isEval");
380 Handle<String> constructor_key = Factory::LookupAsciiSymbol("isConstructor");
381
382 StackTraceFrameIterator it;
383 int frames_seen = 0;
384 while (!it.done() && (frames_seen < limit)) {
385 // Create a JSObject to hold the information for the StackFrame.
386 Handle<JSObject> stackFrame = Factory::NewJSObject(object_function());
387
388 JavaScriptFrame* frame = it.frame();
389 JSFunction* fun(JSFunction::cast(frame->function()));
390 Script* script = Script::cast(fun->shared()->script());
391
392 if (options & StackTrace::kLineNumber) {
393 int script_line_offset = script->line_offset()->value();
394 int position = frame->code()->SourcePosition(frame->pc());
395 int line_number = GetScriptLineNumber(Handle<Script>(script), position);
396 // line_number is already shifted by the script_line_offset.
397 int relative_line_number = line_number - script_line_offset;
398 if (options & StackTrace::kColumnOffset && relative_line_number >= 0) {
399 Handle<FixedArray> line_ends(FixedArray::cast(script->line_ends()));
400 int start = (relative_line_number == 0) ? 0 :
401 Smi::cast(line_ends->get(relative_line_number - 1))->value() + 1;
402 int column_offset = position - start;
403 if (relative_line_number == 0) {
404 // For the case where the code is on the same line as the script tag.
405 column_offset += script->column_offset()->value();
406 }
407 SetProperty(stackFrame, column_key,
408 Handle<Smi>(Smi::FromInt(column_offset + 1)), NONE);
409 }
410 SetProperty(stackFrame, line_key,
411 Handle<Smi>(Smi::FromInt(line_number + 1)), NONE);
412 }
413
414 if (options & StackTrace::kScriptName) {
415 Handle<Object> script_name(script->name());
416 SetProperty(stackFrame, script_key, script_name, NONE);
417 }
418
419 if (options & StackTrace::kFunctionName) {
420 Handle<Object> fun_name(fun->shared()->name());
421 if (fun_name->ToBoolean()->IsFalse()) {
422 fun_name = Handle<Object>(fun->shared()->inferred_name());
423 }
424 SetProperty(stackFrame, function_key, fun_name, NONE);
425 }
426
427 if (options & StackTrace::kIsEval) {
428 int type = Smi::cast(script->compilation_type())->value();
429 Handle<Object> is_eval = (type == Script::COMPILATION_TYPE_EVAL) ?
430 Factory::true_value() : Factory::false_value();
431 SetProperty(stackFrame, eval_key, is_eval, NONE);
432 }
433
434 if (options & StackTrace::kIsConstructor) {
435 Handle<Object> is_constructor = (frame->IsConstructor()) ?
436 Factory::true_value() : Factory::false_value();
437 SetProperty(stackFrame, constructor_key, is_constructor, NONE);
438 }
439
Leon Clarkef7060e22010-06-03 12:02:55 +0100440 FixedArray::cast(stack_trace->elements())->set(frames_seen, *stackFrame);
Kristian Monsen25f61362010-05-21 11:50:48 +0100441 frames_seen++;
442 it.Advance();
443 }
444
Leon Clarkef7060e22010-06-03 12:02:55 +0100445 stack_trace->set_length(Smi::FromInt(frames_seen));
446 return scope.Close(Utils::StackTraceToLocal(stack_trace));
Kristian Monsen25f61362010-05-21 11:50:48 +0100447}
448
449
Steve Blocka7e24c12009-10-30 11:49:00 +0000450void Top::PrintStack() {
451 if (stack_trace_nesting_level == 0) {
452 stack_trace_nesting_level++;
453
454 StringAllocator* allocator;
455 if (preallocated_message_space == NULL) {
456 allocator = new HeapStringAllocator();
457 } else {
458 allocator = preallocated_message_space;
459 }
460
461 NativeAllocationChecker allocation_checker(
462 !FLAG_preallocate_message_memory ?
463 NativeAllocationChecker::ALLOW :
464 NativeAllocationChecker::DISALLOW);
465
466 StringStream::ClearMentionedObjectCache();
467 StringStream accumulator(allocator);
468 incomplete_message = &accumulator;
469 PrintStack(&accumulator);
470 accumulator.OutputToStdOut();
471 accumulator.Log();
472 incomplete_message = NULL;
473 stack_trace_nesting_level = 0;
474 if (preallocated_message_space == NULL) {
475 // Remove the HeapStringAllocator created above.
476 delete allocator;
477 }
478 } else if (stack_trace_nesting_level == 1) {
479 stack_trace_nesting_level++;
480 OS::PrintError(
481 "\n\nAttempt to print stack while printing stack (double fault)\n");
482 OS::PrintError(
483 "If you are lucky you may find a partial stack dump on stdout.\n\n");
484 incomplete_message->OutputToStdOut();
485 }
486}
487
488
489static void PrintFrames(StringStream* accumulator,
490 StackFrame::PrintMode mode) {
491 StackFrameIterator it;
492 for (int i = 0; !it.done(); it.Advance()) {
493 it.frame()->Print(accumulator, mode, i++);
494 }
495}
496
497
498void Top::PrintStack(StringStream* accumulator) {
499 // The MentionedObjectCache is not GC-proof at the moment.
500 AssertNoAllocation nogc;
501 ASSERT(StringStream::IsMentionedObjectCacheClear());
502
503 // Avoid printing anything if there are no frames.
504 if (c_entry_fp(GetCurrentThread()) == 0) return;
505
506 accumulator->Add(
507 "\n==== Stack trace ============================================\n\n");
508 PrintFrames(accumulator, StackFrame::OVERVIEW);
509
510 accumulator->Add(
511 "\n==== Details ================================================\n\n");
512 PrintFrames(accumulator, StackFrame::DETAILS);
513
514 accumulator->PrintMentionedObjectCache();
515 accumulator->Add("=====================\n\n");
516}
517
518
519void Top::SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback) {
520 ASSERT(thread_local_.failed_access_check_callback_ == NULL);
521 thread_local_.failed_access_check_callback_ = callback;
522}
523
524
525void Top::ReportFailedAccessCheck(JSObject* receiver, v8::AccessType type) {
526 if (!thread_local_.failed_access_check_callback_) return;
527
528 ASSERT(receiver->IsAccessCheckNeeded());
529 ASSERT(Top::context());
530 // The callers of this method are not expecting a GC.
531 AssertNoAllocation no_gc;
532
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
684 // precomputed message. This is somewhat problematic in that it
685 // doesn't use ReportUncaughtException to determine the location
686 // from where the exception occurred. It should probably be
687 // reworked.
688 DoThrow(*exception, NULL, kStackOverflowMessage);
689 return Failure::Exception();
690}
691
692
693Failure* Top::TerminateExecution() {
694 DoThrow(Heap::termination_exception(), NULL, NULL);
695 return Failure::Exception();
696}
697
698
699Failure* Top::Throw(Object* exception, MessageLocation* location) {
700 DoThrow(exception, location, NULL);
701 return Failure::Exception();
702}
703
704
705Failure* Top::ReThrow(Object* exception, MessageLocation* location) {
706 // Set the exception being re-thrown.
707 set_pending_exception(exception);
708 return Failure::Exception();
709}
710
711
712Failure* Top::ThrowIllegalOperation() {
713 return Throw(Heap::illegal_access_symbol());
714}
715
716
717void Top::ScheduleThrow(Object* exception) {
718 // When scheduling a throw we first throw the exception to get the
719 // error reporting if it is uncaught before rescheduling it.
720 Throw(exception);
721 thread_local_.scheduled_exception_ = pending_exception();
722 thread_local_.external_caught_exception_ = false;
723 clear_pending_exception();
724}
725
726
727Object* Top::PromoteScheduledException() {
728 Object* thrown = scheduled_exception();
729 clear_scheduled_exception();
730 // Re-throw the exception to avoid getting repeated error reporting.
731 return ReThrow(thrown);
732}
733
734
735void Top::PrintCurrentStackTrace(FILE* out) {
736 StackTraceFrameIterator it;
737 while (!it.done()) {
738 HandleScope scope;
739 // Find code position if recorded in relocation info.
740 JavaScriptFrame* frame = it.frame();
741 int pos = frame->code()->SourcePosition(frame->pc());
742 Handle<Object> pos_obj(Smi::FromInt(pos));
743 // Fetch function and receiver.
744 Handle<JSFunction> fun(JSFunction::cast(frame->function()));
745 Handle<Object> recv(frame->receiver());
746 // Advance to the next JavaScript frame and determine if the
747 // current frame is the top-level frame.
748 it.Advance();
749 Handle<Object> is_top_level = it.done()
750 ? Factory::true_value()
751 : Factory::false_value();
752 // Generate and print stack trace line.
753 Handle<String> line =
754 Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level);
755 if (line->length() > 0) {
756 line->PrintOn(out);
757 fprintf(out, "\n");
758 }
759 }
760}
761
762
763void Top::ComputeLocation(MessageLocation* target) {
Andrei Popescu31002712010-02-23 13:46:05 +0000764 *target = MessageLocation(Handle<Script>(Heap::empty_script()), -1, -1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000765 StackTraceFrameIterator it;
766 if (!it.done()) {
767 JavaScriptFrame* frame = it.frame();
768 JSFunction* fun = JSFunction::cast(frame->function());
769 Object* script = fun->shared()->script();
770 if (script->IsScript() &&
771 !(Script::cast(script)->source()->IsUndefined())) {
772 int pos = frame->code()->SourcePosition(frame->pc());
773 // Compute the location from the function and the reloc info.
774 Handle<Script> casted_script(Script::cast(script));
775 *target = MessageLocation(casted_script, pos, pos + 1);
776 }
777 }
778}
779
780
781void Top::ReportUncaughtException(Handle<Object> exception,
782 MessageLocation* location,
783 Handle<String> stack_trace) {
784 Handle<Object> message;
785 if (!Bootstrapper::IsActive()) {
786 // It's not safe to try to make message objects while the bootstrapper
787 // is active since the infrastructure may not have been properly
788 // initialized.
789 message =
790 MessageHandler::MakeMessageObject("uncaught_exception",
791 location,
792 HandleVector<Object>(&exception, 1),
793 stack_trace);
794 }
795 // Report the uncaught exception.
796 MessageHandler::ReportMessage(location, message);
797}
798
799
800bool Top::ShouldReturnException(bool* is_caught_externally,
801 bool catchable_by_javascript) {
802 // Find the top-most try-catch handler.
803 StackHandler* handler =
804 StackHandler::FromAddress(Top::handler(Top::GetCurrentThread()));
805 while (handler != NULL && !handler->is_try_catch()) {
806 handler = handler->next();
807 }
808
809 // Get the address of the external handler so we can compare the address to
810 // determine which one is closer to the top of the stack.
Steve Blockd0582a62009-12-15 09:54:21 +0000811 Address external_handler_address = thread_local_.try_catch_handler_address();
Steve Blocka7e24c12009-10-30 11:49:00 +0000812
813 // The exception has been externally caught if and only if there is
814 // an external handler which is on top of the top-most try-catch
815 // handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000816 *is_caught_externally = external_handler_address != NULL &&
817 (handler == NULL || handler->address() > external_handler_address ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000818 !catchable_by_javascript);
819
820 if (*is_caught_externally) {
821 // Only report the exception if the external handler is verbose.
Steve Blockd0582a62009-12-15 09:54:21 +0000822 return thread_local_.TryCatchHandler()->is_verbose_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000823 } else {
824 // Report the exception if it isn't caught by JavaScript code.
825 return handler == NULL;
826 }
827}
828
829
830void Top::DoThrow(Object* exception,
831 MessageLocation* location,
832 const char* message) {
833 ASSERT(!has_pending_exception());
834
835 HandleScope scope;
836 Handle<Object> exception_handle(exception);
837
838 // Determine reporting and whether the exception is caught externally.
839 bool is_caught_externally = false;
840 bool is_out_of_memory = exception == Failure::OutOfMemoryException();
841 bool is_termination_exception = exception == Heap::termination_exception();
842 bool catchable_by_javascript = !is_termination_exception && !is_out_of_memory;
843 bool should_return_exception =
844 ShouldReturnException(&is_caught_externally, catchable_by_javascript);
845 bool report_exception = catchable_by_javascript && should_return_exception;
846
847#ifdef ENABLE_DEBUGGER_SUPPORT
848 // Notify debugger of exception.
849 if (catchable_by_javascript) {
850 Debugger::OnException(exception_handle, report_exception);
851 }
852#endif
853
854 // Generate the message.
855 Handle<Object> message_obj;
856 MessageLocation potential_computed_location;
857 bool try_catch_needs_message =
858 is_caught_externally &&
Steve Blockd0582a62009-12-15 09:54:21 +0000859 thread_local_.TryCatchHandler()->capture_message_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000860 if (report_exception || try_catch_needs_message) {
861 if (location == NULL) {
862 // If no location was specified we use a computed one instead
863 ComputeLocation(&potential_computed_location);
864 location = &potential_computed_location;
865 }
866 if (!Bootstrapper::IsActive()) {
867 // It's not safe to try to make message objects or collect stack
868 // traces while the bootstrapper is active since the infrastructure
869 // may not have been properly initialized.
870 Handle<String> stack_trace;
Kristian Monsen25f61362010-05-21 11:50:48 +0100871 if (FLAG_trace_exception) stack_trace = StackTraceString();
Steve Blocka7e24c12009-10-30 11:49:00 +0000872 message_obj = MessageHandler::MakeMessageObject("uncaught_exception",
873 location, HandleVector<Object>(&exception_handle, 1), stack_trace);
874 }
875 }
876
877 // Save the message for reporting if the the exception remains uncaught.
878 thread_local_.has_pending_message_ = report_exception;
879 thread_local_.pending_message_ = message;
880 if (!message_obj.is_null()) {
881 thread_local_.pending_message_obj_ = *message_obj;
882 if (location != NULL) {
883 thread_local_.pending_message_script_ = *location->script();
884 thread_local_.pending_message_start_pos_ = location->start_pos();
885 thread_local_.pending_message_end_pos_ = location->end_pos();
886 }
887 }
888
889 if (is_caught_externally) {
Steve Blockd0582a62009-12-15 09:54:21 +0000890 thread_local_.catcher_ = thread_local_.TryCatchHandler();
Steve Blocka7e24c12009-10-30 11:49:00 +0000891 }
892
893 // NOTE: Notifying the debugger or generating the message
894 // may have caused new exceptions. For now, we just ignore
895 // that and set the pending exception to the original one.
896 set_pending_exception(*exception_handle);
897}
898
899
900void Top::ReportPendingMessages() {
901 ASSERT(has_pending_exception());
902 setup_external_caught();
903 // If the pending exception is OutOfMemoryException set out_of_memory in
904 // the global context. Note: We have to mark the global context here
905 // since the GenerateThrowOutOfMemory stub cannot make a RuntimeCall to
906 // set it.
907 bool external_caught = thread_local_.external_caught_exception_;
908 HandleScope scope;
909 if (thread_local_.pending_exception_ == Failure::OutOfMemoryException()) {
910 context()->mark_out_of_memory();
911 } else if (thread_local_.pending_exception_ ==
912 Heap::termination_exception()) {
913 if (external_caught) {
Steve Blockd0582a62009-12-15 09:54:21 +0000914 thread_local_.TryCatchHandler()->can_continue_ = false;
915 thread_local_.TryCatchHandler()->exception_ = Heap::null_value();
Steve Blocka7e24c12009-10-30 11:49:00 +0000916 }
917 } else {
918 Handle<Object> exception(pending_exception());
919 thread_local_.external_caught_exception_ = false;
920 if (external_caught) {
Steve Blockd0582a62009-12-15 09:54:21 +0000921 thread_local_.TryCatchHandler()->can_continue_ = true;
922 thread_local_.TryCatchHandler()->exception_ =
Steve Blocka7e24c12009-10-30 11:49:00 +0000923 thread_local_.pending_exception_;
924 if (!thread_local_.pending_message_obj_->IsTheHole()) {
925 try_catch_handler()->message_ = thread_local_.pending_message_obj_;
926 }
927 }
928 if (thread_local_.has_pending_message_) {
929 thread_local_.has_pending_message_ = false;
930 if (thread_local_.pending_message_ != NULL) {
931 MessageHandler::ReportMessage(thread_local_.pending_message_);
932 } else if (!thread_local_.pending_message_obj_->IsTheHole()) {
933 Handle<Object> message_obj(thread_local_.pending_message_obj_);
934 if (thread_local_.pending_message_script_ != NULL) {
935 Handle<Script> script(thread_local_.pending_message_script_);
936 int start_pos = thread_local_.pending_message_start_pos_;
937 int end_pos = thread_local_.pending_message_end_pos_;
938 MessageLocation location(script, start_pos, end_pos);
939 MessageHandler::ReportMessage(&location, message_obj);
940 } else {
941 MessageHandler::ReportMessage(NULL, message_obj);
942 }
943 }
944 }
945 thread_local_.external_caught_exception_ = external_caught;
946 set_pending_exception(*exception);
947 }
948 clear_pending_message();
949}
950
951
952void Top::TraceException(bool flag) {
953 FLAG_trace_exception = flag;
954}
955
956
957bool Top::OptionalRescheduleException(bool is_bottom_call) {
958 // Allways reschedule out of memory exceptions.
959 if (!is_out_of_memory()) {
960 bool is_termination_exception =
961 pending_exception() == Heap::termination_exception();
962
963 // Do not reschedule the exception if this is the bottom call.
964 bool clear_exception = is_bottom_call;
965
966 if (is_termination_exception) {
967 if (is_bottom_call) {
968 thread_local_.external_caught_exception_ = false;
969 clear_pending_exception();
970 return false;
971 }
972 } else if (thread_local_.external_caught_exception_) {
973 // If the exception is externally caught, clear it if there are no
974 // JavaScript frames on the way to the C++ frame that has the
975 // external handler.
Steve Blockd0582a62009-12-15 09:54:21 +0000976 ASSERT(thread_local_.try_catch_handler_address() != NULL);
Steve Blocka7e24c12009-10-30 11:49:00 +0000977 Address external_handler_address =
Steve Blockd0582a62009-12-15 09:54:21 +0000978 thread_local_.try_catch_handler_address();
Steve Blocka7e24c12009-10-30 11:49:00 +0000979 JavaScriptFrameIterator it;
980 if (it.done() || (it.frame()->sp() > external_handler_address)) {
981 clear_exception = true;
982 }
983 }
984
985 // Clear the exception if needed.
986 if (clear_exception) {
987 thread_local_.external_caught_exception_ = false;
988 clear_pending_exception();
989 return false;
990 }
991 }
992
993 // Reschedule the exception.
994 thread_local_.scheduled_exception_ = pending_exception();
995 clear_pending_exception();
996 return true;
997}
998
999
1000bool Top::is_out_of_memory() {
1001 if (has_pending_exception()) {
1002 Object* e = pending_exception();
1003 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1004 return true;
1005 }
1006 }
1007 if (has_scheduled_exception()) {
1008 Object* e = scheduled_exception();
1009 if (e->IsFailure() && Failure::cast(e)->IsOutOfMemoryException()) {
1010 return true;
1011 }
1012 }
1013 return false;
1014}
1015
1016
1017Handle<Context> Top::global_context() {
1018 GlobalObject* global = thread_local_.context_->global();
1019 return Handle<Context>(global->global_context());
1020}
1021
1022
1023Handle<Context> Top::GetCallingGlobalContext() {
1024 JavaScriptFrameIterator it;
Steve Blockd0582a62009-12-15 09:54:21 +00001025#ifdef ENABLE_DEBUGGER_SUPPORT
1026 if (Debug::InDebugger()) {
1027 while (!it.done()) {
1028 JavaScriptFrame* frame = it.frame();
1029 Context* context = Context::cast(frame->context());
1030 if (context->global_context() == *Debug::debug_context()) {
1031 it.Advance();
1032 } else {
1033 break;
1034 }
1035 }
1036 }
1037#endif // ENABLE_DEBUGGER_SUPPORT
Steve Blocka7e24c12009-10-30 11:49:00 +00001038 if (it.done()) return Handle<Context>::null();
1039 JavaScriptFrame* frame = it.frame();
1040 Context* context = Context::cast(frame->context());
1041 return Handle<Context>(context->global_context());
1042}
1043
1044
Steve Blocka7e24c12009-10-30 11:49:00 +00001045char* Top::ArchiveThread(char* to) {
1046 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(thread_local_));
1047 InitializeThreadLocal();
1048 return to + sizeof(thread_local_);
1049}
1050
1051
1052char* Top::RestoreThread(char* from) {
1053 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(thread_local_));
1054 return from + sizeof(thread_local_);
1055}
1056
1057
1058ExecutionAccess::ExecutionAccess() {
1059 Top::break_access_->Lock();
1060}
1061
1062
1063ExecutionAccess::~ExecutionAccess() {
1064 Top::break_access_->Unlock();
1065}
1066
1067
1068} } // namespace v8::internal