debug.cc revision 69a99ed0b2b2ef69d393c371b03db3a98aaf880e
1// Copyright 2011 the V8 project authors. All rights reserved. 2// Redistribution and use in source and binary forms, with or without 3// modification, are permitted provided that the following conditions are 4// met: 5// 6// * Redistributions of source code must retain the above copyright 7// notice, this list of conditions and the following disclaimer. 8// * Redistributions in binary form must reproduce the above 9// copyright notice, this list of conditions and the following 10// disclaimer in the documentation and/or other materials provided 11// with the distribution. 12// * Neither the name of Google Inc. nor the names of its 13// contributors may be used to endorse or promote products derived 14// from this software without specific prior written permission. 15// 16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 28#include "v8.h" 29 30#include "api.h" 31#include "arguments.h" 32#include "bootstrapper.h" 33#include "code-stubs.h" 34#include "codegen.h" 35#include "compilation-cache.h" 36#include "compiler.h" 37#include "debug.h" 38#include "deoptimizer.h" 39#include "execution.h" 40#include "global-handles.h" 41#include "ic.h" 42#include "ic-inl.h" 43#include "messages.h" 44#include "natives.h" 45#include "stub-cache.h" 46#include "log.h" 47 48#include "../include/v8-debug.h" 49 50namespace v8 { 51namespace internal { 52 53#ifdef ENABLE_DEBUGGER_SUPPORT 54 55 56Debug::Debug(Isolate* isolate) 57 : has_break_points_(false), 58 script_cache_(NULL), 59 debug_info_list_(NULL), 60 disable_break_(false), 61 break_on_exception_(false), 62 break_on_uncaught_exception_(false), 63 debug_break_return_(NULL), 64 debug_break_slot_(NULL), 65 isolate_(isolate) { 66 memset(registers_, 0, sizeof(JSCallerSavedBuffer)); 67} 68 69 70Debug::~Debug() { 71} 72 73 74static void PrintLn(v8::Local<v8::Value> value) { 75 v8::Local<v8::String> s = value->ToString(); 76 ScopedVector<char> data(s->Length() + 1); 77 if (data.start() == NULL) { 78 V8::FatalProcessOutOfMemory("PrintLn"); 79 return; 80 } 81 s->WriteAscii(data.start()); 82 PrintF("%s\n", data.start()); 83} 84 85 86static Handle<Code> ComputeCallDebugBreak(int argc, Code::Kind kind) { 87 Isolate* isolate = Isolate::Current(); 88 CALL_HEAP_FUNCTION( 89 isolate, 90 isolate->stub_cache()->ComputeCallDebugBreak(argc, kind), 91 Code); 92} 93 94 95static Handle<Code> ComputeCallDebugPrepareStepIn(int argc, Code::Kind kind) { 96 Isolate* isolate = Isolate::Current(); 97 CALL_HEAP_FUNCTION( 98 isolate, 99 isolate->stub_cache()->ComputeCallDebugPrepareStepIn(argc, kind), 100 Code); 101} 102 103 104static v8::Handle<v8::Context> GetDebugEventContext(Isolate* isolate) { 105 Handle<Context> context = isolate->debug()->debugger_entry()->GetContext(); 106 // Isolate::context() may have been NULL when "script collected" event 107 // occured. 108 if (context.is_null()) return v8::Local<v8::Context>(); 109 Handle<Context> global_context(context->global_context()); 110 return v8::Utils::ToLocal(global_context); 111} 112 113 114BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info, 115 BreakLocatorType type) { 116 debug_info_ = debug_info; 117 type_ = type; 118 reloc_iterator_ = NULL; 119 reloc_iterator_original_ = NULL; 120 Reset(); // Initialize the rest of the member variables. 121} 122 123 124BreakLocationIterator::~BreakLocationIterator() { 125 ASSERT(reloc_iterator_ != NULL); 126 ASSERT(reloc_iterator_original_ != NULL); 127 delete reloc_iterator_; 128 delete reloc_iterator_original_; 129} 130 131 132void BreakLocationIterator::Next() { 133 AssertNoAllocation nogc; 134 ASSERT(!RinfoDone()); 135 136 // Iterate through reloc info for code and original code stopping at each 137 // breakable code target. 138 bool first = break_point_ == -1; 139 while (!RinfoDone()) { 140 if (!first) RinfoNext(); 141 first = false; 142 if (RinfoDone()) return; 143 144 // Whenever a statement position or (plain) position is passed update the 145 // current value of these. 146 if (RelocInfo::IsPosition(rmode())) { 147 if (RelocInfo::IsStatementPosition(rmode())) { 148 statement_position_ = static_cast<int>( 149 rinfo()->data() - debug_info_->shared()->start_position()); 150 } 151 // Always update the position as we don't want that to be before the 152 // statement position. 153 position_ = static_cast<int>( 154 rinfo()->data() - debug_info_->shared()->start_position()); 155 ASSERT(position_ >= 0); 156 ASSERT(statement_position_ >= 0); 157 } 158 159 if (IsDebugBreakSlot()) { 160 // There is always a possible break point at a debug break slot. 161 break_point_++; 162 return; 163 } else if (RelocInfo::IsCodeTarget(rmode())) { 164 // Check for breakable code target. Look in the original code as setting 165 // break points can cause the code targets in the running (debugged) code 166 // to be of a different kind than in the original code. 167 Address target = original_rinfo()->target_address(); 168 Code* code = Code::GetCodeFromTargetAddress(target); 169 if ((code->is_inline_cache_stub() && 170 !code->is_binary_op_stub() && 171 !code->is_unary_op_stub() && 172 !code->is_compare_ic_stub() && 173 !code->is_to_boolean_ic_stub()) || 174 RelocInfo::IsConstructCall(rmode())) { 175 break_point_++; 176 return; 177 } 178 if (code->kind() == Code::STUB) { 179 if (IsDebuggerStatement()) { 180 break_point_++; 181 return; 182 } 183 if (type_ == ALL_BREAK_LOCATIONS) { 184 if (Debug::IsBreakStub(code)) { 185 break_point_++; 186 return; 187 } 188 } else { 189 ASSERT(type_ == SOURCE_BREAK_LOCATIONS); 190 if (Debug::IsSourceBreakStub(code)) { 191 break_point_++; 192 return; 193 } 194 } 195 } 196 } 197 198 // Check for break at return. 199 if (RelocInfo::IsJSReturn(rmode())) { 200 // Set the positions to the end of the function. 201 if (debug_info_->shared()->HasSourceCode()) { 202 position_ = debug_info_->shared()->end_position() - 203 debug_info_->shared()->start_position() - 1; 204 } else { 205 position_ = 0; 206 } 207 statement_position_ = position_; 208 break_point_++; 209 return; 210 } 211 } 212} 213 214 215void BreakLocationIterator::Next(int count) { 216 while (count > 0) { 217 Next(); 218 count--; 219 } 220} 221 222 223// Find the break point closest to the supplied address. 224void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) { 225 // Run through all break points to locate the one closest to the address. 226 int closest_break_point = 0; 227 int distance = kMaxInt; 228 while (!Done()) { 229 // Check if this break point is closer that what was previously found. 230 if (this->pc() < pc && pc - this->pc() < distance) { 231 closest_break_point = break_point(); 232 distance = static_cast<int>(pc - this->pc()); 233 // Check whether we can't get any closer. 234 if (distance == 0) break; 235 } 236 Next(); 237 } 238 239 // Move to the break point found. 240 Reset(); 241 Next(closest_break_point); 242} 243 244 245// Find the break point closest to the supplied source position. 246void BreakLocationIterator::FindBreakLocationFromPosition(int position) { 247 // Run through all break points to locate the one closest to the source 248 // position. 249 int closest_break_point = 0; 250 int distance = kMaxInt; 251 while (!Done()) { 252 // Check if this break point is closer that what was previously found. 253 if (position <= statement_position() && 254 statement_position() - position < distance) { 255 closest_break_point = break_point(); 256 distance = statement_position() - position; 257 // Check whether we can't get any closer. 258 if (distance == 0) break; 259 } 260 Next(); 261 } 262 263 // Move to the break point found. 264 Reset(); 265 Next(closest_break_point); 266} 267 268 269void BreakLocationIterator::Reset() { 270 // Create relocation iterators for the two code objects. 271 if (reloc_iterator_ != NULL) delete reloc_iterator_; 272 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_; 273 reloc_iterator_ = new RelocIterator(debug_info_->code()); 274 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code()); 275 276 // Position at the first break point. 277 break_point_ = -1; 278 position_ = 1; 279 statement_position_ = 1; 280 Next(); 281} 282 283 284bool BreakLocationIterator::Done() const { 285 return RinfoDone(); 286} 287 288 289void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) { 290 // If there is not already a real break point here patch code with debug 291 // break. 292 if (!HasBreakPoint()) { 293 SetDebugBreak(); 294 } 295 ASSERT(IsDebugBreak() || IsDebuggerStatement()); 296 // Set the break point information. 297 DebugInfo::SetBreakPoint(debug_info_, code_position(), 298 position(), statement_position(), 299 break_point_object); 300} 301 302 303void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) { 304 // Clear the break point information. 305 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object); 306 // If there are no more break points here remove the debug break. 307 if (!HasBreakPoint()) { 308 ClearDebugBreak(); 309 ASSERT(!IsDebugBreak()); 310 } 311} 312 313 314void BreakLocationIterator::SetOneShot() { 315 // Debugger statement always calls debugger. No need to modify it. 316 if (IsDebuggerStatement()) { 317 return; 318 } 319 320 // If there is a real break point here no more to do. 321 if (HasBreakPoint()) { 322 ASSERT(IsDebugBreak()); 323 return; 324 } 325 326 // Patch code with debug break. 327 SetDebugBreak(); 328} 329 330 331void BreakLocationIterator::ClearOneShot() { 332 // Debugger statement always calls debugger. No need to modify it. 333 if (IsDebuggerStatement()) { 334 return; 335 } 336 337 // If there is a real break point here no more to do. 338 if (HasBreakPoint()) { 339 ASSERT(IsDebugBreak()); 340 return; 341 } 342 343 // Patch code removing debug break. 344 ClearDebugBreak(); 345 ASSERT(!IsDebugBreak()); 346} 347 348 349void BreakLocationIterator::SetDebugBreak() { 350 // Debugger statement always calls debugger. No need to modify it. 351 if (IsDebuggerStatement()) { 352 return; 353 } 354 355 // If there is already a break point here just return. This might happen if 356 // the same code is flooded with break points twice. Flooding the same 357 // function twice might happen when stepping in a function with an exception 358 // handler as the handler and the function is the same. 359 if (IsDebugBreak()) { 360 return; 361 } 362 363 if (RelocInfo::IsJSReturn(rmode())) { 364 // Patch the frame exit code with a break point. 365 SetDebugBreakAtReturn(); 366 } else if (IsDebugBreakSlot()) { 367 // Patch the code in the break slot. 368 SetDebugBreakAtSlot(); 369 } else { 370 // Patch the IC call. 371 SetDebugBreakAtIC(); 372 } 373 ASSERT(IsDebugBreak()); 374} 375 376 377void BreakLocationIterator::ClearDebugBreak() { 378 // Debugger statement always calls debugger. No need to modify it. 379 if (IsDebuggerStatement()) { 380 return; 381 } 382 383 if (RelocInfo::IsJSReturn(rmode())) { 384 // Restore the frame exit code. 385 ClearDebugBreakAtReturn(); 386 } else if (IsDebugBreakSlot()) { 387 // Restore the code in the break slot. 388 ClearDebugBreakAtSlot(); 389 } else { 390 // Patch the IC call. 391 ClearDebugBreakAtIC(); 392 } 393 ASSERT(!IsDebugBreak()); 394} 395 396 397void BreakLocationIterator::PrepareStepIn() { 398 HandleScope scope; 399 400 // Step in can only be prepared if currently positioned on an IC call, 401 // construct call or CallFunction stub call. 402 Address target = rinfo()->target_address(); 403 Handle<Code> code(Code::GetCodeFromTargetAddress(target)); 404 if (code->is_call_stub() || code->is_keyed_call_stub()) { 405 // Step in through IC call is handled by the runtime system. Therefore make 406 // sure that the any current IC is cleared and the runtime system is 407 // called. If the executing code has a debug break at the location change 408 // the call in the original code as it is the code there that will be 409 // executed in place of the debug break call. 410 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count(), 411 code->kind()); 412 if (IsDebugBreak()) { 413 original_rinfo()->set_target_address(stub->entry()); 414 } else { 415 rinfo()->set_target_address(stub->entry()); 416 } 417 } else { 418#ifdef DEBUG 419 // All the following stuff is needed only for assertion checks so the code 420 // is wrapped in ifdef. 421 Handle<Code> maybe_call_function_stub = code; 422 if (IsDebugBreak()) { 423 Address original_target = original_rinfo()->target_address(); 424 maybe_call_function_stub = 425 Handle<Code>(Code::GetCodeFromTargetAddress(original_target)); 426 } 427 bool is_call_function_stub = 428 (maybe_call_function_stub->kind() == Code::STUB && 429 maybe_call_function_stub->major_key() == CodeStub::CallFunction); 430 431 // Step in through construct call requires no changes to the running code. 432 // Step in through getters/setters should already be prepared as well 433 // because caller of this function (Debug::PrepareStep) is expected to 434 // flood the top frame's function with one shot breakpoints. 435 // Step in through CallFunction stub should also be prepared by caller of 436 // this function (Debug::PrepareStep) which should flood target function 437 // with breakpoints. 438 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub() 439 || is_call_function_stub); 440#endif 441 } 442} 443 444 445// Check whether the break point is at a position which will exit the function. 446bool BreakLocationIterator::IsExit() const { 447 return (RelocInfo::IsJSReturn(rmode())); 448} 449 450 451bool BreakLocationIterator::HasBreakPoint() { 452 return debug_info_->HasBreakPoint(code_position()); 453} 454 455 456// Check whether there is a debug break at the current position. 457bool BreakLocationIterator::IsDebugBreak() { 458 if (RelocInfo::IsJSReturn(rmode())) { 459 return IsDebugBreakAtReturn(); 460 } else if (IsDebugBreakSlot()) { 461 return IsDebugBreakAtSlot(); 462 } else { 463 return Debug::IsDebugBreak(rinfo()->target_address()); 464 } 465} 466 467 468void BreakLocationIterator::SetDebugBreakAtIC() { 469 // Patch the original code with the current address as the current address 470 // might have changed by the inline caching since the code was copied. 471 original_rinfo()->set_target_address(rinfo()->target_address()); 472 473 RelocInfo::Mode mode = rmode(); 474 if (RelocInfo::IsCodeTarget(mode)) { 475 Address target = rinfo()->target_address(); 476 Handle<Code> code(Code::GetCodeFromTargetAddress(target)); 477 478 // Patch the code to invoke the builtin debug break function matching the 479 // calling convention used by the call site. 480 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode)); 481 rinfo()->set_target_address(dbgbrk_code->entry()); 482 } 483} 484 485 486void BreakLocationIterator::ClearDebugBreakAtIC() { 487 // Patch the code to the original invoke. 488 rinfo()->set_target_address(original_rinfo()->target_address()); 489} 490 491 492bool BreakLocationIterator::IsDebuggerStatement() { 493 return RelocInfo::DEBUG_BREAK == rmode(); 494} 495 496 497bool BreakLocationIterator::IsDebugBreakSlot() { 498 return RelocInfo::DEBUG_BREAK_SLOT == rmode(); 499} 500 501 502Object* BreakLocationIterator::BreakPointObjects() { 503 return debug_info_->GetBreakPointObjects(code_position()); 504} 505 506 507// Clear out all the debug break code. This is ONLY supposed to be used when 508// shutting down the debugger as it will leave the break point information in 509// DebugInfo even though the code is patched back to the non break point state. 510void BreakLocationIterator::ClearAllDebugBreak() { 511 while (!Done()) { 512 ClearDebugBreak(); 513 Next(); 514 } 515} 516 517 518bool BreakLocationIterator::RinfoDone() const { 519 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done()); 520 return reloc_iterator_->done(); 521} 522 523 524void BreakLocationIterator::RinfoNext() { 525 reloc_iterator_->next(); 526 reloc_iterator_original_->next(); 527#ifdef DEBUG 528 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done()); 529 if (!reloc_iterator_->done()) { 530 ASSERT(rmode() == original_rmode()); 531 } 532#endif 533} 534 535 536// Threading support. 537void Debug::ThreadInit() { 538 thread_local_.break_count_ = 0; 539 thread_local_.break_id_ = 0; 540 thread_local_.break_frame_id_ = StackFrame::NO_ID; 541 thread_local_.last_step_action_ = StepNone; 542 thread_local_.last_statement_position_ = RelocInfo::kNoPosition; 543 thread_local_.step_count_ = 0; 544 thread_local_.last_fp_ = 0; 545 thread_local_.step_into_fp_ = 0; 546 thread_local_.step_out_fp_ = 0; 547 thread_local_.after_break_target_ = 0; 548 // TODO(isolates): frames_are_dropped_? 549 thread_local_.debugger_entry_ = NULL; 550 thread_local_.pending_interrupts_ = 0; 551 thread_local_.restarter_frame_function_pointer_ = NULL; 552} 553 554 555char* Debug::ArchiveDebug(char* storage) { 556 char* to = storage; 557 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal)); 558 to += sizeof(ThreadLocal); 559 memcpy(to, reinterpret_cast<char*>(®isters_), sizeof(registers_)); 560 ThreadInit(); 561 ASSERT(to <= storage + ArchiveSpacePerThread()); 562 return storage + ArchiveSpacePerThread(); 563} 564 565 566char* Debug::RestoreDebug(char* storage) { 567 char* from = storage; 568 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal)); 569 from += sizeof(ThreadLocal); 570 memcpy(reinterpret_cast<char*>(®isters_), from, sizeof(registers_)); 571 ASSERT(from <= storage + ArchiveSpacePerThread()); 572 return storage + ArchiveSpacePerThread(); 573} 574 575 576int Debug::ArchiveSpacePerThread() { 577 return sizeof(ThreadLocal) + sizeof(JSCallerSavedBuffer); 578} 579 580 581// Frame structure (conforms InternalFrame structure): 582// -- code 583// -- SMI maker 584// -- function (slot is called "context") 585// -- frame base 586Object** Debug::SetUpFrameDropperFrame(StackFrame* bottom_js_frame, 587 Handle<Code> code) { 588 ASSERT(bottom_js_frame->is_java_script()); 589 590 Address fp = bottom_js_frame->fp(); 591 592 // Move function pointer into "context" slot. 593 Memory::Object_at(fp + StandardFrameConstants::kContextOffset) = 594 Memory::Object_at(fp + JavaScriptFrameConstants::kFunctionOffset); 595 596 Memory::Object_at(fp + InternalFrameConstants::kCodeOffset) = *code; 597 Memory::Object_at(fp + StandardFrameConstants::kMarkerOffset) = 598 Smi::FromInt(StackFrame::INTERNAL); 599 600 return reinterpret_cast<Object**>(&Memory::Object_at( 601 fp + StandardFrameConstants::kContextOffset)); 602} 603 604const int Debug::kFrameDropperFrameSize = 4; 605 606 607void ScriptCache::Add(Handle<Script> script) { 608 GlobalHandles* global_handles = Isolate::Current()->global_handles(); 609 // Create an entry in the hash map for the script. 610 int id = Smi::cast(script->id())->value(); 611 HashMap::Entry* entry = 612 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true); 613 if (entry->value != NULL) { 614 ASSERT(*script == *reinterpret_cast<Script**>(entry->value)); 615 return; 616 } 617 618 // Globalize the script object, make it weak and use the location of the 619 // global handle as the value in the hash map. 620 Handle<Script> script_ = 621 Handle<Script>::cast( 622 (global_handles->Create(*script))); 623 global_handles->MakeWeak( 624 reinterpret_cast<Object**>(script_.location()), 625 this, 626 ScriptCache::HandleWeakScript); 627 entry->value = script_.location(); 628} 629 630 631Handle<FixedArray> ScriptCache::GetScripts() { 632 Handle<FixedArray> instances = FACTORY->NewFixedArray(occupancy()); 633 int count = 0; 634 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) { 635 ASSERT(entry->value != NULL); 636 if (entry->value != NULL) { 637 instances->set(count, *reinterpret_cast<Script**>(entry->value)); 638 count++; 639 } 640 } 641 return instances; 642} 643 644 645void ScriptCache::ProcessCollectedScripts() { 646 Debugger* debugger = Isolate::Current()->debugger(); 647 for (int i = 0; i < collected_scripts_.length(); i++) { 648 debugger->OnScriptCollected(collected_scripts_[i]); 649 } 650 collected_scripts_.Clear(); 651} 652 653 654void ScriptCache::Clear() { 655 GlobalHandles* global_handles = Isolate::Current()->global_handles(); 656 // Iterate the script cache to get rid of all the weak handles. 657 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) { 658 ASSERT(entry != NULL); 659 Object** location = reinterpret_cast<Object**>(entry->value); 660 ASSERT((*location)->IsScript()); 661 global_handles->ClearWeakness(location); 662 global_handles->Destroy(location); 663 } 664 // Clear the content of the hash map. 665 HashMap::Clear(); 666} 667 668 669void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) { 670 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data); 671 // Find the location of the global handle. 672 Script** location = 673 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location()); 674 ASSERT((*location)->IsScript()); 675 676 // Remove the entry from the cache. 677 int id = Smi::cast((*location)->id())->value(); 678 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id)); 679 script_cache->collected_scripts_.Add(id); 680 681 // Clear the weak handle. 682 obj.Dispose(); 683 obj.Clear(); 684} 685 686 687void Debug::Setup(bool create_heap_objects) { 688 ThreadInit(); 689 if (create_heap_objects) { 690 // Get code to handle debug break on return. 691 debug_break_return_ = 692 isolate_->builtins()->builtin(Builtins::kReturn_DebugBreak); 693 ASSERT(debug_break_return_->IsCode()); 694 // Get code to handle debug break in debug break slots. 695 debug_break_slot_ = 696 isolate_->builtins()->builtin(Builtins::kSlot_DebugBreak); 697 ASSERT(debug_break_slot_->IsCode()); 698 } 699} 700 701 702void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) { 703 Debug* debug = Isolate::Current()->debug(); 704 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data); 705 // We need to clear all breakpoints associated with the function to restore 706 // original code and avoid patching the code twice later because 707 // the function will live in the heap until next gc, and can be found by 708 // Runtime::FindSharedFunctionInfoInScript. 709 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS); 710 it.ClearAllDebugBreak(); 711 debug->RemoveDebugInfo(node->debug_info()); 712#ifdef DEBUG 713 node = debug->debug_info_list_; 714 while (node != NULL) { 715 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data)); 716 node = node->next(); 717 } 718#endif 719} 720 721 722DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) { 723 GlobalHandles* global_handles = Isolate::Current()->global_handles(); 724 // Globalize the request debug info object and make it weak. 725 debug_info_ = Handle<DebugInfo>::cast( 726 (global_handles->Create(debug_info))); 727 global_handles->MakeWeak( 728 reinterpret_cast<Object**>(debug_info_.location()), 729 this, 730 Debug::HandleWeakDebugInfo); 731} 732 733 734DebugInfoListNode::~DebugInfoListNode() { 735 Isolate::Current()->global_handles()->Destroy( 736 reinterpret_cast<Object**>(debug_info_.location())); 737} 738 739 740bool Debug::CompileDebuggerScript(int index) { 741 Isolate* isolate = Isolate::Current(); 742 Factory* factory = isolate->factory(); 743 HandleScope scope(isolate); 744 745 // Bail out if the index is invalid. 746 if (index == -1) { 747 return false; 748 } 749 750 // Find source and name for the requested script. 751 Handle<String> source_code = 752 isolate->bootstrapper()->NativesSourceLookup(index); 753 Vector<const char> name = Natives::GetScriptName(index); 754 Handle<String> script_name = factory->NewStringFromAscii(name); 755 756 // Compile the script. 757 Handle<SharedFunctionInfo> function_info; 758 function_info = Compiler::Compile(source_code, 759 script_name, 760 0, 0, NULL, NULL, 761 Handle<String>::null(), 762 NATIVES_CODE); 763 764 // Silently ignore stack overflows during compilation. 765 if (function_info.is_null()) { 766 ASSERT(isolate->has_pending_exception()); 767 isolate->clear_pending_exception(); 768 return false; 769 } 770 771 // Execute the shared function in the debugger context. 772 Handle<Context> context = isolate->global_context(); 773 bool caught_exception = false; 774 Handle<JSFunction> function = 775 factory->NewFunctionFromSharedFunctionInfo(function_info, context); 776 777 Execution::TryCall(function, Handle<Object>(context->global()), 778 0, NULL, &caught_exception); 779 780 // Check for caught exceptions. 781 if (caught_exception) { 782 Handle<Object> message = MessageHandler::MakeMessageObject( 783 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(), 784 Handle<String>(), Handle<JSArray>()); 785 MessageHandler::ReportMessage(Isolate::Current(), NULL, message); 786 return false; 787 } 788 789 // Mark this script as native and return successfully. 790 Handle<Script> script(Script::cast(function->shared()->script())); 791 script->set_type(Smi::FromInt(Script::TYPE_NATIVE)); 792 return true; 793} 794 795 796bool Debug::Load() { 797 // Return if debugger is already loaded. 798 if (IsLoaded()) return true; 799 800 Debugger* debugger = isolate_->debugger(); 801 802 // Bail out if we're already in the process of compiling the native 803 // JavaScript source code for the debugger. 804 if (debugger->compiling_natives() || 805 debugger->is_loading_debugger()) 806 return false; 807 debugger->set_loading_debugger(true); 808 809 // Disable breakpoints and interrupts while compiling and running the 810 // debugger scripts including the context creation code. 811 DisableBreak disable(true); 812 PostponeInterruptsScope postpone(isolate_); 813 814 // Create the debugger context. 815 HandleScope scope(isolate_); 816 Handle<Context> context = 817 isolate_->bootstrapper()->CreateEnvironment( 818 isolate_, 819 Handle<Object>::null(), 820 v8::Handle<ObjectTemplate>(), 821 NULL); 822 823 // Use the debugger context. 824 SaveContext save(isolate_); 825 isolate_->set_context(*context); 826 827 // Expose the builtins object in the debugger context. 828 Handle<String> key = isolate_->factory()->LookupAsciiSymbol("builtins"); 829 Handle<GlobalObject> global = Handle<GlobalObject>(context->global()); 830 RETURN_IF_EMPTY_HANDLE_VALUE( 831 isolate_, 832 SetProperty(global, key, Handle<Object>(global->builtins()), 833 NONE, kNonStrictMode), 834 false); 835 836 // Compile the JavaScript for the debugger in the debugger context. 837 debugger->set_compiling_natives(true); 838 bool caught_exception = 839 !CompileDebuggerScript(Natives::GetIndex("mirror")) || 840 !CompileDebuggerScript(Natives::GetIndex("debug")); 841 842 if (FLAG_enable_liveedit) { 843 caught_exception = caught_exception || 844 !CompileDebuggerScript(Natives::GetIndex("liveedit")); 845 } 846 847 debugger->set_compiling_natives(false); 848 849 // Make sure we mark the debugger as not loading before we might 850 // return. 851 debugger->set_loading_debugger(false); 852 853 // Check for caught exceptions. 854 if (caught_exception) return false; 855 856 // Debugger loaded. 857 debug_context_ = context; 858 859 return true; 860} 861 862 863void Debug::Unload() { 864 // Return debugger is not loaded. 865 if (!IsLoaded()) { 866 return; 867 } 868 869 // Clear the script cache. 870 DestroyScriptCache(); 871 872 // Clear debugger context global handle. 873 Isolate::Current()->global_handles()->Destroy( 874 reinterpret_cast<Object**>(debug_context_.location())); 875 debug_context_ = Handle<Context>(); 876} 877 878 879// Set the flag indicating that preemption happened during debugging. 880void Debug::PreemptionWhileInDebugger() { 881 ASSERT(InDebugger()); 882 Debug::set_interrupts_pending(PREEMPT); 883} 884 885 886void Debug::Iterate(ObjectVisitor* v) { 887 v->VisitPointer(BitCast<Object**>(&(debug_break_return_))); 888 v->VisitPointer(BitCast<Object**>(&(debug_break_slot_))); 889} 890 891 892Object* Debug::Break(Arguments args) { 893 Heap* heap = isolate_->heap(); 894 HandleScope scope(isolate_); 895 ASSERT(args.length() == 0); 896 897 thread_local_.frame_drop_mode_ = FRAMES_UNTOUCHED; 898 899 // Get the top-most JavaScript frame. 900 JavaScriptFrameIterator it(isolate_); 901 JavaScriptFrame* frame = it.frame(); 902 903 // Just continue if breaks are disabled or debugger cannot be loaded. 904 if (disable_break() || !Load()) { 905 SetAfterBreakTarget(frame); 906 return heap->undefined_value(); 907 } 908 909 // Enter the debugger. 910 EnterDebugger debugger; 911 if (debugger.FailedToEnter()) { 912 return heap->undefined_value(); 913 } 914 915 // Postpone interrupt during breakpoint processing. 916 PostponeInterruptsScope postpone(isolate_); 917 918 // Get the debug info (create it if it does not exist). 919 Handle<SharedFunctionInfo> shared = 920 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared()); 921 Handle<DebugInfo> debug_info = GetDebugInfo(shared); 922 923 // Find the break point where execution has stopped. 924 BreakLocationIterator break_location_iterator(debug_info, 925 ALL_BREAK_LOCATIONS); 926 break_location_iterator.FindBreakLocationFromAddress(frame->pc()); 927 928 // Check whether step next reached a new statement. 929 if (!StepNextContinue(&break_location_iterator, frame)) { 930 // Decrease steps left if performing multiple steps. 931 if (thread_local_.step_count_ > 0) { 932 thread_local_.step_count_--; 933 } 934 } 935 936 // If there is one or more real break points check whether any of these are 937 // triggered. 938 Handle<Object> break_points_hit(heap->undefined_value()); 939 if (break_location_iterator.HasBreakPoint()) { 940 Handle<Object> break_point_objects = 941 Handle<Object>(break_location_iterator.BreakPointObjects()); 942 break_points_hit = CheckBreakPoints(break_point_objects); 943 } 944 945 // If step out is active skip everything until the frame where we need to step 946 // out to is reached, unless real breakpoint is hit. 947 if (StepOutActive() && frame->fp() != step_out_fp() && 948 break_points_hit->IsUndefined() ) { 949 // Step count should always be 0 for StepOut. 950 ASSERT(thread_local_.step_count_ == 0); 951 } else if (!break_points_hit->IsUndefined() || 952 (thread_local_.last_step_action_ != StepNone && 953 thread_local_.step_count_ == 0)) { 954 // Notify debugger if a real break point is triggered or if performing 955 // single stepping with no more steps to perform. Otherwise do another step. 956 957 // Clear all current stepping setup. 958 ClearStepping(); 959 960 // Notify the debug event listeners. 961 isolate_->debugger()->OnDebugBreak(break_points_hit, false); 962 } else if (thread_local_.last_step_action_ != StepNone) { 963 // Hold on to last step action as it is cleared by the call to 964 // ClearStepping. 965 StepAction step_action = thread_local_.last_step_action_; 966 int step_count = thread_local_.step_count_; 967 968 // Clear all current stepping setup. 969 ClearStepping(); 970 971 // Set up for the remaining steps. 972 PrepareStep(step_action, step_count); 973 } 974 975 if (thread_local_.frame_drop_mode_ == FRAMES_UNTOUCHED) { 976 SetAfterBreakTarget(frame); 977 } else if (thread_local_.frame_drop_mode_ == 978 FRAME_DROPPED_IN_IC_CALL) { 979 // We must have been calling IC stub. Do not go there anymore. 980 Code* plain_return = isolate_->builtins()->builtin( 981 Builtins::kPlainReturn_LiveEdit); 982 thread_local_.after_break_target_ = plain_return->entry(); 983 } else if (thread_local_.frame_drop_mode_ == 984 FRAME_DROPPED_IN_DEBUG_SLOT_CALL) { 985 // Debug break slot stub does not return normally, instead it manually 986 // cleans the stack and jumps. We should patch the jump address. 987 Code* plain_return = isolate_->builtins()->builtin( 988 Builtins::kFrameDropper_LiveEdit); 989 thread_local_.after_break_target_ = plain_return->entry(); 990 } else if (thread_local_.frame_drop_mode_ == 991 FRAME_DROPPED_IN_DIRECT_CALL) { 992 // Nothing to do, after_break_target is not used here. 993 } else if (thread_local_.frame_drop_mode_ == 994 FRAME_DROPPED_IN_RETURN_CALL) { 995 Code* plain_return = isolate_->builtins()->builtin( 996 Builtins::kFrameDropper_LiveEdit); 997 thread_local_.after_break_target_ = plain_return->entry(); 998 } else { 999 UNREACHABLE(); 1000 } 1001 1002 return heap->undefined_value(); 1003} 1004 1005 1006RUNTIME_FUNCTION(Object*, Debug_Break) { 1007 return isolate->debug()->Break(args); 1008} 1009 1010 1011// Check the break point objects for whether one or more are actually 1012// triggered. This function returns a JSArray with the break point objects 1013// which is triggered. 1014Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) { 1015 Factory* factory = isolate_->factory(); 1016 1017 // Count the number of break points hit. If there are multiple break points 1018 // they are in a FixedArray. 1019 Handle<FixedArray> break_points_hit; 1020 int break_points_hit_count = 0; 1021 ASSERT(!break_point_objects->IsUndefined()); 1022 if (break_point_objects->IsFixedArray()) { 1023 Handle<FixedArray> array(FixedArray::cast(*break_point_objects)); 1024 break_points_hit = factory->NewFixedArray(array->length()); 1025 for (int i = 0; i < array->length(); i++) { 1026 Handle<Object> o(array->get(i)); 1027 if (CheckBreakPoint(o)) { 1028 break_points_hit->set(break_points_hit_count++, *o); 1029 } 1030 } 1031 } else { 1032 break_points_hit = factory->NewFixedArray(1); 1033 if (CheckBreakPoint(break_point_objects)) { 1034 break_points_hit->set(break_points_hit_count++, *break_point_objects); 1035 } 1036 } 1037 1038 // Return undefined if no break points were triggered. 1039 if (break_points_hit_count == 0) { 1040 return factory->undefined_value(); 1041 } 1042 // Return break points hit as a JSArray. 1043 Handle<JSArray> result = factory->NewJSArrayWithElements(break_points_hit); 1044 result->set_length(Smi::FromInt(break_points_hit_count)); 1045 return result; 1046} 1047 1048 1049// Check whether a single break point object is triggered. 1050bool Debug::CheckBreakPoint(Handle<Object> break_point_object) { 1051 Factory* factory = isolate_->factory(); 1052 HandleScope scope(isolate_); 1053 1054 // Ignore check if break point object is not a JSObject. 1055 if (!break_point_object->IsJSObject()) return true; 1056 1057 // Get the function IsBreakPointTriggered (defined in debug-debugger.js). 1058 Handle<String> is_break_point_triggered_symbol = 1059 factory->LookupAsciiSymbol("IsBreakPointTriggered"); 1060 Handle<JSFunction> check_break_point = 1061 Handle<JSFunction>(JSFunction::cast( 1062 debug_context()->global()->GetPropertyNoExceptionThrown( 1063 *is_break_point_triggered_symbol))); 1064 1065 // Get the break id as an object. 1066 Handle<Object> break_id = factory->NewNumberFromInt(Debug::break_id()); 1067 1068 // Call HandleBreakPointx. 1069 bool caught_exception = false; 1070 const int argc = 2; 1071 Object** argv[argc] = { 1072 break_id.location(), 1073 reinterpret_cast<Object**>(break_point_object.location()) 1074 }; 1075 Handle<Object> result = Execution::TryCall(check_break_point, 1076 isolate_->js_builtins_object(), argc, argv, &caught_exception); 1077 1078 // If exception or non boolean result handle as not triggered 1079 if (caught_exception || !result->IsBoolean()) { 1080 return false; 1081 } 1082 1083 // Return whether the break point is triggered. 1084 ASSERT(!result.is_null()); 1085 return (*result)->IsTrue(); 1086} 1087 1088 1089// Check whether the function has debug information. 1090bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) { 1091 return !shared->debug_info()->IsUndefined(); 1092} 1093 1094 1095// Return the debug info for this function. EnsureDebugInfo must be called 1096// prior to ensure the debug info has been generated for shared. 1097Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) { 1098 ASSERT(HasDebugInfo(shared)); 1099 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info())); 1100} 1101 1102 1103void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared, 1104 Handle<Object> break_point_object, 1105 int* source_position) { 1106 HandleScope scope(isolate_); 1107 1108 if (!EnsureDebugInfo(shared)) { 1109 // Return if retrieving debug info failed. 1110 return; 1111 } 1112 1113 Handle<DebugInfo> debug_info = GetDebugInfo(shared); 1114 // Source positions starts with zero. 1115 ASSERT(source_position >= 0); 1116 1117 // Find the break point and change it. 1118 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS); 1119 it.FindBreakLocationFromPosition(*source_position); 1120 it.SetBreakPoint(break_point_object); 1121 1122 *source_position = it.position(); 1123 1124 // At least one active break point now. 1125 ASSERT(debug_info->GetBreakPointCount() > 0); 1126} 1127 1128 1129void Debug::ClearBreakPoint(Handle<Object> break_point_object) { 1130 HandleScope scope(isolate_); 1131 1132 DebugInfoListNode* node = debug_info_list_; 1133 while (node != NULL) { 1134 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(), 1135 break_point_object); 1136 if (!result->IsUndefined()) { 1137 // Get information in the break point. 1138 BreakPointInfo* break_point_info = BreakPointInfo::cast(result); 1139 Handle<DebugInfo> debug_info = node->debug_info(); 1140 Handle<SharedFunctionInfo> shared(debug_info->shared()); 1141 int source_position = break_point_info->statement_position()->value(); 1142 1143 // Source positions starts with zero. 1144 ASSERT(source_position >= 0); 1145 1146 // Find the break point and clear it. 1147 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS); 1148 it.FindBreakLocationFromPosition(source_position); 1149 it.ClearBreakPoint(break_point_object); 1150 1151 // If there are no more break points left remove the debug info for this 1152 // function. 1153 if (debug_info->GetBreakPointCount() == 0) { 1154 RemoveDebugInfo(debug_info); 1155 } 1156 1157 return; 1158 } 1159 node = node->next(); 1160 } 1161} 1162 1163 1164void Debug::ClearAllBreakPoints() { 1165 DebugInfoListNode* node = debug_info_list_; 1166 while (node != NULL) { 1167 // Remove all debug break code. 1168 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS); 1169 it.ClearAllDebugBreak(); 1170 node = node->next(); 1171 } 1172 1173 // Remove all debug info. 1174 while (debug_info_list_ != NULL) { 1175 RemoveDebugInfo(debug_info_list_->debug_info()); 1176 } 1177} 1178 1179 1180void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) { 1181 // Make sure the function has setup the debug info. 1182 if (!EnsureDebugInfo(shared)) { 1183 // Return if we failed to retrieve the debug info. 1184 return; 1185 } 1186 1187 // Flood the function with break points. 1188 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS); 1189 while (!it.Done()) { 1190 it.SetOneShot(); 1191 it.Next(); 1192 } 1193} 1194 1195 1196void Debug::FloodHandlerWithOneShot() { 1197 // Iterate through the JavaScript stack looking for handlers. 1198 StackFrame::Id id = break_frame_id(); 1199 if (id == StackFrame::NO_ID) { 1200 // If there is no JavaScript stack don't do anything. 1201 return; 1202 } 1203 for (JavaScriptFrameIterator it(isolate_, id); !it.done(); it.Advance()) { 1204 JavaScriptFrame* frame = it.frame(); 1205 if (frame->HasHandler()) { 1206 Handle<SharedFunctionInfo> shared = 1207 Handle<SharedFunctionInfo>( 1208 JSFunction::cast(frame->function())->shared()); 1209 // Flood the function with the catch block with break points 1210 FloodWithOneShot(shared); 1211 return; 1212 } 1213 } 1214} 1215 1216 1217void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) { 1218 if (type == BreakUncaughtException) { 1219 break_on_uncaught_exception_ = enable; 1220 } else { 1221 break_on_exception_ = enable; 1222 } 1223} 1224 1225 1226bool Debug::IsBreakOnException(ExceptionBreakType type) { 1227 if (type == BreakUncaughtException) { 1228 return break_on_uncaught_exception_; 1229 } else { 1230 return break_on_exception_; 1231 } 1232} 1233 1234 1235void Debug::PrepareStep(StepAction step_action, int step_count) { 1236 HandleScope scope(isolate_); 1237 ASSERT(Debug::InDebugger()); 1238 1239 // Remember this step action and count. 1240 thread_local_.last_step_action_ = step_action; 1241 if (step_action == StepOut) { 1242 // For step out target frame will be found on the stack so there is no need 1243 // to set step counter for it. It's expected to always be 0 for StepOut. 1244 thread_local_.step_count_ = 0; 1245 } else { 1246 thread_local_.step_count_ = step_count; 1247 } 1248 1249 // Get the frame where the execution has stopped and skip the debug frame if 1250 // any. The debug frame will only be present if execution was stopped due to 1251 // hitting a break point. In other situations (e.g. unhandled exception) the 1252 // debug frame is not present. 1253 StackFrame::Id id = break_frame_id(); 1254 if (id == StackFrame::NO_ID) { 1255 // If there is no JavaScript stack don't do anything. 1256 return; 1257 } 1258 JavaScriptFrameIterator frames_it(isolate_, id); 1259 JavaScriptFrame* frame = frames_it.frame(); 1260 1261 // First of all ensure there is one-shot break points in the top handler 1262 // if any. 1263 FloodHandlerWithOneShot(); 1264 1265 // If the function on the top frame is unresolved perform step out. This will 1266 // be the case when calling unknown functions and having the debugger stopped 1267 // in an unhandled exception. 1268 if (!frame->function()->IsJSFunction()) { 1269 // Step out: Find the calling JavaScript frame and flood it with 1270 // breakpoints. 1271 frames_it.Advance(); 1272 // Fill the function to return to with one-shot break points. 1273 JSFunction* function = JSFunction::cast(frames_it.frame()->function()); 1274 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared())); 1275 return; 1276 } 1277 1278 // Get the debug info (create it if it does not exist). 1279 Handle<SharedFunctionInfo> shared = 1280 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared()); 1281 if (!EnsureDebugInfo(shared)) { 1282 // Return if ensuring debug info failed. 1283 return; 1284 } 1285 Handle<DebugInfo> debug_info = GetDebugInfo(shared); 1286 1287 // Find the break location where execution has stopped. 1288 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS); 1289 it.FindBreakLocationFromAddress(frame->pc()); 1290 1291 // Compute whether or not the target is a call target. 1292 bool is_load_or_store = false; 1293 bool is_inline_cache_stub = false; 1294 bool is_at_restarted_function = false; 1295 Handle<Code> call_function_stub; 1296 1297 if (thread_local_.restarter_frame_function_pointer_ == NULL) { 1298 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) { 1299 bool is_call_target = false; 1300 Address target = it.rinfo()->target_address(); 1301 Code* code = Code::GetCodeFromTargetAddress(target); 1302 if (code->is_call_stub() || code->is_keyed_call_stub()) { 1303 is_call_target = true; 1304 } 1305 if (code->is_inline_cache_stub()) { 1306 is_inline_cache_stub = true; 1307 is_load_or_store = !is_call_target; 1308 } 1309 1310 // Check if target code is CallFunction stub. 1311 Code* maybe_call_function_stub = code; 1312 // If there is a breakpoint at this line look at the original code to 1313 // check if it is a CallFunction stub. 1314 if (it.IsDebugBreak()) { 1315 Address original_target = it.original_rinfo()->target_address(); 1316 maybe_call_function_stub = 1317 Code::GetCodeFromTargetAddress(original_target); 1318 } 1319 if (maybe_call_function_stub->kind() == Code::STUB && 1320 maybe_call_function_stub->major_key() == CodeStub::CallFunction) { 1321 // Save reference to the code as we may need it to find out arguments 1322 // count for 'step in' later. 1323 call_function_stub = Handle<Code>(maybe_call_function_stub); 1324 } 1325 } 1326 } else { 1327 is_at_restarted_function = true; 1328 } 1329 1330 // If this is the last break code target step out is the only possibility. 1331 if (it.IsExit() || step_action == StepOut) { 1332 if (step_action == StepOut) { 1333 // Skip step_count frames starting with the current one. 1334 while (step_count-- > 0 && !frames_it.done()) { 1335 frames_it.Advance(); 1336 } 1337 } else { 1338 ASSERT(it.IsExit()); 1339 frames_it.Advance(); 1340 } 1341 // Skip builtin functions on the stack. 1342 while (!frames_it.done() && 1343 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) { 1344 frames_it.Advance(); 1345 } 1346 // Step out: If there is a JavaScript caller frame, we need to 1347 // flood it with breakpoints. 1348 if (!frames_it.done()) { 1349 // Fill the function to return to with one-shot break points. 1350 JSFunction* function = JSFunction::cast(frames_it.frame()->function()); 1351 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared())); 1352 // Set target frame pointer. 1353 ActivateStepOut(frames_it.frame()); 1354 } 1355 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) || 1356 !call_function_stub.is_null() || is_at_restarted_function) 1357 || step_action == StepNext || step_action == StepMin) { 1358 // Step next or step min. 1359 1360 // Fill the current function with one-shot break points. 1361 FloodWithOneShot(shared); 1362 1363 // Remember source position and frame to handle step next. 1364 thread_local_.last_statement_position_ = 1365 debug_info->code()->SourceStatementPosition(frame->pc()); 1366 thread_local_.last_fp_ = frame->fp(); 1367 } else { 1368 // If there's restarter frame on top of the stack, just get the pointer 1369 // to function which is going to be restarted. 1370 if (is_at_restarted_function) { 1371 Handle<JSFunction> restarted_function( 1372 JSFunction::cast(*thread_local_.restarter_frame_function_pointer_)); 1373 Handle<SharedFunctionInfo> restarted_shared( 1374 restarted_function->shared()); 1375 FloodWithOneShot(restarted_shared); 1376 } else if (!call_function_stub.is_null()) { 1377 // If it's CallFunction stub ensure target function is compiled and flood 1378 // it with one shot breakpoints. 1379 1380 // Find out number of arguments from the stub minor key. 1381 // Reverse lookup required as the minor key cannot be retrieved 1382 // from the code object. 1383 Handle<Object> obj( 1384 isolate_->heap()->code_stubs()->SlowReverseLookup( 1385 *call_function_stub)); 1386 ASSERT(!obj.is_null()); 1387 ASSERT(!(*obj)->IsUndefined()); 1388 ASSERT(obj->IsSmi()); 1389 // Get the STUB key and extract major and minor key. 1390 uint32_t key = Smi::cast(*obj)->value(); 1391 // Argc in the stub is the number of arguments passed - not the 1392 // expected arguments of the called function. 1393 int call_function_arg_count = 1394 CallFunctionStub::ExtractArgcFromMinorKey( 1395 CodeStub::MinorKeyFromKey(key)); 1396 ASSERT(call_function_stub->major_key() == 1397 CodeStub::MajorKeyFromKey(key)); 1398 1399 // Find target function on the expression stack. 1400 // Expression stack looks like this (top to bottom): 1401 // argN 1402 // ... 1403 // arg0 1404 // Receiver 1405 // Function to call 1406 int expressions_count = frame->ComputeExpressionsCount(); 1407 ASSERT(expressions_count - 2 - call_function_arg_count >= 0); 1408 Object* fun = frame->GetExpression( 1409 expressions_count - 2 - call_function_arg_count); 1410 if (fun->IsJSFunction()) { 1411 Handle<JSFunction> js_function(JSFunction::cast(fun)); 1412 // Don't step into builtins. 1413 if (!js_function->IsBuiltin()) { 1414 // It will also compile target function if it's not compiled yet. 1415 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared())); 1416 } 1417 } 1418 } 1419 1420 // Fill the current function with one-shot break points even for step in on 1421 // a call target as the function called might be a native function for 1422 // which step in will not stop. It also prepares for stepping in 1423 // getters/setters. 1424 FloodWithOneShot(shared); 1425 1426 if (is_load_or_store) { 1427 // Remember source position and frame to handle step in getter/setter. If 1428 // there is a custom getter/setter it will be handled in 1429 // Object::Get/SetPropertyWithCallback, otherwise the step action will be 1430 // propagated on the next Debug::Break. 1431 thread_local_.last_statement_position_ = 1432 debug_info->code()->SourceStatementPosition(frame->pc()); 1433 thread_local_.last_fp_ = frame->fp(); 1434 } 1435 1436 // Step in or Step in min 1437 it.PrepareStepIn(); 1438 ActivateStepIn(frame); 1439 } 1440} 1441 1442 1443// Check whether the current debug break should be reported to the debugger. It 1444// is used to have step next and step in only report break back to the debugger 1445// if on a different frame or in a different statement. In some situations 1446// there will be several break points in the same statement when the code is 1447// flooded with one-shot break points. This function helps to perform several 1448// steps before reporting break back to the debugger. 1449bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator, 1450 JavaScriptFrame* frame) { 1451 // If the step last action was step next or step in make sure that a new 1452 // statement is hit. 1453 if (thread_local_.last_step_action_ == StepNext || 1454 thread_local_.last_step_action_ == StepIn) { 1455 // Never continue if returning from function. 1456 if (break_location_iterator->IsExit()) return false; 1457 1458 // Continue if we are still on the same frame and in the same statement. 1459 int current_statement_position = 1460 break_location_iterator->code()->SourceStatementPosition(frame->pc()); 1461 return thread_local_.last_fp_ == frame->fp() && 1462 thread_local_.last_statement_position_ == current_statement_position; 1463 } 1464 1465 // No step next action - don't continue. 1466 return false; 1467} 1468 1469 1470// Check whether the code object at the specified address is a debug break code 1471// object. 1472bool Debug::IsDebugBreak(Address addr) { 1473 Code* code = Code::GetCodeFromTargetAddress(addr); 1474 return code->ic_state() == DEBUG_BREAK; 1475} 1476 1477 1478// Check whether a code stub with the specified major key is a possible break 1479// point location when looking for source break locations. 1480bool Debug::IsSourceBreakStub(Code* code) { 1481 CodeStub::Major major_key = CodeStub::GetMajorKey(code); 1482 return major_key == CodeStub::CallFunction; 1483} 1484 1485 1486// Check whether a code stub with the specified major key is a possible break 1487// location. 1488bool Debug::IsBreakStub(Code* code) { 1489 CodeStub::Major major_key = CodeStub::GetMajorKey(code); 1490 return major_key == CodeStub::CallFunction; 1491} 1492 1493 1494// Find the builtin to use for invoking the debug break 1495Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) { 1496 // Find the builtin debug break function matching the calling convention 1497 // used by the call site. 1498 if (code->is_inline_cache_stub()) { 1499 switch (code->kind()) { 1500 case Code::CALL_IC: 1501 case Code::KEYED_CALL_IC: 1502 return ComputeCallDebugBreak(code->arguments_count(), code->kind()); 1503 1504 case Code::LOAD_IC: 1505 return Isolate::Current()->builtins()->LoadIC_DebugBreak(); 1506 1507 case Code::STORE_IC: 1508 return Isolate::Current()->builtins()->StoreIC_DebugBreak(); 1509 1510 case Code::KEYED_LOAD_IC: 1511 return Isolate::Current()->builtins()->KeyedLoadIC_DebugBreak(); 1512 1513 case Code::KEYED_STORE_IC: 1514 return Isolate::Current()->builtins()->KeyedStoreIC_DebugBreak(); 1515 1516 default: 1517 UNREACHABLE(); 1518 } 1519 } 1520 if (RelocInfo::IsConstructCall(mode)) { 1521 Handle<Code> result = 1522 Isolate::Current()->builtins()->ConstructCall_DebugBreak(); 1523 return result; 1524 } 1525 if (code->kind() == Code::STUB) { 1526 ASSERT(code->major_key() == CodeStub::CallFunction); 1527 Handle<Code> result = 1528 Isolate::Current()->builtins()->StubNoRegisters_DebugBreak(); 1529 return result; 1530 } 1531 1532 UNREACHABLE(); 1533 return Handle<Code>::null(); 1534} 1535 1536 1537// Simple function for returning the source positions for active break points. 1538Handle<Object> Debug::GetSourceBreakLocations( 1539 Handle<SharedFunctionInfo> shared) { 1540 Isolate* isolate = Isolate::Current(); 1541 Heap* heap = isolate->heap(); 1542 if (!HasDebugInfo(shared)) return Handle<Object>(heap->undefined_value()); 1543 Handle<DebugInfo> debug_info = GetDebugInfo(shared); 1544 if (debug_info->GetBreakPointCount() == 0) { 1545 return Handle<Object>(heap->undefined_value()); 1546 } 1547 Handle<FixedArray> locations = 1548 isolate->factory()->NewFixedArray(debug_info->GetBreakPointCount()); 1549 int count = 0; 1550 for (int i = 0; i < debug_info->break_points()->length(); i++) { 1551 if (!debug_info->break_points()->get(i)->IsUndefined()) { 1552 BreakPointInfo* break_point_info = 1553 BreakPointInfo::cast(debug_info->break_points()->get(i)); 1554 if (break_point_info->GetBreakPointCount() > 0) { 1555 locations->set(count++, break_point_info->statement_position()); 1556 } 1557 } 1558 } 1559 return locations; 1560} 1561 1562 1563void Debug::NewBreak(StackFrame::Id break_frame_id) { 1564 thread_local_.break_frame_id_ = break_frame_id; 1565 thread_local_.break_id_ = ++thread_local_.break_count_; 1566} 1567 1568 1569void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) { 1570 thread_local_.break_frame_id_ = break_frame_id; 1571 thread_local_.break_id_ = break_id; 1572} 1573 1574 1575// Handle stepping into a function. 1576void Debug::HandleStepIn(Handle<JSFunction> function, 1577 Handle<Object> holder, 1578 Address fp, 1579 bool is_constructor) { 1580 // If the frame pointer is not supplied by the caller find it. 1581 if (fp == 0) { 1582 StackFrameIterator it; 1583 it.Advance(); 1584 // For constructor functions skip another frame. 1585 if (is_constructor) { 1586 ASSERT(it.frame()->is_construct()); 1587 it.Advance(); 1588 } 1589 fp = it.frame()->fp(); 1590 } 1591 1592 // Flood the function with one-shot break points if it is called from where 1593 // step into was requested. 1594 if (fp == step_in_fp()) { 1595 // Don't allow step into functions in the native context. 1596 if (!function->IsBuiltin()) { 1597 if (function->shared()->code() == 1598 Isolate::Current()->builtins()->builtin(Builtins::kFunctionApply) || 1599 function->shared()->code() == 1600 Isolate::Current()->builtins()->builtin(Builtins::kFunctionCall)) { 1601 // Handle function.apply and function.call separately to flood the 1602 // function to be called and not the code for Builtins::FunctionApply or 1603 // Builtins::FunctionCall. The receiver of call/apply is the target 1604 // function. 1605 if (!holder.is_null() && holder->IsJSFunction() && 1606 !JSFunction::cast(*holder)->IsBuiltin()) { 1607 Handle<SharedFunctionInfo> shared_info( 1608 JSFunction::cast(*holder)->shared()); 1609 Debug::FloodWithOneShot(shared_info); 1610 } 1611 } else { 1612 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared())); 1613 } 1614 } 1615 } 1616} 1617 1618 1619void Debug::ClearStepping() { 1620 // Clear the various stepping setup. 1621 ClearOneShot(); 1622 ClearStepIn(); 1623 ClearStepOut(); 1624 ClearStepNext(); 1625 1626 // Clear multiple step counter. 1627 thread_local_.step_count_ = 0; 1628} 1629 1630// Clears all the one-shot break points that are currently set. Normally this 1631// function is called each time a break point is hit as one shot break points 1632// are used to support stepping. 1633void Debug::ClearOneShot() { 1634 // The current implementation just runs through all the breakpoints. When the 1635 // last break point for a function is removed that function is automatically 1636 // removed from the list. 1637 1638 DebugInfoListNode* node = debug_info_list_; 1639 while (node != NULL) { 1640 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS); 1641 while (!it.Done()) { 1642 it.ClearOneShot(); 1643 it.Next(); 1644 } 1645 node = node->next(); 1646 } 1647} 1648 1649 1650void Debug::ActivateStepIn(StackFrame* frame) { 1651 ASSERT(!StepOutActive()); 1652 thread_local_.step_into_fp_ = frame->fp(); 1653} 1654 1655 1656void Debug::ClearStepIn() { 1657 thread_local_.step_into_fp_ = 0; 1658} 1659 1660 1661void Debug::ActivateStepOut(StackFrame* frame) { 1662 ASSERT(!StepInActive()); 1663 thread_local_.step_out_fp_ = frame->fp(); 1664} 1665 1666 1667void Debug::ClearStepOut() { 1668 thread_local_.step_out_fp_ = 0; 1669} 1670 1671 1672void Debug::ClearStepNext() { 1673 thread_local_.last_step_action_ = StepNone; 1674 thread_local_.last_statement_position_ = RelocInfo::kNoPosition; 1675 thread_local_.last_fp_ = 0; 1676} 1677 1678 1679// Ensures the debug information is present for shared. 1680bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) { 1681 // Return if we already have the debug info for shared. 1682 if (HasDebugInfo(shared)) return true; 1683 1684 // Ensure shared in compiled. Return false if this failed. 1685 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false; 1686 1687 // If preparing for the first break point make sure to deoptimize all 1688 // functions as debugging does not work with optimized code. 1689 if (!has_break_points_) { 1690 Deoptimizer::DeoptimizeAll(); 1691 } 1692 1693 // Create the debug info object. 1694 Handle<DebugInfo> debug_info = FACTORY->NewDebugInfo(shared); 1695 1696 // Add debug info to the list. 1697 DebugInfoListNode* node = new DebugInfoListNode(*debug_info); 1698 node->set_next(debug_info_list_); 1699 debug_info_list_ = node; 1700 1701 // Now there is at least one break point. 1702 has_break_points_ = true; 1703 1704 return true; 1705} 1706 1707 1708void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) { 1709 ASSERT(debug_info_list_ != NULL); 1710 // Run through the debug info objects to find this one and remove it. 1711 DebugInfoListNode* prev = NULL; 1712 DebugInfoListNode* current = debug_info_list_; 1713 while (current != NULL) { 1714 if (*current->debug_info() == *debug_info) { 1715 // Unlink from list. If prev is NULL we are looking at the first element. 1716 if (prev == NULL) { 1717 debug_info_list_ = current->next(); 1718 } else { 1719 prev->set_next(current->next()); 1720 } 1721 current->debug_info()->shared()->set_debug_info( 1722 isolate_->heap()->undefined_value()); 1723 delete current; 1724 1725 // If there are no more debug info objects there are not more break 1726 // points. 1727 has_break_points_ = debug_info_list_ != NULL; 1728 1729 return; 1730 } 1731 // Move to next in list. 1732 prev = current; 1733 current = current->next(); 1734 } 1735 UNREACHABLE(); 1736} 1737 1738 1739void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) { 1740 HandleScope scope(isolate_); 1741 1742 // Get the executing function in which the debug break occurred. 1743 Handle<SharedFunctionInfo> shared = 1744 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared()); 1745 if (!EnsureDebugInfo(shared)) { 1746 // Return if we failed to retrieve the debug info. 1747 return; 1748 } 1749 Handle<DebugInfo> debug_info = GetDebugInfo(shared); 1750 Handle<Code> code(debug_info->code()); 1751 Handle<Code> original_code(debug_info->original_code()); 1752#ifdef DEBUG 1753 // Get the code which is actually executing. 1754 Handle<Code> frame_code(frame->LookupCode()); 1755 ASSERT(frame_code.is_identical_to(code)); 1756#endif 1757 1758 // Find the call address in the running code. This address holds the call to 1759 // either a DebugBreakXXX or to the debug break return entry code if the 1760 // break point is still active after processing the break point. 1761 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset; 1762 1763 // Check if the location is at JS exit or debug break slot. 1764 bool at_js_return = false; 1765 bool break_at_js_return_active = false; 1766 bool at_debug_break_slot = false; 1767 RelocIterator it(debug_info->code()); 1768 while (!it.done() && !at_js_return && !at_debug_break_slot) { 1769 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) { 1770 at_js_return = (it.rinfo()->pc() == 1771 addr - Assembler::kPatchReturnSequenceAddressOffset); 1772 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence(); 1773 } 1774 if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) { 1775 at_debug_break_slot = (it.rinfo()->pc() == 1776 addr - Assembler::kPatchDebugBreakSlotAddressOffset); 1777 } 1778 it.next(); 1779 } 1780 1781 // Handle the jump to continue execution after break point depending on the 1782 // break location. 1783 if (at_js_return) { 1784 // If the break point as return is still active jump to the corresponding 1785 // place in the original code. If not the break point was removed during 1786 // break point processing. 1787 if (break_at_js_return_active) { 1788 addr += original_code->instruction_start() - code->instruction_start(); 1789 } 1790 1791 // Move back to where the call instruction sequence started. 1792 thread_local_.after_break_target_ = 1793 addr - Assembler::kPatchReturnSequenceAddressOffset; 1794 } else if (at_debug_break_slot) { 1795 // Address of where the debug break slot starts. 1796 addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset; 1797 1798 // Continue just after the slot. 1799 thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength; 1800 } else if (IsDebugBreak(Assembler::target_address_at(addr))) { 1801 // We now know that there is still a debug break call at the target address, 1802 // so the break point is still there and the original code will hold the 1803 // address to jump to in order to complete the call which is replaced by a 1804 // call to DebugBreakXXX. 1805 1806 // Find the corresponding address in the original code. 1807 addr += original_code->instruction_start() - code->instruction_start(); 1808 1809 // Install jump to the call address in the original code. This will be the 1810 // call which was overwritten by the call to DebugBreakXXX. 1811 thread_local_.after_break_target_ = Assembler::target_address_at(addr); 1812 } else { 1813 // There is no longer a break point present. Don't try to look in the 1814 // original code as the running code will have the right address. This takes 1815 // care of the case where the last break point is removed from the function 1816 // and therefore no "original code" is available. 1817 thread_local_.after_break_target_ = Assembler::target_address_at(addr); 1818 } 1819} 1820 1821 1822bool Debug::IsBreakAtReturn(JavaScriptFrame* frame) { 1823 HandleScope scope(isolate_); 1824 1825 // If there are no break points this cannot be break at return, as 1826 // the debugger statement and stack guard bebug break cannot be at 1827 // return. 1828 if (!has_break_points_) { 1829 return false; 1830 } 1831 1832 // Get the executing function in which the debug break occurred. 1833 Handle<SharedFunctionInfo> shared = 1834 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared()); 1835 if (!EnsureDebugInfo(shared)) { 1836 // Return if we failed to retrieve the debug info. 1837 return false; 1838 } 1839 Handle<DebugInfo> debug_info = GetDebugInfo(shared); 1840 Handle<Code> code(debug_info->code()); 1841#ifdef DEBUG 1842 // Get the code which is actually executing. 1843 Handle<Code> frame_code(frame->LookupCode()); 1844 ASSERT(frame_code.is_identical_to(code)); 1845#endif 1846 1847 // Find the call address in the running code. 1848 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset; 1849 1850 // Check if the location is at JS return. 1851 RelocIterator it(debug_info->code()); 1852 while (!it.done()) { 1853 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) { 1854 return (it.rinfo()->pc() == 1855 addr - Assembler::kPatchReturnSequenceAddressOffset); 1856 } 1857 it.next(); 1858 } 1859 return false; 1860} 1861 1862 1863void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id, 1864 FrameDropMode mode, 1865 Object** restarter_frame_function_pointer) { 1866 thread_local_.frame_drop_mode_ = mode; 1867 thread_local_.break_frame_id_ = new_break_frame_id; 1868 thread_local_.restarter_frame_function_pointer_ = 1869 restarter_frame_function_pointer; 1870} 1871 1872 1873bool Debug::IsDebugGlobal(GlobalObject* global) { 1874 return IsLoaded() && global == debug_context()->global(); 1875} 1876 1877 1878void Debug::ClearMirrorCache() { 1879 PostponeInterruptsScope postpone(isolate_); 1880 HandleScope scope(isolate_); 1881 ASSERT(isolate_->context() == *Debug::debug_context()); 1882 1883 // Clear the mirror cache. 1884 Handle<String> function_name = 1885 isolate_->factory()->LookupSymbol(CStrVector("ClearMirrorCache")); 1886 Handle<Object> fun(Isolate::Current()->global()->GetPropertyNoExceptionThrown( 1887 *function_name)); 1888 ASSERT(fun->IsJSFunction()); 1889 bool caught_exception; 1890 Execution::TryCall(Handle<JSFunction>::cast(fun), 1891 Handle<JSObject>(Debug::debug_context()->global()), 1892 0, NULL, &caught_exception); 1893} 1894 1895 1896void Debug::CreateScriptCache() { 1897 Heap* heap = isolate_->heap(); 1898 HandleScope scope(isolate_); 1899 1900 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets 1901 // rid of all the cached script wrappers and the second gets rid of the 1902 // scripts which are no longer referenced. 1903 heap->CollectAllGarbage(false); 1904 heap->CollectAllGarbage(false); 1905 1906 ASSERT(script_cache_ == NULL); 1907 script_cache_ = new ScriptCache(); 1908 1909 // Scan heap for Script objects. 1910 int count = 0; 1911 HeapIterator iterator; 1912 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) { 1913 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) { 1914 script_cache_->Add(Handle<Script>(Script::cast(obj))); 1915 count++; 1916 } 1917 } 1918} 1919 1920 1921void Debug::DestroyScriptCache() { 1922 // Get rid of the script cache if it was created. 1923 if (script_cache_ != NULL) { 1924 delete script_cache_; 1925 script_cache_ = NULL; 1926 } 1927} 1928 1929 1930void Debug::AddScriptToScriptCache(Handle<Script> script) { 1931 if (script_cache_ != NULL) { 1932 script_cache_->Add(script); 1933 } 1934} 1935 1936 1937Handle<FixedArray> Debug::GetLoadedScripts() { 1938 // Create and fill the script cache when the loaded scripts is requested for 1939 // the first time. 1940 if (script_cache_ == NULL) { 1941 CreateScriptCache(); 1942 } 1943 1944 // If the script cache is not active just return an empty array. 1945 ASSERT(script_cache_ != NULL); 1946 if (script_cache_ == NULL) { 1947 isolate_->factory()->NewFixedArray(0); 1948 } 1949 1950 // Perform GC to get unreferenced scripts evicted from the cache before 1951 // returning the content. 1952 isolate_->heap()->CollectAllGarbage(false); 1953 1954 // Get the scripts from the cache. 1955 return script_cache_->GetScripts(); 1956} 1957 1958 1959void Debug::AfterGarbageCollection() { 1960 // Generate events for collected scripts. 1961 if (script_cache_ != NULL) { 1962 script_cache_->ProcessCollectedScripts(); 1963 } 1964} 1965 1966 1967Debugger::Debugger(Isolate* isolate) 1968 : debugger_access_(isolate->debugger_access()), 1969 event_listener_(Handle<Object>()), 1970 event_listener_data_(Handle<Object>()), 1971 compiling_natives_(false), 1972 is_loading_debugger_(false), 1973 never_unload_debugger_(false), 1974 message_handler_(NULL), 1975 debugger_unload_pending_(false), 1976 host_dispatch_handler_(NULL), 1977 dispatch_handler_access_(OS::CreateMutex()), 1978 debug_message_dispatch_handler_(NULL), 1979 message_dispatch_helper_thread_(NULL), 1980 host_dispatch_micros_(100 * 1000), 1981 agent_(NULL), 1982 command_queue_(isolate->logger(), kQueueInitialSize), 1983 command_received_(OS::CreateSemaphore(0)), 1984 event_command_queue_(isolate->logger(), kQueueInitialSize), 1985 isolate_(isolate) { 1986} 1987 1988 1989Debugger::~Debugger() { 1990 delete dispatch_handler_access_; 1991 dispatch_handler_access_ = 0; 1992 delete command_received_; 1993 command_received_ = 0; 1994} 1995 1996 1997Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name, 1998 int argc, Object*** argv, 1999 bool* caught_exception) { 2000 ASSERT(isolate_->context() == *isolate_->debug()->debug_context()); 2001 2002 // Create the execution state object. 2003 Handle<String> constructor_str = 2004 isolate_->factory()->LookupSymbol(constructor_name); 2005 Handle<Object> constructor( 2006 isolate_->global()->GetPropertyNoExceptionThrown(*constructor_str)); 2007 ASSERT(constructor->IsJSFunction()); 2008 if (!constructor->IsJSFunction()) { 2009 *caught_exception = true; 2010 return isolate_->factory()->undefined_value(); 2011 } 2012 Handle<Object> js_object = Execution::TryCall( 2013 Handle<JSFunction>::cast(constructor), 2014 Handle<JSObject>(isolate_->debug()->debug_context()->global()), 2015 argc, argv, caught_exception); 2016 return js_object; 2017} 2018 2019 2020Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) { 2021 // Create the execution state object. 2022 Handle<Object> break_id = isolate_->factory()->NewNumberFromInt( 2023 isolate_->debug()->break_id()); 2024 const int argc = 1; 2025 Object** argv[argc] = { break_id.location() }; 2026 return MakeJSObject(CStrVector("MakeExecutionState"), 2027 argc, argv, caught_exception); 2028} 2029 2030 2031Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state, 2032 Handle<Object> break_points_hit, 2033 bool* caught_exception) { 2034 // Create the new break event object. 2035 const int argc = 2; 2036 Object** argv[argc] = { exec_state.location(), 2037 break_points_hit.location() }; 2038 return MakeJSObject(CStrVector("MakeBreakEvent"), 2039 argc, 2040 argv, 2041 caught_exception); 2042} 2043 2044 2045Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state, 2046 Handle<Object> exception, 2047 bool uncaught, 2048 bool* caught_exception) { 2049 Factory* factory = isolate_->factory(); 2050 // Create the new exception event object. 2051 const int argc = 3; 2052 Object** argv[argc] = { exec_state.location(), 2053 exception.location(), 2054 uncaught ? factory->true_value().location() : 2055 factory->false_value().location()}; 2056 return MakeJSObject(CStrVector("MakeExceptionEvent"), 2057 argc, argv, caught_exception); 2058} 2059 2060 2061Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function, 2062 bool* caught_exception) { 2063 // Create the new function event object. 2064 const int argc = 1; 2065 Object** argv[argc] = { function.location() }; 2066 return MakeJSObject(CStrVector("MakeNewFunctionEvent"), 2067 argc, argv, caught_exception); 2068} 2069 2070 2071Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script, 2072 bool before, 2073 bool* caught_exception) { 2074 Factory* factory = isolate_->factory(); 2075 // Create the compile event object. 2076 Handle<Object> exec_state = MakeExecutionState(caught_exception); 2077 Handle<Object> script_wrapper = GetScriptWrapper(script); 2078 const int argc = 3; 2079 Object** argv[argc] = { exec_state.location(), 2080 script_wrapper.location(), 2081 before ? factory->true_value().location() : 2082 factory->false_value().location() }; 2083 2084 return MakeJSObject(CStrVector("MakeCompileEvent"), 2085 argc, 2086 argv, 2087 caught_exception); 2088} 2089 2090 2091Handle<Object> Debugger::MakeScriptCollectedEvent(int id, 2092 bool* caught_exception) { 2093 // Create the script collected event object. 2094 Handle<Object> exec_state = MakeExecutionState(caught_exception); 2095 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id)); 2096 const int argc = 2; 2097 Object** argv[argc] = { exec_state.location(), id_object.location() }; 2098 2099 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"), 2100 argc, 2101 argv, 2102 caught_exception); 2103} 2104 2105 2106void Debugger::OnException(Handle<Object> exception, bool uncaught) { 2107 HandleScope scope(isolate_); 2108 Debug* debug = isolate_->debug(); 2109 2110 // Bail out based on state or if there is no listener for this event 2111 if (debug->InDebugger()) return; 2112 if (!Debugger::EventActive(v8::Exception)) return; 2113 2114 // Bail out if exception breaks are not active 2115 if (uncaught) { 2116 // Uncaught exceptions are reported by either flags. 2117 if (!(debug->break_on_uncaught_exception() || 2118 debug->break_on_exception())) return; 2119 } else { 2120 // Caught exceptions are reported is activated. 2121 if (!debug->break_on_exception()) return; 2122 } 2123 2124 // Enter the debugger. 2125 EnterDebugger debugger; 2126 if (debugger.FailedToEnter()) return; 2127 2128 // Clear all current stepping setup. 2129 debug->ClearStepping(); 2130 // Create the event data object. 2131 bool caught_exception = false; 2132 Handle<Object> exec_state = MakeExecutionState(&caught_exception); 2133 Handle<Object> event_data; 2134 if (!caught_exception) { 2135 event_data = MakeExceptionEvent(exec_state, exception, uncaught, 2136 &caught_exception); 2137 } 2138 // Bail out and don't call debugger if exception. 2139 if (caught_exception) { 2140 return; 2141 } 2142 2143 // Process debug event. 2144 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false); 2145 // Return to continue execution from where the exception was thrown. 2146} 2147 2148 2149void Debugger::OnDebugBreak(Handle<Object> break_points_hit, 2150 bool auto_continue) { 2151 HandleScope scope(isolate_); 2152 2153 // Debugger has already been entered by caller. 2154 ASSERT(isolate_->context() == *isolate_->debug()->debug_context()); 2155 2156 // Bail out if there is no listener for this event 2157 if (!Debugger::EventActive(v8::Break)) return; 2158 2159 // Debugger must be entered in advance. 2160 ASSERT(isolate_->context() == *isolate_->debug()->debug_context()); 2161 2162 // Create the event data object. 2163 bool caught_exception = false; 2164 Handle<Object> exec_state = MakeExecutionState(&caught_exception); 2165 Handle<Object> event_data; 2166 if (!caught_exception) { 2167 event_data = MakeBreakEvent(exec_state, break_points_hit, 2168 &caught_exception); 2169 } 2170 // Bail out and don't call debugger if exception. 2171 if (caught_exception) { 2172 return; 2173 } 2174 2175 // Process debug event. 2176 ProcessDebugEvent(v8::Break, 2177 Handle<JSObject>::cast(event_data), 2178 auto_continue); 2179} 2180 2181 2182void Debugger::OnBeforeCompile(Handle<Script> script) { 2183 HandleScope scope(isolate_); 2184 2185 // Bail out based on state or if there is no listener for this event 2186 if (isolate_->debug()->InDebugger()) return; 2187 if (compiling_natives()) return; 2188 if (!EventActive(v8::BeforeCompile)) return; 2189 2190 // Enter the debugger. 2191 EnterDebugger debugger; 2192 if (debugger.FailedToEnter()) return; 2193 2194 // Create the event data object. 2195 bool caught_exception = false; 2196 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception); 2197 // Bail out and don't call debugger if exception. 2198 if (caught_exception) { 2199 return; 2200 } 2201 2202 // Process debug event. 2203 ProcessDebugEvent(v8::BeforeCompile, 2204 Handle<JSObject>::cast(event_data), 2205 true); 2206} 2207 2208 2209// Handle debugger actions when a new script is compiled. 2210void Debugger::OnAfterCompile(Handle<Script> script, 2211 AfterCompileFlags after_compile_flags) { 2212 HandleScope scope(isolate_); 2213 Debug* debug = isolate_->debug(); 2214 2215 // Add the newly compiled script to the script cache. 2216 debug->AddScriptToScriptCache(script); 2217 2218 // No more to do if not debugging. 2219 if (!IsDebuggerActive()) return; 2220 2221 // No compile events while compiling natives. 2222 if (compiling_natives()) return; 2223 2224 // Store whether in debugger before entering debugger. 2225 bool in_debugger = debug->InDebugger(); 2226 2227 // Enter the debugger. 2228 EnterDebugger debugger; 2229 if (debugger.FailedToEnter()) return; 2230 2231 // If debugging there might be script break points registered for this 2232 // script. Make sure that these break points are set. 2233 2234 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js). 2235 Handle<String> update_script_break_points_symbol = 2236 isolate_->factory()->LookupAsciiSymbol("UpdateScriptBreakPoints"); 2237 Handle<Object> update_script_break_points = 2238 Handle<Object>(debug->debug_context()->global()-> 2239 GetPropertyNoExceptionThrown(*update_script_break_points_symbol)); 2240 if (!update_script_break_points->IsJSFunction()) { 2241 return; 2242 } 2243 ASSERT(update_script_break_points->IsJSFunction()); 2244 2245 // Wrap the script object in a proper JS object before passing it 2246 // to JavaScript. 2247 Handle<JSValue> wrapper = GetScriptWrapper(script); 2248 2249 // Call UpdateScriptBreakPoints expect no exceptions. 2250 bool caught_exception = false; 2251 const int argc = 1; 2252 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) }; 2253 Execution::TryCall(Handle<JSFunction>::cast(update_script_break_points), 2254 Isolate::Current()->js_builtins_object(), argc, argv, 2255 &caught_exception); 2256 if (caught_exception) { 2257 return; 2258 } 2259 // Bail out based on state or if there is no listener for this event 2260 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return; 2261 if (!Debugger::EventActive(v8::AfterCompile)) return; 2262 2263 // Create the compile state object. 2264 Handle<Object> event_data = MakeCompileEvent(script, 2265 false, 2266 &caught_exception); 2267 // Bail out and don't call debugger if exception. 2268 if (caught_exception) { 2269 return; 2270 } 2271 // Process debug event. 2272 ProcessDebugEvent(v8::AfterCompile, 2273 Handle<JSObject>::cast(event_data), 2274 true); 2275} 2276 2277 2278void Debugger::OnScriptCollected(int id) { 2279 HandleScope scope(isolate_); 2280 2281 // No more to do if not debugging. 2282 if (!IsDebuggerActive()) return; 2283 if (!Debugger::EventActive(v8::ScriptCollected)) return; 2284 2285 // Enter the debugger. 2286 EnterDebugger debugger; 2287 if (debugger.FailedToEnter()) return; 2288 2289 // Create the script collected state object. 2290 bool caught_exception = false; 2291 Handle<Object> event_data = MakeScriptCollectedEvent(id, 2292 &caught_exception); 2293 // Bail out and don't call debugger if exception. 2294 if (caught_exception) { 2295 return; 2296 } 2297 2298 // Process debug event. 2299 ProcessDebugEvent(v8::ScriptCollected, 2300 Handle<JSObject>::cast(event_data), 2301 true); 2302} 2303 2304 2305void Debugger::ProcessDebugEvent(v8::DebugEvent event, 2306 Handle<JSObject> event_data, 2307 bool auto_continue) { 2308 HandleScope scope(isolate_); 2309 2310 // Clear any pending debug break if this is a real break. 2311 if (!auto_continue) { 2312 isolate_->debug()->clear_interrupt_pending(DEBUGBREAK); 2313 } 2314 2315 // Create the execution state. 2316 bool caught_exception = false; 2317 Handle<Object> exec_state = MakeExecutionState(&caught_exception); 2318 if (caught_exception) { 2319 return; 2320 } 2321 // First notify the message handler if any. 2322 if (message_handler_ != NULL) { 2323 NotifyMessageHandler(event, 2324 Handle<JSObject>::cast(exec_state), 2325 event_data, 2326 auto_continue); 2327 } 2328 // Notify registered debug event listener. This can be either a C or 2329 // a JavaScript function. Don't call event listener for v8::Break 2330 // here, if it's only a debug command -- they will be processed later. 2331 if ((event != v8::Break || !auto_continue) && !event_listener_.is_null()) { 2332 CallEventCallback(event, exec_state, event_data, NULL); 2333 } 2334 // Process pending debug commands. 2335 if (event == v8::Break) { 2336 while (!event_command_queue_.IsEmpty()) { 2337 CommandMessage command = event_command_queue_.Get(); 2338 if (!event_listener_.is_null()) { 2339 CallEventCallback(v8::BreakForCommand, 2340 exec_state, 2341 event_data, 2342 command.client_data()); 2343 } 2344 command.Dispose(); 2345 } 2346 } 2347} 2348 2349 2350void Debugger::CallEventCallback(v8::DebugEvent event, 2351 Handle<Object> exec_state, 2352 Handle<Object> event_data, 2353 v8::Debug::ClientData* client_data) { 2354 if (event_listener_->IsForeign()) { 2355 CallCEventCallback(event, exec_state, event_data, client_data); 2356 } else { 2357 CallJSEventCallback(event, exec_state, event_data); 2358 } 2359} 2360 2361 2362void Debugger::CallCEventCallback(v8::DebugEvent event, 2363 Handle<Object> exec_state, 2364 Handle<Object> event_data, 2365 v8::Debug::ClientData* client_data) { 2366 Handle<Foreign> callback_obj(Handle<Foreign>::cast(event_listener_)); 2367 v8::Debug::EventCallback2 callback = 2368 FUNCTION_CAST<v8::Debug::EventCallback2>(callback_obj->address()); 2369 EventDetailsImpl event_details( 2370 event, 2371 Handle<JSObject>::cast(exec_state), 2372 Handle<JSObject>::cast(event_data), 2373 event_listener_data_, 2374 client_data); 2375 callback(event_details); 2376} 2377 2378 2379void Debugger::CallJSEventCallback(v8::DebugEvent event, 2380 Handle<Object> exec_state, 2381 Handle<Object> event_data) { 2382 ASSERT(event_listener_->IsJSFunction()); 2383 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_)); 2384 2385 // Invoke the JavaScript debug event listener. 2386 const int argc = 4; 2387 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(), 2388 exec_state.location(), 2389 Handle<Object>::cast(event_data).location(), 2390 event_listener_data_.location() }; 2391 bool caught_exception = false; 2392 Execution::TryCall(fun, isolate_->global(), argc, argv, &caught_exception); 2393 // Silently ignore exceptions from debug event listeners. 2394} 2395 2396 2397Handle<Context> Debugger::GetDebugContext() { 2398 never_unload_debugger_ = true; 2399 EnterDebugger debugger; 2400 return isolate_->debug()->debug_context(); 2401} 2402 2403 2404void Debugger::UnloadDebugger() { 2405 Debug* debug = isolate_->debug(); 2406 2407 // Make sure that there are no breakpoints left. 2408 debug->ClearAllBreakPoints(); 2409 2410 // Unload the debugger if feasible. 2411 if (!never_unload_debugger_) { 2412 debug->Unload(); 2413 } 2414 2415 // Clear the flag indicating that the debugger should be unloaded. 2416 debugger_unload_pending_ = false; 2417} 2418 2419 2420void Debugger::NotifyMessageHandler(v8::DebugEvent event, 2421 Handle<JSObject> exec_state, 2422 Handle<JSObject> event_data, 2423 bool auto_continue) { 2424 HandleScope scope(isolate_); 2425 2426 if (!isolate_->debug()->Load()) return; 2427 2428 // Process the individual events. 2429 bool sendEventMessage = false; 2430 switch (event) { 2431 case v8::Break: 2432 case v8::BreakForCommand: 2433 sendEventMessage = !auto_continue; 2434 break; 2435 case v8::Exception: 2436 sendEventMessage = true; 2437 break; 2438 case v8::BeforeCompile: 2439 break; 2440 case v8::AfterCompile: 2441 sendEventMessage = true; 2442 break; 2443 case v8::ScriptCollected: 2444 sendEventMessage = true; 2445 break; 2446 case v8::NewFunction: 2447 break; 2448 default: 2449 UNREACHABLE(); 2450 } 2451 2452 // The debug command interrupt flag might have been set when the command was 2453 // added. It should be enough to clear the flag only once while we are in the 2454 // debugger. 2455 ASSERT(isolate_->debug()->InDebugger()); 2456 isolate_->stack_guard()->Continue(DEBUGCOMMAND); 2457 2458 // Notify the debugger that a debug event has occurred unless auto continue is 2459 // active in which case no event is send. 2460 if (sendEventMessage) { 2461 MessageImpl message = MessageImpl::NewEvent( 2462 event, 2463 auto_continue, 2464 Handle<JSObject>::cast(exec_state), 2465 Handle<JSObject>::cast(event_data)); 2466 InvokeMessageHandler(message); 2467 } 2468 2469 // If auto continue don't make the event cause a break, but process messages 2470 // in the queue if any. For script collected events don't even process 2471 // messages in the queue as the execution state might not be what is expected 2472 // by the client. 2473 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) { 2474 return; 2475 } 2476 2477 v8::TryCatch try_catch; 2478 2479 // DebugCommandProcessor goes here. 2480 v8::Local<v8::Object> cmd_processor; 2481 { 2482 v8::Local<v8::Object> api_exec_state = 2483 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)); 2484 v8::Local<v8::String> fun_name = 2485 v8::String::New("debugCommandProcessor"); 2486 v8::Local<v8::Function> fun = 2487 v8::Function::Cast(*api_exec_state->Get(fun_name)); 2488 2489 v8::Handle<v8::Boolean> running = 2490 auto_continue ? v8::True() : v8::False(); 2491 static const int kArgc = 1; 2492 v8::Handle<Value> argv[kArgc] = { running }; 2493 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv)); 2494 if (try_catch.HasCaught()) { 2495 PrintLn(try_catch.Exception()); 2496 return; 2497 } 2498 } 2499 2500 bool running = auto_continue; 2501 2502 // Process requests from the debugger. 2503 while (true) { 2504 // Wait for new command in the queue. 2505 if (Debugger::host_dispatch_handler_) { 2506 // In case there is a host dispatch - do periodic dispatches. 2507 if (!command_received_->Wait(host_dispatch_micros_)) { 2508 // Timout expired, do the dispatch. 2509 Debugger::host_dispatch_handler_(); 2510 continue; 2511 } 2512 } else { 2513 // In case there is no host dispatch - just wait. 2514 command_received_->Wait(); 2515 } 2516 2517 // Get the command from the queue. 2518 CommandMessage command = command_queue_.Get(); 2519 isolate_->logger()->DebugTag( 2520 "Got request from command queue, in interactive loop."); 2521 if (!Debugger::IsDebuggerActive()) { 2522 // Delete command text and user data. 2523 command.Dispose(); 2524 return; 2525 } 2526 2527 // Invoke JavaScript to process the debug request. 2528 v8::Local<v8::String> fun_name; 2529 v8::Local<v8::Function> fun; 2530 v8::Local<v8::Value> request; 2531 v8::TryCatch try_catch; 2532 fun_name = v8::String::New("processDebugRequest"); 2533 fun = v8::Function::Cast(*cmd_processor->Get(fun_name)); 2534 2535 request = v8::String::New(command.text().start(), 2536 command.text().length()); 2537 static const int kArgc = 1; 2538 v8::Handle<Value> argv[kArgc] = { request }; 2539 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv); 2540 2541 // Get the response. 2542 v8::Local<v8::String> response; 2543 if (!try_catch.HasCaught()) { 2544 // Get response string. 2545 if (!response_val->IsUndefined()) { 2546 response = v8::String::Cast(*response_val); 2547 } else { 2548 response = v8::String::New(""); 2549 } 2550 2551 // Log the JSON request/response. 2552 if (FLAG_trace_debug_json) { 2553 PrintLn(request); 2554 PrintLn(response); 2555 } 2556 2557 // Get the running state. 2558 fun_name = v8::String::New("isRunning"); 2559 fun = v8::Function::Cast(*cmd_processor->Get(fun_name)); 2560 static const int kArgc = 1; 2561 v8::Handle<Value> argv[kArgc] = { response }; 2562 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv); 2563 if (!try_catch.HasCaught()) { 2564 running = running_val->ToBoolean()->Value(); 2565 } 2566 } else { 2567 // In case of failure the result text is the exception text. 2568 response = try_catch.Exception()->ToString(); 2569 } 2570 2571 // Return the result. 2572 MessageImpl message = MessageImpl::NewResponse( 2573 event, 2574 running, 2575 Handle<JSObject>::cast(exec_state), 2576 Handle<JSObject>::cast(event_data), 2577 Handle<String>(Utils::OpenHandle(*response)), 2578 command.client_data()); 2579 InvokeMessageHandler(message); 2580 command.Dispose(); 2581 2582 // Return from debug event processing if either the VM is put into the 2583 // runnning state (through a continue command) or auto continue is active 2584 // and there are no more commands queued. 2585 if (running && !HasCommands()) { 2586 return; 2587 } 2588 } 2589} 2590 2591 2592void Debugger::SetEventListener(Handle<Object> callback, 2593 Handle<Object> data) { 2594 HandleScope scope(isolate_); 2595 GlobalHandles* global_handles = isolate_->global_handles(); 2596 2597 // Clear the global handles for the event listener and the event listener data 2598 // object. 2599 if (!event_listener_.is_null()) { 2600 global_handles->Destroy( 2601 reinterpret_cast<Object**>(event_listener_.location())); 2602 event_listener_ = Handle<Object>(); 2603 } 2604 if (!event_listener_data_.is_null()) { 2605 global_handles->Destroy( 2606 reinterpret_cast<Object**>(event_listener_data_.location())); 2607 event_listener_data_ = Handle<Object>(); 2608 } 2609 2610 // If there is a new debug event listener register it together with its data 2611 // object. 2612 if (!callback->IsUndefined() && !callback->IsNull()) { 2613 event_listener_ = Handle<Object>::cast( 2614 global_handles->Create(*callback)); 2615 if (data.is_null()) { 2616 data = isolate_->factory()->undefined_value(); 2617 } 2618 event_listener_data_ = Handle<Object>::cast( 2619 global_handles->Create(*data)); 2620 } 2621 2622 ListenersChanged(); 2623} 2624 2625 2626void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) { 2627 ScopedLock with(debugger_access_); 2628 2629 message_handler_ = handler; 2630 ListenersChanged(); 2631 if (handler == NULL) { 2632 // Send an empty command to the debugger if in a break to make JavaScript 2633 // run again if the debugger is closed. 2634 if (isolate_->debug()->InDebugger()) { 2635 ProcessCommand(Vector<const uint16_t>::empty()); 2636 } 2637 } 2638} 2639 2640 2641void Debugger::ListenersChanged() { 2642 if (IsDebuggerActive()) { 2643 // Disable the compilation cache when the debugger is active. 2644 isolate_->compilation_cache()->Disable(); 2645 debugger_unload_pending_ = false; 2646 } else { 2647 isolate_->compilation_cache()->Enable(); 2648 // Unload the debugger if event listener and message handler cleared. 2649 // Schedule this for later, because we may be in non-V8 thread. 2650 debugger_unload_pending_ = true; 2651 } 2652} 2653 2654 2655void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler, 2656 int period) { 2657 host_dispatch_handler_ = handler; 2658 host_dispatch_micros_ = period * 1000; 2659} 2660 2661 2662void Debugger::SetDebugMessageDispatchHandler( 2663 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) { 2664 ScopedLock with(dispatch_handler_access_); 2665 debug_message_dispatch_handler_ = handler; 2666 2667 if (provide_locker && message_dispatch_helper_thread_ == NULL) { 2668 message_dispatch_helper_thread_ = new MessageDispatchHelperThread(isolate_); 2669 message_dispatch_helper_thread_->Start(); 2670 } 2671} 2672 2673 2674// Calls the registered debug message handler. This callback is part of the 2675// public API. 2676void Debugger::InvokeMessageHandler(MessageImpl message) { 2677 ScopedLock with(debugger_access_); 2678 2679 if (message_handler_ != NULL) { 2680 message_handler_(message); 2681 } 2682} 2683 2684 2685// Puts a command coming from the public API on the queue. Creates 2686// a copy of the command string managed by the debugger. Up to this 2687// point, the command data was managed by the API client. Called 2688// by the API client thread. 2689void Debugger::ProcessCommand(Vector<const uint16_t> command, 2690 v8::Debug::ClientData* client_data) { 2691 // Need to cast away const. 2692 CommandMessage message = CommandMessage::New( 2693 Vector<uint16_t>(const_cast<uint16_t*>(command.start()), 2694 command.length()), 2695 client_data); 2696 isolate_->logger()->DebugTag("Put command on command_queue."); 2697 command_queue_.Put(message); 2698 command_received_->Signal(); 2699 2700 // Set the debug command break flag to have the command processed. 2701 if (!isolate_->debug()->InDebugger()) { 2702 isolate_->stack_guard()->DebugCommand(); 2703 } 2704 2705 MessageDispatchHelperThread* dispatch_thread; 2706 { 2707 ScopedLock with(dispatch_handler_access_); 2708 dispatch_thread = message_dispatch_helper_thread_; 2709 } 2710 2711 if (dispatch_thread == NULL) { 2712 CallMessageDispatchHandler(); 2713 } else { 2714 dispatch_thread->Schedule(); 2715 } 2716} 2717 2718 2719bool Debugger::HasCommands() { 2720 return !command_queue_.IsEmpty(); 2721} 2722 2723 2724void Debugger::EnqueueDebugCommand(v8::Debug::ClientData* client_data) { 2725 CommandMessage message = CommandMessage::New(Vector<uint16_t>(), client_data); 2726 event_command_queue_.Put(message); 2727 2728 // Set the debug command break flag to have the command processed. 2729 if (!isolate_->debug()->InDebugger()) { 2730 isolate_->stack_guard()->DebugCommand(); 2731 } 2732} 2733 2734 2735bool Debugger::IsDebuggerActive() { 2736 ScopedLock with(debugger_access_); 2737 2738 return message_handler_ != NULL || !event_listener_.is_null(); 2739} 2740 2741 2742Handle<Object> Debugger::Call(Handle<JSFunction> fun, 2743 Handle<Object> data, 2744 bool* pending_exception) { 2745 // When calling functions in the debugger prevent it from beeing unloaded. 2746 Debugger::never_unload_debugger_ = true; 2747 2748 // Enter the debugger. 2749 EnterDebugger debugger; 2750 if (debugger.FailedToEnter()) { 2751 return isolate_->factory()->undefined_value(); 2752 } 2753 2754 // Create the execution state. 2755 bool caught_exception = false; 2756 Handle<Object> exec_state = MakeExecutionState(&caught_exception); 2757 if (caught_exception) { 2758 return isolate_->factory()->undefined_value(); 2759 } 2760 2761 static const int kArgc = 2; 2762 Object** argv[kArgc] = { exec_state.location(), data.location() }; 2763 Handle<Object> result = Execution::Call( 2764 fun, 2765 Handle<Object>(isolate_->debug()->debug_context_->global_proxy()), 2766 kArgc, 2767 argv, 2768 pending_exception); 2769 return result; 2770} 2771 2772 2773static void StubMessageHandler2(const v8::Debug::Message& message) { 2774 // Simply ignore message. 2775} 2776 2777 2778bool Debugger::StartAgent(const char* name, int port, 2779 bool wait_for_connection) { 2780 ASSERT(Isolate::Current() == isolate_); 2781 if (wait_for_connection) { 2782 // Suspend V8 if it is already running or set V8 to suspend whenever 2783 // it starts. 2784 // Provide stub message handler; V8 auto-continues each suspend 2785 // when there is no message handler; we doesn't need it. 2786 // Once become suspended, V8 will stay so indefinitely long, until remote 2787 // debugger connects and issues "continue" command. 2788 Debugger::message_handler_ = StubMessageHandler2; 2789 v8::Debug::DebugBreak(); 2790 } 2791 2792 if (Socket::Setup()) { 2793 if (agent_ == NULL) { 2794 agent_ = new DebuggerAgent(name, port); 2795 agent_->Start(); 2796 } 2797 return true; 2798 } 2799 2800 return false; 2801} 2802 2803 2804void Debugger::StopAgent() { 2805 ASSERT(Isolate::Current() == isolate_); 2806 if (agent_ != NULL) { 2807 agent_->Shutdown(); 2808 agent_->Join(); 2809 delete agent_; 2810 agent_ = NULL; 2811 } 2812} 2813 2814 2815void Debugger::WaitForAgent() { 2816 ASSERT(Isolate::Current() == isolate_); 2817 if (agent_ != NULL) 2818 agent_->WaitUntilListening(); 2819} 2820 2821 2822void Debugger::CallMessageDispatchHandler() { 2823 v8::Debug::DebugMessageDispatchHandler handler; 2824 { 2825 ScopedLock with(dispatch_handler_access_); 2826 handler = Debugger::debug_message_dispatch_handler_; 2827 } 2828 if (handler != NULL) { 2829 handler(); 2830 } 2831} 2832 2833 2834MessageImpl MessageImpl::NewEvent(DebugEvent event, 2835 bool running, 2836 Handle<JSObject> exec_state, 2837 Handle<JSObject> event_data) { 2838 MessageImpl message(true, event, running, 2839 exec_state, event_data, Handle<String>(), NULL); 2840 return message; 2841} 2842 2843 2844MessageImpl MessageImpl::NewResponse(DebugEvent event, 2845 bool running, 2846 Handle<JSObject> exec_state, 2847 Handle<JSObject> event_data, 2848 Handle<String> response_json, 2849 v8::Debug::ClientData* client_data) { 2850 MessageImpl message(false, event, running, 2851 exec_state, event_data, response_json, client_data); 2852 return message; 2853} 2854 2855 2856MessageImpl::MessageImpl(bool is_event, 2857 DebugEvent event, 2858 bool running, 2859 Handle<JSObject> exec_state, 2860 Handle<JSObject> event_data, 2861 Handle<String> response_json, 2862 v8::Debug::ClientData* client_data) 2863 : is_event_(is_event), 2864 event_(event), 2865 running_(running), 2866 exec_state_(exec_state), 2867 event_data_(event_data), 2868 response_json_(response_json), 2869 client_data_(client_data) {} 2870 2871 2872bool MessageImpl::IsEvent() const { 2873 return is_event_; 2874} 2875 2876 2877bool MessageImpl::IsResponse() const { 2878 return !is_event_; 2879} 2880 2881 2882DebugEvent MessageImpl::GetEvent() const { 2883 return event_; 2884} 2885 2886 2887bool MessageImpl::WillStartRunning() const { 2888 return running_; 2889} 2890 2891 2892v8::Handle<v8::Object> MessageImpl::GetExecutionState() const { 2893 return v8::Utils::ToLocal(exec_state_); 2894} 2895 2896 2897v8::Handle<v8::Object> MessageImpl::GetEventData() const { 2898 return v8::Utils::ToLocal(event_data_); 2899} 2900 2901 2902v8::Handle<v8::String> MessageImpl::GetJSON() const { 2903 v8::HandleScope scope; 2904 2905 if (IsEvent()) { 2906 // Call toJSONProtocol on the debug event object. 2907 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol"); 2908 if (!fun->IsJSFunction()) { 2909 return v8::Handle<v8::String>(); 2910 } 2911 bool caught_exception; 2912 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun), 2913 event_data_, 2914 0, NULL, &caught_exception); 2915 if (caught_exception || !json->IsString()) { 2916 return v8::Handle<v8::String>(); 2917 } 2918 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json))); 2919 } else { 2920 return v8::Utils::ToLocal(response_json_); 2921 } 2922} 2923 2924 2925v8::Handle<v8::Context> MessageImpl::GetEventContext() const { 2926 Isolate* isolate = Isolate::Current(); 2927 v8::Handle<v8::Context> context = GetDebugEventContext(isolate); 2928 // Isolate::context() may be NULL when "script collected" event occures. 2929 ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected); 2930 return context; 2931} 2932 2933 2934v8::Debug::ClientData* MessageImpl::GetClientData() const { 2935 return client_data_; 2936} 2937 2938 2939EventDetailsImpl::EventDetailsImpl(DebugEvent event, 2940 Handle<JSObject> exec_state, 2941 Handle<JSObject> event_data, 2942 Handle<Object> callback_data, 2943 v8::Debug::ClientData* client_data) 2944 : event_(event), 2945 exec_state_(exec_state), 2946 event_data_(event_data), 2947 callback_data_(callback_data), 2948 client_data_(client_data) {} 2949 2950 2951DebugEvent EventDetailsImpl::GetEvent() const { 2952 return event_; 2953} 2954 2955 2956v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const { 2957 return v8::Utils::ToLocal(exec_state_); 2958} 2959 2960 2961v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const { 2962 return v8::Utils::ToLocal(event_data_); 2963} 2964 2965 2966v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const { 2967 return GetDebugEventContext(Isolate::Current()); 2968} 2969 2970 2971v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const { 2972 return v8::Utils::ToLocal(callback_data_); 2973} 2974 2975 2976v8::Debug::ClientData* EventDetailsImpl::GetClientData() const { 2977 return client_data_; 2978} 2979 2980 2981CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()), 2982 client_data_(NULL) { 2983} 2984 2985 2986CommandMessage::CommandMessage(const Vector<uint16_t>& text, 2987 v8::Debug::ClientData* data) 2988 : text_(text), 2989 client_data_(data) { 2990} 2991 2992 2993CommandMessage::~CommandMessage() { 2994} 2995 2996 2997void CommandMessage::Dispose() { 2998 text_.Dispose(); 2999 delete client_data_; 3000 client_data_ = NULL; 3001} 3002 3003 3004CommandMessage CommandMessage::New(const Vector<uint16_t>& command, 3005 v8::Debug::ClientData* data) { 3006 return CommandMessage(command.Clone(), data); 3007} 3008 3009 3010CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0), 3011 size_(size) { 3012 messages_ = NewArray<CommandMessage>(size); 3013} 3014 3015 3016CommandMessageQueue::~CommandMessageQueue() { 3017 while (!IsEmpty()) { 3018 CommandMessage m = Get(); 3019 m.Dispose(); 3020 } 3021 DeleteArray(messages_); 3022} 3023 3024 3025CommandMessage CommandMessageQueue::Get() { 3026 ASSERT(!IsEmpty()); 3027 int result = start_; 3028 start_ = (start_ + 1) % size_; 3029 return messages_[result]; 3030} 3031 3032 3033void CommandMessageQueue::Put(const CommandMessage& message) { 3034 if ((end_ + 1) % size_ == start_) { 3035 Expand(); 3036 } 3037 messages_[end_] = message; 3038 end_ = (end_ + 1) % size_; 3039} 3040 3041 3042void CommandMessageQueue::Expand() { 3043 CommandMessageQueue new_queue(size_ * 2); 3044 while (!IsEmpty()) { 3045 new_queue.Put(Get()); 3046 } 3047 CommandMessage* array_to_free = messages_; 3048 *this = new_queue; 3049 new_queue.messages_ = array_to_free; 3050 // Make the new_queue empty so that it doesn't call Dispose on any messages. 3051 new_queue.start_ = new_queue.end_; 3052 // Automatic destructor called on new_queue, freeing array_to_free. 3053} 3054 3055 3056LockingCommandMessageQueue::LockingCommandMessageQueue(Logger* logger, int size) 3057 : logger_(logger), queue_(size) { 3058 lock_ = OS::CreateMutex(); 3059} 3060 3061 3062LockingCommandMessageQueue::~LockingCommandMessageQueue() { 3063 delete lock_; 3064} 3065 3066 3067bool LockingCommandMessageQueue::IsEmpty() const { 3068 ScopedLock sl(lock_); 3069 return queue_.IsEmpty(); 3070} 3071 3072 3073CommandMessage LockingCommandMessageQueue::Get() { 3074 ScopedLock sl(lock_); 3075 CommandMessage result = queue_.Get(); 3076 logger_->DebugEvent("Get", result.text()); 3077 return result; 3078} 3079 3080 3081void LockingCommandMessageQueue::Put(const CommandMessage& message) { 3082 ScopedLock sl(lock_); 3083 queue_.Put(message); 3084 logger_->DebugEvent("Put", message.text()); 3085} 3086 3087 3088void LockingCommandMessageQueue::Clear() { 3089 ScopedLock sl(lock_); 3090 queue_.Clear(); 3091} 3092 3093 3094MessageDispatchHelperThread::MessageDispatchHelperThread(Isolate* isolate) 3095 : Thread("v8:MsgDispHelpr"), 3096 sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()), 3097 already_signalled_(false) { 3098} 3099 3100 3101MessageDispatchHelperThread::~MessageDispatchHelperThread() { 3102 delete mutex_; 3103 delete sem_; 3104} 3105 3106 3107void MessageDispatchHelperThread::Schedule() { 3108 { 3109 ScopedLock lock(mutex_); 3110 if (already_signalled_) { 3111 return; 3112 } 3113 already_signalled_ = true; 3114 } 3115 sem_->Signal(); 3116} 3117 3118 3119void MessageDispatchHelperThread::Run() { 3120 while (true) { 3121 sem_->Wait(); 3122 { 3123 ScopedLock lock(mutex_); 3124 already_signalled_ = false; 3125 } 3126 { 3127 Locker locker; 3128 Isolate::Current()->debugger()->CallMessageDispatchHandler(); 3129 } 3130 } 3131} 3132 3133#endif // ENABLE_DEBUGGER_SUPPORT 3134 3135} } // namespace v8::internal 3136