1 // Copyright 2012 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
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.
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.
31 #include "arguments.h"
32 #include "bootstrapper.h"
33 #include "code-stubs.h"
35 #include "compilation-cache.h"
38 #include "deoptimizer.h"
39 #include "execution.h"
40 #include "full-codegen.h"
41 #include "global-handles.h"
44 #include "isolate-inl.h"
48 #include "stub-cache.h"
51 #include "../include/v8-debug.h"
56 #ifdef ENABLE_DEBUGGER_SUPPORT
59 Debug::Debug(Isolate* isolate)
60 : has_break_points_(false),
62 debug_info_list_(NULL),
63 disable_break_(false),
64 break_on_exception_(false),
65 break_on_uncaught_exception_(false),
66 debug_break_return_(NULL),
67 debug_break_slot_(NULL),
69 memset(registers_, 0, sizeof(JSCallerSavedBuffer));
77 static void PrintLn(v8::Local<v8::Value> value) {
78 v8::Local<v8::String> s = value->ToString();
79 ScopedVector<char> data(s->Utf8Length() + 1);
80 if (data.start() == NULL) {
81 V8::FatalProcessOutOfMemory("PrintLn");
84 s->WriteUtf8(data.start());
85 PrintF("%s\n", data.start());
89 static v8::Handle<v8::Context> GetDebugEventContext(Isolate* isolate) {
90 Handle<Context> context = isolate->debug()->debugger_entry()->GetContext();
91 // Isolate::context() may have been NULL when "script collected" event
93 if (context.is_null()) return v8::Local<v8::Context>();
94 Handle<Context> native_context(context->native_context());
95 return v8::Utils::ToLocal(native_context);
99 BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
100 BreakLocatorType type) {
101 debug_info_ = debug_info;
103 reloc_iterator_ = NULL;
104 reloc_iterator_original_ = NULL;
105 Reset(); // Initialize the rest of the member variables.
109 BreakLocationIterator::~BreakLocationIterator() {
110 ASSERT(reloc_iterator_ != NULL);
111 ASSERT(reloc_iterator_original_ != NULL);
112 delete reloc_iterator_;
113 delete reloc_iterator_original_;
117 void BreakLocationIterator::Next() {
118 DisallowHeapAllocation no_gc;
119 ASSERT(!RinfoDone());
121 // Iterate through reloc info for code and original code stopping at each
122 // breakable code target.
123 bool first = break_point_ == -1;
124 while (!RinfoDone()) {
125 if (!first) RinfoNext();
127 if (RinfoDone()) return;
129 // Whenever a statement position or (plain) position is passed update the
130 // current value of these.
131 if (RelocInfo::IsPosition(rmode())) {
132 if (RelocInfo::IsStatementPosition(rmode())) {
133 statement_position_ = static_cast<int>(
134 rinfo()->data() - debug_info_->shared()->start_position());
136 // Always update the position as we don't want that to be before the
137 // statement position.
138 position_ = static_cast<int>(
139 rinfo()->data() - debug_info_->shared()->start_position());
140 ASSERT(position_ >= 0);
141 ASSERT(statement_position_ >= 0);
144 if (IsDebugBreakSlot()) {
145 // There is always a possible break point at a debug break slot.
148 } else if (RelocInfo::IsCodeTarget(rmode())) {
149 // Check for breakable code target. Look in the original code as setting
150 // break points can cause the code targets in the running (debugged) code
151 // to be of a different kind than in the original code.
152 Address target = original_rinfo()->target_address();
153 Code* code = Code::GetCodeFromTargetAddress(target);
154 if ((code->is_inline_cache_stub() &&
155 !code->is_binary_op_stub() &&
156 !code->is_compare_ic_stub() &&
157 !code->is_to_boolean_ic_stub()) ||
158 RelocInfo::IsConstructCall(rmode())) {
162 if (code->kind() == Code::STUB) {
163 if (IsDebuggerStatement()) {
167 if (type_ == ALL_BREAK_LOCATIONS) {
168 if (Debug::IsBreakStub(code)) {
173 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
174 if (Debug::IsSourceBreakStub(code)) {
182 // Check for break at return.
183 if (RelocInfo::IsJSReturn(rmode())) {
184 // Set the positions to the end of the function.
185 if (debug_info_->shared()->HasSourceCode()) {
186 position_ = debug_info_->shared()->end_position() -
187 debug_info_->shared()->start_position() - 1;
191 statement_position_ = position_;
199 void BreakLocationIterator::Next(int count) {
207 // Find the break point at the supplied address, or the closest one before
209 void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
210 // Run through all break points to locate the one closest to the address.
211 int closest_break_point = 0;
212 int distance = kMaxInt;
214 // Check if this break point is closer that what was previously found.
215 if (this->pc() <= pc && pc - this->pc() < distance) {
216 closest_break_point = break_point();
217 distance = static_cast<int>(pc - this->pc());
218 // Check whether we can't get any closer.
219 if (distance == 0) break;
224 // Move to the break point found.
226 Next(closest_break_point);
230 // Find the break point closest to the supplied source position.
231 void BreakLocationIterator::FindBreakLocationFromPosition(int position,
232 BreakPositionAlignment alignment) {
233 // Run through all break points to locate the one closest to the source
235 int closest_break_point = 0;
236 int distance = kMaxInt;
241 case STATEMENT_ALIGNED:
242 next_position = this->statement_position();
244 case BREAK_POSITION_ALIGNED:
245 next_position = this->position();
249 next_position = this->statement_position();
251 // Check if this break point is closer that what was previously found.
252 if (position <= next_position && next_position - position < distance) {
253 closest_break_point = break_point();
254 distance = next_position - position;
255 // Check whether we can't get any closer.
256 if (distance == 0) break;
261 // Move to the break point found.
263 Next(closest_break_point);
267 void BreakLocationIterator::Reset() {
268 // Create relocation iterators for the two code objects.
269 if (reloc_iterator_ != NULL) delete reloc_iterator_;
270 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
271 reloc_iterator_ = new RelocIterator(
273 ~RelocInfo::ModeMask(RelocInfo::CODE_AGE_SEQUENCE));
274 reloc_iterator_original_ = new RelocIterator(
275 debug_info_->original_code(),
276 ~RelocInfo::ModeMask(RelocInfo::CODE_AGE_SEQUENCE));
278 // Position at the first break point.
281 statement_position_ = 1;
286 bool BreakLocationIterator::Done() const {
291 void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
292 // If there is not already a real break point here patch code with debug
294 if (!HasBreakPoint()) {
297 ASSERT(IsDebugBreak() || IsDebuggerStatement());
298 // Set the break point information.
299 DebugInfo::SetBreakPoint(debug_info_, code_position(),
300 position(), statement_position(),
305 void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
306 // Clear the break point information.
307 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
308 // If there are no more break points here remove the debug break.
309 if (!HasBreakPoint()) {
311 ASSERT(!IsDebugBreak());
316 void BreakLocationIterator::SetOneShot() {
317 // Debugger statement always calls debugger. No need to modify it.
318 if (IsDebuggerStatement()) {
322 // If there is a real break point here no more to do.
323 if (HasBreakPoint()) {
324 ASSERT(IsDebugBreak());
328 // Patch code with debug break.
333 void BreakLocationIterator::ClearOneShot() {
334 // Debugger statement always calls debugger. No need to modify it.
335 if (IsDebuggerStatement()) {
339 // If there is a real break point here no more to do.
340 if (HasBreakPoint()) {
341 ASSERT(IsDebugBreak());
345 // Patch code removing debug break.
347 ASSERT(!IsDebugBreak());
351 void BreakLocationIterator::SetDebugBreak() {
352 // Debugger statement always calls debugger. No need to modify it.
353 if (IsDebuggerStatement()) {
357 // If there is already a break point here just return. This might happen if
358 // the same code is flooded with break points twice. Flooding the same
359 // function twice might happen when stepping in a function with an exception
360 // handler as the handler and the function is the same.
361 if (IsDebugBreak()) {
365 if (RelocInfo::IsJSReturn(rmode())) {
366 // Patch the frame exit code with a break point.
367 SetDebugBreakAtReturn();
368 } else if (IsDebugBreakSlot()) {
369 // Patch the code in the break slot.
370 SetDebugBreakAtSlot();
372 // Patch the IC call.
375 ASSERT(IsDebugBreak());
379 void BreakLocationIterator::ClearDebugBreak() {
380 // Debugger statement always calls debugger. No need to modify it.
381 if (IsDebuggerStatement()) {
385 if (RelocInfo::IsJSReturn(rmode())) {
386 // Restore the frame exit code.
387 ClearDebugBreakAtReturn();
388 } else if (IsDebugBreakSlot()) {
389 // Restore the code in the break slot.
390 ClearDebugBreakAtSlot();
392 // Patch the IC call.
393 ClearDebugBreakAtIC();
395 ASSERT(!IsDebugBreak());
399 bool BreakLocationIterator::IsStepInLocation(Isolate* isolate) {
400 if (RelocInfo::IsConstructCall(original_rmode())) {
402 } else if (RelocInfo::IsCodeTarget(rmode())) {
403 HandleScope scope(debug_info_->GetIsolate());
404 Address target = original_rinfo()->target_address();
405 Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
406 if (target_code->kind() == Code::STUB) {
407 return target_code->major_key() == CodeStub::CallFunction;
414 void BreakLocationIterator::PrepareStepIn(Isolate* isolate) {
416 HandleScope scope(isolate);
417 // Step in can only be prepared if currently positioned on an IC call,
418 // construct call or CallFunction stub call.
419 Address target = rinfo()->target_address();
420 Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
421 // All the following stuff is needed only for assertion checks so the code
422 // is wrapped in ifdef.
423 Handle<Code> maybe_call_function_stub = target_code;
424 if (IsDebugBreak()) {
425 Address original_target = original_rinfo()->target_address();
426 maybe_call_function_stub =
427 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
429 bool is_call_function_stub =
430 (maybe_call_function_stub->kind() == Code::STUB &&
431 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
433 // Step in through construct call requires no changes to the running code.
434 // Step in through getters/setters should already be prepared as well
435 // because caller of this function (Debug::PrepareStep) is expected to
436 // flood the top frame's function with one shot breakpoints.
437 // Step in through CallFunction stub should also be prepared by caller of
438 // this function (Debug::PrepareStep) which should flood target function
440 ASSERT(RelocInfo::IsConstructCall(rmode()) ||
441 target_code->is_inline_cache_stub() ||
442 is_call_function_stub);
447 // Check whether the break point is at a position which will exit the function.
448 bool BreakLocationIterator::IsExit() const {
449 return (RelocInfo::IsJSReturn(rmode()));
453 bool BreakLocationIterator::HasBreakPoint() {
454 return debug_info_->HasBreakPoint(code_position());
458 // Check whether there is a debug break at the current position.
459 bool BreakLocationIterator::IsDebugBreak() {
460 if (RelocInfo::IsJSReturn(rmode())) {
461 return IsDebugBreakAtReturn();
462 } else if (IsDebugBreakSlot()) {
463 return IsDebugBreakAtSlot();
465 return Debug::IsDebugBreak(rinfo()->target_address());
470 void BreakLocationIterator::SetDebugBreakAtIC() {
471 // Patch the original code with the current address as the current address
472 // might have changed by the inline caching since the code was copied.
473 original_rinfo()->set_target_address(rinfo()->target_address());
475 RelocInfo::Mode mode = rmode();
476 if (RelocInfo::IsCodeTarget(mode)) {
477 Address target = rinfo()->target_address();
478 Handle<Code> target_code(Code::GetCodeFromTargetAddress(target));
480 // Patch the code to invoke the builtin debug break function matching the
481 // calling convention used by the call site.
482 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(target_code, mode));
483 rinfo()->set_target_address(dbgbrk_code->entry());
488 void BreakLocationIterator::ClearDebugBreakAtIC() {
489 // Patch the code to the original invoke.
490 rinfo()->set_target_address(original_rinfo()->target_address());
494 bool BreakLocationIterator::IsDebuggerStatement() {
495 return RelocInfo::DEBUG_BREAK == rmode();
499 bool BreakLocationIterator::IsDebugBreakSlot() {
500 return RelocInfo::DEBUG_BREAK_SLOT == rmode();
504 Object* BreakLocationIterator::BreakPointObjects() {
505 return debug_info_->GetBreakPointObjects(code_position());
509 // Clear out all the debug break code. This is ONLY supposed to be used when
510 // shutting down the debugger as it will leave the break point information in
511 // DebugInfo even though the code is patched back to the non break point state.
512 void BreakLocationIterator::ClearAllDebugBreak() {
520 bool BreakLocationIterator::RinfoDone() const {
521 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
522 return reloc_iterator_->done();
526 void BreakLocationIterator::RinfoNext() {
527 reloc_iterator_->next();
528 reloc_iterator_original_->next();
530 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
531 if (!reloc_iterator_->done()) {
532 ASSERT(rmode() == original_rmode());
538 // Threading support.
539 void Debug::ThreadInit() {
540 thread_local_.break_count_ = 0;
541 thread_local_.break_id_ = 0;
542 thread_local_.break_frame_id_ = StackFrame::NO_ID;
543 thread_local_.last_step_action_ = StepNone;
544 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
545 thread_local_.step_count_ = 0;
546 thread_local_.last_fp_ = 0;
547 thread_local_.queued_step_count_ = 0;
548 thread_local_.step_into_fp_ = 0;
549 thread_local_.step_out_fp_ = 0;
550 thread_local_.after_break_target_ = 0;
551 // TODO(isolates): frames_are_dropped_?
552 thread_local_.debugger_entry_ = NULL;
553 thread_local_.pending_interrupts_ = 0;
554 thread_local_.restarter_frame_function_pointer_ = NULL;
558 char* Debug::ArchiveDebug(char* storage) {
560 OS::MemCopy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
561 to += sizeof(ThreadLocal);
562 OS::MemCopy(to, reinterpret_cast<char*>(®isters_), sizeof(registers_));
564 ASSERT(to <= storage + ArchiveSpacePerThread());
565 return storage + ArchiveSpacePerThread();
569 char* Debug::RestoreDebug(char* storage) {
570 char* from = storage;
572 reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
573 from += sizeof(ThreadLocal);
574 OS::MemCopy(reinterpret_cast<char*>(®isters_), from, sizeof(registers_));
575 ASSERT(from <= storage + ArchiveSpacePerThread());
576 return storage + ArchiveSpacePerThread();
580 int Debug::ArchiveSpacePerThread() {
581 return sizeof(ThreadLocal) + sizeof(JSCallerSavedBuffer);
585 // Frame structure (conforms InternalFrame structure):
588 // -- function (slot is called "context")
590 Object** Debug::SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
592 ASSERT(bottom_js_frame->is_java_script());
594 Address fp = bottom_js_frame->fp();
596 // Move function pointer into "context" slot.
597 Memory::Object_at(fp + StandardFrameConstants::kContextOffset) =
598 Memory::Object_at(fp + JavaScriptFrameConstants::kFunctionOffset);
600 Memory::Object_at(fp + InternalFrameConstants::kCodeOffset) = *code;
601 Memory::Object_at(fp + StandardFrameConstants::kMarkerOffset) =
602 Smi::FromInt(StackFrame::INTERNAL);
604 return reinterpret_cast<Object**>(&Memory::Object_at(
605 fp + StandardFrameConstants::kContextOffset));
608 const int Debug::kFrameDropperFrameSize = 4;
611 void ScriptCache::Add(Handle<Script> script) {
612 GlobalHandles* global_handles = isolate_->global_handles();
613 // Create an entry in the hash map for the script.
614 int id = script->id()->value();
615 HashMap::Entry* entry =
616 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
617 if (entry->value != NULL) {
618 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
621 // Globalize the script object, make it weak and use the location of the
622 // global handle as the value in the hash map.
623 Handle<Script> script_ =
624 Handle<Script>::cast(global_handles->Create(*script));
625 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
627 ScriptCache::HandleWeakScript);
628 entry->value = script_.location();
632 Handle<FixedArray> ScriptCache::GetScripts() {
633 Factory* factory = isolate_->factory();
634 Handle<FixedArray> instances = factory->NewFixedArray(occupancy());
636 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
637 ASSERT(entry->value != NULL);
638 if (entry->value != NULL) {
639 instances->set(count, *reinterpret_cast<Script**>(entry->value));
647 void ScriptCache::ProcessCollectedScripts() {
648 Debugger* debugger = isolate_->debugger();
649 for (int i = 0; i < collected_scripts_.length(); i++) {
650 debugger->OnScriptCollected(collected_scripts_[i]);
652 collected_scripts_.Clear();
656 void ScriptCache::Clear() {
657 // Iterate the script cache to get rid of all the weak handles.
658 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
659 ASSERT(entry != NULL);
660 Object** location = reinterpret_cast<Object**>(entry->value);
661 ASSERT((*location)->IsScript());
662 GlobalHandles::ClearWeakness(location);
663 GlobalHandles::Destroy(location);
665 // Clear the content of the hash map.
670 void ScriptCache::HandleWeakScript(
671 const v8::WeakCallbackData<v8::Value, void>& data) {
672 // Retrieve the script identifier.
673 Handle<Object> object = Utils::OpenHandle(*data.GetValue());
674 int id = Handle<Script>::cast(object)->id()->value();
675 void* key = reinterpret_cast<void*>(id);
676 uint32_t hash = Hash(id);
678 // Remove the corresponding entry from the cache.
679 ScriptCache* script_cache =
680 reinterpret_cast<ScriptCache*>(data.GetParameter());
681 HashMap::Entry* entry = script_cache->Lookup(key, hash, false);
682 Object** location = reinterpret_cast<Object**>(entry->value);
683 script_cache->Remove(key, hash);
684 script_cache->collected_scripts_.Add(id);
686 // Clear the weak handle.
687 GlobalHandles::Destroy(location);
691 void Debug::SetUp(bool create_heap_objects) {
693 if (create_heap_objects) {
694 // Get code to handle debug break on return.
695 debug_break_return_ =
696 isolate_->builtins()->builtin(Builtins::kReturn_DebugBreak);
697 ASSERT(debug_break_return_->IsCode());
698 // Get code to handle debug break in debug break slots.
700 isolate_->builtins()->builtin(Builtins::kSlot_DebugBreak);
701 ASSERT(debug_break_slot_->IsCode());
706 void Debug::HandleWeakDebugInfo(
707 const v8::WeakCallbackData<v8::Value, void>& data) {
708 Debug* debug = reinterpret_cast<Isolate*>(data.GetIsolate())->debug();
709 DebugInfoListNode* node =
710 reinterpret_cast<DebugInfoListNode*>(data.GetParameter());
711 // We need to clear all breakpoints associated with the function to restore
712 // original code and avoid patching the code twice later because
713 // the function will live in the heap until next gc, and can be found by
714 // Debug::FindSharedFunctionInfoInScript.
715 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
716 it.ClearAllDebugBreak();
717 debug->RemoveDebugInfo(node->debug_info());
719 for (DebugInfoListNode* n = debug->debug_info_list_;
728 DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
729 // Globalize the request debug info object and make it weak.
730 GlobalHandles* global_handles = debug_info->GetIsolate()->global_handles();
731 debug_info_ = Handle<DebugInfo>::cast(global_handles->Create(debug_info));
732 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
734 Debug::HandleWeakDebugInfo);
738 DebugInfoListNode::~DebugInfoListNode() {
739 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
743 bool Debug::CompileDebuggerScript(Isolate* isolate, int index) {
744 Factory* factory = isolate->factory();
745 HandleScope scope(isolate);
747 // Bail out if the index is invalid.
752 // Find source and name for the requested script.
753 Handle<String> source_code =
754 isolate->bootstrapper()->NativesSourceLookup(index);
755 Vector<const char> name = Natives::GetScriptName(index);
756 Handle<String> script_name = factory->NewStringFromAscii(name);
757 ASSERT(!script_name.is_null());
758 Handle<Context> context = isolate->native_context();
760 // Compile the script.
761 Handle<SharedFunctionInfo> function_info;
762 function_info = Compiler::CompileScript(source_code,
766 NULL, NULL, NO_CACHED_DATA,
769 // Silently ignore stack overflows during compilation.
770 if (function_info.is_null()) {
771 ASSERT(isolate->has_pending_exception());
772 isolate->clear_pending_exception();
776 // Execute the shared function in the debugger context.
777 bool caught_exception;
778 Handle<JSFunction> function =
779 factory->NewFunctionFromSharedFunctionInfo(function_info, context);
781 Handle<Object> exception =
782 Execution::TryCall(function,
783 Handle<Object>(context->global_object(), isolate),
788 // Check for caught exceptions.
789 if (caught_exception) {
790 ASSERT(!isolate->has_pending_exception());
791 MessageLocation computed_location;
792 isolate->ComputeLocation(&computed_location);
793 Handle<Object> message = MessageHandler::MakeMessageObject(
794 isolate, "error_loading_debugger", &computed_location,
795 Vector<Handle<Object> >::empty(), Handle<JSArray>());
796 ASSERT(!isolate->has_pending_exception());
797 if (!exception.is_null()) {
798 isolate->set_pending_exception(*exception);
799 MessageHandler::ReportMessage(isolate, NULL, message);
800 isolate->clear_pending_exception();
805 // Mark this script as native and return successfully.
806 Handle<Script> script(Script::cast(function->shared()->script()));
807 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
813 // Return if debugger is already loaded.
814 if (IsLoaded()) return true;
816 Debugger* debugger = isolate_->debugger();
818 // Bail out if we're already in the process of compiling the native
819 // JavaScript source code for the debugger.
820 if (debugger->compiling_natives() ||
821 debugger->is_loading_debugger())
823 debugger->set_loading_debugger(true);
825 // Disable breakpoints and interrupts while compiling and running the
826 // debugger scripts including the context creation code.
827 DisableBreak disable(isolate_, true);
828 PostponeInterruptsScope postpone(isolate_);
830 // Create the debugger context.
831 HandleScope scope(isolate_);
832 ExtensionConfiguration no_extensions;
833 Handle<Context> context =
834 isolate_->bootstrapper()->CreateEnvironment(
835 Handle<Object>::null(),
836 v8::Handle<ObjectTemplate>(),
839 // Fail if no context could be created.
840 if (context.is_null()) return false;
842 // Use the debugger context.
843 SaveContext save(isolate_);
844 isolate_->set_context(*context);
846 // Expose the builtins object in the debugger context.
847 Handle<String> key = isolate_->factory()->InternalizeOneByteString(
848 STATIC_ASCII_VECTOR("builtins"));
849 Handle<GlobalObject> global = Handle<GlobalObject>(context->global_object());
850 RETURN_IF_EMPTY_HANDLE_VALUE(
852 JSReceiver::SetProperty(global,
854 Handle<Object>(global->builtins(), isolate_),
859 // Compile the JavaScript for the debugger in the debugger context.
860 debugger->set_compiling_natives(true);
861 bool caught_exception =
862 !CompileDebuggerScript(isolate_, Natives::GetIndex("mirror")) ||
863 !CompileDebuggerScript(isolate_, Natives::GetIndex("debug"));
865 if (FLAG_enable_liveedit) {
866 caught_exception = caught_exception ||
867 !CompileDebuggerScript(isolate_, Natives::GetIndex("liveedit"));
870 debugger->set_compiling_natives(false);
872 // Make sure we mark the debugger as not loading before we might
874 debugger->set_loading_debugger(false);
876 // Check for caught exceptions.
877 if (caught_exception) return false;
879 // Debugger loaded, create debugger context global handle.
880 debug_context_ = Handle<Context>::cast(
881 isolate_->global_handles()->Create(*context));
887 void Debug::Unload() {
888 // Return debugger is not loaded.
893 // Clear the script cache.
894 DestroyScriptCache();
896 // Clear debugger context global handle.
897 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
898 debug_context_ = Handle<Context>();
902 // Set the flag indicating that preemption happened during debugging.
903 void Debug::PreemptionWhileInDebugger() {
904 ASSERT(InDebugger());
905 Debug::set_interrupts_pending(PREEMPT);
909 void Debug::Iterate(ObjectVisitor* v) {
910 v->VisitPointer(BitCast<Object**>(&(debug_break_return_)));
911 v->VisitPointer(BitCast<Object**>(&(debug_break_slot_)));
915 Object* Debug::Break(Arguments args) {
916 Heap* heap = isolate_->heap();
917 HandleScope scope(isolate_);
918 ASSERT(args.length() == 0);
920 thread_local_.frame_drop_mode_ = FRAMES_UNTOUCHED;
922 // Get the top-most JavaScript frame.
923 JavaScriptFrameIterator it(isolate_);
924 JavaScriptFrame* frame = it.frame();
926 // Just continue if breaks are disabled or debugger cannot be loaded.
927 if (disable_break() || !Load()) {
928 SetAfterBreakTarget(frame);
929 return heap->undefined_value();
932 // Enter the debugger.
933 EnterDebugger debugger(isolate_);
934 if (debugger.FailedToEnter()) {
935 return heap->undefined_value();
938 // Postpone interrupt during breakpoint processing.
939 PostponeInterruptsScope postpone(isolate_);
941 // Get the debug info (create it if it does not exist).
942 Handle<SharedFunctionInfo> shared =
943 Handle<SharedFunctionInfo>(frame->function()->shared());
944 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
946 // Find the break point where execution has stopped.
947 BreakLocationIterator break_location_iterator(debug_info,
948 ALL_BREAK_LOCATIONS);
949 // pc points to the instruction after the current one, possibly a break
950 // location as well. So the "- 1" to exclude it from the search.
951 break_location_iterator.FindBreakLocationFromAddress(frame->pc() - 1);
953 // Check whether step next reached a new statement.
954 if (!StepNextContinue(&break_location_iterator, frame)) {
955 // Decrease steps left if performing multiple steps.
956 if (thread_local_.step_count_ > 0) {
957 thread_local_.step_count_--;
961 // If there is one or more real break points check whether any of these are
963 Handle<Object> break_points_hit(heap->undefined_value(), isolate_);
964 if (break_location_iterator.HasBreakPoint()) {
965 Handle<Object> break_point_objects =
966 Handle<Object>(break_location_iterator.BreakPointObjects(), isolate_);
967 break_points_hit = CheckBreakPoints(break_point_objects);
970 // If step out is active skip everything until the frame where we need to step
971 // out to is reached, unless real breakpoint is hit.
972 if (StepOutActive() && frame->fp() != step_out_fp() &&
973 break_points_hit->IsUndefined() ) {
974 // Step count should always be 0 for StepOut.
975 ASSERT(thread_local_.step_count_ == 0);
976 } else if (!break_points_hit->IsUndefined() ||
977 (thread_local_.last_step_action_ != StepNone &&
978 thread_local_.step_count_ == 0)) {
979 // Notify debugger if a real break point is triggered or if performing
980 // single stepping with no more steps to perform. Otherwise do another step.
982 // Clear all current stepping setup.
985 if (thread_local_.queued_step_count_ > 0) {
986 // Perform queued steps
987 int step_count = thread_local_.queued_step_count_;
990 thread_local_.queued_step_count_ = 0;
992 PrepareStep(StepNext, step_count, StackFrame::NO_ID);
994 // Notify the debug event listeners.
995 isolate_->debugger()->OnDebugBreak(break_points_hit, false);
997 } else if (thread_local_.last_step_action_ != StepNone) {
998 // Hold on to last step action as it is cleared by the call to
1000 StepAction step_action = thread_local_.last_step_action_;
1001 int step_count = thread_local_.step_count_;
1003 // If StepNext goes deeper in code, StepOut until original frame
1004 // and keep step count queued up in the meantime.
1005 if (step_action == StepNext && frame->fp() < thread_local_.last_fp_) {
1006 // Count frames until target frame
1008 JavaScriptFrameIterator it(isolate_);
1009 while (!it.done() && it.frame()->fp() < thread_local_.last_fp_) {
1014 // Check that we indeed found the frame we are looking for.
1015 CHECK(!it.done() && (it.frame()->fp() == thread_local_.last_fp_));
1016 if (step_count > 1) {
1017 // Save old count and action to continue stepping after StepOut.
1018 thread_local_.queued_step_count_ = step_count - 1;
1021 // Set up for StepOut to reach target frame.
1022 step_action = StepOut;
1026 // Clear all current stepping setup.
1029 // Set up for the remaining steps.
1030 PrepareStep(step_action, step_count, StackFrame::NO_ID);
1033 if (thread_local_.frame_drop_mode_ == FRAMES_UNTOUCHED) {
1034 SetAfterBreakTarget(frame);
1035 } else if (thread_local_.frame_drop_mode_ ==
1036 FRAME_DROPPED_IN_IC_CALL) {
1037 // We must have been calling IC stub. Do not go there anymore.
1038 Code* plain_return = isolate_->builtins()->builtin(
1039 Builtins::kPlainReturn_LiveEdit);
1040 thread_local_.after_break_target_ = plain_return->entry();
1041 } else if (thread_local_.frame_drop_mode_ ==
1042 FRAME_DROPPED_IN_DEBUG_SLOT_CALL) {
1043 // Debug break slot stub does not return normally, instead it manually
1044 // cleans the stack and jumps. We should patch the jump address.
1045 Code* plain_return = isolate_->builtins()->builtin(
1046 Builtins::kFrameDropper_LiveEdit);
1047 thread_local_.after_break_target_ = plain_return->entry();
1048 } else if (thread_local_.frame_drop_mode_ ==
1049 FRAME_DROPPED_IN_DIRECT_CALL) {
1050 // Nothing to do, after_break_target is not used here.
1051 } else if (thread_local_.frame_drop_mode_ ==
1052 FRAME_DROPPED_IN_RETURN_CALL) {
1053 Code* plain_return = isolate_->builtins()->builtin(
1054 Builtins::kFrameDropper_LiveEdit);
1055 thread_local_.after_break_target_ = plain_return->entry();
1060 return heap->undefined_value();
1064 RUNTIME_FUNCTION(Object*, Debug_Break) {
1065 return isolate->debug()->Break(args);
1069 // Check the break point objects for whether one or more are actually
1070 // triggered. This function returns a JSArray with the break point objects
1071 // which is triggered.
1072 Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
1073 Factory* factory = isolate_->factory();
1075 // Count the number of break points hit. If there are multiple break points
1076 // they are in a FixedArray.
1077 Handle<FixedArray> break_points_hit;
1078 int break_points_hit_count = 0;
1079 ASSERT(!break_point_objects->IsUndefined());
1080 if (break_point_objects->IsFixedArray()) {
1081 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
1082 break_points_hit = factory->NewFixedArray(array->length());
1083 for (int i = 0; i < array->length(); i++) {
1084 Handle<Object> o(array->get(i), isolate_);
1085 if (CheckBreakPoint(o)) {
1086 break_points_hit->set(break_points_hit_count++, *o);
1090 break_points_hit = factory->NewFixedArray(1);
1091 if (CheckBreakPoint(break_point_objects)) {
1092 break_points_hit->set(break_points_hit_count++, *break_point_objects);
1096 // Return undefined if no break points were triggered.
1097 if (break_points_hit_count == 0) {
1098 return factory->undefined_value();
1100 // Return break points hit as a JSArray.
1101 Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit);
1102 result->set_length(Smi::FromInt(break_points_hit_count));
1107 // Check whether a single break point object is triggered.
1108 bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
1109 Factory* factory = isolate_->factory();
1110 HandleScope scope(isolate_);
1112 // Ignore check if break point object is not a JSObject.
1113 if (!break_point_object->IsJSObject()) return true;
1115 // Get the function IsBreakPointTriggered (defined in debug-debugger.js).
1116 Handle<String> is_break_point_triggered_string =
1117 factory->InternalizeOneByteString(
1118 STATIC_ASCII_VECTOR("IsBreakPointTriggered"));
1119 Handle<JSFunction> check_break_point =
1120 Handle<JSFunction>(JSFunction::cast(
1121 debug_context()->global_object()->GetPropertyNoExceptionThrown(
1122 *is_break_point_triggered_string)));
1124 // Get the break id as an object.
1125 Handle<Object> break_id = factory->NewNumberFromInt(Debug::break_id());
1127 // Call HandleBreakPointx.
1128 bool caught_exception;
1129 Handle<Object> argv[] = { break_id, break_point_object };
1130 Handle<Object> result = Execution::TryCall(check_break_point,
1131 isolate_->js_builtins_object(),
1136 // If exception or non boolean result handle as not triggered
1137 if (caught_exception || !result->IsBoolean()) {
1141 // Return whether the break point is triggered.
1142 ASSERT(!result.is_null());
1143 return (*result)->IsTrue();
1147 // Check whether the function has debug information.
1148 bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
1149 return !shared->debug_info()->IsUndefined();
1153 // Return the debug info for this function. EnsureDebugInfo must be called
1154 // prior to ensure the debug info has been generated for shared.
1155 Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
1156 ASSERT(HasDebugInfo(shared));
1157 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
1161 void Debug::SetBreakPoint(Handle<JSFunction> function,
1162 Handle<Object> break_point_object,
1163 int* source_position) {
1164 HandleScope scope(isolate_);
1166 PrepareForBreakPoints();
1168 // Make sure the function is compiled and has set up the debug info.
1169 Handle<SharedFunctionInfo> shared(function->shared());
1170 if (!EnsureDebugInfo(shared, function)) {
1171 // Return if retrieving debug info failed.
1175 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1176 // Source positions starts with zero.
1177 ASSERT(*source_position >= 0);
1179 // Find the break point and change it.
1180 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1181 it.FindBreakLocationFromPosition(*source_position, STATEMENT_ALIGNED);
1182 it.SetBreakPoint(break_point_object);
1184 *source_position = it.position();
1186 // At least one active break point now.
1187 ASSERT(debug_info->GetBreakPointCount() > 0);
1191 bool Debug::SetBreakPointForScript(Handle<Script> script,
1192 Handle<Object> break_point_object,
1193 int* source_position,
1194 BreakPositionAlignment alignment) {
1195 HandleScope scope(isolate_);
1197 PrepareForBreakPoints();
1199 // Obtain shared function info for the function.
1200 Object* result = FindSharedFunctionInfoInScript(script, *source_position);
1201 if (result->IsUndefined()) return false;
1203 // Make sure the function has set up the debug info.
1204 Handle<SharedFunctionInfo> shared(SharedFunctionInfo::cast(result));
1205 if (!EnsureDebugInfo(shared, Handle<JSFunction>::null())) {
1206 // Return if retrieving debug info failed.
1210 // Find position within function. The script position might be before the
1211 // source position of the first function.
1213 if (shared->start_position() > *source_position) {
1216 position = *source_position - shared->start_position();
1219 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1220 // Source positions starts with zero.
1221 ASSERT(position >= 0);
1223 // Find the break point and change it.
1224 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1225 it.FindBreakLocationFromPosition(position, alignment);
1226 it.SetBreakPoint(break_point_object);
1228 *source_position = it.position() + shared->start_position();
1230 // At least one active break point now.
1231 ASSERT(debug_info->GetBreakPointCount() > 0);
1236 void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
1237 HandleScope scope(isolate_);
1239 DebugInfoListNode* node = debug_info_list_;
1240 while (node != NULL) {
1241 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1242 break_point_object);
1243 if (!result->IsUndefined()) {
1244 // Get information in the break point.
1245 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1246 Handle<DebugInfo> debug_info = node->debug_info();
1248 // Find the break point and clear it.
1249 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1250 it.FindBreakLocationFromAddress(debug_info->code()->entry() +
1251 break_point_info->code_position()->value());
1252 it.ClearBreakPoint(break_point_object);
1254 // If there are no more break points left remove the debug info for this
1256 if (debug_info->GetBreakPointCount() == 0) {
1257 RemoveDebugInfo(debug_info);
1262 node = node->next();
1267 void Debug::ClearAllBreakPoints() {
1268 DebugInfoListNode* node = debug_info_list_;
1269 while (node != NULL) {
1270 // Remove all debug break code.
1271 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1272 it.ClearAllDebugBreak();
1273 node = node->next();
1276 // Remove all debug info.
1277 while (debug_info_list_ != NULL) {
1278 RemoveDebugInfo(debug_info_list_->debug_info());
1283 void Debug::FloodWithOneShot(Handle<JSFunction> function) {
1284 PrepareForBreakPoints();
1286 // Make sure the function is compiled and has set up the debug info.
1287 Handle<SharedFunctionInfo> shared(function->shared());
1288 if (!EnsureDebugInfo(shared, function)) {
1289 // Return if we failed to retrieve the debug info.
1293 // Flood the function with break points.
1294 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
1295 while (!it.Done()) {
1302 void Debug::FloodBoundFunctionWithOneShot(Handle<JSFunction> function) {
1303 Handle<FixedArray> new_bindings(function->function_bindings());
1304 Handle<Object> bindee(new_bindings->get(JSFunction::kBoundFunctionIndex),
1307 if (!bindee.is_null() && bindee->IsJSFunction() &&
1308 !JSFunction::cast(*bindee)->IsBuiltin()) {
1309 Handle<JSFunction> bindee_function(JSFunction::cast(*bindee));
1310 Debug::FloodWithOneShot(bindee_function);
1315 void Debug::FloodHandlerWithOneShot() {
1316 // Iterate through the JavaScript stack looking for handlers.
1317 StackFrame::Id id = break_frame_id();
1318 if (id == StackFrame::NO_ID) {
1319 // If there is no JavaScript stack don't do anything.
1322 for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) {
1323 JavaScriptFrame* frame = it.frame();
1324 if (frame->HasHandler()) {
1325 // Flood the function with the catch block with break points
1326 FloodWithOneShot(Handle<JSFunction>(frame->function()));
1333 void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1334 if (type == BreakUncaughtException) {
1335 break_on_uncaught_exception_ = enable;
1337 break_on_exception_ = enable;
1342 bool Debug::IsBreakOnException(ExceptionBreakType type) {
1343 if (type == BreakUncaughtException) {
1344 return break_on_uncaught_exception_;
1346 return break_on_exception_;
1351 void Debug::PrepareStep(StepAction step_action,
1353 StackFrame::Id frame_id) {
1354 HandleScope scope(isolate_);
1356 PrepareForBreakPoints();
1358 ASSERT(Debug::InDebugger());
1360 // Remember this step action and count.
1361 thread_local_.last_step_action_ = step_action;
1362 if (step_action == StepOut) {
1363 // For step out target frame will be found on the stack so there is no need
1364 // to set step counter for it. It's expected to always be 0 for StepOut.
1365 thread_local_.step_count_ = 0;
1367 thread_local_.step_count_ = step_count;
1370 // Get the frame where the execution has stopped and skip the debug frame if
1371 // any. The debug frame will only be present if execution was stopped due to
1372 // hitting a break point. In other situations (e.g. unhandled exception) the
1373 // debug frame is not present.
1374 StackFrame::Id id = break_frame_id();
1375 if (id == StackFrame::NO_ID) {
1376 // If there is no JavaScript stack don't do anything.
1379 if (frame_id != StackFrame::NO_ID) {
1382 JavaScriptFrameIterator frames_it(isolate_, id);
1383 JavaScriptFrame* frame = frames_it.frame();
1385 // First of all ensure there is one-shot break points in the top handler
1387 FloodHandlerWithOneShot();
1389 // If the function on the top frame is unresolved perform step out. This will
1390 // be the case when calling unknown functions and having the debugger stopped
1391 // in an unhandled exception.
1392 if (!frame->function()->IsJSFunction()) {
1393 // Step out: Find the calling JavaScript frame and flood it with
1395 frames_it.Advance();
1396 // Fill the function to return to with one-shot break points.
1397 JSFunction* function = frames_it.frame()->function();
1398 FloodWithOneShot(Handle<JSFunction>(function));
1402 // Get the debug info (create it if it does not exist).
1403 Handle<JSFunction> function(frame->function());
1404 Handle<SharedFunctionInfo> shared(function->shared());
1405 if (!EnsureDebugInfo(shared, function)) {
1406 // Return if ensuring debug info failed.
1409 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1411 // Find the break location where execution has stopped.
1412 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1413 // pc points to the instruction after the current one, possibly a break
1414 // location as well. So the "- 1" to exclude it from the search.
1415 it.FindBreakLocationFromAddress(frame->pc() - 1);
1417 // Compute whether or not the target is a call target.
1418 bool is_load_or_store = false;
1419 bool is_inline_cache_stub = false;
1420 bool is_at_restarted_function = false;
1421 Handle<Code> call_function_stub;
1423 if (thread_local_.restarter_frame_function_pointer_ == NULL) {
1424 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
1425 bool is_call_target = false;
1426 Address target = it.rinfo()->target_address();
1427 Code* code = Code::GetCodeFromTargetAddress(target);
1428 if (code->is_inline_cache_stub()) {
1429 is_inline_cache_stub = true;
1430 is_load_or_store = !is_call_target;
1433 // Check if target code is CallFunction stub.
1434 Code* maybe_call_function_stub = code;
1435 // If there is a breakpoint at this line look at the original code to
1436 // check if it is a CallFunction stub.
1437 if (it.IsDebugBreak()) {
1438 Address original_target = it.original_rinfo()->target_address();
1439 maybe_call_function_stub =
1440 Code::GetCodeFromTargetAddress(original_target);
1442 if (maybe_call_function_stub->kind() == Code::STUB &&
1443 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1444 // Save reference to the code as we may need it to find out arguments
1445 // count for 'step in' later.
1446 call_function_stub = Handle<Code>(maybe_call_function_stub);
1450 is_at_restarted_function = true;
1453 // If this is the last break code target step out is the only possibility.
1454 if (it.IsExit() || step_action == StepOut) {
1455 if (step_action == StepOut) {
1456 // Skip step_count frames starting with the current one.
1457 while (step_count-- > 0 && !frames_it.done()) {
1458 frames_it.Advance();
1461 ASSERT(it.IsExit());
1462 frames_it.Advance();
1464 // Skip builtin functions on the stack.
1465 while (!frames_it.done() && frames_it.frame()->function()->IsBuiltin()) {
1466 frames_it.Advance();
1468 // Step out: If there is a JavaScript caller frame, we need to
1469 // flood it with breakpoints.
1470 if (!frames_it.done()) {
1471 // Fill the function to return to with one-shot break points.
1472 JSFunction* function = frames_it.frame()->function();
1473 FloodWithOneShot(Handle<JSFunction>(function));
1474 // Set target frame pointer.
1475 ActivateStepOut(frames_it.frame());
1477 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1478 !call_function_stub.is_null() || is_at_restarted_function)
1479 || step_action == StepNext || step_action == StepMin) {
1480 // Step next or step min.
1482 // Fill the current function with one-shot break points.
1483 FloodWithOneShot(function);
1485 // Remember source position and frame to handle step next.
1486 thread_local_.last_statement_position_ =
1487 debug_info->code()->SourceStatementPosition(frame->pc());
1488 thread_local_.last_fp_ = frame->UnpaddedFP();
1490 // If there's restarter frame on top of the stack, just get the pointer
1491 // to function which is going to be restarted.
1492 if (is_at_restarted_function) {
1493 Handle<JSFunction> restarted_function(
1494 JSFunction::cast(*thread_local_.restarter_frame_function_pointer_));
1495 FloodWithOneShot(restarted_function);
1496 } else if (!call_function_stub.is_null()) {
1497 // If it's CallFunction stub ensure target function is compiled and flood
1498 // it with one shot breakpoints.
1500 // Find out number of arguments from the stub minor key.
1501 // Reverse lookup required as the minor key cannot be retrieved
1502 // from the code object.
1504 isolate_->heap()->code_stubs()->SlowReverseLookup(
1505 *call_function_stub),
1507 ASSERT(!obj.is_null());
1508 ASSERT(!(*obj)->IsUndefined());
1509 ASSERT(obj->IsSmi());
1510 // Get the STUB key and extract major and minor key.
1511 uint32_t key = Smi::cast(*obj)->value();
1512 // Argc in the stub is the number of arguments passed - not the
1513 // expected arguments of the called function.
1514 int call_function_arg_count =
1515 CallFunctionStub::ExtractArgcFromMinorKey(
1516 CodeStub::MinorKeyFromKey(key));
1517 ASSERT(call_function_stub->major_key() ==
1518 CodeStub::MajorKeyFromKey(key));
1520 // Find target function on the expression stack.
1521 // Expression stack looks like this (top to bottom):
1527 int expressions_count = frame->ComputeExpressionsCount();
1528 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1529 Object* fun = frame->GetExpression(
1530 expressions_count - 2 - call_function_arg_count);
1532 // Flood the actual target of call/apply.
1533 if (fun->IsJSFunction()) {
1534 Isolate* isolate = JSFunction::cast(fun)->GetIsolate();
1535 Code* apply = isolate->builtins()->builtin(Builtins::kFunctionApply);
1536 Code* call = isolate->builtins()->builtin(Builtins::kFunctionCall);
1537 while (fun->IsJSFunction()) {
1538 Code* code = JSFunction::cast(fun)->shared()->code();
1539 if (code != apply && code != call) break;
1540 fun = frame->GetExpression(
1541 expressions_count - 1 - call_function_arg_count);
1545 if (fun->IsJSFunction()) {
1546 Handle<JSFunction> js_function(JSFunction::cast(fun));
1547 if (js_function->shared()->bound()) {
1548 Debug::FloodBoundFunctionWithOneShot(js_function);
1549 } else if (!js_function->IsBuiltin()) {
1550 // Don't step into builtins.
1551 // It will also compile target function if it's not compiled yet.
1552 FloodWithOneShot(js_function);
1557 // Fill the current function with one-shot break points even for step in on
1558 // a call target as the function called might be a native function for
1559 // which step in will not stop. It also prepares for stepping in
1561 FloodWithOneShot(function);
1563 if (is_load_or_store) {
1564 // Remember source position and frame to handle step in getter/setter. If
1565 // there is a custom getter/setter it will be handled in
1566 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1567 // propagated on the next Debug::Break.
1568 thread_local_.last_statement_position_ =
1569 debug_info->code()->SourceStatementPosition(frame->pc());
1570 thread_local_.last_fp_ = frame->UnpaddedFP();
1573 // Step in or Step in min
1574 it.PrepareStepIn(isolate_);
1575 ActivateStepIn(frame);
1580 // Check whether the current debug break should be reported to the debugger. It
1581 // is used to have step next and step in only report break back to the debugger
1582 // if on a different frame or in a different statement. In some situations
1583 // there will be several break points in the same statement when the code is
1584 // flooded with one-shot break points. This function helps to perform several
1585 // steps before reporting break back to the debugger.
1586 bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1587 JavaScriptFrame* frame) {
1588 // StepNext and StepOut shouldn't bring us deeper in code, so last frame
1589 // shouldn't be a parent of current frame.
1590 if (thread_local_.last_step_action_ == StepNext ||
1591 thread_local_.last_step_action_ == StepOut) {
1592 if (frame->fp() < thread_local_.last_fp_) return true;
1595 // If the step last action was step next or step in make sure that a new
1596 // statement is hit.
1597 if (thread_local_.last_step_action_ == StepNext ||
1598 thread_local_.last_step_action_ == StepIn) {
1599 // Never continue if returning from function.
1600 if (break_location_iterator->IsExit()) return false;
1602 // Continue if we are still on the same frame and in the same statement.
1603 int current_statement_position =
1604 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1605 return thread_local_.last_fp_ == frame->UnpaddedFP() &&
1606 thread_local_.last_statement_position_ == current_statement_position;
1609 // No step next action - don't continue.
1614 // Check whether the code object at the specified address is a debug break code
1616 bool Debug::IsDebugBreak(Address addr) {
1617 Code* code = Code::GetCodeFromTargetAddress(addr);
1618 return code->is_debug_stub() && code->extra_ic_state() == DEBUG_BREAK;
1622 // Check whether a code stub with the specified major key is a possible break
1623 // point location when looking for source break locations.
1624 bool Debug::IsSourceBreakStub(Code* code) {
1625 CodeStub::Major major_key = CodeStub::GetMajorKey(code);
1626 return major_key == CodeStub::CallFunction;
1630 // Check whether a code stub with the specified major key is a possible break
1632 bool Debug::IsBreakStub(Code* code) {
1633 CodeStub::Major major_key = CodeStub::GetMajorKey(code);
1634 return major_key == CodeStub::CallFunction;
1638 // Find the builtin to use for invoking the debug break
1639 Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
1640 Isolate* isolate = code->GetIsolate();
1642 // Find the builtin debug break function matching the calling convention
1643 // used by the call site.
1644 if (code->is_inline_cache_stub()) {
1645 switch (code->kind()) {
1647 return isolate->builtins()->LoadIC_DebugBreak();
1649 case Code::STORE_IC:
1650 return isolate->builtins()->StoreIC_DebugBreak();
1652 case Code::KEYED_LOAD_IC:
1653 return isolate->builtins()->KeyedLoadIC_DebugBreak();
1655 case Code::KEYED_STORE_IC:
1656 return isolate->builtins()->KeyedStoreIC_DebugBreak();
1658 case Code::COMPARE_NIL_IC:
1659 return isolate->builtins()->CompareNilIC_DebugBreak();
1665 if (RelocInfo::IsConstructCall(mode)) {
1666 if (code->has_function_cache()) {
1667 return isolate->builtins()->CallConstructStub_Recording_DebugBreak();
1669 return isolate->builtins()->CallConstructStub_DebugBreak();
1672 if (code->kind() == Code::STUB) {
1673 ASSERT(code->major_key() == CodeStub::CallFunction);
1674 if (code->has_function_cache()) {
1675 return isolate->builtins()->CallFunctionStub_Recording_DebugBreak();
1677 return isolate->builtins()->CallFunctionStub_DebugBreak();
1682 return Handle<Code>::null();
1686 // Simple function for returning the source positions for active break points.
1687 Handle<Object> Debug::GetSourceBreakLocations(
1688 Handle<SharedFunctionInfo> shared,
1689 BreakPositionAlignment position_alignment) {
1690 Isolate* isolate = shared->GetIsolate();
1691 Heap* heap = isolate->heap();
1692 if (!HasDebugInfo(shared)) {
1693 return Handle<Object>(heap->undefined_value(), isolate);
1695 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1696 if (debug_info->GetBreakPointCount() == 0) {
1697 return Handle<Object>(heap->undefined_value(), isolate);
1699 Handle<FixedArray> locations =
1700 isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount());
1702 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1703 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1704 BreakPointInfo* break_point_info =
1705 BreakPointInfo::cast(debug_info->break_points()->get(i));
1706 if (break_point_info->GetBreakPointCount() > 0) {
1708 switch (position_alignment) {
1709 case STATEMENT_ALIGNED:
1710 position = break_point_info->statement_position();
1712 case BREAK_POSITION_ALIGNED:
1713 position = break_point_info->source_position();
1717 position = break_point_info->statement_position();
1720 locations->set(count++, position);
1728 void Debug::NewBreak(StackFrame::Id break_frame_id) {
1729 thread_local_.break_frame_id_ = break_frame_id;
1730 thread_local_.break_id_ = ++thread_local_.break_count_;
1734 void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1735 thread_local_.break_frame_id_ = break_frame_id;
1736 thread_local_.break_id_ = break_id;
1740 // Handle stepping into a function.
1741 void Debug::HandleStepIn(Handle<JSFunction> function,
1742 Handle<Object> holder,
1744 bool is_constructor) {
1745 Isolate* isolate = function->GetIsolate();
1746 // If the frame pointer is not supplied by the caller find it.
1748 StackFrameIterator it(isolate);
1750 // For constructor functions skip another frame.
1751 if (is_constructor) {
1752 ASSERT(it.frame()->is_construct());
1755 fp = it.frame()->fp();
1758 // Flood the function with one-shot break points if it is called from where
1759 // step into was requested.
1760 if (fp == step_in_fp()) {
1761 if (function->shared()->bound()) {
1762 // Handle Function.prototype.bind
1763 Debug::FloodBoundFunctionWithOneShot(function);
1764 } else if (!function->IsBuiltin()) {
1765 // Don't allow step into functions in the native context.
1766 if (function->shared()->code() ==
1767 isolate->builtins()->builtin(Builtins::kFunctionApply) ||
1768 function->shared()->code() ==
1769 isolate->builtins()->builtin(Builtins::kFunctionCall)) {
1770 // Handle function.apply and function.call separately to flood the
1771 // function to be called and not the code for Builtins::FunctionApply or
1772 // Builtins::FunctionCall. The receiver of call/apply is the target
1774 if (!holder.is_null() && holder->IsJSFunction()) {
1775 Handle<JSFunction> js_function = Handle<JSFunction>::cast(holder);
1776 if (!js_function->IsBuiltin()) {
1777 Debug::FloodWithOneShot(js_function);
1778 } else if (js_function->shared()->bound()) {
1779 // Handle Function.prototype.bind
1780 Debug::FloodBoundFunctionWithOneShot(js_function);
1784 Debug::FloodWithOneShot(function);
1791 void Debug::ClearStepping() {
1792 // Clear the various stepping setup.
1798 // Clear multiple step counter.
1799 thread_local_.step_count_ = 0;
1803 // Clears all the one-shot break points that are currently set. Normally this
1804 // function is called each time a break point is hit as one shot break points
1805 // are used to support stepping.
1806 void Debug::ClearOneShot() {
1807 // The current implementation just runs through all the breakpoints. When the
1808 // last break point for a function is removed that function is automatically
1809 // removed from the list.
1811 DebugInfoListNode* node = debug_info_list_;
1812 while (node != NULL) {
1813 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1814 while (!it.Done()) {
1818 node = node->next();
1823 void Debug::ActivateStepIn(StackFrame* frame) {
1824 ASSERT(!StepOutActive());
1825 thread_local_.step_into_fp_ = frame->UnpaddedFP();
1829 void Debug::ClearStepIn() {
1830 thread_local_.step_into_fp_ = 0;
1834 void Debug::ActivateStepOut(StackFrame* frame) {
1835 ASSERT(!StepInActive());
1836 thread_local_.step_out_fp_ = frame->UnpaddedFP();
1840 void Debug::ClearStepOut() {
1841 thread_local_.step_out_fp_ = 0;
1845 void Debug::ClearStepNext() {
1846 thread_local_.last_step_action_ = StepNone;
1847 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
1848 thread_local_.last_fp_ = 0;
1852 static void CollectActiveFunctionsFromThread(
1854 ThreadLocalTop* top,
1855 List<Handle<JSFunction> >* active_functions,
1856 Object* active_code_marker) {
1857 // Find all non-optimized code functions with activation frames
1858 // on the stack. This includes functions which have optimized
1859 // activations (including inlined functions) on the stack as the
1860 // non-optimized code is needed for the lazy deoptimization.
1861 for (JavaScriptFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1862 JavaScriptFrame* frame = it.frame();
1863 if (frame->is_optimized()) {
1864 List<JSFunction*> functions(FLAG_max_inlining_levels + 1);
1865 frame->GetFunctions(&functions);
1866 for (int i = 0; i < functions.length(); i++) {
1867 JSFunction* function = functions[i];
1868 active_functions->Add(Handle<JSFunction>(function));
1869 function->shared()->code()->set_gc_metadata(active_code_marker);
1871 } else if (frame->function()->IsJSFunction()) {
1872 JSFunction* function = frame->function();
1873 ASSERT(frame->LookupCode()->kind() == Code::FUNCTION);
1874 active_functions->Add(Handle<JSFunction>(function));
1875 function->shared()->code()->set_gc_metadata(active_code_marker);
1881 static void RedirectActivationsToRecompiledCodeOnThread(
1883 ThreadLocalTop* top) {
1884 for (JavaScriptFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1885 JavaScriptFrame* frame = it.frame();
1887 if (frame->is_optimized() || !frame->function()->IsJSFunction()) continue;
1889 JSFunction* function = frame->function();
1891 ASSERT(frame->LookupCode()->kind() == Code::FUNCTION);
1893 Handle<Code> frame_code(frame->LookupCode());
1894 if (frame_code->has_debug_break_slots()) continue;
1896 Handle<Code> new_code(function->shared()->code());
1897 if (new_code->kind() != Code::FUNCTION ||
1898 !new_code->has_debug_break_slots()) {
1902 // Iterate over the RelocInfo in the original code to compute the sum of the
1903 // constant pools and veneer pools sizes. (See Assembler::CheckConstPool()
1904 // and Assembler::CheckVeneerPool())
1905 // Note that this is only useful for architectures using constant pools or
1907 int pool_mask = RelocInfo::ModeMask(RelocInfo::CONST_POOL) |
1908 RelocInfo::ModeMask(RelocInfo::VENEER_POOL);
1909 int frame_pool_size = 0;
1910 for (RelocIterator it(*frame_code, pool_mask); !it.done(); it.next()) {
1911 RelocInfo* info = it.rinfo();
1912 if (info->pc() >= frame->pc()) break;
1913 frame_pool_size += static_cast<int>(info->data());
1915 intptr_t frame_offset =
1916 frame->pc() - frame_code->instruction_start() - frame_pool_size;
1918 // Iterate over the RelocInfo for new code to find the number of bytes
1919 // generated for debug slots and constant pools.
1920 int debug_break_slot_bytes = 0;
1921 int new_code_pool_size = 0;
1922 int mask = RelocInfo::ModeMask(RelocInfo::DEBUG_BREAK_SLOT) |
1923 RelocInfo::ModeMask(RelocInfo::CONST_POOL) |
1924 RelocInfo::ModeMask(RelocInfo::VENEER_POOL);
1925 for (RelocIterator it(*new_code, mask); !it.done(); it.next()) {
1926 // Check if the pc in the new code with debug break
1927 // slots is before this slot.
1928 RelocInfo* info = it.rinfo();
1929 intptr_t new_offset = info->pc() - new_code->instruction_start() -
1930 new_code_pool_size - debug_break_slot_bytes;
1931 if (new_offset >= frame_offset) {
1935 if (RelocInfo::IsDebugBreakSlot(info->rmode())) {
1936 debug_break_slot_bytes += Assembler::kDebugBreakSlotLength;
1938 ASSERT(RelocInfo::IsConstPool(info->rmode()));
1939 // The size of the pools is encoded in the data.
1940 new_code_pool_size += static_cast<int>(info->data());
1944 // Compute the equivalent pc in the new code.
1945 byte* new_pc = new_code->instruction_start() + frame_offset +
1946 debug_break_slot_bytes + new_code_pool_size;
1948 if (FLAG_trace_deopt) {
1949 PrintF("Replacing code %08" V8PRIxPTR " - %08" V8PRIxPTR " (%d) "
1950 "with %08" V8PRIxPTR " - %08" V8PRIxPTR " (%d) "
1952 "changing pc from %08" V8PRIxPTR " to %08" V8PRIxPTR "\n",
1953 reinterpret_cast<intptr_t>(
1954 frame_code->instruction_start()),
1955 reinterpret_cast<intptr_t>(
1956 frame_code->instruction_start()) +
1957 frame_code->instruction_size(),
1958 frame_code->instruction_size(),
1959 reinterpret_cast<intptr_t>(new_code->instruction_start()),
1960 reinterpret_cast<intptr_t>(new_code->instruction_start()) +
1961 new_code->instruction_size(),
1962 new_code->instruction_size(),
1963 reinterpret_cast<intptr_t>(frame->pc()),
1964 reinterpret_cast<intptr_t>(new_pc));
1967 // Patch the return address to return into the code with
1968 // debug break slots.
1969 frame->set_pc(new_pc);
1974 class ActiveFunctionsCollector : public ThreadVisitor {
1976 explicit ActiveFunctionsCollector(List<Handle<JSFunction> >* active_functions,
1977 Object* active_code_marker)
1978 : active_functions_(active_functions),
1979 active_code_marker_(active_code_marker) { }
1981 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1982 CollectActiveFunctionsFromThread(isolate,
1985 active_code_marker_);
1989 List<Handle<JSFunction> >* active_functions_;
1990 Object* active_code_marker_;
1994 class ActiveFunctionsRedirector : public ThreadVisitor {
1996 void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1997 RedirectActivationsToRecompiledCodeOnThread(isolate, top);
2002 void Debug::PrepareForBreakPoints() {
2003 // If preparing for the first break point make sure to deoptimize all
2004 // functions as debugging does not work with optimized code.
2005 if (!has_break_points_) {
2006 if (isolate_->concurrent_recompilation_enabled()) {
2007 isolate_->optimizing_compiler_thread()->Flush();
2010 Deoptimizer::DeoptimizeAll(isolate_);
2012 Handle<Code> lazy_compile = isolate_->builtins()->CompileUnoptimized();
2014 // There will be at least one break point when we are done.
2015 has_break_points_ = true;
2017 // Keep the list of activated functions in a handlified list as it
2018 // is used both in GC and non-GC code.
2019 List<Handle<JSFunction> > active_functions(100);
2022 // We are going to iterate heap to find all functions without
2023 // debug break slots.
2024 Heap* heap = isolate_->heap();
2025 heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
2026 "preparing for breakpoints");
2028 // Ensure no GC in this scope as we are going to use gc_metadata
2029 // field in the Code object to mark active functions.
2030 DisallowHeapAllocation no_allocation;
2032 Object* active_code_marker = heap->the_hole_value();
2034 CollectActiveFunctionsFromThread(isolate_,
2035 isolate_->thread_local_top(),
2037 active_code_marker);
2038 ActiveFunctionsCollector active_functions_collector(&active_functions,
2039 active_code_marker);
2040 isolate_->thread_manager()->IterateArchivedThreads(
2041 &active_functions_collector);
2043 // Scan the heap for all non-optimized functions which have no
2044 // debug break slots and are not active or inlined into an active
2045 // function and mark them for lazy compilation.
2046 HeapIterator iterator(heap);
2047 HeapObject* obj = NULL;
2048 while (((obj = iterator.next()) != NULL)) {
2049 if (obj->IsJSFunction()) {
2050 JSFunction* function = JSFunction::cast(obj);
2051 SharedFunctionInfo* shared = function->shared();
2053 if (!shared->allows_lazy_compilation()) continue;
2054 if (!shared->script()->IsScript()) continue;
2055 if (function->IsBuiltin()) continue;
2056 if (shared->code()->gc_metadata() == active_code_marker) continue;
2058 Code::Kind kind = function->code()->kind();
2059 if (kind == Code::FUNCTION &&
2060 !function->code()->has_debug_break_slots()) {
2061 function->set_code(*lazy_compile);
2062 function->shared()->set_code(*lazy_compile);
2063 } else if (kind == Code::BUILTIN &&
2064 (function->IsInOptimizationQueue() ||
2065 function->IsMarkedForOptimization() ||
2066 function->IsMarkedForConcurrentOptimization())) {
2067 // Abort in-flight compilation.
2068 Code* shared_code = function->shared()->code();
2069 if (shared_code->kind() == Code::FUNCTION &&
2070 shared_code->has_debug_break_slots()) {
2071 function->set_code(shared_code);
2073 function->set_code(*lazy_compile);
2074 function->shared()->set_code(*lazy_compile);
2080 // Clear gc_metadata field.
2081 for (int i = 0; i < active_functions.length(); i++) {
2082 Handle<JSFunction> function = active_functions[i];
2083 function->shared()->code()->set_gc_metadata(Smi::FromInt(0));
2087 // Now recompile all functions with activation frames and and
2088 // patch the return address to run in the new compiled code.
2089 for (int i = 0; i < active_functions.length(); i++) {
2090 Handle<JSFunction> function = active_functions[i];
2091 Handle<SharedFunctionInfo> shared(function->shared());
2093 if (function->code()->kind() == Code::FUNCTION &&
2094 function->code()->has_debug_break_slots()) {
2095 // Nothing to do. Function code already had debug break slots.
2099 // If recompilation is not possible just skip it.
2100 if (shared->is_toplevel() ||
2101 !shared->allows_lazy_compilation() ||
2102 shared->code()->kind() == Code::BUILTIN) {
2106 // Make sure that the shared full code is compiled with debug
2108 if (!shared->code()->has_debug_break_slots()) {
2109 // Try to compile the full code with debug break slots. If it
2110 // fails just keep the current code.
2111 bool prev_force_debugger_active =
2112 isolate_->debugger()->force_debugger_active();
2113 isolate_->debugger()->set_force_debugger_active(true);
2114 Handle<Code> code = Compiler::GetCodeForDebugging(function);
2115 function->ReplaceCode(*code);
2116 isolate_->debugger()->set_force_debugger_active(
2117 prev_force_debugger_active);
2120 // Keep function code in sync with shared function info.
2121 function->set_code(shared->code());
2124 RedirectActivationsToRecompiledCodeOnThread(isolate_,
2125 isolate_->thread_local_top());
2127 ActiveFunctionsRedirector active_functions_redirector;
2128 isolate_->thread_manager()->IterateArchivedThreads(
2129 &active_functions_redirector);
2134 Object* Debug::FindSharedFunctionInfoInScript(Handle<Script> script,
2136 // Iterate the heap looking for SharedFunctionInfo generated from the
2137 // script. The inner most SharedFunctionInfo containing the source position
2138 // for the requested break point is found.
2139 // NOTE: This might require several heap iterations. If the SharedFunctionInfo
2140 // which is found is not compiled it is compiled and the heap is iterated
2141 // again as the compilation might create inner functions from the newly
2142 // compiled function and the actual requested break point might be in one of
2144 // NOTE: The below fix-point iteration depends on all functions that cannot be
2145 // compiled lazily without a context to not be compiled at all. Compilation
2146 // will be triggered at points where we do not need a context.
2148 // The current candidate for the source position:
2149 int target_start_position = RelocInfo::kNoPosition;
2150 Handle<JSFunction> target_function;
2151 Handle<SharedFunctionInfo> target;
2152 Heap* heap = isolate_->heap();
2154 { // Extra scope for iterator and no-allocation.
2155 heap->EnsureHeapIsIterable();
2156 DisallowHeapAllocation no_alloc_during_heap_iteration;
2157 HeapIterator iterator(heap);
2158 for (HeapObject* obj = iterator.next();
2159 obj != NULL; obj = iterator.next()) {
2160 bool found_next_candidate = false;
2161 Handle<JSFunction> function;
2162 Handle<SharedFunctionInfo> shared;
2163 if (obj->IsJSFunction()) {
2164 function = Handle<JSFunction>(JSFunction::cast(obj));
2165 shared = Handle<SharedFunctionInfo>(function->shared());
2166 ASSERT(shared->allows_lazy_compilation() || shared->is_compiled());
2167 found_next_candidate = true;
2168 } else if (obj->IsSharedFunctionInfo()) {
2169 shared = Handle<SharedFunctionInfo>(SharedFunctionInfo::cast(obj));
2170 // Skip functions that we cannot compile lazily without a context,
2171 // which is not available here, because there is no closure.
2172 found_next_candidate = shared->is_compiled() ||
2173 shared->allows_lazy_compilation_without_context();
2175 if (!found_next_candidate) continue;
2176 if (shared->script() == *script) {
2177 // If the SharedFunctionInfo found has the requested script data and
2178 // contains the source position it is a candidate.
2179 int start_position = shared->function_token_position();
2180 if (start_position == RelocInfo::kNoPosition) {
2181 start_position = shared->start_position();
2183 if (start_position <= position &&
2184 position <= shared->end_position()) {
2185 // If there is no candidate or this function is within the current
2186 // candidate this is the new candidate.
2187 if (target.is_null()) {
2188 target_start_position = start_position;
2189 target_function = function;
2192 if (target_start_position == start_position &&
2193 shared->end_position() == target->end_position()) {
2194 // If a top-level function contains only one function
2195 // declaration the source for the top-level and the function
2196 // is the same. In that case prefer the non top-level function.
2197 if (!shared->is_toplevel()) {
2198 target_start_position = start_position;
2199 target_function = function;
2202 } else if (target_start_position <= start_position &&
2203 shared->end_position() <= target->end_position()) {
2204 // This containment check includes equality as a function
2205 // inside a top-level function can share either start or end
2206 // position with the top-level function.
2207 target_start_position = start_position;
2208 target_function = function;
2215 } // End no-allocation scope.
2217 if (target.is_null()) return heap->undefined_value();
2219 // There will be at least one break point when we are done.
2220 has_break_points_ = true;
2222 // If the candidate found is compiled we are done.
2223 done = target->is_compiled();
2225 // If the candidate is not compiled, compile it to reveal any inner
2226 // functions which might contain the requested source position. This
2227 // will compile all inner functions that cannot be compiled without a
2228 // context, because Compiler::BuildFunctionInfo checks whether the
2229 // debugger is active.
2230 Handle<Code> result = target_function.is_null()
2231 ? Compiler::GetUnoptimizedCode(target)
2232 : Compiler::GetUnoptimizedCode(target_function);
2233 if (result.is_null()) return isolate_->heap()->undefined_value();
2235 } // End while loop.
2241 // Ensures the debug information is present for shared.
2242 bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared,
2243 Handle<JSFunction> function) {
2244 Isolate* isolate = shared->GetIsolate();
2246 // Return if we already have the debug info for shared.
2247 if (HasDebugInfo(shared)) {
2248 ASSERT(shared->is_compiled());
2252 // There will be at least one break point when we are done.
2253 has_break_points_ = true;
2255 // Ensure function is compiled. Return false if this failed.
2256 if (!function.is_null() &&
2257 !Compiler::EnsureCompiled(function, CLEAR_EXCEPTION)) {
2261 // Create the debug info object.
2262 Handle<DebugInfo> debug_info = isolate->factory()->NewDebugInfo(shared);
2264 // Add debug info to the list.
2265 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
2266 node->set_next(debug_info_list_);
2267 debug_info_list_ = node;
2273 void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
2274 ASSERT(debug_info_list_ != NULL);
2275 // Run through the debug info objects to find this one and remove it.
2276 DebugInfoListNode* prev = NULL;
2277 DebugInfoListNode* current = debug_info_list_;
2278 while (current != NULL) {
2279 if (*current->debug_info() == *debug_info) {
2280 // Unlink from list. If prev is NULL we are looking at the first element.
2282 debug_info_list_ = current->next();
2284 prev->set_next(current->next());
2286 current->debug_info()->shared()->set_debug_info(
2287 isolate_->heap()->undefined_value());
2290 // If there are no more debug info objects there are not more break
2292 has_break_points_ = debug_info_list_ != NULL;
2296 // Move to next in list.
2298 current = current->next();
2304 void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
2305 HandleScope scope(isolate_);
2307 PrepareForBreakPoints();
2309 // Get the executing function in which the debug break occurred.
2310 Handle<JSFunction> function(JSFunction::cast(frame->function()));
2311 Handle<SharedFunctionInfo> shared(function->shared());
2312 if (!EnsureDebugInfo(shared, function)) {
2313 // Return if we failed to retrieve the debug info.
2316 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
2317 Handle<Code> code(debug_info->code());
2318 Handle<Code> original_code(debug_info->original_code());
2320 // Get the code which is actually executing.
2321 Handle<Code> frame_code(frame->LookupCode());
2322 ASSERT(frame_code.is_identical_to(code));
2325 // Find the call address in the running code. This address holds the call to
2326 // either a DebugBreakXXX or to the debug break return entry code if the
2327 // break point is still active after processing the break point.
2328 Address addr = frame->pc() - Assembler::kPatchDebugBreakSlotReturnOffset;
2330 // Check if the location is at JS exit or debug break slot.
2331 bool at_js_return = false;
2332 bool break_at_js_return_active = false;
2333 bool at_debug_break_slot = false;
2334 RelocIterator it(debug_info->code());
2335 while (!it.done() && !at_js_return && !at_debug_break_slot) {
2336 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
2337 at_js_return = (it.rinfo()->pc() ==
2338 addr - Assembler::kPatchReturnSequenceAddressOffset);
2339 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
2341 if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
2342 at_debug_break_slot = (it.rinfo()->pc() ==
2343 addr - Assembler::kPatchDebugBreakSlotAddressOffset);
2348 // Handle the jump to continue execution after break point depending on the
2351 // If the break point as return is still active jump to the corresponding
2352 // place in the original code. If not the break point was removed during
2353 // break point processing.
2354 if (break_at_js_return_active) {
2355 addr += original_code->instruction_start() - code->instruction_start();
2358 // Move back to where the call instruction sequence started.
2359 thread_local_.after_break_target_ =
2360 addr - Assembler::kPatchReturnSequenceAddressOffset;
2361 } else if (at_debug_break_slot) {
2362 // Address of where the debug break slot starts.
2363 addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;
2365 // Continue just after the slot.
2366 thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
2367 } else if (IsDebugBreak(Assembler::target_address_at(addr, *code))) {
2368 // We now know that there is still a debug break call at the target address,
2369 // so the break point is still there and the original code will hold the
2370 // address to jump to in order to complete the call which is replaced by a
2371 // call to DebugBreakXXX.
2373 // Find the corresponding address in the original code.
2374 addr += original_code->instruction_start() - code->instruction_start();
2376 // Install jump to the call address in the original code. This will be the
2377 // call which was overwritten by the call to DebugBreakXXX.
2378 thread_local_.after_break_target_ =
2379 Assembler::target_address_at(addr, *original_code);
2381 // There is no longer a break point present. Don't try to look in the
2382 // original code as the running code will have the right address. This takes
2383 // care of the case where the last break point is removed from the function
2384 // and therefore no "original code" is available.
2385 thread_local_.after_break_target_ =
2386 Assembler::target_address_at(addr, *code);
2391 bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) {
2392 HandleScope scope(isolate_);
2394 // If there are no break points this cannot be break at return, as
2395 // the debugger statement and stack guard bebug break cannot be at
2397 if (!has_break_points_) {
2401 PrepareForBreakPoints();
2403 // Get the executing function in which the debug break occurred.
2404 Handle<JSFunction> function(JSFunction::cast(frame->function()));
2405 Handle<SharedFunctionInfo> shared(function->shared());
2406 if (!EnsureDebugInfo(shared, function)) {
2407 // Return if we failed to retrieve the debug info.
2410 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
2411 Handle<Code> code(debug_info->code());
2413 // Get the code which is actually executing.
2414 Handle<Code> frame_code(frame->LookupCode());
2415 ASSERT(frame_code.is_identical_to(code));
2418 // Find the call address in the running code.
2419 Address addr = frame->pc() - Assembler::kPatchDebugBreakSlotReturnOffset;
2421 // Check if the location is at JS return.
2422 RelocIterator it(debug_info->code());
2423 while (!it.done()) {
2424 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
2425 return (it.rinfo()->pc() ==
2426 addr - Assembler::kPatchReturnSequenceAddressOffset);
2434 void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id,
2436 Object** restarter_frame_function_pointer) {
2437 if (mode != CURRENTLY_SET_MODE) {
2438 thread_local_.frame_drop_mode_ = mode;
2440 thread_local_.break_frame_id_ = new_break_frame_id;
2441 thread_local_.restarter_frame_function_pointer_ =
2442 restarter_frame_function_pointer;
2446 const int Debug::FramePaddingLayout::kInitialSize = 1;
2449 // Any even value bigger than kInitialSize as needed for stack scanning.
2450 const int Debug::FramePaddingLayout::kPaddingValue = kInitialSize + 1;
2453 bool Debug::IsDebugGlobal(GlobalObject* global) {
2454 return IsLoaded() && global == debug_context()->global_object();
2458 void Debug::ClearMirrorCache() {
2459 PostponeInterruptsScope postpone(isolate_);
2460 HandleScope scope(isolate_);
2461 ASSERT(isolate_->context() == *Debug::debug_context());
2463 // Clear the mirror cache.
2464 Handle<String> function_name = isolate_->factory()->InternalizeOneByteString(
2465 STATIC_ASCII_VECTOR("ClearMirrorCache"));
2467 isolate_->global_object()->GetPropertyNoExceptionThrown(*function_name),
2469 ASSERT(fun->IsJSFunction());
2470 bool caught_exception;
2471 Execution::TryCall(Handle<JSFunction>::cast(fun),
2472 Handle<JSObject>(Debug::debug_context()->global_object()),
2473 0, NULL, &caught_exception);
2477 void Debug::CreateScriptCache() {
2478 Heap* heap = isolate_->heap();
2479 HandleScope scope(isolate_);
2481 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
2482 // rid of all the cached script wrappers and the second gets rid of the
2483 // scripts which are no longer referenced. The second also sweeps precisely,
2484 // which saves us doing yet another GC to make the heap iterable.
2485 heap->CollectAllGarbage(Heap::kNoGCFlags, "Debug::CreateScriptCache");
2486 heap->CollectAllGarbage(Heap::kMakeHeapIterableMask,
2487 "Debug::CreateScriptCache");
2489 ASSERT(script_cache_ == NULL);
2490 script_cache_ = new ScriptCache(isolate_);
2492 // Scan heap for Script objects.
2494 HeapIterator iterator(heap);
2495 DisallowHeapAllocation no_allocation;
2497 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
2498 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
2499 script_cache_->Add(Handle<Script>(Script::cast(obj)));
2506 void Debug::DestroyScriptCache() {
2507 // Get rid of the script cache if it was created.
2508 if (script_cache_ != NULL) {
2509 delete script_cache_;
2510 script_cache_ = NULL;
2515 void Debug::AddScriptToScriptCache(Handle<Script> script) {
2516 if (script_cache_ != NULL) {
2517 script_cache_->Add(script);
2522 Handle<FixedArray> Debug::GetLoadedScripts() {
2523 // Create and fill the script cache when the loaded scripts is requested for
2525 if (script_cache_ == NULL) {
2526 CreateScriptCache();
2529 // If the script cache is not active just return an empty array.
2530 ASSERT(script_cache_ != NULL);
2531 if (script_cache_ == NULL) {
2532 isolate_->factory()->NewFixedArray(0);
2535 // Perform GC to get unreferenced scripts evicted from the cache before
2536 // returning the content.
2537 isolate_->heap()->CollectAllGarbage(Heap::kNoGCFlags,
2538 "Debug::GetLoadedScripts");
2540 // Get the scripts from the cache.
2541 return script_cache_->GetScripts();
2545 void Debug::RecordEvalCaller(Handle<Script> script) {
2546 script->set_compilation_type(Script::COMPILATION_TYPE_EVAL);
2547 // For eval scripts add information on the function from which eval was
2549 StackTraceFrameIterator it(script->GetIsolate());
2551 script->set_eval_from_shared(it.frame()->function()->shared());
2552 Code* code = it.frame()->LookupCode();
2553 int offset = static_cast<int>(
2554 it.frame()->pc() - code->instruction_start());
2555 script->set_eval_from_instructions_offset(Smi::FromInt(offset));
2560 void Debug::AfterGarbageCollection() {
2561 // Generate events for collected scripts.
2562 if (script_cache_ != NULL) {
2563 script_cache_->ProcessCollectedScripts();
2568 Debugger::Debugger(Isolate* isolate)
2569 : debugger_access_(isolate->debugger_access()),
2570 event_listener_(Handle<Object>()),
2571 event_listener_data_(Handle<Object>()),
2572 compiling_natives_(false),
2573 is_loading_debugger_(false),
2574 live_edit_enabled_(true),
2575 never_unload_debugger_(false),
2576 force_debugger_active_(false),
2577 message_handler_(NULL),
2578 debugger_unload_pending_(false),
2579 host_dispatch_handler_(NULL),
2580 debug_message_dispatch_handler_(NULL),
2581 message_dispatch_helper_thread_(NULL),
2582 host_dispatch_period_(TimeDelta::FromMilliseconds(100)),
2584 command_queue_(isolate->logger(), kQueueInitialSize),
2585 command_received_(0),
2586 event_command_queue_(isolate->logger(), kQueueInitialSize),
2591 Debugger::~Debugger() {}
2594 Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
2596 Handle<Object> argv[],
2597 bool* caught_exception) {
2598 ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2600 // Create the execution state object.
2601 Handle<String> constructor_str =
2602 isolate_->factory()->InternalizeUtf8String(constructor_name);
2603 ASSERT(!constructor_str.is_null());
2604 Handle<Object> constructor(
2605 isolate_->global_object()->GetPropertyNoExceptionThrown(*constructor_str),
2607 ASSERT(constructor->IsJSFunction());
2608 if (!constructor->IsJSFunction()) {
2609 *caught_exception = true;
2610 return isolate_->factory()->undefined_value();
2612 Handle<Object> js_object = Execution::TryCall(
2613 Handle<JSFunction>::cast(constructor),
2614 Handle<JSObject>(isolate_->debug()->debug_context()->global_object()),
2622 Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
2623 // Create the execution state object.
2624 Handle<Object> break_id = isolate_->factory()->NewNumberFromInt(
2625 isolate_->debug()->break_id());
2626 Handle<Object> argv[] = { break_id };
2627 return MakeJSObject(CStrVector("MakeExecutionState"),
2634 Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
2635 Handle<Object> break_points_hit,
2636 bool* caught_exception) {
2637 // Create the new break event object.
2638 Handle<Object> argv[] = { exec_state, break_points_hit };
2639 return MakeJSObject(CStrVector("MakeBreakEvent"),
2646 Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
2647 Handle<Object> exception,
2649 bool* caught_exception) {
2650 Factory* factory = isolate_->factory();
2651 // Create the new exception event object.
2652 Handle<Object> argv[] = { exec_state,
2654 factory->ToBoolean(uncaught) };
2655 return MakeJSObject(CStrVector("MakeExceptionEvent"),
2662 Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
2663 bool* caught_exception) {
2664 // Create the new function event object.
2665 Handle<Object> argv[] = { function };
2666 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
2673 Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
2675 bool* caught_exception) {
2676 Factory* factory = isolate_->factory();
2677 // Create the compile event object.
2678 Handle<Object> exec_state = MakeExecutionState(caught_exception);
2679 Handle<Object> script_wrapper = GetScriptWrapper(script);
2680 Handle<Object> argv[] = { exec_state,
2682 factory->ToBoolean(before) };
2683 return MakeJSObject(CStrVector("MakeCompileEvent"),
2690 Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
2691 bool* caught_exception) {
2692 // Create the script collected event object.
2693 Handle<Object> exec_state = MakeExecutionState(caught_exception);
2694 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id), isolate_);
2695 Handle<Object> argv[] = { exec_state, id_object };
2697 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
2704 void Debugger::OnException(Handle<Object> exception, bool uncaught) {
2705 HandleScope scope(isolate_);
2706 Debug* debug = isolate_->debug();
2708 // Bail out based on state or if there is no listener for this event
2709 if (debug->InDebugger()) return;
2710 if (!Debugger::EventActive(v8::Exception)) return;
2712 // Bail out if exception breaks are not active
2714 // Uncaught exceptions are reported by either flags.
2715 if (!(debug->break_on_uncaught_exception() ||
2716 debug->break_on_exception())) return;
2718 // Caught exceptions are reported is activated.
2719 if (!debug->break_on_exception()) return;
2722 // Enter the debugger.
2723 EnterDebugger debugger(isolate_);
2724 if (debugger.FailedToEnter()) return;
2726 // Clear all current stepping setup.
2727 debug->ClearStepping();
2728 // Create the event data object.
2729 bool caught_exception = false;
2730 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2731 Handle<Object> event_data;
2732 if (!caught_exception) {
2733 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
2736 // Bail out and don't call debugger if exception.
2737 if (caught_exception) {
2741 // Process debug event.
2742 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
2743 // Return to continue execution from where the exception was thrown.
2747 void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
2748 bool auto_continue) {
2749 HandleScope scope(isolate_);
2751 // Debugger has already been entered by caller.
2752 ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2754 // Bail out if there is no listener for this event
2755 if (!Debugger::EventActive(v8::Break)) return;
2757 // Debugger must be entered in advance.
2758 ASSERT(isolate_->context() == *isolate_->debug()->debug_context());
2760 // Create the event data object.
2761 bool caught_exception = false;
2762 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2763 Handle<Object> event_data;
2764 if (!caught_exception) {
2765 event_data = MakeBreakEvent(exec_state, break_points_hit,
2768 // Bail out and don't call debugger if exception.
2769 if (caught_exception) {
2773 // Process debug event.
2774 ProcessDebugEvent(v8::Break,
2775 Handle<JSObject>::cast(event_data),
2780 void Debugger::OnBeforeCompile(Handle<Script> script) {
2781 HandleScope scope(isolate_);
2783 // Bail out based on state or if there is no listener for this event
2784 if (isolate_->debug()->InDebugger()) return;
2785 if (compiling_natives()) return;
2786 if (!EventActive(v8::BeforeCompile)) return;
2788 // Enter the debugger.
2789 EnterDebugger debugger(isolate_);
2790 if (debugger.FailedToEnter()) return;
2792 // Create the event data object.
2793 bool caught_exception = false;
2794 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
2795 // Bail out and don't call debugger if exception.
2796 if (caught_exception) {
2800 // Process debug event.
2801 ProcessDebugEvent(v8::BeforeCompile,
2802 Handle<JSObject>::cast(event_data),
2807 // Handle debugger actions when a new script is compiled.
2808 void Debugger::OnAfterCompile(Handle<Script> script,
2809 AfterCompileFlags after_compile_flags) {
2810 HandleScope scope(isolate_);
2811 Debug* debug = isolate_->debug();
2813 // Add the newly compiled script to the script cache.
2814 debug->AddScriptToScriptCache(script);
2816 // No more to do if not debugging.
2817 if (!IsDebuggerActive()) return;
2819 // No compile events while compiling natives.
2820 if (compiling_natives()) return;
2822 // Store whether in debugger before entering debugger.
2823 bool in_debugger = debug->InDebugger();
2825 // Enter the debugger.
2826 EnterDebugger debugger(isolate_);
2827 if (debugger.FailedToEnter()) return;
2829 // If debugging there might be script break points registered for this
2830 // script. Make sure that these break points are set.
2832 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
2833 Handle<String> update_script_break_points_string =
2834 isolate_->factory()->InternalizeOneByteString(
2835 STATIC_ASCII_VECTOR("UpdateScriptBreakPoints"));
2836 Handle<Object> update_script_break_points =
2838 debug->debug_context()->global_object()->GetPropertyNoExceptionThrown(
2839 *update_script_break_points_string),
2841 if (!update_script_break_points->IsJSFunction()) {
2844 ASSERT(update_script_break_points->IsJSFunction());
2846 // Wrap the script object in a proper JS object before passing it
2848 Handle<JSValue> wrapper = GetScriptWrapper(script);
2850 // Call UpdateScriptBreakPoints expect no exceptions.
2851 bool caught_exception;
2852 Handle<Object> argv[] = { wrapper };
2853 Execution::TryCall(Handle<JSFunction>::cast(update_script_break_points),
2854 isolate_->js_builtins_object(),
2858 if (caught_exception) {
2861 // Bail out based on state or if there is no listener for this event
2862 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
2863 if (!Debugger::EventActive(v8::AfterCompile)) return;
2865 // Create the compile state object.
2866 Handle<Object> event_data = MakeCompileEvent(script,
2869 // Bail out and don't call debugger if exception.
2870 if (caught_exception) {
2873 // Process debug event.
2874 ProcessDebugEvent(v8::AfterCompile,
2875 Handle<JSObject>::cast(event_data),
2880 void Debugger::OnScriptCollected(int id) {
2881 HandleScope scope(isolate_);
2883 // No more to do if not debugging.
2884 if (isolate_->debug()->InDebugger()) return;
2885 if (!IsDebuggerActive()) return;
2886 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2888 // Enter the debugger.
2889 EnterDebugger debugger(isolate_);
2890 if (debugger.FailedToEnter()) return;
2892 // Create the script collected state object.
2893 bool caught_exception = false;
2894 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2896 // Bail out and don't call debugger if exception.
2897 if (caught_exception) {
2901 // Process debug event.
2902 ProcessDebugEvent(v8::ScriptCollected,
2903 Handle<JSObject>::cast(event_data),
2908 void Debugger::ProcessDebugEvent(v8::DebugEvent event,
2909 Handle<JSObject> event_data,
2910 bool auto_continue) {
2911 HandleScope scope(isolate_);
2913 // Clear any pending debug break if this is a real break.
2914 if (!auto_continue) {
2915 isolate_->debug()->clear_interrupt_pending(DEBUGBREAK);
2918 // Create the execution state.
2919 bool caught_exception = false;
2920 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2921 if (caught_exception) {
2924 // First notify the message handler if any.
2925 if (message_handler_ != NULL) {
2926 NotifyMessageHandler(event,
2927 Handle<JSObject>::cast(exec_state),
2931 // Notify registered debug event listener. This can be either a C or
2932 // a JavaScript function. Don't call event listener for v8::Break
2933 // here, if it's only a debug command -- they will be processed later.
2934 if ((event != v8::Break || !auto_continue) && !event_listener_.is_null()) {
2935 CallEventCallback(event, exec_state, event_data, NULL);
2937 // Process pending debug commands.
2938 if (event == v8::Break) {
2939 while (!event_command_queue_.IsEmpty()) {
2940 CommandMessage command = event_command_queue_.Get();
2941 if (!event_listener_.is_null()) {
2942 CallEventCallback(v8::BreakForCommand,
2945 command.client_data());
2953 void Debugger::CallEventCallback(v8::DebugEvent event,
2954 Handle<Object> exec_state,
2955 Handle<Object> event_data,
2956 v8::Debug::ClientData* client_data) {
2957 if (event_listener_->IsForeign()) {
2958 CallCEventCallback(event, exec_state, event_data, client_data);
2960 CallJSEventCallback(event, exec_state, event_data);
2965 void Debugger::CallCEventCallback(v8::DebugEvent event,
2966 Handle<Object> exec_state,
2967 Handle<Object> event_data,
2968 v8::Debug::ClientData* client_data) {
2969 Handle<Foreign> callback_obj(Handle<Foreign>::cast(event_listener_));
2970 v8::Debug::EventCallback2 callback =
2971 FUNCTION_CAST<v8::Debug::EventCallback2>(
2972 callback_obj->foreign_address());
2973 EventDetailsImpl event_details(
2975 Handle<JSObject>::cast(exec_state),
2976 Handle<JSObject>::cast(event_data),
2977 event_listener_data_,
2979 callback(event_details);
2983 void Debugger::CallJSEventCallback(v8::DebugEvent event,
2984 Handle<Object> exec_state,
2985 Handle<Object> event_data) {
2986 ASSERT(event_listener_->IsJSFunction());
2987 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
2989 // Invoke the JavaScript debug event listener.
2990 Handle<Object> argv[] = { Handle<Object>(Smi::FromInt(event), isolate_),
2993 event_listener_data_ };
2994 bool caught_exception;
2995 Execution::TryCall(fun,
2996 isolate_->global_object(),
3000 // Silently ignore exceptions from debug event listeners.
3004 Handle<Context> Debugger::GetDebugContext() {
3005 never_unload_debugger_ = true;
3006 EnterDebugger debugger(isolate_);
3007 return isolate_->debug()->debug_context();
3011 void Debugger::UnloadDebugger() {
3012 Debug* debug = isolate_->debug();
3014 // Make sure that there are no breakpoints left.
3015 debug->ClearAllBreakPoints();
3017 // Unload the debugger if feasible.
3018 if (!never_unload_debugger_) {
3022 // Clear the flag indicating that the debugger should be unloaded.
3023 debugger_unload_pending_ = false;
3027 void Debugger::NotifyMessageHandler(v8::DebugEvent event,
3028 Handle<JSObject> exec_state,
3029 Handle<JSObject> event_data,
3030 bool auto_continue) {
3031 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(isolate_);
3032 HandleScope scope(isolate_);
3034 if (!isolate_->debug()->Load()) return;
3036 // Process the individual events.
3037 bool sendEventMessage = false;
3040 case v8::BreakForCommand:
3041 sendEventMessage = !auto_continue;
3044 sendEventMessage = true;
3046 case v8::BeforeCompile:
3048 case v8::AfterCompile:
3049 sendEventMessage = true;
3051 case v8::ScriptCollected:
3052 sendEventMessage = true;
3054 case v8::NewFunction:
3060 // The debug command interrupt flag might have been set when the command was
3061 // added. It should be enough to clear the flag only once while we are in the
3063 ASSERT(isolate_->debug()->InDebugger());
3064 isolate_->stack_guard()->Continue(DEBUGCOMMAND);
3066 // Notify the debugger that a debug event has occurred unless auto continue is
3067 // active in which case no event is send.
3068 if (sendEventMessage) {
3069 MessageImpl message = MessageImpl::NewEvent(
3072 Handle<JSObject>::cast(exec_state),
3073 Handle<JSObject>::cast(event_data));
3074 InvokeMessageHandler(message);
3077 // If auto continue don't make the event cause a break, but process messages
3078 // in the queue if any. For script collected events don't even process
3079 // messages in the queue as the execution state might not be what is expected
3081 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
3085 v8::TryCatch try_catch;
3087 // DebugCommandProcessor goes here.
3088 v8::Local<v8::Object> cmd_processor;
3090 v8::Local<v8::Object> api_exec_state =
3091 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
3092 v8::Local<v8::String> fun_name = v8::String::NewFromUtf8(
3093 isolate, "debugCommandProcessor");
3094 v8::Local<v8::Function> fun =
3095 v8::Local<v8::Function>::Cast(api_exec_state->Get(fun_name));
3097 v8::Handle<v8::Boolean> running = v8::Boolean::New(isolate, auto_continue);
3098 static const int kArgc = 1;
3099 v8::Handle<Value> argv[kArgc] = { running };
3100 cmd_processor = v8::Local<v8::Object>::Cast(
3101 fun->Call(api_exec_state, kArgc, argv));
3102 if (try_catch.HasCaught()) {
3103 PrintLn(try_catch.Exception());
3108 bool running = auto_continue;
3110 // Process requests from the debugger.
3112 // Wait for new command in the queue.
3113 if (Debugger::host_dispatch_handler_) {
3114 // In case there is a host dispatch - do periodic dispatches.
3115 if (!command_received_.WaitFor(host_dispatch_period_)) {
3116 // Timout expired, do the dispatch.
3117 Debugger::host_dispatch_handler_();
3121 // In case there is no host dispatch - just wait.
3122 command_received_.Wait();
3125 // Get the command from the queue.
3126 CommandMessage command = command_queue_.Get();
3127 isolate_->logger()->DebugTag(
3128 "Got request from command queue, in interactive loop.");
3129 if (!Debugger::IsDebuggerActive()) {
3130 // Delete command text and user data.
3135 // Invoke JavaScript to process the debug request.
3136 v8::Local<v8::String> fun_name;
3137 v8::Local<v8::Function> fun;
3138 v8::Local<v8::Value> request;
3139 v8::TryCatch try_catch;
3140 fun_name = v8::String::NewFromUtf8(isolate, "processDebugRequest");
3141 fun = v8::Local<v8::Function>::Cast(cmd_processor->Get(fun_name));
3143 request = v8::String::NewFromTwoByte(isolate, command.text().start(),
3144 v8::String::kNormalString,
3145 command.text().length());
3146 static const int kArgc = 1;
3147 v8::Handle<Value> argv[kArgc] = { request };
3148 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
3150 // Get the response.
3151 v8::Local<v8::String> response;
3152 if (!try_catch.HasCaught()) {
3153 // Get response string.
3154 if (!response_val->IsUndefined()) {
3155 response = v8::Local<v8::String>::Cast(response_val);
3157 response = v8::String::NewFromUtf8(isolate, "");
3160 // Log the JSON request/response.
3161 if (FLAG_trace_debug_json) {
3166 // Get the running state.
3167 fun_name = v8::String::NewFromUtf8(isolate, "isRunning");
3168 fun = v8::Local<v8::Function>::Cast(cmd_processor->Get(fun_name));
3169 static const int kArgc = 1;
3170 v8::Handle<Value> argv[kArgc] = { response };
3171 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
3172 if (!try_catch.HasCaught()) {
3173 running = running_val->ToBoolean()->Value();
3176 // In case of failure the result text is the exception text.
3177 response = try_catch.Exception()->ToString();
3180 // Return the result.
3181 MessageImpl message = MessageImpl::NewResponse(
3184 Handle<JSObject>::cast(exec_state),
3185 Handle<JSObject>::cast(event_data),
3186 Handle<String>(Utils::OpenHandle(*response)),
3187 command.client_data());
3188 InvokeMessageHandler(message);
3191 // Return from debug event processing if either the VM is put into the
3192 // running state (through a continue command) or auto continue is active
3193 // and there are no more commands queued.
3194 if (running && !HasCommands()) {
3201 void Debugger::SetEventListener(Handle<Object> callback,
3202 Handle<Object> data) {
3203 HandleScope scope(isolate_);
3204 GlobalHandles* global_handles = isolate_->global_handles();
3206 // Clear the global handles for the event listener and the event listener data
3208 if (!event_listener_.is_null()) {
3209 GlobalHandles::Destroy(
3210 reinterpret_cast<Object**>(event_listener_.location()));
3211 event_listener_ = Handle<Object>();
3213 if (!event_listener_data_.is_null()) {
3214 GlobalHandles::Destroy(
3215 reinterpret_cast<Object**>(event_listener_data_.location()));
3216 event_listener_data_ = Handle<Object>();
3219 // If there is a new debug event listener register it together with its data
3221 if (!callback->IsUndefined() && !callback->IsNull()) {
3222 event_listener_ = Handle<Object>::cast(
3223 global_handles->Create(*callback));
3224 if (data.is_null()) {
3225 data = isolate_->factory()->undefined_value();
3227 event_listener_data_ = Handle<Object>::cast(
3228 global_handles->Create(*data));
3235 void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
3236 LockGuard<RecursiveMutex> with(debugger_access_);
3238 message_handler_ = handler;
3240 if (handler == NULL) {
3241 // Send an empty command to the debugger if in a break to make JavaScript
3242 // run again if the debugger is closed.
3243 if (isolate_->debug()->InDebugger()) {
3244 ProcessCommand(Vector<const uint16_t>::empty());
3250 void Debugger::ListenersChanged() {
3251 if (IsDebuggerActive()) {
3252 // Disable the compilation cache when the debugger is active.
3253 isolate_->compilation_cache()->Disable();
3254 debugger_unload_pending_ = false;
3256 isolate_->compilation_cache()->Enable();
3257 // Unload the debugger if event listener and message handler cleared.
3258 // Schedule this for later, because we may be in non-V8 thread.
3259 debugger_unload_pending_ = true;
3264 void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
3266 host_dispatch_handler_ = handler;
3267 host_dispatch_period_ = period;
3271 void Debugger::SetDebugMessageDispatchHandler(
3272 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
3273 LockGuard<Mutex> lock_guard(&dispatch_handler_access_);
3274 debug_message_dispatch_handler_ = handler;
3276 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
3277 message_dispatch_helper_thread_ = new MessageDispatchHelperThread(isolate_);
3278 message_dispatch_helper_thread_->Start();
3283 // Calls the registered debug message handler. This callback is part of the
3285 void Debugger::InvokeMessageHandler(MessageImpl message) {
3286 LockGuard<RecursiveMutex> with(debugger_access_);
3288 if (message_handler_ != NULL) {
3289 message_handler_(message);
3294 // Puts a command coming from the public API on the queue. Creates
3295 // a copy of the command string managed by the debugger. Up to this
3296 // point, the command data was managed by the API client. Called
3297 // by the API client thread.
3298 void Debugger::ProcessCommand(Vector<const uint16_t> command,
3299 v8::Debug::ClientData* client_data) {
3300 // Need to cast away const.
3301 CommandMessage message = CommandMessage::New(
3302 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
3305 isolate_->logger()->DebugTag("Put command on command_queue.");
3306 command_queue_.Put(message);
3307 command_received_.Signal();
3309 // Set the debug command break flag to have the command processed.
3310 if (!isolate_->debug()->InDebugger()) {
3311 isolate_->stack_guard()->DebugCommand();
3314 MessageDispatchHelperThread* dispatch_thread;
3316 LockGuard<Mutex> lock_guard(&dispatch_handler_access_);
3317 dispatch_thread = message_dispatch_helper_thread_;
3320 if (dispatch_thread == NULL) {
3321 CallMessageDispatchHandler();
3323 dispatch_thread->Schedule();
3328 bool Debugger::HasCommands() {
3329 return !command_queue_.IsEmpty();
3333 void Debugger::EnqueueDebugCommand(v8::Debug::ClientData* client_data) {
3334 CommandMessage message = CommandMessage::New(Vector<uint16_t>(), client_data);
3335 event_command_queue_.Put(message);
3337 // Set the debug command break flag to have the command processed.
3338 if (!isolate_->debug()->InDebugger()) {
3339 isolate_->stack_guard()->DebugCommand();
3344 bool Debugger::IsDebuggerActive() {
3345 LockGuard<RecursiveMutex> with(debugger_access_);
3347 return message_handler_ != NULL ||
3348 !event_listener_.is_null() ||
3349 force_debugger_active_;
3353 Handle<Object> Debugger::Call(Handle<JSFunction> fun,
3354 Handle<Object> data,
3355 bool* pending_exception) {
3356 // When calling functions in the debugger prevent it from beeing unloaded.
3357 Debugger::never_unload_debugger_ = true;
3359 // Enter the debugger.
3360 EnterDebugger debugger(isolate_);
3361 if (debugger.FailedToEnter()) {
3362 return isolate_->factory()->undefined_value();
3365 // Create the execution state.
3366 bool caught_exception = false;
3367 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
3368 if (caught_exception) {
3369 return isolate_->factory()->undefined_value();
3372 Handle<Object> argv[] = { exec_state, data };
3373 Handle<Object> result = Execution::Call(
3376 Handle<Object>(isolate_->debug()->debug_context_->global_proxy(),
3385 static void StubMessageHandler2(const v8::Debug::Message& message) {
3386 // Simply ignore message.
3390 bool Debugger::StartAgent(const char* name, int port,
3391 bool wait_for_connection) {
3392 if (wait_for_connection) {
3393 // Suspend V8 if it is already running or set V8 to suspend whenever
3395 // Provide stub message handler; V8 auto-continues each suspend
3396 // when there is no message handler; we doesn't need it.
3397 // Once become suspended, V8 will stay so indefinitely long, until remote
3398 // debugger connects and issues "continue" command.
3399 Debugger::message_handler_ = StubMessageHandler2;
3400 v8::Debug::DebugBreak();
3403 if (agent_ == NULL) {
3404 agent_ = new DebuggerAgent(isolate_, name, port);
3411 void Debugger::StopAgent() {
3412 if (agent_ != NULL) {
3421 void Debugger::WaitForAgent() {
3423 agent_->WaitUntilListening();
3427 void Debugger::CallMessageDispatchHandler() {
3428 v8::Debug::DebugMessageDispatchHandler handler;
3430 LockGuard<Mutex> lock_guard(&dispatch_handler_access_);
3431 handler = Debugger::debug_message_dispatch_handler_;
3433 if (handler != NULL) {
3439 EnterDebugger::EnterDebugger(Isolate* isolate)
3440 : isolate_(isolate),
3441 prev_(isolate_->debug()->debugger_entry()),
3443 has_js_frames_(!it_.done()),
3445 Debug* debug = isolate_->debug();
3446 ASSERT(prev_ != NULL || !debug->is_interrupt_pending(PREEMPT));
3447 ASSERT(prev_ != NULL || !debug->is_interrupt_pending(DEBUGBREAK));
3449 // Link recursive debugger entry.
3450 debug->set_debugger_entry(this);
3452 // Store the previous break id and frame id.
3453 break_id_ = debug->break_id();
3454 break_frame_id_ = debug->break_frame_id();
3456 // Create the new break info. If there is no JavaScript frames there is no
3458 if (has_js_frames_) {
3459 debug->NewBreak(it_.frame()->id());
3461 debug->NewBreak(StackFrame::NO_ID);
3464 // Make sure that debugger is loaded and enter the debugger context.
3465 load_failed_ = !debug->Load();
3466 if (!load_failed_) {
3467 // NOTE the member variable save which saves the previous context before
3469 isolate_->set_context(*debug->debug_context());
3474 EnterDebugger::~EnterDebugger() {
3475 Debug* debug = isolate_->debug();
3477 // Restore to the previous break state.
3478 debug->SetBreak(break_frame_id_, break_id_);
3480 // Check for leaving the debugger.
3481 if (!load_failed_ && prev_ == NULL) {
3482 // Clear mirror cache when leaving the debugger. Skip this if there is a
3483 // pending exception as clearing the mirror cache calls back into
3484 // JavaScript. This can happen if the v8::Debug::Call is used in which
3485 // case the exception should end up in the calling code.
3486 if (!isolate_->has_pending_exception()) {
3487 // Try to avoid any pending debug break breaking in the clear mirror
3488 // cache JavaScript code.
3489 if (isolate_->stack_guard()->IsDebugBreak()) {
3490 debug->set_interrupts_pending(DEBUGBREAK);
3491 isolate_->stack_guard()->Continue(DEBUGBREAK);
3493 debug->ClearMirrorCache();
3496 // Request preemption and debug break when leaving the last debugger entry
3497 // if any of these where recorded while debugging.
3498 if (debug->is_interrupt_pending(PREEMPT)) {
3499 // This re-scheduling of preemption is to avoid starvation in some
3500 // debugging scenarios.
3501 debug->clear_interrupt_pending(PREEMPT);
3502 isolate_->stack_guard()->Preempt();
3504 if (debug->is_interrupt_pending(DEBUGBREAK)) {
3505 debug->clear_interrupt_pending(DEBUGBREAK);
3506 isolate_->stack_guard()->DebugBreak();
3509 // If there are commands in the queue when leaving the debugger request
3510 // that these commands are processed.
3511 if (isolate_->debugger()->HasCommands()) {
3512 isolate_->stack_guard()->DebugCommand();
3515 // If leaving the debugger with the debugger no longer active unload it.
3516 if (!isolate_->debugger()->IsDebuggerActive()) {
3517 isolate_->debugger()->UnloadDebugger();
3521 // Leaving this debugger entry.
3522 debug->set_debugger_entry(prev_);
3526 MessageImpl MessageImpl::NewEvent(DebugEvent event,
3528 Handle<JSObject> exec_state,
3529 Handle<JSObject> event_data) {
3530 MessageImpl message(true, event, running,
3531 exec_state, event_data, Handle<String>(), NULL);
3536 MessageImpl MessageImpl::NewResponse(DebugEvent event,
3538 Handle<JSObject> exec_state,
3539 Handle<JSObject> event_data,
3540 Handle<String> response_json,
3541 v8::Debug::ClientData* client_data) {
3542 MessageImpl message(false, event, running,
3543 exec_state, event_data, response_json, client_data);
3548 MessageImpl::MessageImpl(bool is_event,
3551 Handle<JSObject> exec_state,
3552 Handle<JSObject> event_data,
3553 Handle<String> response_json,
3554 v8::Debug::ClientData* client_data)
3555 : is_event_(is_event),
3558 exec_state_(exec_state),
3559 event_data_(event_data),
3560 response_json_(response_json),
3561 client_data_(client_data) {}
3564 bool MessageImpl::IsEvent() const {
3569 bool MessageImpl::IsResponse() const {
3574 DebugEvent MessageImpl::GetEvent() const {
3579 bool MessageImpl::WillStartRunning() const {
3584 v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
3585 return v8::Utils::ToLocal(exec_state_);
3589 v8::Isolate* MessageImpl::GetIsolate() const {
3590 return reinterpret_cast<v8::Isolate*>(exec_state_->GetIsolate());
3594 v8::Handle<v8::Object> MessageImpl::GetEventData() const {
3595 return v8::Utils::ToLocal(event_data_);
3599 v8::Handle<v8::String> MessageImpl::GetJSON() const {
3600 v8::EscapableHandleScope scope(
3601 reinterpret_cast<v8::Isolate*>(event_data_->GetIsolate()));
3604 // Call toJSONProtocol on the debug event object.
3605 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
3606 if (!fun->IsJSFunction()) {
3607 return v8::Handle<v8::String>();
3609 bool caught_exception;
3610 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
3612 0, NULL, &caught_exception);
3613 if (caught_exception || !json->IsString()) {
3614 return v8::Handle<v8::String>();
3616 return scope.Escape(v8::Utils::ToLocal(Handle<String>::cast(json)));
3618 return v8::Utils::ToLocal(response_json_);
3623 v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
3624 Isolate* isolate = event_data_->GetIsolate();
3625 v8::Handle<v8::Context> context = GetDebugEventContext(isolate);
3626 // Isolate::context() may be NULL when "script collected" event occures.
3627 ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
3632 v8::Debug::ClientData* MessageImpl::GetClientData() const {
3633 return client_data_;
3637 EventDetailsImpl::EventDetailsImpl(DebugEvent event,
3638 Handle<JSObject> exec_state,
3639 Handle<JSObject> event_data,
3640 Handle<Object> callback_data,
3641 v8::Debug::ClientData* client_data)
3643 exec_state_(exec_state),
3644 event_data_(event_data),
3645 callback_data_(callback_data),
3646 client_data_(client_data) {}
3649 DebugEvent EventDetailsImpl::GetEvent() const {
3654 v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
3655 return v8::Utils::ToLocal(exec_state_);
3659 v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
3660 return v8::Utils::ToLocal(event_data_);
3664 v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
3665 return GetDebugEventContext(exec_state_->GetIsolate());
3669 v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
3670 return v8::Utils::ToLocal(callback_data_);
3674 v8::Debug::ClientData* EventDetailsImpl::GetClientData() const {
3675 return client_data_;
3679 CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
3680 client_data_(NULL) {
3684 CommandMessage::CommandMessage(const Vector<uint16_t>& text,
3685 v8::Debug::ClientData* data)
3687 client_data_(data) {
3691 CommandMessage::~CommandMessage() {
3695 void CommandMessage::Dispose() {
3697 delete client_data_;
3698 client_data_ = NULL;
3702 CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
3703 v8::Debug::ClientData* data) {
3704 return CommandMessage(command.Clone(), data);
3708 CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
3710 messages_ = NewArray<CommandMessage>(size);
3714 CommandMessageQueue::~CommandMessageQueue() {
3715 while (!IsEmpty()) {
3716 CommandMessage m = Get();
3719 DeleteArray(messages_);
3723 CommandMessage CommandMessageQueue::Get() {
3725 int result = start_;
3726 start_ = (start_ + 1) % size_;
3727 return messages_[result];
3731 void CommandMessageQueue::Put(const CommandMessage& message) {
3732 if ((end_ + 1) % size_ == start_) {
3735 messages_[end_] = message;
3736 end_ = (end_ + 1) % size_;
3740 void CommandMessageQueue::Expand() {
3741 CommandMessageQueue new_queue(size_ * 2);
3742 while (!IsEmpty()) {
3743 new_queue.Put(Get());
3745 CommandMessage* array_to_free = messages_;
3747 new_queue.messages_ = array_to_free;
3748 // Make the new_queue empty so that it doesn't call Dispose on any messages.
3749 new_queue.start_ = new_queue.end_;
3750 // Automatic destructor called on new_queue, freeing array_to_free.
3754 LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size)
3755 : logger_(logger), queue_(size) {}
3758 bool LockingCommandMessageQueue::IsEmpty() const {
3759 LockGuard<Mutex> lock_guard(&mutex_);
3760 return queue_.IsEmpty();
3764 CommandMessage LockingCommandMessageQueue::Get() {
3765 LockGuard<Mutex> lock_guard(&mutex_);
3766 CommandMessage result = queue_.Get();
3767 logger_->DebugEvent("Get", result.text());
3772 void LockingCommandMessageQueue::Put(const CommandMessage& message) {
3773 LockGuard<Mutex> lock_guard(&mutex_);
3774 queue_.Put(message);
3775 logger_->DebugEvent("Put", message.text());
3779 void LockingCommandMessageQueue::Clear() {
3780 LockGuard<Mutex> lock_guard(&mutex_);
3785 MessageDispatchHelperThread::MessageDispatchHelperThread(Isolate* isolate)
3786 : Thread("v8:MsgDispHelpr"),
3787 isolate_(isolate), sem_(0),
3788 already_signalled_(false) {
3792 void MessageDispatchHelperThread::Schedule() {
3794 LockGuard<Mutex> lock_guard(&mutex_);
3795 if (already_signalled_) {
3798 already_signalled_ = true;
3804 void MessageDispatchHelperThread::Run() {
3808 LockGuard<Mutex> lock_guard(&mutex_);
3809 already_signalled_ = false;
3812 Locker locker(reinterpret_cast<v8::Isolate*>(isolate_));
3813 isolate_->debugger()->CallMessageDispatchHandler();
3818 #endif // ENABLE_DEBUGGER_SUPPORT
3820 } } // namespace v8::internal