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