test-debug.cc revision f7060e27768c550ace7ec48ad8c093466db52dfa
1// Copyright 2007-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 <stdlib.h> 29 30#include "v8.h" 31 32#include "api.h" 33#include "compilation-cache.h" 34#include "debug.h" 35#include "platform.h" 36#include "stub-cache.h" 37#include "cctest.h" 38 39 40using ::v8::internal::EmbeddedVector; 41using ::v8::internal::Object; 42using ::v8::internal::OS; 43using ::v8::internal::Handle; 44using ::v8::internal::Heap; 45using ::v8::internal::JSGlobalProxy; 46using ::v8::internal::Code; 47using ::v8::internal::Debug; 48using ::v8::internal::Debugger; 49using ::v8::internal::CommandMessage; 50using ::v8::internal::CommandMessageQueue; 51using ::v8::internal::StepAction; 52using ::v8::internal::StepIn; // From StepAction enum 53using ::v8::internal::StepNext; // From StepAction enum 54using ::v8::internal::StepOut; // From StepAction enum 55using ::v8::internal::Vector; 56using ::v8::internal::StrLength; 57 58// Size of temp buffer for formatting small strings. 59#define SMALL_STRING_BUFFER_SIZE 80 60 61// --- A d d i t i o n a l C h e c k H e l p e r s 62 63 64// Helper function used by the CHECK_EQ function when given Address 65// arguments. Should not be called directly. 66static inline void CheckEqualsHelper(const char* file, int line, 67 const char* expected_source, 68 ::v8::internal::Address expected, 69 const char* value_source, 70 ::v8::internal::Address value) { 71 if (expected != value) { 72 V8_Fatal(file, line, "CHECK_EQ(%s, %s) failed\n# " 73 "Expected: %i\n# Found: %i", 74 expected_source, value_source, expected, value); 75 } 76} 77 78 79// Helper function used by the CHECK_NE function when given Address 80// arguments. Should not be called directly. 81static inline void CheckNonEqualsHelper(const char* file, int line, 82 const char* unexpected_source, 83 ::v8::internal::Address unexpected, 84 const char* value_source, 85 ::v8::internal::Address value) { 86 if (unexpected == value) { 87 V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %i", 88 unexpected_source, value_source, value); 89 } 90} 91 92 93// Helper function used by the CHECK function when given code 94// arguments. Should not be called directly. 95static inline void CheckEqualsHelper(const char* file, int line, 96 const char* expected_source, 97 const Code* expected, 98 const char* value_source, 99 const Code* value) { 100 if (expected != value) { 101 V8_Fatal(file, line, "CHECK_EQ(%s, %s) failed\n# " 102 "Expected: %p\n# Found: %p", 103 expected_source, value_source, expected, value); 104 } 105} 106 107 108static inline void CheckNonEqualsHelper(const char* file, int line, 109 const char* expected_source, 110 const Code* expected, 111 const char* value_source, 112 const Code* value) { 113 if (expected == value) { 114 V8_Fatal(file, line, "CHECK_NE(%s, %s) failed\n# Value: %p", 115 expected_source, value_source, value); 116 } 117} 118 119 120// --- H e l p e r C l a s s e s 121 122 123// Helper class for creating a V8 enviromnent for running tests 124class DebugLocalContext { 125 public: 126 inline DebugLocalContext( 127 v8::ExtensionConfiguration* extensions = 0, 128 v8::Handle<v8::ObjectTemplate> global_template = 129 v8::Handle<v8::ObjectTemplate>(), 130 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>()) 131 : context_(v8::Context::New(extensions, global_template, global_object)) { 132 context_->Enter(); 133 } 134 inline ~DebugLocalContext() { 135 context_->Exit(); 136 context_.Dispose(); 137 } 138 inline v8::Context* operator->() { return *context_; } 139 inline v8::Context* operator*() { return *context_; } 140 inline bool IsReady() { return !context_.IsEmpty(); } 141 void ExposeDebug() { 142 // Expose the debug context global object in the global object for testing. 143 Debug::Load(); 144 Debug::debug_context()->set_security_token( 145 v8::Utils::OpenHandle(*context_)->security_token()); 146 147 Handle<JSGlobalProxy> global(Handle<JSGlobalProxy>::cast( 148 v8::Utils::OpenHandle(*context_->Global()))); 149 Handle<v8::internal::String> debug_string = 150 v8::internal::Factory::LookupAsciiSymbol("debug"); 151 SetProperty(global, debug_string, 152 Handle<Object>(Debug::debug_context()->global_proxy()), DONT_ENUM); 153 } 154 private: 155 v8::Persistent<v8::Context> context_; 156}; 157 158 159// --- H e l p e r F u n c t i o n s 160 161 162// Compile and run the supplied source and return the fequested function. 163static v8::Local<v8::Function> CompileFunction(DebugLocalContext* env, 164 const char* source, 165 const char* function_name) { 166 v8::Script::Compile(v8::String::New(source))->Run(); 167 return v8::Local<v8::Function>::Cast( 168 (*env)->Global()->Get(v8::String::New(function_name))); 169} 170 171 172// Compile and run the supplied source and return the requested function. 173static v8::Local<v8::Function> CompileFunction(const char* source, 174 const char* function_name) { 175 v8::Script::Compile(v8::String::New(source))->Run(); 176 return v8::Local<v8::Function>::Cast( 177 v8::Context::GetCurrent()->Global()->Get(v8::String::New(function_name))); 178} 179 180 181// Is there any debug info for the function? 182static bool HasDebugInfo(v8::Handle<v8::Function> fun) { 183 Handle<v8::internal::JSFunction> f = v8::Utils::OpenHandle(*fun); 184 Handle<v8::internal::SharedFunctionInfo> shared(f->shared()); 185 return Debug::HasDebugInfo(shared); 186} 187 188 189// Set a break point in a function and return the associated break point 190// number. 191static int SetBreakPoint(Handle<v8::internal::JSFunction> fun, int position) { 192 static int break_point = 0; 193 Handle<v8::internal::SharedFunctionInfo> shared(fun->shared()); 194 Debug::SetBreakPoint( 195 shared, position, 196 Handle<Object>(v8::internal::Smi::FromInt(++break_point))); 197 return break_point; 198} 199 200 201// Set a break point in a function and return the associated break point 202// number. 203static int SetBreakPoint(v8::Handle<v8::Function> fun, int position) { 204 return SetBreakPoint(v8::Utils::OpenHandle(*fun), position); 205} 206 207 208// Set a break point in a function using the Debug object and return the 209// associated break point number. 210static int SetBreakPointFromJS(const char* function_name, 211 int line, int position) { 212 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 213 OS::SNPrintF(buffer, 214 "debug.Debug.setBreakPoint(%s,%d,%d)", 215 function_name, line, position); 216 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 217 v8::Handle<v8::String> str = v8::String::New(buffer.start()); 218 return v8::Script::Compile(str)->Run()->Int32Value(); 219} 220 221 222// Set a break point in a script identified by id using the global Debug object. 223static int SetScriptBreakPointByIdFromJS(int script_id, int line, int column) { 224 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 225 if (column >= 0) { 226 // Column specified set script break point on precise location. 227 OS::SNPrintF(buffer, 228 "debug.Debug.setScriptBreakPointById(%d,%d,%d)", 229 script_id, line, column); 230 } else { 231 // Column not specified set script break point on line. 232 OS::SNPrintF(buffer, 233 "debug.Debug.setScriptBreakPointById(%d,%d)", 234 script_id, line); 235 } 236 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 237 { 238 v8::TryCatch try_catch; 239 v8::Handle<v8::String> str = v8::String::New(buffer.start()); 240 v8::Handle<v8::Value> value = v8::Script::Compile(str)->Run(); 241 CHECK(!try_catch.HasCaught()); 242 return value->Int32Value(); 243 } 244} 245 246 247// Set a break point in a script identified by name using the global Debug 248// object. 249static int SetScriptBreakPointByNameFromJS(const char* script_name, 250 int line, int column) { 251 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 252 if (column >= 0) { 253 // Column specified set script break point on precise location. 254 OS::SNPrintF(buffer, 255 "debug.Debug.setScriptBreakPointByName(\"%s\",%d,%d)", 256 script_name, line, column); 257 } else { 258 // Column not specified set script break point on line. 259 OS::SNPrintF(buffer, 260 "debug.Debug.setScriptBreakPointByName(\"%s\",%d)", 261 script_name, line); 262 } 263 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 264 { 265 v8::TryCatch try_catch; 266 v8::Handle<v8::String> str = v8::String::New(buffer.start()); 267 v8::Handle<v8::Value> value = v8::Script::Compile(str)->Run(); 268 CHECK(!try_catch.HasCaught()); 269 return value->Int32Value(); 270 } 271} 272 273 274// Clear a break point. 275static void ClearBreakPoint(int break_point) { 276 Debug::ClearBreakPoint( 277 Handle<Object>(v8::internal::Smi::FromInt(break_point))); 278} 279 280 281// Clear a break point using the global Debug object. 282static void ClearBreakPointFromJS(int break_point_number) { 283 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 284 OS::SNPrintF(buffer, 285 "debug.Debug.clearBreakPoint(%d)", 286 break_point_number); 287 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 288 v8::Script::Compile(v8::String::New(buffer.start()))->Run(); 289} 290 291 292static void EnableScriptBreakPointFromJS(int break_point_number) { 293 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 294 OS::SNPrintF(buffer, 295 "debug.Debug.enableScriptBreakPoint(%d)", 296 break_point_number); 297 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 298 v8::Script::Compile(v8::String::New(buffer.start()))->Run(); 299} 300 301 302static void DisableScriptBreakPointFromJS(int break_point_number) { 303 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 304 OS::SNPrintF(buffer, 305 "debug.Debug.disableScriptBreakPoint(%d)", 306 break_point_number); 307 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 308 v8::Script::Compile(v8::String::New(buffer.start()))->Run(); 309} 310 311 312static void ChangeScriptBreakPointConditionFromJS(int break_point_number, 313 const char* condition) { 314 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 315 OS::SNPrintF(buffer, 316 "debug.Debug.changeScriptBreakPointCondition(%d, \"%s\")", 317 break_point_number, condition); 318 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 319 v8::Script::Compile(v8::String::New(buffer.start()))->Run(); 320} 321 322 323static void ChangeScriptBreakPointIgnoreCountFromJS(int break_point_number, 324 int ignoreCount) { 325 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 326 OS::SNPrintF(buffer, 327 "debug.Debug.changeScriptBreakPointIgnoreCount(%d, %d)", 328 break_point_number, ignoreCount); 329 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0'; 330 v8::Script::Compile(v8::String::New(buffer.start()))->Run(); 331} 332 333 334// Change break on exception. 335static void ChangeBreakOnException(bool caught, bool uncaught) { 336 Debug::ChangeBreakOnException(v8::internal::BreakException, caught); 337 Debug::ChangeBreakOnException(v8::internal::BreakUncaughtException, uncaught); 338} 339 340 341// Change break on exception using the global Debug object. 342static void ChangeBreakOnExceptionFromJS(bool caught, bool uncaught) { 343 if (caught) { 344 v8::Script::Compile( 345 v8::String::New("debug.Debug.setBreakOnException()"))->Run(); 346 } else { 347 v8::Script::Compile( 348 v8::String::New("debug.Debug.clearBreakOnException()"))->Run(); 349 } 350 if (uncaught) { 351 v8::Script::Compile( 352 v8::String::New("debug.Debug.setBreakOnUncaughtException()"))->Run(); 353 } else { 354 v8::Script::Compile( 355 v8::String::New("debug.Debug.clearBreakOnUncaughtException()"))->Run(); 356 } 357} 358 359 360// Prepare to step to next break location. 361static void PrepareStep(StepAction step_action) { 362 Debug::PrepareStep(step_action, 1); 363} 364 365 366// This function is in namespace v8::internal to be friend with class 367// v8::internal::Debug. 368namespace v8 { 369namespace internal { 370 371// Collect the currently debugged functions. 372Handle<FixedArray> GetDebuggedFunctions() { 373 v8::internal::DebugInfoListNode* node = Debug::debug_info_list_; 374 375 // Find the number of debugged functions. 376 int count = 0; 377 while (node) { 378 count++; 379 node = node->next(); 380 } 381 382 // Allocate array for the debugged functions 383 Handle<FixedArray> debugged_functions = 384 v8::internal::Factory::NewFixedArray(count); 385 386 // Run through the debug info objects and collect all functions. 387 count = 0; 388 while (node) { 389 debugged_functions->set(count++, *node->debug_info()); 390 node = node->next(); 391 } 392 393 return debugged_functions; 394} 395 396 397static Handle<Code> ComputeCallDebugBreak(int argc) { 398 CALL_HEAP_FUNCTION(v8::internal::StubCache::ComputeCallDebugBreak(argc), 399 Code); 400} 401 402 403// Check that the debugger has been fully unloaded. 404void CheckDebuggerUnloaded(bool check_functions) { 405 // Check that the debugger context is cleared and that there is no debug 406 // information stored for the debugger. 407 CHECK(Debug::debug_context().is_null()); 408 CHECK_EQ(NULL, Debug::debug_info_list_); 409 410 // Collect garbage to ensure weak handles are cleared. 411 Heap::CollectAllGarbage(false); 412 Heap::CollectAllGarbage(false); 413 414 // Iterate the head and check that there are no debugger related objects left. 415 HeapIterator iterator; 416 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) { 417 CHECK(!obj->IsDebugInfo()); 418 CHECK(!obj->IsBreakPointInfo()); 419 420 // If deep check of functions is requested check that no debug break code 421 // is left in all functions. 422 if (check_functions) { 423 if (obj->IsJSFunction()) { 424 JSFunction* fun = JSFunction::cast(obj); 425 for (RelocIterator it(fun->shared()->code()); !it.done(); it.next()) { 426 RelocInfo::Mode rmode = it.rinfo()->rmode(); 427 if (RelocInfo::IsCodeTarget(rmode)) { 428 CHECK(!Debug::IsDebugBreak(it.rinfo()->target_address())); 429 } else if (RelocInfo::IsJSReturn(rmode)) { 430 CHECK(!Debug::IsDebugBreakAtReturn(it.rinfo())); 431 } 432 } 433 } 434 } 435 } 436} 437 438 439void ForceUnloadDebugger() { 440 Debugger::never_unload_debugger_ = false; 441 Debugger::UnloadDebugger(); 442} 443 444 445} } // namespace v8::internal 446 447 448// Check that the debugger has been fully unloaded. 449static void CheckDebuggerUnloaded(bool check_functions = false) { 450 // Let debugger to unload itself synchronously 451 v8::Debug::ProcessDebugMessages(); 452 453 v8::internal::CheckDebuggerUnloaded(check_functions); 454} 455 456 457// Inherit from BreakLocationIterator to get access to protected parts for 458// testing. 459class TestBreakLocationIterator: public v8::internal::BreakLocationIterator { 460 public: 461 explicit TestBreakLocationIterator(Handle<v8::internal::DebugInfo> debug_info) 462 : BreakLocationIterator(debug_info, v8::internal::SOURCE_BREAK_LOCATIONS) {} 463 v8::internal::RelocIterator* it() { return reloc_iterator_; } 464 v8::internal::RelocIterator* it_original() { 465 return reloc_iterator_original_; 466 } 467}; 468 469 470// Compile a function, set a break point and check that the call at the break 471// location in the code is the expected debug_break function. 472void CheckDebugBreakFunction(DebugLocalContext* env, 473 const char* source, const char* name, 474 int position, v8::internal::RelocInfo::Mode mode, 475 Code* debug_break) { 476 // Create function and set the break point. 477 Handle<v8::internal::JSFunction> fun = v8::Utils::OpenHandle( 478 *CompileFunction(env, source, name)); 479 int bp = SetBreakPoint(fun, position); 480 481 // Check that the debug break function is as expected. 482 Handle<v8::internal::SharedFunctionInfo> shared(fun->shared()); 483 CHECK(Debug::HasDebugInfo(shared)); 484 TestBreakLocationIterator it1(Debug::GetDebugInfo(shared)); 485 it1.FindBreakLocationFromPosition(position); 486 CHECK_EQ(mode, it1.it()->rinfo()->rmode()); 487 if (mode != v8::internal::RelocInfo::JS_RETURN) { 488 CHECK_EQ(debug_break, 489 Code::GetCodeFromTargetAddress(it1.it()->rinfo()->target_address())); 490 } else { 491 CHECK(Debug::IsDebugBreakAtReturn(it1.it()->rinfo())); 492 } 493 494 // Clear the break point and check that the debug break function is no longer 495 // there 496 ClearBreakPoint(bp); 497 CHECK(!Debug::HasDebugInfo(shared)); 498 CHECK(Debug::EnsureDebugInfo(shared)); 499 TestBreakLocationIterator it2(Debug::GetDebugInfo(shared)); 500 it2.FindBreakLocationFromPosition(position); 501 CHECK_EQ(mode, it2.it()->rinfo()->rmode()); 502 if (mode == v8::internal::RelocInfo::JS_RETURN) { 503 CHECK(!Debug::IsDebugBreakAtReturn(it2.it()->rinfo())); 504 } 505} 506 507 508// --- D e b u g E v e n t H a n d l e r s 509// --- 510// --- The different tests uses a number of debug event handlers. 511// --- 512 513 514// Source for The JavaScript function which picks out the function name of the 515// top frame. 516const char* frame_function_name_source = 517 "function frame_function_name(exec_state) {" 518 " return exec_state.frame(0).func().name();" 519 "}"; 520v8::Local<v8::Function> frame_function_name; 521 522 523// Source for The JavaScript function which picks out the source line for the 524// top frame. 525const char* frame_source_line_source = 526 "function frame_source_line(exec_state) {" 527 " return exec_state.frame(0).sourceLine();" 528 "}"; 529v8::Local<v8::Function> frame_source_line; 530 531 532// Source for The JavaScript function which picks out the source column for the 533// top frame. 534const char* frame_source_column_source = 535 "function frame_source_column(exec_state) {" 536 " return exec_state.frame(0).sourceColumn();" 537 "}"; 538v8::Local<v8::Function> frame_source_column; 539 540 541// Source for The JavaScript function which picks out the script name for the 542// top frame. 543const char* frame_script_name_source = 544 "function frame_script_name(exec_state) {" 545 " return exec_state.frame(0).func().script().name();" 546 "}"; 547v8::Local<v8::Function> frame_script_name; 548 549 550// Source for The JavaScript function which picks out the script data for the 551// top frame. 552const char* frame_script_data_source = 553 "function frame_script_data(exec_state) {" 554 " return exec_state.frame(0).func().script().data();" 555 "}"; 556v8::Local<v8::Function> frame_script_data; 557 558 559// Source for The JavaScript function which picks out the script data from 560// AfterCompile event 561const char* compiled_script_data_source = 562 "function compiled_script_data(event_data) {" 563 " return event_data.script().data();" 564 "}"; 565v8::Local<v8::Function> compiled_script_data; 566 567 568// Source for The JavaScript function which returns the number of frames. 569static const char* frame_count_source = 570 "function frame_count(exec_state) {" 571 " return exec_state.frameCount();" 572 "}"; 573v8::Handle<v8::Function> frame_count; 574 575 576// Global variable to store the last function hit - used by some tests. 577char last_function_hit[80]; 578 579// Global variable to store the name and data for last script hit - used by some 580// tests. 581char last_script_name_hit[80]; 582char last_script_data_hit[80]; 583 584// Global variables to store the last source position - used by some tests. 585int last_source_line = -1; 586int last_source_column = -1; 587 588// Debug event handler which counts the break points which have been hit. 589int break_point_hit_count = 0; 590static void DebugEventBreakPointHitCount(v8::DebugEvent event, 591 v8::Handle<v8::Object> exec_state, 592 v8::Handle<v8::Object> event_data, 593 v8::Handle<v8::Value> data) { 594 // When hitting a debug event listener there must be a break set. 595 CHECK_NE(v8::internal::Debug::break_id(), 0); 596 597 // Count the number of breaks. 598 if (event == v8::Break) { 599 break_point_hit_count++; 600 if (!frame_function_name.IsEmpty()) { 601 // Get the name of the function. 602 const int argc = 1; 603 v8::Handle<v8::Value> argv[argc] = { exec_state }; 604 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state, 605 argc, argv); 606 if (result->IsUndefined()) { 607 last_function_hit[0] = '\0'; 608 } else { 609 CHECK(result->IsString()); 610 v8::Handle<v8::String> function_name(result->ToString()); 611 function_name->WriteAscii(last_function_hit); 612 } 613 } 614 615 if (!frame_source_line.IsEmpty()) { 616 // Get the source line. 617 const int argc = 1; 618 v8::Handle<v8::Value> argv[argc] = { exec_state }; 619 v8::Handle<v8::Value> result = frame_source_line->Call(exec_state, 620 argc, argv); 621 CHECK(result->IsNumber()); 622 last_source_line = result->Int32Value(); 623 } 624 625 if (!frame_source_column.IsEmpty()) { 626 // Get the source column. 627 const int argc = 1; 628 v8::Handle<v8::Value> argv[argc] = { exec_state }; 629 v8::Handle<v8::Value> result = frame_source_column->Call(exec_state, 630 argc, argv); 631 CHECK(result->IsNumber()); 632 last_source_column = result->Int32Value(); 633 } 634 635 if (!frame_script_name.IsEmpty()) { 636 // Get the script name of the function script. 637 const int argc = 1; 638 v8::Handle<v8::Value> argv[argc] = { exec_state }; 639 v8::Handle<v8::Value> result = frame_script_name->Call(exec_state, 640 argc, argv); 641 if (result->IsUndefined()) { 642 last_script_name_hit[0] = '\0'; 643 } else { 644 CHECK(result->IsString()); 645 v8::Handle<v8::String> script_name(result->ToString()); 646 script_name->WriteAscii(last_script_name_hit); 647 } 648 } 649 650 if (!frame_script_data.IsEmpty()) { 651 // Get the script data of the function script. 652 const int argc = 1; 653 v8::Handle<v8::Value> argv[argc] = { exec_state }; 654 v8::Handle<v8::Value> result = frame_script_data->Call(exec_state, 655 argc, argv); 656 if (result->IsUndefined()) { 657 last_script_data_hit[0] = '\0'; 658 } else { 659 result = result->ToString(); 660 CHECK(result->IsString()); 661 v8::Handle<v8::String> script_data(result->ToString()); 662 script_data->WriteAscii(last_script_data_hit); 663 } 664 } 665 } else if (event == v8::AfterCompile && !compiled_script_data.IsEmpty()) { 666 const int argc = 1; 667 v8::Handle<v8::Value> argv[argc] = { event_data }; 668 v8::Handle<v8::Value> result = compiled_script_data->Call(exec_state, 669 argc, argv); 670 if (result->IsUndefined()) { 671 last_script_data_hit[0] = '\0'; 672 } else { 673 result = result->ToString(); 674 CHECK(result->IsString()); 675 v8::Handle<v8::String> script_data(result->ToString()); 676 script_data->WriteAscii(last_script_data_hit); 677 } 678 } 679} 680 681 682// Debug event handler which counts a number of events and collects the stack 683// height if there is a function compiled for that. 684int exception_hit_count = 0; 685int uncaught_exception_hit_count = 0; 686int last_js_stack_height = -1; 687 688static void DebugEventCounterClear() { 689 break_point_hit_count = 0; 690 exception_hit_count = 0; 691 uncaught_exception_hit_count = 0; 692} 693 694static void DebugEventCounter(v8::DebugEvent event, 695 v8::Handle<v8::Object> exec_state, 696 v8::Handle<v8::Object> event_data, 697 v8::Handle<v8::Value> data) { 698 // When hitting a debug event listener there must be a break set. 699 CHECK_NE(v8::internal::Debug::break_id(), 0); 700 701 // Count the number of breaks. 702 if (event == v8::Break) { 703 break_point_hit_count++; 704 } else if (event == v8::Exception) { 705 exception_hit_count++; 706 707 // Check whether the exception was uncaught. 708 v8::Local<v8::String> fun_name = v8::String::New("uncaught"); 709 v8::Local<v8::Function> fun = 710 v8::Function::Cast(*event_data->Get(fun_name)); 711 v8::Local<v8::Value> result = *fun->Call(event_data, 0, NULL); 712 if (result->IsTrue()) { 713 uncaught_exception_hit_count++; 714 } 715 } 716 717 // Collect the JavsScript stack height if the function frame_count is 718 // compiled. 719 if (!frame_count.IsEmpty()) { 720 static const int kArgc = 1; 721 v8::Handle<v8::Value> argv[kArgc] = { exec_state }; 722 // Using exec_state as receiver is just to have a receiver. 723 v8::Handle<v8::Value> result = frame_count->Call(exec_state, kArgc, argv); 724 last_js_stack_height = result->Int32Value(); 725 } 726} 727 728 729// Debug event handler which evaluates a number of expressions when a break 730// point is hit. Each evaluated expression is compared with an expected value. 731// For this debug event handler to work the following two global varaibles 732// must be initialized. 733// checks: An array of expressions and expected results 734// evaluate_check_function: A JavaScript function (see below) 735 736// Structure for holding checks to do. 737struct EvaluateCheck { 738 const char* expr; // An expression to evaluate when a break point is hit. 739 v8::Handle<v8::Value> expected; // The expected result. 740}; 741// Array of checks to do. 742struct EvaluateCheck* checks = NULL; 743// Source for The JavaScript function which can do the evaluation when a break 744// point is hit. 745const char* evaluate_check_source = 746 "function evaluate_check(exec_state, expr, expected) {" 747 " return exec_state.frame(0).evaluate(expr).value() === expected;" 748 "}"; 749v8::Local<v8::Function> evaluate_check_function; 750 751// The actual debug event described by the longer comment above. 752static void DebugEventEvaluate(v8::DebugEvent event, 753 v8::Handle<v8::Object> exec_state, 754 v8::Handle<v8::Object> event_data, 755 v8::Handle<v8::Value> data) { 756 // When hitting a debug event listener there must be a break set. 757 CHECK_NE(v8::internal::Debug::break_id(), 0); 758 759 if (event == v8::Break) { 760 for (int i = 0; checks[i].expr != NULL; i++) { 761 const int argc = 3; 762 v8::Handle<v8::Value> argv[argc] = { exec_state, 763 v8::String::New(checks[i].expr), 764 checks[i].expected }; 765 v8::Handle<v8::Value> result = 766 evaluate_check_function->Call(exec_state, argc, argv); 767 if (!result->IsTrue()) { 768 v8::String::AsciiValue ascii(checks[i].expected->ToString()); 769 V8_Fatal(__FILE__, __LINE__, "%s != %s", checks[i].expr, *ascii); 770 } 771 } 772 } 773} 774 775 776// This debug event listener removes a breakpoint in a function 777int debug_event_remove_break_point = 0; 778static void DebugEventRemoveBreakPoint(v8::DebugEvent event, 779 v8::Handle<v8::Object> exec_state, 780 v8::Handle<v8::Object> event_data, 781 v8::Handle<v8::Value> data) { 782 // When hitting a debug event listener there must be a break set. 783 CHECK_NE(v8::internal::Debug::break_id(), 0); 784 785 if (event == v8::Break) { 786 break_point_hit_count++; 787 v8::Handle<v8::Function> fun = v8::Handle<v8::Function>::Cast(data); 788 ClearBreakPoint(debug_event_remove_break_point); 789 } 790} 791 792 793// Debug event handler which counts break points hit and performs a step 794// afterwards. 795StepAction step_action = StepIn; // Step action to perform when stepping. 796static void DebugEventStep(v8::DebugEvent event, 797 v8::Handle<v8::Object> exec_state, 798 v8::Handle<v8::Object> event_data, 799 v8::Handle<v8::Value> data) { 800 // When hitting a debug event listener there must be a break set. 801 CHECK_NE(v8::internal::Debug::break_id(), 0); 802 803 if (event == v8::Break) { 804 break_point_hit_count++; 805 PrepareStep(step_action); 806 } 807} 808 809 810// Debug event handler which counts break points hit and performs a step 811// afterwards. For each call the expected function is checked. 812// For this debug event handler to work the following two global varaibles 813// must be initialized. 814// expected_step_sequence: An array of the expected function call sequence. 815// frame_function_name: A JavaScript function (see below). 816 817// String containing the expected function call sequence. Note: this only works 818// if functions have name length of one. 819const char* expected_step_sequence = NULL; 820 821// The actual debug event described by the longer comment above. 822static void DebugEventStepSequence(v8::DebugEvent event, 823 v8::Handle<v8::Object> exec_state, 824 v8::Handle<v8::Object> event_data, 825 v8::Handle<v8::Value> data) { 826 // When hitting a debug event listener there must be a break set. 827 CHECK_NE(v8::internal::Debug::break_id(), 0); 828 829 if (event == v8::Break || event == v8::Exception) { 830 // Check that the current function is the expected. 831 CHECK(break_point_hit_count < 832 StrLength(expected_step_sequence)); 833 const int argc = 1; 834 v8::Handle<v8::Value> argv[argc] = { exec_state }; 835 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state, 836 argc, argv); 837 CHECK(result->IsString()); 838 v8::String::AsciiValue function_name(result->ToString()); 839 CHECK_EQ(1, StrLength(*function_name)); 840 CHECK_EQ((*function_name)[0], 841 expected_step_sequence[break_point_hit_count]); 842 843 // Perform step. 844 break_point_hit_count++; 845 PrepareStep(step_action); 846 } 847} 848 849 850// Debug event handler which performs a garbage collection. 851static void DebugEventBreakPointCollectGarbage( 852 v8::DebugEvent event, 853 v8::Handle<v8::Object> exec_state, 854 v8::Handle<v8::Object> event_data, 855 v8::Handle<v8::Value> data) { 856 // When hitting a debug event listener there must be a break set. 857 CHECK_NE(v8::internal::Debug::break_id(), 0); 858 859 // Perform a garbage collection when break point is hit and continue. Based 860 // on the number of break points hit either scavenge or mark compact 861 // collector is used. 862 if (event == v8::Break) { 863 break_point_hit_count++; 864 if (break_point_hit_count % 2 == 0) { 865 // Scavenge. 866 Heap::CollectGarbage(0, v8::internal::NEW_SPACE); 867 } else { 868 // Mark sweep (and perhaps compact). 869 Heap::CollectAllGarbage(false); 870 } 871 } 872} 873 874 875// Debug event handler which re-issues a debug break and calls the garbage 876// collector to have the heap verified. 877static void DebugEventBreak(v8::DebugEvent event, 878 v8::Handle<v8::Object> exec_state, 879 v8::Handle<v8::Object> event_data, 880 v8::Handle<v8::Value> data) { 881 // When hitting a debug event listener there must be a break set. 882 CHECK_NE(v8::internal::Debug::break_id(), 0); 883 884 if (event == v8::Break) { 885 // Count the number of breaks. 886 break_point_hit_count++; 887 888 // Run the garbage collector to enforce heap verification if option 889 // --verify-heap is set. 890 Heap::CollectGarbage(0, v8::internal::NEW_SPACE); 891 892 // Set the break flag again to come back here as soon as possible. 893 v8::Debug::DebugBreak(); 894 } 895} 896 897 898// Debug event handler which re-issues a debug break until a limit has been 899// reached. 900int max_break_point_hit_count = 0; 901static void DebugEventBreakMax(v8::DebugEvent event, 902 v8::Handle<v8::Object> exec_state, 903 v8::Handle<v8::Object> event_data, 904 v8::Handle<v8::Value> data) { 905 // When hitting a debug event listener there must be a break set. 906 CHECK_NE(v8::internal::Debug::break_id(), 0); 907 908 if (event == v8::Break && break_point_hit_count < max_break_point_hit_count) { 909 // Count the number of breaks. 910 break_point_hit_count++; 911 912 // Set the break flag again to come back here as soon as possible. 913 v8::Debug::DebugBreak(); 914 } 915} 916 917 918// --- M e s s a g e C a l l b a c k 919 920 921// Message callback which counts the number of messages. 922int message_callback_count = 0; 923 924static void MessageCallbackCountClear() { 925 message_callback_count = 0; 926} 927 928static void MessageCallbackCount(v8::Handle<v8::Message> message, 929 v8::Handle<v8::Value> data) { 930 message_callback_count++; 931} 932 933 934// --- T h e A c t u a l T e s t s 935 936 937// Test that the debug break function is the expected one for different kinds 938// of break locations. 939TEST(DebugStub) { 940 using ::v8::internal::Builtins; 941 v8::HandleScope scope; 942 DebugLocalContext env; 943 944 CheckDebugBreakFunction(&env, 945 "function f1(){}", "f1", 946 0, 947 v8::internal::RelocInfo::JS_RETURN, 948 NULL); 949 CheckDebugBreakFunction(&env, 950 "function f2(){x=1;}", "f2", 951 0, 952 v8::internal::RelocInfo::CODE_TARGET, 953 Builtins::builtin(Builtins::StoreIC_DebugBreak)); 954 CheckDebugBreakFunction(&env, 955 "function f3(){var a=x;}", "f3", 956 0, 957 v8::internal::RelocInfo::CODE_TARGET_CONTEXT, 958 Builtins::builtin(Builtins::LoadIC_DebugBreak)); 959 960// TODO(1240753): Make the test architecture independent or split 961// parts of the debugger into architecture dependent files. This 962// part currently disabled as it is not portable between IA32/ARM. 963// Currently on ICs for keyed store/load on ARM. 964#if !defined (__arm__) && !defined(__thumb__) 965 CheckDebugBreakFunction( 966 &env, 967 "function f4(){var index='propertyName'; var a={}; a[index] = 'x';}", 968 "f4", 969 0, 970 v8::internal::RelocInfo::CODE_TARGET, 971 Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak)); 972 CheckDebugBreakFunction( 973 &env, 974 "function f5(){var index='propertyName'; var a={}; return a[index];}", 975 "f5", 976 0, 977 v8::internal::RelocInfo::CODE_TARGET, 978 Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak)); 979#endif 980 981 // Check the debug break code stubs for call ICs with different number of 982 // parameters. 983 Handle<Code> debug_break_0 = v8::internal::ComputeCallDebugBreak(0); 984 Handle<Code> debug_break_1 = v8::internal::ComputeCallDebugBreak(1); 985 Handle<Code> debug_break_4 = v8::internal::ComputeCallDebugBreak(4); 986 987 CheckDebugBreakFunction(&env, 988 "function f4_0(){x();}", "f4_0", 989 0, 990 v8::internal::RelocInfo::CODE_TARGET_CONTEXT, 991 *debug_break_0); 992 993 CheckDebugBreakFunction(&env, 994 "function f4_1(){x(1);}", "f4_1", 995 0, 996 v8::internal::RelocInfo::CODE_TARGET_CONTEXT, 997 *debug_break_1); 998 999 CheckDebugBreakFunction(&env, 1000 "function f4_4(){x(1,2,3,4);}", "f4_4", 1001 0, 1002 v8::internal::RelocInfo::CODE_TARGET_CONTEXT, 1003 *debug_break_4); 1004} 1005 1006 1007// Test that the debug info in the VM is in sync with the functions being 1008// debugged. 1009TEST(DebugInfo) { 1010 v8::HandleScope scope; 1011 DebugLocalContext env; 1012 // Create a couple of functions for the test. 1013 v8::Local<v8::Function> foo = 1014 CompileFunction(&env, "function foo(){}", "foo"); 1015 v8::Local<v8::Function> bar = 1016 CompileFunction(&env, "function bar(){}", "bar"); 1017 // Initially no functions are debugged. 1018 CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length()); 1019 CHECK(!HasDebugInfo(foo)); 1020 CHECK(!HasDebugInfo(bar)); 1021 // One function (foo) is debugged. 1022 int bp1 = SetBreakPoint(foo, 0); 1023 CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length()); 1024 CHECK(HasDebugInfo(foo)); 1025 CHECK(!HasDebugInfo(bar)); 1026 // Two functions are debugged. 1027 int bp2 = SetBreakPoint(bar, 0); 1028 CHECK_EQ(2, v8::internal::GetDebuggedFunctions()->length()); 1029 CHECK(HasDebugInfo(foo)); 1030 CHECK(HasDebugInfo(bar)); 1031 // One function (bar) is debugged. 1032 ClearBreakPoint(bp1); 1033 CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length()); 1034 CHECK(!HasDebugInfo(foo)); 1035 CHECK(HasDebugInfo(bar)); 1036 // No functions are debugged. 1037 ClearBreakPoint(bp2); 1038 CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length()); 1039 CHECK(!HasDebugInfo(foo)); 1040 CHECK(!HasDebugInfo(bar)); 1041} 1042 1043 1044// Test that a break point can be set at an IC store location. 1045TEST(BreakPointICStore) { 1046 break_point_hit_count = 0; 1047 v8::HandleScope scope; 1048 DebugLocalContext env; 1049 1050 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1051 v8::Undefined()); 1052 v8::Script::Compile(v8::String::New("function foo(){bar=0;}"))->Run(); 1053 v8::Local<v8::Function> foo = 1054 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 1055 1056 // Run without breakpoints. 1057 foo->Call(env->Global(), 0, NULL); 1058 CHECK_EQ(0, break_point_hit_count); 1059 1060 // Run with breakpoint 1061 int bp = SetBreakPoint(foo, 0); 1062 foo->Call(env->Global(), 0, NULL); 1063 CHECK_EQ(1, break_point_hit_count); 1064 foo->Call(env->Global(), 0, NULL); 1065 CHECK_EQ(2, break_point_hit_count); 1066 1067 // Run without breakpoints. 1068 ClearBreakPoint(bp); 1069 foo->Call(env->Global(), 0, NULL); 1070 CHECK_EQ(2, break_point_hit_count); 1071 1072 v8::Debug::SetDebugEventListener(NULL); 1073 CheckDebuggerUnloaded(); 1074} 1075 1076 1077// Test that a break point can be set at an IC load location. 1078TEST(BreakPointICLoad) { 1079 break_point_hit_count = 0; 1080 v8::HandleScope scope; 1081 DebugLocalContext env; 1082 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1083 v8::Undefined()); 1084 v8::Script::Compile(v8::String::New("bar=1"))->Run(); 1085 v8::Script::Compile(v8::String::New("function foo(){var x=bar;}"))->Run(); 1086 v8::Local<v8::Function> foo = 1087 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 1088 1089 // Run without breakpoints. 1090 foo->Call(env->Global(), 0, NULL); 1091 CHECK_EQ(0, break_point_hit_count); 1092 1093 // Run with breakpoint 1094 int bp = SetBreakPoint(foo, 0); 1095 foo->Call(env->Global(), 0, NULL); 1096 CHECK_EQ(1, break_point_hit_count); 1097 foo->Call(env->Global(), 0, NULL); 1098 CHECK_EQ(2, break_point_hit_count); 1099 1100 // Run without breakpoints. 1101 ClearBreakPoint(bp); 1102 foo->Call(env->Global(), 0, NULL); 1103 CHECK_EQ(2, break_point_hit_count); 1104 1105 v8::Debug::SetDebugEventListener(NULL); 1106 CheckDebuggerUnloaded(); 1107} 1108 1109 1110// Test that a break point can be set at an IC call location. 1111TEST(BreakPointICCall) { 1112 break_point_hit_count = 0; 1113 v8::HandleScope scope; 1114 DebugLocalContext env; 1115 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1116 v8::Undefined()); 1117 v8::Script::Compile(v8::String::New("function bar(){}"))->Run(); 1118 v8::Script::Compile(v8::String::New("function foo(){bar();}"))->Run(); 1119 v8::Local<v8::Function> foo = 1120 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 1121 1122 // Run without breakpoints. 1123 foo->Call(env->Global(), 0, NULL); 1124 CHECK_EQ(0, break_point_hit_count); 1125 1126 // Run with breakpoint 1127 int bp = SetBreakPoint(foo, 0); 1128 foo->Call(env->Global(), 0, NULL); 1129 CHECK_EQ(1, break_point_hit_count); 1130 foo->Call(env->Global(), 0, NULL); 1131 CHECK_EQ(2, break_point_hit_count); 1132 1133 // Run without breakpoints. 1134 ClearBreakPoint(bp); 1135 foo->Call(env->Global(), 0, NULL); 1136 CHECK_EQ(2, break_point_hit_count); 1137 1138 v8::Debug::SetDebugEventListener(NULL); 1139 CheckDebuggerUnloaded(); 1140} 1141 1142 1143// Test that a break point can be set at a return store location. 1144TEST(BreakPointReturn) { 1145 break_point_hit_count = 0; 1146 v8::HandleScope scope; 1147 DebugLocalContext env; 1148 1149 // Create a functions for checking the source line and column when hitting 1150 // a break point. 1151 frame_source_line = CompileFunction(&env, 1152 frame_source_line_source, 1153 "frame_source_line"); 1154 frame_source_column = CompileFunction(&env, 1155 frame_source_column_source, 1156 "frame_source_column"); 1157 1158 1159 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1160 v8::Undefined()); 1161 v8::Script::Compile(v8::String::New("function foo(){}"))->Run(); 1162 v8::Local<v8::Function> foo = 1163 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 1164 1165 // Run without breakpoints. 1166 foo->Call(env->Global(), 0, NULL); 1167 CHECK_EQ(0, break_point_hit_count); 1168 1169 // Run with breakpoint 1170 int bp = SetBreakPoint(foo, 0); 1171 foo->Call(env->Global(), 0, NULL); 1172 CHECK_EQ(1, break_point_hit_count); 1173 CHECK_EQ(0, last_source_line); 1174 CHECK_EQ(16, last_source_column); 1175 foo->Call(env->Global(), 0, NULL); 1176 CHECK_EQ(2, break_point_hit_count); 1177 CHECK_EQ(0, last_source_line); 1178 CHECK_EQ(16, last_source_column); 1179 1180 // Run without breakpoints. 1181 ClearBreakPoint(bp); 1182 foo->Call(env->Global(), 0, NULL); 1183 CHECK_EQ(2, break_point_hit_count); 1184 1185 v8::Debug::SetDebugEventListener(NULL); 1186 CheckDebuggerUnloaded(); 1187} 1188 1189 1190static void CallWithBreakPoints(v8::Local<v8::Object> recv, 1191 v8::Local<v8::Function> f, 1192 int break_point_count, 1193 int call_count) { 1194 break_point_hit_count = 0; 1195 for (int i = 0; i < call_count; i++) { 1196 f->Call(recv, 0, NULL); 1197 CHECK_EQ((i + 1) * break_point_count, break_point_hit_count); 1198 } 1199} 1200 1201// Test GC during break point processing. 1202TEST(GCDuringBreakPointProcessing) { 1203 break_point_hit_count = 0; 1204 v8::HandleScope scope; 1205 DebugLocalContext env; 1206 1207 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage, 1208 v8::Undefined()); 1209 v8::Local<v8::Function> foo; 1210 1211 // Test IC store break point with garbage collection. 1212 foo = CompileFunction(&env, "function foo(){bar=0;}", "foo"); 1213 SetBreakPoint(foo, 0); 1214 CallWithBreakPoints(env->Global(), foo, 1, 10); 1215 1216 // Test IC load break point with garbage collection. 1217 foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo"); 1218 SetBreakPoint(foo, 0); 1219 CallWithBreakPoints(env->Global(), foo, 1, 10); 1220 1221 // Test IC call break point with garbage collection. 1222 foo = CompileFunction(&env, "function bar(){};function foo(){bar();}", "foo"); 1223 SetBreakPoint(foo, 0); 1224 CallWithBreakPoints(env->Global(), foo, 1, 10); 1225 1226 // Test return break point with garbage collection. 1227 foo = CompileFunction(&env, "function foo(){}", "foo"); 1228 SetBreakPoint(foo, 0); 1229 CallWithBreakPoints(env->Global(), foo, 1, 25); 1230 1231 v8::Debug::SetDebugEventListener(NULL); 1232 CheckDebuggerUnloaded(); 1233} 1234 1235 1236// Call the function three times with different garbage collections in between 1237// and make sure that the break point survives. 1238static void CallAndGC(v8::Local<v8::Object> recv, v8::Local<v8::Function> f) { 1239 break_point_hit_count = 0; 1240 1241 for (int i = 0; i < 3; i++) { 1242 // Call function. 1243 f->Call(recv, 0, NULL); 1244 CHECK_EQ(1 + i * 3, break_point_hit_count); 1245 1246 // Scavenge and call function. 1247 Heap::CollectGarbage(0, v8::internal::NEW_SPACE); 1248 f->Call(recv, 0, NULL); 1249 CHECK_EQ(2 + i * 3, break_point_hit_count); 1250 1251 // Mark sweep (and perhaps compact) and call function. 1252 Heap::CollectAllGarbage(false); 1253 f->Call(recv, 0, NULL); 1254 CHECK_EQ(3 + i * 3, break_point_hit_count); 1255 } 1256} 1257 1258 1259// Test that a break point can be set at a return store location. 1260TEST(BreakPointSurviveGC) { 1261 break_point_hit_count = 0; 1262 v8::HandleScope scope; 1263 DebugLocalContext env; 1264 1265 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1266 v8::Undefined()); 1267 v8::Local<v8::Function> foo; 1268 1269 // Test IC store break point with garbage collection. 1270 foo = CompileFunction(&env, "function foo(){bar=0;}", "foo"); 1271 SetBreakPoint(foo, 0); 1272 CallAndGC(env->Global(), foo); 1273 1274 // Test IC load break point with garbage collection. 1275 foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo"); 1276 SetBreakPoint(foo, 0); 1277 CallAndGC(env->Global(), foo); 1278 1279 // Test IC call break point with garbage collection. 1280 foo = CompileFunction(&env, "function bar(){};function foo(){bar();}", "foo"); 1281 SetBreakPoint(foo, 0); 1282 CallAndGC(env->Global(), foo); 1283 1284 // Test return break point with garbage collection. 1285 foo = CompileFunction(&env, "function foo(){}", "foo"); 1286 SetBreakPoint(foo, 0); 1287 CallAndGC(env->Global(), foo); 1288 1289 v8::Debug::SetDebugEventListener(NULL); 1290 CheckDebuggerUnloaded(); 1291} 1292 1293 1294// Test that break points can be set using the global Debug object. 1295TEST(BreakPointThroughJavaScript) { 1296 break_point_hit_count = 0; 1297 v8::HandleScope scope; 1298 DebugLocalContext env; 1299 env.ExposeDebug(); 1300 1301 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1302 v8::Undefined()); 1303 v8::Script::Compile(v8::String::New("function bar(){}"))->Run(); 1304 v8::Script::Compile(v8::String::New("function foo(){bar();bar();}"))->Run(); 1305 // 012345678901234567890 1306 // 1 2 1307 // Break points are set at position 3 and 9 1308 v8::Local<v8::Script> foo = v8::Script::Compile(v8::String::New("foo()")); 1309 1310 // Run without breakpoints. 1311 foo->Run(); 1312 CHECK_EQ(0, break_point_hit_count); 1313 1314 // Run with one breakpoint 1315 int bp1 = SetBreakPointFromJS("foo", 0, 3); 1316 foo->Run(); 1317 CHECK_EQ(1, break_point_hit_count); 1318 foo->Run(); 1319 CHECK_EQ(2, break_point_hit_count); 1320 1321 // Run with two breakpoints 1322 int bp2 = SetBreakPointFromJS("foo", 0, 9); 1323 foo->Run(); 1324 CHECK_EQ(4, break_point_hit_count); 1325 foo->Run(); 1326 CHECK_EQ(6, break_point_hit_count); 1327 1328 // Run with one breakpoint 1329 ClearBreakPointFromJS(bp2); 1330 foo->Run(); 1331 CHECK_EQ(7, break_point_hit_count); 1332 foo->Run(); 1333 CHECK_EQ(8, break_point_hit_count); 1334 1335 // Run without breakpoints. 1336 ClearBreakPointFromJS(bp1); 1337 foo->Run(); 1338 CHECK_EQ(8, break_point_hit_count); 1339 1340 v8::Debug::SetDebugEventListener(NULL); 1341 CheckDebuggerUnloaded(); 1342 1343 // Make sure that the break point numbers are consecutive. 1344 CHECK_EQ(1, bp1); 1345 CHECK_EQ(2, bp2); 1346} 1347 1348 1349// Test that break points on scripts identified by name can be set using the 1350// global Debug object. 1351TEST(ScriptBreakPointByNameThroughJavaScript) { 1352 break_point_hit_count = 0; 1353 v8::HandleScope scope; 1354 DebugLocalContext env; 1355 env.ExposeDebug(); 1356 1357 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1358 v8::Undefined()); 1359 1360 v8::Local<v8::String> script = v8::String::New( 1361 "function f() {\n" 1362 " function h() {\n" 1363 " a = 0; // line 2\n" 1364 " }\n" 1365 " b = 1; // line 4\n" 1366 " return h();\n" 1367 "}\n" 1368 "\n" 1369 "function g() {\n" 1370 " function h() {\n" 1371 " a = 0;\n" 1372 " }\n" 1373 " b = 2; // line 12\n" 1374 " h();\n" 1375 " b = 3; // line 14\n" 1376 " f(); // line 15\n" 1377 "}"); 1378 1379 // Compile the script and get the two functions. 1380 v8::ScriptOrigin origin = 1381 v8::ScriptOrigin(v8::String::New("test")); 1382 v8::Script::Compile(script, &origin)->Run(); 1383 v8::Local<v8::Function> f = 1384 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1385 v8::Local<v8::Function> g = 1386 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g"))); 1387 1388 // Call f and g without break points. 1389 break_point_hit_count = 0; 1390 f->Call(env->Global(), 0, NULL); 1391 CHECK_EQ(0, break_point_hit_count); 1392 g->Call(env->Global(), 0, NULL); 1393 CHECK_EQ(0, break_point_hit_count); 1394 1395 // Call f and g with break point on line 12. 1396 int sbp1 = SetScriptBreakPointByNameFromJS("test", 12, 0); 1397 break_point_hit_count = 0; 1398 f->Call(env->Global(), 0, NULL); 1399 CHECK_EQ(0, break_point_hit_count); 1400 g->Call(env->Global(), 0, NULL); 1401 CHECK_EQ(1, break_point_hit_count); 1402 1403 // Remove the break point again. 1404 break_point_hit_count = 0; 1405 ClearBreakPointFromJS(sbp1); 1406 f->Call(env->Global(), 0, NULL); 1407 CHECK_EQ(0, break_point_hit_count); 1408 g->Call(env->Global(), 0, NULL); 1409 CHECK_EQ(0, break_point_hit_count); 1410 1411 // Call f and g with break point on line 2. 1412 int sbp2 = SetScriptBreakPointByNameFromJS("test", 2, 0); 1413 break_point_hit_count = 0; 1414 f->Call(env->Global(), 0, NULL); 1415 CHECK_EQ(1, break_point_hit_count); 1416 g->Call(env->Global(), 0, NULL); 1417 CHECK_EQ(2, break_point_hit_count); 1418 1419 // Call f and g with break point on line 2, 4, 12, 14 and 15. 1420 int sbp3 = SetScriptBreakPointByNameFromJS("test", 4, 0); 1421 int sbp4 = SetScriptBreakPointByNameFromJS("test", 12, 0); 1422 int sbp5 = SetScriptBreakPointByNameFromJS("test", 14, 0); 1423 int sbp6 = SetScriptBreakPointByNameFromJS("test", 15, 0); 1424 break_point_hit_count = 0; 1425 f->Call(env->Global(), 0, NULL); 1426 CHECK_EQ(2, break_point_hit_count); 1427 g->Call(env->Global(), 0, NULL); 1428 CHECK_EQ(7, break_point_hit_count); 1429 1430 // Remove all the break points again. 1431 break_point_hit_count = 0; 1432 ClearBreakPointFromJS(sbp2); 1433 ClearBreakPointFromJS(sbp3); 1434 ClearBreakPointFromJS(sbp4); 1435 ClearBreakPointFromJS(sbp5); 1436 ClearBreakPointFromJS(sbp6); 1437 f->Call(env->Global(), 0, NULL); 1438 CHECK_EQ(0, break_point_hit_count); 1439 g->Call(env->Global(), 0, NULL); 1440 CHECK_EQ(0, break_point_hit_count); 1441 1442 v8::Debug::SetDebugEventListener(NULL); 1443 CheckDebuggerUnloaded(); 1444 1445 // Make sure that the break point numbers are consecutive. 1446 CHECK_EQ(1, sbp1); 1447 CHECK_EQ(2, sbp2); 1448 CHECK_EQ(3, sbp3); 1449 CHECK_EQ(4, sbp4); 1450 CHECK_EQ(5, sbp5); 1451 CHECK_EQ(6, sbp6); 1452} 1453 1454 1455TEST(ScriptBreakPointByIdThroughJavaScript) { 1456 break_point_hit_count = 0; 1457 v8::HandleScope scope; 1458 DebugLocalContext env; 1459 env.ExposeDebug(); 1460 1461 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1462 v8::Undefined()); 1463 1464 v8::Local<v8::String> source = v8::String::New( 1465 "function f() {\n" 1466 " function h() {\n" 1467 " a = 0; // line 2\n" 1468 " }\n" 1469 " b = 1; // line 4\n" 1470 " return h();\n" 1471 "}\n" 1472 "\n" 1473 "function g() {\n" 1474 " function h() {\n" 1475 " a = 0;\n" 1476 " }\n" 1477 " b = 2; // line 12\n" 1478 " h();\n" 1479 " b = 3; // line 14\n" 1480 " f(); // line 15\n" 1481 "}"); 1482 1483 // Compile the script and get the two functions. 1484 v8::ScriptOrigin origin = 1485 v8::ScriptOrigin(v8::String::New("test")); 1486 v8::Local<v8::Script> script = v8::Script::Compile(source, &origin); 1487 script->Run(); 1488 v8::Local<v8::Function> f = 1489 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1490 v8::Local<v8::Function> g = 1491 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g"))); 1492 1493 // Get the script id knowing that internally it is a 32 integer. 1494 uint32_t script_id = script->Id()->Uint32Value(); 1495 1496 // Call f and g without break points. 1497 break_point_hit_count = 0; 1498 f->Call(env->Global(), 0, NULL); 1499 CHECK_EQ(0, break_point_hit_count); 1500 g->Call(env->Global(), 0, NULL); 1501 CHECK_EQ(0, break_point_hit_count); 1502 1503 // Call f and g with break point on line 12. 1504 int sbp1 = SetScriptBreakPointByIdFromJS(script_id, 12, 0); 1505 break_point_hit_count = 0; 1506 f->Call(env->Global(), 0, NULL); 1507 CHECK_EQ(0, break_point_hit_count); 1508 g->Call(env->Global(), 0, NULL); 1509 CHECK_EQ(1, break_point_hit_count); 1510 1511 // Remove the break point again. 1512 break_point_hit_count = 0; 1513 ClearBreakPointFromJS(sbp1); 1514 f->Call(env->Global(), 0, NULL); 1515 CHECK_EQ(0, break_point_hit_count); 1516 g->Call(env->Global(), 0, NULL); 1517 CHECK_EQ(0, break_point_hit_count); 1518 1519 // Call f and g with break point on line 2. 1520 int sbp2 = SetScriptBreakPointByIdFromJS(script_id, 2, 0); 1521 break_point_hit_count = 0; 1522 f->Call(env->Global(), 0, NULL); 1523 CHECK_EQ(1, break_point_hit_count); 1524 g->Call(env->Global(), 0, NULL); 1525 CHECK_EQ(2, break_point_hit_count); 1526 1527 // Call f and g with break point on line 2, 4, 12, 14 and 15. 1528 int sbp3 = SetScriptBreakPointByIdFromJS(script_id, 4, 0); 1529 int sbp4 = SetScriptBreakPointByIdFromJS(script_id, 12, 0); 1530 int sbp5 = SetScriptBreakPointByIdFromJS(script_id, 14, 0); 1531 int sbp6 = SetScriptBreakPointByIdFromJS(script_id, 15, 0); 1532 break_point_hit_count = 0; 1533 f->Call(env->Global(), 0, NULL); 1534 CHECK_EQ(2, break_point_hit_count); 1535 g->Call(env->Global(), 0, NULL); 1536 CHECK_EQ(7, break_point_hit_count); 1537 1538 // Remove all the break points again. 1539 break_point_hit_count = 0; 1540 ClearBreakPointFromJS(sbp2); 1541 ClearBreakPointFromJS(sbp3); 1542 ClearBreakPointFromJS(sbp4); 1543 ClearBreakPointFromJS(sbp5); 1544 ClearBreakPointFromJS(sbp6); 1545 f->Call(env->Global(), 0, NULL); 1546 CHECK_EQ(0, break_point_hit_count); 1547 g->Call(env->Global(), 0, NULL); 1548 CHECK_EQ(0, break_point_hit_count); 1549 1550 v8::Debug::SetDebugEventListener(NULL); 1551 CheckDebuggerUnloaded(); 1552 1553 // Make sure that the break point numbers are consecutive. 1554 CHECK_EQ(1, sbp1); 1555 CHECK_EQ(2, sbp2); 1556 CHECK_EQ(3, sbp3); 1557 CHECK_EQ(4, sbp4); 1558 CHECK_EQ(5, sbp5); 1559 CHECK_EQ(6, sbp6); 1560} 1561 1562 1563// Test conditional script break points. 1564TEST(EnableDisableScriptBreakPoint) { 1565 break_point_hit_count = 0; 1566 v8::HandleScope scope; 1567 DebugLocalContext env; 1568 env.ExposeDebug(); 1569 1570 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1571 v8::Undefined()); 1572 1573 v8::Local<v8::String> script = v8::String::New( 1574 "function f() {\n" 1575 " a = 0; // line 1\n" 1576 "};"); 1577 1578 // Compile the script and get function f. 1579 v8::ScriptOrigin origin = 1580 v8::ScriptOrigin(v8::String::New("test")); 1581 v8::Script::Compile(script, &origin)->Run(); 1582 v8::Local<v8::Function> f = 1583 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1584 1585 // Set script break point on line 1 (in function f). 1586 int sbp = SetScriptBreakPointByNameFromJS("test", 1, 0); 1587 1588 // Call f while enabeling and disabling the script break point. 1589 break_point_hit_count = 0; 1590 f->Call(env->Global(), 0, NULL); 1591 CHECK_EQ(1, break_point_hit_count); 1592 1593 DisableScriptBreakPointFromJS(sbp); 1594 f->Call(env->Global(), 0, NULL); 1595 CHECK_EQ(1, break_point_hit_count); 1596 1597 EnableScriptBreakPointFromJS(sbp); 1598 f->Call(env->Global(), 0, NULL); 1599 CHECK_EQ(2, break_point_hit_count); 1600 1601 DisableScriptBreakPointFromJS(sbp); 1602 f->Call(env->Global(), 0, NULL); 1603 CHECK_EQ(2, break_point_hit_count); 1604 1605 // Reload the script and get f again checking that the disabeling survives. 1606 v8::Script::Compile(script, &origin)->Run(); 1607 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1608 f->Call(env->Global(), 0, NULL); 1609 CHECK_EQ(2, break_point_hit_count); 1610 1611 EnableScriptBreakPointFromJS(sbp); 1612 f->Call(env->Global(), 0, NULL); 1613 CHECK_EQ(3, break_point_hit_count); 1614 1615 v8::Debug::SetDebugEventListener(NULL); 1616 CheckDebuggerUnloaded(); 1617} 1618 1619 1620// Test conditional script break points. 1621TEST(ConditionalScriptBreakPoint) { 1622 break_point_hit_count = 0; 1623 v8::HandleScope scope; 1624 DebugLocalContext env; 1625 env.ExposeDebug(); 1626 1627 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1628 v8::Undefined()); 1629 1630 v8::Local<v8::String> script = v8::String::New( 1631 "count = 0;\n" 1632 "function f() {\n" 1633 " g(count++); // line 2\n" 1634 "};\n" 1635 "function g(x) {\n" 1636 " var a=x; // line 5\n" 1637 "};"); 1638 1639 // Compile the script and get function f. 1640 v8::ScriptOrigin origin = 1641 v8::ScriptOrigin(v8::String::New("test")); 1642 v8::Script::Compile(script, &origin)->Run(); 1643 v8::Local<v8::Function> f = 1644 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1645 1646 // Set script break point on line 5 (in function g). 1647 int sbp1 = SetScriptBreakPointByNameFromJS("test", 5, 0); 1648 1649 // Call f with different conditions on the script break point. 1650 break_point_hit_count = 0; 1651 ChangeScriptBreakPointConditionFromJS(sbp1, "false"); 1652 f->Call(env->Global(), 0, NULL); 1653 CHECK_EQ(0, break_point_hit_count); 1654 1655 ChangeScriptBreakPointConditionFromJS(sbp1, "true"); 1656 break_point_hit_count = 0; 1657 f->Call(env->Global(), 0, NULL); 1658 CHECK_EQ(1, break_point_hit_count); 1659 1660 ChangeScriptBreakPointConditionFromJS(sbp1, "a % 2 == 0"); 1661 break_point_hit_count = 0; 1662 for (int i = 0; i < 10; i++) { 1663 f->Call(env->Global(), 0, NULL); 1664 } 1665 CHECK_EQ(5, break_point_hit_count); 1666 1667 // Reload the script and get f again checking that the condition survives. 1668 v8::Script::Compile(script, &origin)->Run(); 1669 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1670 1671 break_point_hit_count = 0; 1672 for (int i = 0; i < 10; i++) { 1673 f->Call(env->Global(), 0, NULL); 1674 } 1675 CHECK_EQ(5, break_point_hit_count); 1676 1677 v8::Debug::SetDebugEventListener(NULL); 1678 CheckDebuggerUnloaded(); 1679} 1680 1681 1682// Test ignore count on script break points. 1683TEST(ScriptBreakPointIgnoreCount) { 1684 break_point_hit_count = 0; 1685 v8::HandleScope scope; 1686 DebugLocalContext env; 1687 env.ExposeDebug(); 1688 1689 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1690 v8::Undefined()); 1691 1692 v8::Local<v8::String> script = v8::String::New( 1693 "function f() {\n" 1694 " a = 0; // line 1\n" 1695 "};"); 1696 1697 // Compile the script and get function f. 1698 v8::ScriptOrigin origin = 1699 v8::ScriptOrigin(v8::String::New("test")); 1700 v8::Script::Compile(script, &origin)->Run(); 1701 v8::Local<v8::Function> f = 1702 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1703 1704 // Set script break point on line 1 (in function f). 1705 int sbp = SetScriptBreakPointByNameFromJS("test", 1, 0); 1706 1707 // Call f with different ignores on the script break point. 1708 break_point_hit_count = 0; 1709 ChangeScriptBreakPointIgnoreCountFromJS(sbp, 1); 1710 f->Call(env->Global(), 0, NULL); 1711 CHECK_EQ(0, break_point_hit_count); 1712 f->Call(env->Global(), 0, NULL); 1713 CHECK_EQ(1, break_point_hit_count); 1714 1715 ChangeScriptBreakPointIgnoreCountFromJS(sbp, 5); 1716 break_point_hit_count = 0; 1717 for (int i = 0; i < 10; i++) { 1718 f->Call(env->Global(), 0, NULL); 1719 } 1720 CHECK_EQ(5, break_point_hit_count); 1721 1722 // Reload the script and get f again checking that the ignore survives. 1723 v8::Script::Compile(script, &origin)->Run(); 1724 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1725 1726 break_point_hit_count = 0; 1727 for (int i = 0; i < 10; i++) { 1728 f->Call(env->Global(), 0, NULL); 1729 } 1730 CHECK_EQ(5, break_point_hit_count); 1731 1732 v8::Debug::SetDebugEventListener(NULL); 1733 CheckDebuggerUnloaded(); 1734} 1735 1736 1737// Test that script break points survive when a script is reloaded. 1738TEST(ScriptBreakPointReload) { 1739 break_point_hit_count = 0; 1740 v8::HandleScope scope; 1741 DebugLocalContext env; 1742 env.ExposeDebug(); 1743 1744 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1745 v8::Undefined()); 1746 1747 v8::Local<v8::Function> f; 1748 v8::Local<v8::String> script = v8::String::New( 1749 "function f() {\n" 1750 " function h() {\n" 1751 " a = 0; // line 2\n" 1752 " }\n" 1753 " b = 1; // line 4\n" 1754 " return h();\n" 1755 "}"); 1756 1757 v8::ScriptOrigin origin_1 = v8::ScriptOrigin(v8::String::New("1")); 1758 v8::ScriptOrigin origin_2 = v8::ScriptOrigin(v8::String::New("2")); 1759 1760 // Set a script break point before the script is loaded. 1761 SetScriptBreakPointByNameFromJS("1", 2, 0); 1762 1763 // Compile the script and get the function. 1764 v8::Script::Compile(script, &origin_1)->Run(); 1765 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1766 1767 // Call f and check that the script break point is active. 1768 break_point_hit_count = 0; 1769 f->Call(env->Global(), 0, NULL); 1770 CHECK_EQ(1, break_point_hit_count); 1771 1772 // Compile the script again with a different script data and get the 1773 // function. 1774 v8::Script::Compile(script, &origin_2)->Run(); 1775 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1776 1777 // Call f and check that no break points are set. 1778 break_point_hit_count = 0; 1779 f->Call(env->Global(), 0, NULL); 1780 CHECK_EQ(0, break_point_hit_count); 1781 1782 // Compile the script again and get the function. 1783 v8::Script::Compile(script, &origin_1)->Run(); 1784 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1785 1786 // Call f and check that the script break point is active. 1787 break_point_hit_count = 0; 1788 f->Call(env->Global(), 0, NULL); 1789 CHECK_EQ(1, break_point_hit_count); 1790 1791 v8::Debug::SetDebugEventListener(NULL); 1792 CheckDebuggerUnloaded(); 1793} 1794 1795 1796// Test when several scripts has the same script data 1797TEST(ScriptBreakPointMultiple) { 1798 break_point_hit_count = 0; 1799 v8::HandleScope scope; 1800 DebugLocalContext env; 1801 env.ExposeDebug(); 1802 1803 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1804 v8::Undefined()); 1805 1806 v8::Local<v8::Function> f; 1807 v8::Local<v8::String> script_f = v8::String::New( 1808 "function f() {\n" 1809 " a = 0; // line 1\n" 1810 "}"); 1811 1812 v8::Local<v8::Function> g; 1813 v8::Local<v8::String> script_g = v8::String::New( 1814 "function g() {\n" 1815 " b = 0; // line 1\n" 1816 "}"); 1817 1818 v8::ScriptOrigin origin = 1819 v8::ScriptOrigin(v8::String::New("test")); 1820 1821 // Set a script break point before the scripts are loaded. 1822 int sbp = SetScriptBreakPointByNameFromJS("test", 1, 0); 1823 1824 // Compile the scripts with same script data and get the functions. 1825 v8::Script::Compile(script_f, &origin)->Run(); 1826 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1827 v8::Script::Compile(script_g, &origin)->Run(); 1828 g = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g"))); 1829 1830 // Call f and g and check that the script break point is active. 1831 break_point_hit_count = 0; 1832 f->Call(env->Global(), 0, NULL); 1833 CHECK_EQ(1, break_point_hit_count); 1834 g->Call(env->Global(), 0, NULL); 1835 CHECK_EQ(2, break_point_hit_count); 1836 1837 // Clear the script break point. 1838 ClearBreakPointFromJS(sbp); 1839 1840 // Call f and g and check that the script break point is no longer active. 1841 break_point_hit_count = 0; 1842 f->Call(env->Global(), 0, NULL); 1843 CHECK_EQ(0, break_point_hit_count); 1844 g->Call(env->Global(), 0, NULL); 1845 CHECK_EQ(0, break_point_hit_count); 1846 1847 // Set script break point with the scripts loaded. 1848 sbp = SetScriptBreakPointByNameFromJS("test", 1, 0); 1849 1850 // Call f and g and check that the script break point is active. 1851 break_point_hit_count = 0; 1852 f->Call(env->Global(), 0, NULL); 1853 CHECK_EQ(1, break_point_hit_count); 1854 g->Call(env->Global(), 0, NULL); 1855 CHECK_EQ(2, break_point_hit_count); 1856 1857 v8::Debug::SetDebugEventListener(NULL); 1858 CheckDebuggerUnloaded(); 1859} 1860 1861 1862// Test the script origin which has both name and line offset. 1863TEST(ScriptBreakPointLineOffset) { 1864 break_point_hit_count = 0; 1865 v8::HandleScope scope; 1866 DebugLocalContext env; 1867 env.ExposeDebug(); 1868 1869 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1870 v8::Undefined()); 1871 1872 v8::Local<v8::Function> f; 1873 v8::Local<v8::String> script = v8::String::New( 1874 "function f() {\n" 1875 " a = 0; // line 8 as this script has line offset 7\n" 1876 " b = 0; // line 9 as this script has line offset 7\n" 1877 "}"); 1878 1879 // Create script origin both name and line offset. 1880 v8::ScriptOrigin origin(v8::String::New("test.html"), 1881 v8::Integer::New(7)); 1882 1883 // Set two script break points before the script is loaded. 1884 int sbp1 = SetScriptBreakPointByNameFromJS("test.html", 8, 0); 1885 int sbp2 = SetScriptBreakPointByNameFromJS("test.html", 9, 0); 1886 1887 // Compile the script and get the function. 1888 v8::Script::Compile(script, &origin)->Run(); 1889 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1890 1891 // Call f and check that the script break point is active. 1892 break_point_hit_count = 0; 1893 f->Call(env->Global(), 0, NULL); 1894 CHECK_EQ(2, break_point_hit_count); 1895 1896 // Clear the script break points. 1897 ClearBreakPointFromJS(sbp1); 1898 ClearBreakPointFromJS(sbp2); 1899 1900 // Call f and check that no script break points are active. 1901 break_point_hit_count = 0; 1902 f->Call(env->Global(), 0, NULL); 1903 CHECK_EQ(0, break_point_hit_count); 1904 1905 // Set a script break point with the script loaded. 1906 sbp1 = SetScriptBreakPointByNameFromJS("test.html", 9, 0); 1907 1908 // Call f and check that the script break point is active. 1909 break_point_hit_count = 0; 1910 f->Call(env->Global(), 0, NULL); 1911 CHECK_EQ(1, break_point_hit_count); 1912 1913 v8::Debug::SetDebugEventListener(NULL); 1914 CheckDebuggerUnloaded(); 1915} 1916 1917 1918// Test script break points set on lines. 1919TEST(ScriptBreakPointLine) { 1920 v8::HandleScope scope; 1921 DebugLocalContext env; 1922 env.ExposeDebug(); 1923 1924 // Create a function for checking the function when hitting a break point. 1925 frame_function_name = CompileFunction(&env, 1926 frame_function_name_source, 1927 "frame_function_name"); 1928 1929 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 1930 v8::Undefined()); 1931 1932 v8::Local<v8::Function> f; 1933 v8::Local<v8::Function> g; 1934 v8::Local<v8::String> script = v8::String::New( 1935 "a = 0 // line 0\n" 1936 "function f() {\n" 1937 " a = 1; // line 2\n" 1938 "}\n" 1939 " a = 2; // line 4\n" 1940 " /* xx */ function g() { // line 5\n" 1941 " function h() { // line 6\n" 1942 " a = 3; // line 7\n" 1943 " }\n" 1944 " h(); // line 9\n" 1945 " a = 4; // line 10\n" 1946 " }\n" 1947 " a=5; // line 12"); 1948 1949 // Set a couple script break point before the script is loaded. 1950 int sbp1 = SetScriptBreakPointByNameFromJS("test.html", 0, -1); 1951 int sbp2 = SetScriptBreakPointByNameFromJS("test.html", 1, -1); 1952 int sbp3 = SetScriptBreakPointByNameFromJS("test.html", 5, -1); 1953 1954 // Compile the script and get the function. 1955 break_point_hit_count = 0; 1956 v8::ScriptOrigin origin(v8::String::New("test.html"), v8::Integer::New(0)); 1957 v8::Script::Compile(script, &origin)->Run(); 1958 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 1959 g = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g"))); 1960 1961 // Chesk that a break point was hit when the script was run. 1962 CHECK_EQ(1, break_point_hit_count); 1963 CHECK_EQ(0, StrLength(last_function_hit)); 1964 1965 // Call f and check that the script break point. 1966 f->Call(env->Global(), 0, NULL); 1967 CHECK_EQ(2, break_point_hit_count); 1968 CHECK_EQ("f", last_function_hit); 1969 1970 // Call g and check that the script break point. 1971 g->Call(env->Global(), 0, NULL); 1972 CHECK_EQ(3, break_point_hit_count); 1973 CHECK_EQ("g", last_function_hit); 1974 1975 // Clear the script break point on g and set one on h. 1976 ClearBreakPointFromJS(sbp3); 1977 int sbp4 = SetScriptBreakPointByNameFromJS("test.html", 6, -1); 1978 1979 // Call g and check that the script break point in h is hit. 1980 g->Call(env->Global(), 0, NULL); 1981 CHECK_EQ(4, break_point_hit_count); 1982 CHECK_EQ("h", last_function_hit); 1983 1984 // Clear break points in f and h. Set a new one in the script between 1985 // functions f and g and test that there is no break points in f and g any 1986 // more. 1987 ClearBreakPointFromJS(sbp2); 1988 ClearBreakPointFromJS(sbp4); 1989 int sbp5 = SetScriptBreakPointByNameFromJS("test.html", 4, -1); 1990 break_point_hit_count = 0; 1991 f->Call(env->Global(), 0, NULL); 1992 g->Call(env->Global(), 0, NULL); 1993 CHECK_EQ(0, break_point_hit_count); 1994 1995 // Reload the script which should hit two break points. 1996 break_point_hit_count = 0; 1997 v8::Script::Compile(script, &origin)->Run(); 1998 CHECK_EQ(2, break_point_hit_count); 1999 CHECK_EQ(0, StrLength(last_function_hit)); 2000 2001 // Set a break point in the code after the last function decleration. 2002 int sbp6 = SetScriptBreakPointByNameFromJS("test.html", 12, -1); 2003 2004 // Reload the script which should hit three break points. 2005 break_point_hit_count = 0; 2006 v8::Script::Compile(script, &origin)->Run(); 2007 CHECK_EQ(3, break_point_hit_count); 2008 CHECK_EQ(0, StrLength(last_function_hit)); 2009 2010 // Clear the last break points, and reload the script which should not hit any 2011 // break points. 2012 ClearBreakPointFromJS(sbp1); 2013 ClearBreakPointFromJS(sbp5); 2014 ClearBreakPointFromJS(sbp6); 2015 break_point_hit_count = 0; 2016 v8::Script::Compile(script, &origin)->Run(); 2017 CHECK_EQ(0, break_point_hit_count); 2018 2019 v8::Debug::SetDebugEventListener(NULL); 2020 CheckDebuggerUnloaded(); 2021} 2022 2023 2024// Test that it is possible to remove the last break point for a function 2025// inside the break handling of that break point. 2026TEST(RemoveBreakPointInBreak) { 2027 v8::HandleScope scope; 2028 DebugLocalContext env; 2029 2030 v8::Local<v8::Function> foo = 2031 CompileFunction(&env, "function foo(){a=1;}", "foo"); 2032 debug_event_remove_break_point = SetBreakPoint(foo, 0); 2033 2034 // Register the debug event listener pasing the function 2035 v8::Debug::SetDebugEventListener(DebugEventRemoveBreakPoint, foo); 2036 2037 break_point_hit_count = 0; 2038 foo->Call(env->Global(), 0, NULL); 2039 CHECK_EQ(1, break_point_hit_count); 2040 2041 break_point_hit_count = 0; 2042 foo->Call(env->Global(), 0, NULL); 2043 CHECK_EQ(0, break_point_hit_count); 2044 2045 v8::Debug::SetDebugEventListener(NULL); 2046 CheckDebuggerUnloaded(); 2047} 2048 2049 2050// Test that the debugger statement causes a break. 2051TEST(DebuggerStatement) { 2052 break_point_hit_count = 0; 2053 v8::HandleScope scope; 2054 DebugLocalContext env; 2055 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 2056 v8::Undefined()); 2057 v8::Script::Compile(v8::String::New("function bar(){debugger}"))->Run(); 2058 v8::Script::Compile(v8::String::New( 2059 "function foo(){debugger;debugger;}"))->Run(); 2060 v8::Local<v8::Function> foo = 2061 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 2062 v8::Local<v8::Function> bar = 2063 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("bar"))); 2064 2065 // Run function with debugger statement 2066 bar->Call(env->Global(), 0, NULL); 2067 CHECK_EQ(1, break_point_hit_count); 2068 2069 // Run function with two debugger statement 2070 foo->Call(env->Global(), 0, NULL); 2071 CHECK_EQ(3, break_point_hit_count); 2072 2073 v8::Debug::SetDebugEventListener(NULL); 2074 CheckDebuggerUnloaded(); 2075} 2076 2077 2078// Test setting a breakpoint on the debugger statement. 2079TEST(DebuggerStatementBreakpoint) { 2080 break_point_hit_count = 0; 2081 v8::HandleScope scope; 2082 DebugLocalContext env; 2083 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 2084 v8::Undefined()); 2085 v8::Script::Compile(v8::String::New("function foo(){debugger;}"))->Run(); 2086 v8::Local<v8::Function> foo = 2087 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 2088 2089 // The debugger statement triggers breakpint hit 2090 foo->Call(env->Global(), 0, NULL); 2091 CHECK_EQ(1, break_point_hit_count); 2092 2093 int bp = SetBreakPoint(foo, 0); 2094 2095 // Set breakpoint does not duplicate hits 2096 foo->Call(env->Global(), 0, NULL); 2097 CHECK_EQ(2, break_point_hit_count); 2098 2099 ClearBreakPoint(bp); 2100 v8::Debug::SetDebugEventListener(NULL); 2101 CheckDebuggerUnloaded(); 2102} 2103 2104 2105// Thest that the evaluation of expressions when a break point is hit generates 2106// the correct results. 2107TEST(DebugEvaluate) { 2108 v8::HandleScope scope; 2109 DebugLocalContext env; 2110 env.ExposeDebug(); 2111 2112 // Create a function for checking the evaluation when hitting a break point. 2113 evaluate_check_function = CompileFunction(&env, 2114 evaluate_check_source, 2115 "evaluate_check"); 2116 // Register the debug event listener 2117 v8::Debug::SetDebugEventListener(DebugEventEvaluate); 2118 2119 // Different expected vaules of x and a when in a break point (u = undefined, 2120 // d = Hello, world!). 2121 struct EvaluateCheck checks_uu[] = { 2122 {"x", v8::Undefined()}, 2123 {"a", v8::Undefined()}, 2124 {NULL, v8::Handle<v8::Value>()} 2125 }; 2126 struct EvaluateCheck checks_hu[] = { 2127 {"x", v8::String::New("Hello, world!")}, 2128 {"a", v8::Undefined()}, 2129 {NULL, v8::Handle<v8::Value>()} 2130 }; 2131 struct EvaluateCheck checks_hh[] = { 2132 {"x", v8::String::New("Hello, world!")}, 2133 {"a", v8::String::New("Hello, world!")}, 2134 {NULL, v8::Handle<v8::Value>()} 2135 }; 2136 2137 // Simple test function. The "y=0" is in the function foo to provide a break 2138 // location. For "y=0" the "y" is at position 15 in the barbar function 2139 // therefore setting breakpoint at position 15 will break at "y=0" and 2140 // setting it higher will break after. 2141 v8::Local<v8::Function> foo = CompileFunction(&env, 2142 "function foo(x) {" 2143 " var a;" 2144 " y=0; /* To ensure break location.*/" 2145 " a=x;" 2146 "}", 2147 "foo"); 2148 const int foo_break_position = 15; 2149 2150 // Arguments with one parameter "Hello, world!" 2151 v8::Handle<v8::Value> argv_foo[1] = { v8::String::New("Hello, world!") }; 2152 2153 // Call foo with breakpoint set before a=x and undefined as parameter. 2154 int bp = SetBreakPoint(foo, foo_break_position); 2155 checks = checks_uu; 2156 foo->Call(env->Global(), 0, NULL); 2157 2158 // Call foo with breakpoint set before a=x and parameter "Hello, world!". 2159 checks = checks_hu; 2160 foo->Call(env->Global(), 1, argv_foo); 2161 2162 // Call foo with breakpoint set after a=x and parameter "Hello, world!". 2163 ClearBreakPoint(bp); 2164 SetBreakPoint(foo, foo_break_position + 1); 2165 checks = checks_hh; 2166 foo->Call(env->Global(), 1, argv_foo); 2167 2168 // Test function with an inner function. The "y=0" is in function barbar 2169 // to provide a break location. For "y=0" the "y" is at position 8 in the 2170 // barbar function therefore setting breakpoint at position 8 will break at 2171 // "y=0" and setting it higher will break after. 2172 v8::Local<v8::Function> bar = CompileFunction(&env, 2173 "y = 0;" 2174 "x = 'Goodbye, world!';" 2175 "function bar(x, b) {" 2176 " var a;" 2177 " function barbar() {" 2178 " y=0; /* To ensure break location.*/" 2179 " a=x;" 2180 " };" 2181 " debug.Debug.clearAllBreakPoints();" 2182 " barbar();" 2183 " y=0;a=x;" 2184 "}", 2185 "bar"); 2186 const int barbar_break_position = 8; 2187 2188 // Call bar setting breakpoint before a=x in barbar and undefined as 2189 // parameter. 2190 checks = checks_uu; 2191 v8::Handle<v8::Value> argv_bar_1[2] = { 2192 v8::Undefined(), 2193 v8::Number::New(barbar_break_position) 2194 }; 2195 bar->Call(env->Global(), 2, argv_bar_1); 2196 2197 // Call bar setting breakpoint before a=x in barbar and parameter 2198 // "Hello, world!". 2199 checks = checks_hu; 2200 v8::Handle<v8::Value> argv_bar_2[2] = { 2201 v8::String::New("Hello, world!"), 2202 v8::Number::New(barbar_break_position) 2203 }; 2204 bar->Call(env->Global(), 2, argv_bar_2); 2205 2206 // Call bar setting breakpoint after a=x in barbar and parameter 2207 // "Hello, world!". 2208 checks = checks_hh; 2209 v8::Handle<v8::Value> argv_bar_3[2] = { 2210 v8::String::New("Hello, world!"), 2211 v8::Number::New(barbar_break_position + 1) 2212 }; 2213 bar->Call(env->Global(), 2, argv_bar_3); 2214 2215 v8::Debug::SetDebugEventListener(NULL); 2216 CheckDebuggerUnloaded(); 2217} 2218 2219// Copies a C string to a 16-bit string. Does not check for buffer overflow. 2220// Does not use the V8 engine to convert strings, so it can be used 2221// in any thread. Returns the length of the string. 2222int AsciiToUtf16(const char* input_buffer, uint16_t* output_buffer) { 2223 int i; 2224 for (i = 0; input_buffer[i] != '\0'; ++i) { 2225 // ASCII does not use chars > 127, but be careful anyway. 2226 output_buffer[i] = static_cast<unsigned char>(input_buffer[i]); 2227 } 2228 output_buffer[i] = 0; 2229 return i; 2230} 2231 2232// Copies a 16-bit string to a C string by dropping the high byte of 2233// each character. Does not check for buffer overflow. 2234// Can be used in any thread. Requires string length as an input. 2235int Utf16ToAscii(const uint16_t* input_buffer, int length, 2236 char* output_buffer, int output_len = -1) { 2237 if (output_len >= 0) { 2238 if (length > output_len - 1) { 2239 length = output_len - 1; 2240 } 2241 } 2242 2243 for (int i = 0; i < length; ++i) { 2244 output_buffer[i] = static_cast<char>(input_buffer[i]); 2245 } 2246 output_buffer[length] = '\0'; 2247 return length; 2248} 2249 2250 2251// We match parts of the message to get evaluate result int value. 2252bool GetEvaluateStringResult(char *message, char* buffer, int buffer_size) { 2253 if (strstr(message, "\"command\":\"evaluate\"") == NULL) { 2254 return false; 2255 } 2256 const char* prefix = "\"text\":\""; 2257 char* pos1 = strstr(message, prefix); 2258 if (pos1 == NULL) { 2259 return false; 2260 } 2261 pos1 += strlen(prefix); 2262 char* pos2 = strchr(pos1, '"'); 2263 if (pos2 == NULL) { 2264 return false; 2265 } 2266 Vector<char> buf(buffer, buffer_size); 2267 int len = static_cast<int>(pos2 - pos1); 2268 if (len > buffer_size - 1) { 2269 len = buffer_size - 1; 2270 } 2271 OS::StrNCpy(buf, pos1, len); 2272 buffer[buffer_size - 1] = '\0'; 2273 return true; 2274} 2275 2276 2277struct EvaluateResult { 2278 static const int kBufferSize = 20; 2279 char buffer[kBufferSize]; 2280}; 2281 2282struct DebugProcessDebugMessagesData { 2283 static const int kArraySize = 5; 2284 int counter; 2285 EvaluateResult results[kArraySize]; 2286 2287 void reset() { 2288 counter = 0; 2289 } 2290 EvaluateResult* current() { 2291 return &results[counter % kArraySize]; 2292 } 2293 void next() { 2294 counter++; 2295 } 2296}; 2297 2298DebugProcessDebugMessagesData process_debug_messages_data; 2299 2300static void DebugProcessDebugMessagesHandler( 2301 const uint16_t* message, 2302 int length, 2303 v8::Debug::ClientData* client_data) { 2304 2305 const int kBufferSize = 100000; 2306 char print_buffer[kBufferSize]; 2307 Utf16ToAscii(message, length, print_buffer, kBufferSize); 2308 2309 EvaluateResult* array_item = process_debug_messages_data.current(); 2310 2311 bool res = GetEvaluateStringResult(print_buffer, 2312 array_item->buffer, 2313 EvaluateResult::kBufferSize); 2314 if (res) { 2315 process_debug_messages_data.next(); 2316 } 2317} 2318 2319// Test that the evaluation of expressions works even from ProcessDebugMessages 2320// i.e. with empty stack. 2321TEST(DebugEvaluateWithoutStack) { 2322 v8::Debug::SetMessageHandler(DebugProcessDebugMessagesHandler); 2323 2324 v8::HandleScope scope; 2325 DebugLocalContext env; 2326 2327 const char* source = 2328 "var v1 = 'Pinguin';\n function getAnimal() { return 'Capy' + 'bara'; }"; 2329 2330 v8::Script::Compile(v8::String::New(source))->Run(); 2331 2332 v8::Debug::ProcessDebugMessages(); 2333 2334 const int kBufferSize = 1000; 2335 uint16_t buffer[kBufferSize]; 2336 2337 const char* command_111 = "{\"seq\":111," 2338 "\"type\":\"request\"," 2339 "\"command\":\"evaluate\"," 2340 "\"arguments\":{" 2341 " \"global\":true," 2342 " \"expression\":\"v1\",\"disable_break\":true" 2343 "}}"; 2344 2345 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_111, buffer)); 2346 2347 const char* command_112 = "{\"seq\":112," 2348 "\"type\":\"request\"," 2349 "\"command\":\"evaluate\"," 2350 "\"arguments\":{" 2351 " \"global\":true," 2352 " \"expression\":\"getAnimal()\",\"disable_break\":true" 2353 "}}"; 2354 2355 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_112, buffer)); 2356 2357 const char* command_113 = "{\"seq\":113," 2358 "\"type\":\"request\"," 2359 "\"command\":\"evaluate\"," 2360 "\"arguments\":{" 2361 " \"global\":true," 2362 " \"expression\":\"239 + 566\",\"disable_break\":true" 2363 "}}"; 2364 2365 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_113, buffer)); 2366 2367 v8::Debug::ProcessDebugMessages(); 2368 2369 CHECK_EQ(3, process_debug_messages_data.counter); 2370 2371 CHECK_EQ(strcmp("Pinguin", process_debug_messages_data.results[0].buffer), 0); 2372 CHECK_EQ(strcmp("Capybara", process_debug_messages_data.results[1].buffer), 2373 0); 2374 CHECK_EQ(strcmp("805", process_debug_messages_data.results[2].buffer), 0); 2375 2376 v8::Debug::SetMessageHandler(NULL); 2377 v8::Debug::SetDebugEventListener(NULL); 2378 CheckDebuggerUnloaded(); 2379} 2380 2381 2382// Simple test of the stepping mechanism using only store ICs. 2383TEST(DebugStepLinear) { 2384 v8::HandleScope scope; 2385 DebugLocalContext env; 2386 2387 // Create a function for testing stepping. 2388 v8::Local<v8::Function> foo = CompileFunction(&env, 2389 "function foo(){a=1;b=1;c=1;}", 2390 "foo"); 2391 SetBreakPoint(foo, 3); 2392 2393 // Register a debug event listener which steps and counts. 2394 v8::Debug::SetDebugEventListener(DebugEventStep); 2395 2396 step_action = StepIn; 2397 break_point_hit_count = 0; 2398 foo->Call(env->Global(), 0, NULL); 2399 2400 // With stepping all break locations are hit. 2401 CHECK_EQ(4, break_point_hit_count); 2402 2403 v8::Debug::SetDebugEventListener(NULL); 2404 CheckDebuggerUnloaded(); 2405 2406 // Register a debug event listener which just counts. 2407 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount); 2408 2409 SetBreakPoint(foo, 3); 2410 break_point_hit_count = 0; 2411 foo->Call(env->Global(), 0, NULL); 2412 2413 // Without stepping only active break points are hit. 2414 CHECK_EQ(1, break_point_hit_count); 2415 2416 v8::Debug::SetDebugEventListener(NULL); 2417 CheckDebuggerUnloaded(); 2418} 2419 2420 2421// Test of the stepping mechanism for keyed load in a loop. 2422TEST(DebugStepKeyedLoadLoop) { 2423 v8::HandleScope scope; 2424 DebugLocalContext env; 2425 2426 // Create a function for testing stepping of keyed load. The statement 'y=1' 2427 // is there to have more than one breakable statement in the loop, TODO(315). 2428 v8::Local<v8::Function> foo = CompileFunction( 2429 &env, 2430 "function foo(a) {\n" 2431 " var x;\n" 2432 " var len = a.length;\n" 2433 " for (var i = 0; i < len; i++) {\n" 2434 " y = 1;\n" 2435 " x = a[i];\n" 2436 " }\n" 2437 "}\n", 2438 "foo"); 2439 2440 // Create array [0,1,2,3,4,5,6,7,8,9] 2441 v8::Local<v8::Array> a = v8::Array::New(10); 2442 for (int i = 0; i < 10; i++) { 2443 a->Set(v8::Number::New(i), v8::Number::New(i)); 2444 } 2445 2446 // Call function without any break points to ensure inlining is in place. 2447 const int kArgc = 1; 2448 v8::Handle<v8::Value> args[kArgc] = { a }; 2449 foo->Call(env->Global(), kArgc, args); 2450 2451 // Register a debug event listener which steps and counts. 2452 v8::Debug::SetDebugEventListener(DebugEventStep); 2453 2454 // Setup break point and step through the function. 2455 SetBreakPoint(foo, 3); 2456 step_action = StepNext; 2457 break_point_hit_count = 0; 2458 foo->Call(env->Global(), kArgc, args); 2459 2460 // With stepping all break locations are hit. 2461 CHECK_EQ(22, break_point_hit_count); 2462 2463 v8::Debug::SetDebugEventListener(NULL); 2464 CheckDebuggerUnloaded(); 2465} 2466 2467 2468// Test of the stepping mechanism for keyed store in a loop. 2469TEST(DebugStepKeyedStoreLoop) { 2470 v8::HandleScope scope; 2471 DebugLocalContext env; 2472 2473 // Create a function for testing stepping of keyed store. The statement 'y=1' 2474 // is there to have more than one breakable statement in the loop, TODO(315). 2475 v8::Local<v8::Function> foo = CompileFunction( 2476 &env, 2477 "function foo(a) {\n" 2478 " var len = a.length;\n" 2479 " for (var i = 0; i < len; i++) {\n" 2480 " y = 1;\n" 2481 " a[i] = 42;\n" 2482 " }\n" 2483 "}\n", 2484 "foo"); 2485 2486 // Create array [0,1,2,3,4,5,6,7,8,9] 2487 v8::Local<v8::Array> a = v8::Array::New(10); 2488 for (int i = 0; i < 10; i++) { 2489 a->Set(v8::Number::New(i), v8::Number::New(i)); 2490 } 2491 2492 // Call function without any break points to ensure inlining is in place. 2493 const int kArgc = 1; 2494 v8::Handle<v8::Value> args[kArgc] = { a }; 2495 foo->Call(env->Global(), kArgc, args); 2496 2497 // Register a debug event listener which steps and counts. 2498 v8::Debug::SetDebugEventListener(DebugEventStep); 2499 2500 // Setup break point and step through the function. 2501 SetBreakPoint(foo, 3); 2502 step_action = StepNext; 2503 break_point_hit_count = 0; 2504 foo->Call(env->Global(), kArgc, args); 2505 2506 // With stepping all break locations are hit. 2507 CHECK_EQ(22, break_point_hit_count); 2508 2509 v8::Debug::SetDebugEventListener(NULL); 2510 CheckDebuggerUnloaded(); 2511} 2512 2513 2514// Test of the stepping mechanism for named load in a loop. 2515TEST(DebugStepNamedLoadLoop) { 2516 v8::HandleScope scope; 2517 DebugLocalContext env; 2518 2519 // Create a function for testing stepping of named load. 2520 v8::Local<v8::Function> foo = CompileFunction( 2521 &env, 2522 "function foo() {\n" 2523 " var a = [];\n" 2524 " var s = \"\";\n" 2525 " for (var i = 0; i < 10; i++) {\n" 2526 " var v = new V(i, i + 1);\n" 2527 " v.y;\n" 2528 " a.length;\n" // Special case: array length. 2529 " s.length;\n" // Special case: string length. 2530 " }\n" 2531 "}\n" 2532 "function V(x, y) {\n" 2533 " this.x = x;\n" 2534 " this.y = y;\n" 2535 "}\n", 2536 "foo"); 2537 2538 // Call function without any break points to ensure inlining is in place. 2539 foo->Call(env->Global(), 0, NULL); 2540 2541 // Register a debug event listener which steps and counts. 2542 v8::Debug::SetDebugEventListener(DebugEventStep); 2543 2544 // Setup break point and step through the function. 2545 SetBreakPoint(foo, 4); 2546 step_action = StepNext; 2547 break_point_hit_count = 0; 2548 foo->Call(env->Global(), 0, NULL); 2549 2550 // With stepping all break locations are hit. 2551 CHECK_EQ(41, break_point_hit_count); 2552 2553 v8::Debug::SetDebugEventListener(NULL); 2554 CheckDebuggerUnloaded(); 2555} 2556 2557 2558// Test the stepping mechanism with different ICs. 2559TEST(DebugStepLinearMixedICs) { 2560 v8::HandleScope scope; 2561 DebugLocalContext env; 2562 2563 // Create a function for testing stepping. 2564 v8::Local<v8::Function> foo = CompileFunction(&env, 2565 "function bar() {};" 2566 "function foo() {" 2567 " var x;" 2568 " var index='name';" 2569 " var y = {};" 2570 " a=1;b=2;x=a;y[index]=3;x=y[index];bar();}", "foo"); 2571 SetBreakPoint(foo, 0); 2572 2573 // Register a debug event listener which steps and counts. 2574 v8::Debug::SetDebugEventListener(DebugEventStep); 2575 2576 step_action = StepIn; 2577 break_point_hit_count = 0; 2578 foo->Call(env->Global(), 0, NULL); 2579 2580 // With stepping all break locations are hit. 2581 CHECK_EQ(8, break_point_hit_count); 2582 2583 v8::Debug::SetDebugEventListener(NULL); 2584 CheckDebuggerUnloaded(); 2585 2586 // Register a debug event listener which just counts. 2587 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount); 2588 2589 SetBreakPoint(foo, 0); 2590 break_point_hit_count = 0; 2591 foo->Call(env->Global(), 0, NULL); 2592 2593 // Without stepping only active break points are hit. 2594 CHECK_EQ(1, break_point_hit_count); 2595 2596 v8::Debug::SetDebugEventListener(NULL); 2597 CheckDebuggerUnloaded(); 2598} 2599 2600 2601TEST(DebugStepIf) { 2602 v8::HandleScope scope; 2603 DebugLocalContext env; 2604 2605 // Register a debug event listener which steps and counts. 2606 v8::Debug::SetDebugEventListener(DebugEventStep); 2607 2608 // Create a function for testing stepping. 2609 const int argc = 1; 2610 const char* src = "function foo(x) { " 2611 " a = 1;" 2612 " if (x) {" 2613 " b = 1;" 2614 " } else {" 2615 " c = 1;" 2616 " d = 1;" 2617 " }" 2618 "}"; 2619 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo"); 2620 SetBreakPoint(foo, 0); 2621 2622 // Stepping through the true part. 2623 step_action = StepIn; 2624 break_point_hit_count = 0; 2625 v8::Handle<v8::Value> argv_true[argc] = { v8::True() }; 2626 foo->Call(env->Global(), argc, argv_true); 2627 CHECK_EQ(3, break_point_hit_count); 2628 2629 // Stepping through the false part. 2630 step_action = StepIn; 2631 break_point_hit_count = 0; 2632 v8::Handle<v8::Value> argv_false[argc] = { v8::False() }; 2633 foo->Call(env->Global(), argc, argv_false); 2634 CHECK_EQ(4, break_point_hit_count); 2635 2636 // Get rid of the debug event listener. 2637 v8::Debug::SetDebugEventListener(NULL); 2638 CheckDebuggerUnloaded(); 2639} 2640 2641 2642TEST(DebugStepSwitch) { 2643 v8::HandleScope scope; 2644 DebugLocalContext env; 2645 2646 // Register a debug event listener which steps and counts. 2647 v8::Debug::SetDebugEventListener(DebugEventStep); 2648 2649 // Create a function for testing stepping. 2650 const int argc = 1; 2651 const char* src = "function foo(x) { " 2652 " a = 1;" 2653 " switch (x) {" 2654 " case 1:" 2655 " b = 1;" 2656 " case 2:" 2657 " c = 1;" 2658 " break;" 2659 " case 3:" 2660 " d = 1;" 2661 " e = 1;" 2662 " break;" 2663 " }" 2664 "}"; 2665 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo"); 2666 SetBreakPoint(foo, 0); 2667 2668 // One case with fall-through. 2669 step_action = StepIn; 2670 break_point_hit_count = 0; 2671 v8::Handle<v8::Value> argv_1[argc] = { v8::Number::New(1) }; 2672 foo->Call(env->Global(), argc, argv_1); 2673 CHECK_EQ(4, break_point_hit_count); 2674 2675 // Another case. 2676 step_action = StepIn; 2677 break_point_hit_count = 0; 2678 v8::Handle<v8::Value> argv_2[argc] = { v8::Number::New(2) }; 2679 foo->Call(env->Global(), argc, argv_2); 2680 CHECK_EQ(3, break_point_hit_count); 2681 2682 // Last case. 2683 step_action = StepIn; 2684 break_point_hit_count = 0; 2685 v8::Handle<v8::Value> argv_3[argc] = { v8::Number::New(3) }; 2686 foo->Call(env->Global(), argc, argv_3); 2687 CHECK_EQ(4, break_point_hit_count); 2688 2689 // Get rid of the debug event listener. 2690 v8::Debug::SetDebugEventListener(NULL); 2691 CheckDebuggerUnloaded(); 2692} 2693 2694 2695TEST(DebugStepFor) { 2696 v8::HandleScope scope; 2697 DebugLocalContext env; 2698 2699 // Register a debug event listener which steps and counts. 2700 v8::Debug::SetDebugEventListener(DebugEventStep); 2701 2702 // Create a function for testing stepping. 2703 const int argc = 1; 2704 const char* src = "function foo(x) { " 2705 " a = 1;" 2706 " for (i = 0; i < x; i++) {" 2707 " b = 1;" 2708 " }" 2709 "}"; 2710 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo"); 2711 SetBreakPoint(foo, 8); // "a = 1;" 2712 2713 // Looping 10 times. 2714 step_action = StepIn; 2715 break_point_hit_count = 0; 2716 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) }; 2717 foo->Call(env->Global(), argc, argv_10); 2718 CHECK_EQ(23, break_point_hit_count); 2719 2720 // Looping 100 times. 2721 step_action = StepIn; 2722 break_point_hit_count = 0; 2723 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) }; 2724 foo->Call(env->Global(), argc, argv_100); 2725 CHECK_EQ(203, break_point_hit_count); 2726 2727 // Get rid of the debug event listener. 2728 v8::Debug::SetDebugEventListener(NULL); 2729 CheckDebuggerUnloaded(); 2730} 2731 2732 2733TEST(StepInOutSimple) { 2734 v8::HandleScope scope; 2735 DebugLocalContext env; 2736 2737 // Create a function for checking the function when hitting a break point. 2738 frame_function_name = CompileFunction(&env, 2739 frame_function_name_source, 2740 "frame_function_name"); 2741 2742 // Register a debug event listener which steps and counts. 2743 v8::Debug::SetDebugEventListener(DebugEventStepSequence); 2744 2745 // Create functions for testing stepping. 2746 const char* src = "function a() {b();c();}; " 2747 "function b() {c();}; " 2748 "function c() {}; "; 2749 v8::Local<v8::Function> a = CompileFunction(&env, src, "a"); 2750 SetBreakPoint(a, 0); 2751 2752 // Step through invocation of a with step in. 2753 step_action = StepIn; 2754 break_point_hit_count = 0; 2755 expected_step_sequence = "abcbaca"; 2756 a->Call(env->Global(), 0, NULL); 2757 CHECK_EQ(StrLength(expected_step_sequence), 2758 break_point_hit_count); 2759 2760 // Step through invocation of a with step next. 2761 step_action = StepNext; 2762 break_point_hit_count = 0; 2763 expected_step_sequence = "aaa"; 2764 a->Call(env->Global(), 0, NULL); 2765 CHECK_EQ(StrLength(expected_step_sequence), 2766 break_point_hit_count); 2767 2768 // Step through invocation of a with step out. 2769 step_action = StepOut; 2770 break_point_hit_count = 0; 2771 expected_step_sequence = "a"; 2772 a->Call(env->Global(), 0, NULL); 2773 CHECK_EQ(StrLength(expected_step_sequence), 2774 break_point_hit_count); 2775 2776 // Get rid of the debug event listener. 2777 v8::Debug::SetDebugEventListener(NULL); 2778 CheckDebuggerUnloaded(); 2779} 2780 2781 2782TEST(StepInOutTree) { 2783 v8::HandleScope scope; 2784 DebugLocalContext env; 2785 2786 // Create a function for checking the function when hitting a break point. 2787 frame_function_name = CompileFunction(&env, 2788 frame_function_name_source, 2789 "frame_function_name"); 2790 2791 // Register a debug event listener which steps and counts. 2792 v8::Debug::SetDebugEventListener(DebugEventStepSequence); 2793 2794 // Create functions for testing stepping. 2795 const char* src = "function a() {b(c(d()),d());c(d());d()}; " 2796 "function b(x,y) {c();}; " 2797 "function c(x) {}; " 2798 "function d() {}; "; 2799 v8::Local<v8::Function> a = CompileFunction(&env, src, "a"); 2800 SetBreakPoint(a, 0); 2801 2802 // Step through invocation of a with step in. 2803 step_action = StepIn; 2804 break_point_hit_count = 0; 2805 expected_step_sequence = "adacadabcbadacada"; 2806 a->Call(env->Global(), 0, NULL); 2807 CHECK_EQ(StrLength(expected_step_sequence), 2808 break_point_hit_count); 2809 2810 // Step through invocation of a with step next. 2811 step_action = StepNext; 2812 break_point_hit_count = 0; 2813 expected_step_sequence = "aaaa"; 2814 a->Call(env->Global(), 0, NULL); 2815 CHECK_EQ(StrLength(expected_step_sequence), 2816 break_point_hit_count); 2817 2818 // Step through invocation of a with step out. 2819 step_action = StepOut; 2820 break_point_hit_count = 0; 2821 expected_step_sequence = "a"; 2822 a->Call(env->Global(), 0, NULL); 2823 CHECK_EQ(StrLength(expected_step_sequence), 2824 break_point_hit_count); 2825 2826 // Get rid of the debug event listener. 2827 v8::Debug::SetDebugEventListener(NULL); 2828 CheckDebuggerUnloaded(true); 2829} 2830 2831 2832TEST(StepInOutBranch) { 2833 v8::HandleScope scope; 2834 DebugLocalContext env; 2835 2836 // Create a function for checking the function when hitting a break point. 2837 frame_function_name = CompileFunction(&env, 2838 frame_function_name_source, 2839 "frame_function_name"); 2840 2841 // Register a debug event listener which steps and counts. 2842 v8::Debug::SetDebugEventListener(DebugEventStepSequence); 2843 2844 // Create functions for testing stepping. 2845 const char* src = "function a() {b(false);c();}; " 2846 "function b(x) {if(x){c();};}; " 2847 "function c() {}; "; 2848 v8::Local<v8::Function> a = CompileFunction(&env, src, "a"); 2849 SetBreakPoint(a, 0); 2850 2851 // Step through invocation of a. 2852 step_action = StepIn; 2853 break_point_hit_count = 0; 2854 expected_step_sequence = "abaca"; 2855 a->Call(env->Global(), 0, NULL); 2856 CHECK_EQ(StrLength(expected_step_sequence), 2857 break_point_hit_count); 2858 2859 // Get rid of the debug event listener. 2860 v8::Debug::SetDebugEventListener(NULL); 2861 CheckDebuggerUnloaded(); 2862} 2863 2864 2865// Test that step in does not step into native functions. 2866TEST(DebugStepNatives) { 2867 v8::HandleScope scope; 2868 DebugLocalContext env; 2869 2870 // Create a function for testing stepping. 2871 v8::Local<v8::Function> foo = CompileFunction( 2872 &env, 2873 "function foo(){debugger;Math.sin(1);}", 2874 "foo"); 2875 2876 // Register a debug event listener which steps and counts. 2877 v8::Debug::SetDebugEventListener(DebugEventStep); 2878 2879 step_action = StepIn; 2880 break_point_hit_count = 0; 2881 foo->Call(env->Global(), 0, NULL); 2882 2883 // With stepping all break locations are hit. 2884 CHECK_EQ(3, break_point_hit_count); 2885 2886 v8::Debug::SetDebugEventListener(NULL); 2887 CheckDebuggerUnloaded(); 2888 2889 // Register a debug event listener which just counts. 2890 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount); 2891 2892 break_point_hit_count = 0; 2893 foo->Call(env->Global(), 0, NULL); 2894 2895 // Without stepping only active break points are hit. 2896 CHECK_EQ(1, break_point_hit_count); 2897 2898 v8::Debug::SetDebugEventListener(NULL); 2899 CheckDebuggerUnloaded(); 2900} 2901 2902 2903// Test that step in works with function.apply. 2904TEST(DebugStepFunctionApply) { 2905 v8::HandleScope scope; 2906 DebugLocalContext env; 2907 2908 // Create a function for testing stepping. 2909 v8::Local<v8::Function> foo = CompileFunction( 2910 &env, 2911 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }" 2912 "function foo(){ debugger; bar.apply(this, [1,2,3]); }", 2913 "foo"); 2914 2915 // Register a debug event listener which steps and counts. 2916 v8::Debug::SetDebugEventListener(DebugEventStep); 2917 2918 step_action = StepIn; 2919 break_point_hit_count = 0; 2920 foo->Call(env->Global(), 0, NULL); 2921 2922 // With stepping all break locations are hit. 2923 CHECK_EQ(6, break_point_hit_count); 2924 2925 v8::Debug::SetDebugEventListener(NULL); 2926 CheckDebuggerUnloaded(); 2927 2928 // Register a debug event listener which just counts. 2929 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount); 2930 2931 break_point_hit_count = 0; 2932 foo->Call(env->Global(), 0, NULL); 2933 2934 // Without stepping only the debugger statement is hit. 2935 CHECK_EQ(1, break_point_hit_count); 2936 2937 v8::Debug::SetDebugEventListener(NULL); 2938 CheckDebuggerUnloaded(); 2939} 2940 2941 2942// Test that step in works with function.call. 2943TEST(DebugStepFunctionCall) { 2944 v8::HandleScope scope; 2945 DebugLocalContext env; 2946 2947 // Create a function for testing stepping. 2948 v8::Local<v8::Function> foo = CompileFunction( 2949 &env, 2950 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }" 2951 "function foo(a){ debugger;" 2952 " if (a) {" 2953 " bar.call(this, 1, 2, 3);" 2954 " } else {" 2955 " bar.call(this, 0);" 2956 " }" 2957 "}", 2958 "foo"); 2959 2960 // Register a debug event listener which steps and counts. 2961 v8::Debug::SetDebugEventListener(DebugEventStep); 2962 step_action = StepIn; 2963 2964 // Check stepping where the if condition in bar is false. 2965 break_point_hit_count = 0; 2966 foo->Call(env->Global(), 0, NULL); 2967 CHECK_EQ(4, break_point_hit_count); 2968 2969 // Check stepping where the if condition in bar is true. 2970 break_point_hit_count = 0; 2971 const int argc = 1; 2972 v8::Handle<v8::Value> argv[argc] = { v8::True() }; 2973 foo->Call(env->Global(), argc, argv); 2974 CHECK_EQ(6, break_point_hit_count); 2975 2976 v8::Debug::SetDebugEventListener(NULL); 2977 CheckDebuggerUnloaded(); 2978 2979 // Register a debug event listener which just counts. 2980 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount); 2981 2982 break_point_hit_count = 0; 2983 foo->Call(env->Global(), 0, NULL); 2984 2985 // Without stepping only the debugger statement is hit. 2986 CHECK_EQ(1, break_point_hit_count); 2987 2988 v8::Debug::SetDebugEventListener(NULL); 2989 CheckDebuggerUnloaded(); 2990} 2991 2992 2993// Tests that breakpoint will be hit if it's set in script. 2994TEST(PauseInScript) { 2995 v8::HandleScope scope; 2996 DebugLocalContext env; 2997 env.ExposeDebug(); 2998 2999 // Register a debug event listener which counts. 3000 v8::Debug::SetDebugEventListener(DebugEventCounter); 3001 3002 // Create a script that returns a function. 3003 const char* src = "(function (evt) {})"; 3004 const char* script_name = "StepInHandlerTest"; 3005 3006 // Set breakpoint in the script. 3007 SetScriptBreakPointByNameFromJS(script_name, 0, -1); 3008 break_point_hit_count = 0; 3009 3010 v8::ScriptOrigin origin(v8::String::New(script_name), v8::Integer::New(0)); 3011 v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(src), 3012 &origin); 3013 v8::Local<v8::Value> r = script->Run(); 3014 3015 CHECK(r->IsFunction()); 3016 CHECK_EQ(1, break_point_hit_count); 3017 3018 // Get rid of the debug event listener. 3019 v8::Debug::SetDebugEventListener(NULL); 3020 CheckDebuggerUnloaded(); 3021} 3022 3023 3024// Test break on exceptions. For each exception break combination the number 3025// of debug event exception callbacks and message callbacks are collected. The 3026// number of debug event exception callbacks are used to check that the 3027// debugger is called correctly and the number of message callbacks is used to 3028// check that uncaught exceptions are still returned even if there is a break 3029// for them. 3030TEST(BreakOnException) { 3031 v8::HandleScope scope; 3032 DebugLocalContext env; 3033 env.ExposeDebug(); 3034 3035 v8::internal::Top::TraceException(false); 3036 3037 // Create functions for testing break on exception. 3038 v8::Local<v8::Function> throws = 3039 CompileFunction(&env, "function throws(){throw 1;}", "throws"); 3040 v8::Local<v8::Function> caught = 3041 CompileFunction(&env, 3042 "function caught(){try {throws();} catch(e) {};}", 3043 "caught"); 3044 v8::Local<v8::Function> notCaught = 3045 CompileFunction(&env, "function notCaught(){throws();}", "notCaught"); 3046 3047 v8::V8::AddMessageListener(MessageCallbackCount); 3048 v8::Debug::SetDebugEventListener(DebugEventCounter); 3049 3050 // Initial state should be break on uncaught exception. 3051 DebugEventCounterClear(); 3052 MessageCallbackCountClear(); 3053 caught->Call(env->Global(), 0, NULL); 3054 CHECK_EQ(0, exception_hit_count); 3055 CHECK_EQ(0, uncaught_exception_hit_count); 3056 CHECK_EQ(0, message_callback_count); 3057 notCaught->Call(env->Global(), 0, NULL); 3058 CHECK_EQ(1, exception_hit_count); 3059 CHECK_EQ(1, uncaught_exception_hit_count); 3060 CHECK_EQ(1, message_callback_count); 3061 3062 // No break on exception 3063 DebugEventCounterClear(); 3064 MessageCallbackCountClear(); 3065 ChangeBreakOnException(false, false); 3066 caught->Call(env->Global(), 0, NULL); 3067 CHECK_EQ(0, exception_hit_count); 3068 CHECK_EQ(0, uncaught_exception_hit_count); 3069 CHECK_EQ(0, message_callback_count); 3070 notCaught->Call(env->Global(), 0, NULL); 3071 CHECK_EQ(0, exception_hit_count); 3072 CHECK_EQ(0, uncaught_exception_hit_count); 3073 CHECK_EQ(1, message_callback_count); 3074 3075 // Break on uncaught exception 3076 DebugEventCounterClear(); 3077 MessageCallbackCountClear(); 3078 ChangeBreakOnException(false, true); 3079 caught->Call(env->Global(), 0, NULL); 3080 CHECK_EQ(0, exception_hit_count); 3081 CHECK_EQ(0, uncaught_exception_hit_count); 3082 CHECK_EQ(0, message_callback_count); 3083 notCaught->Call(env->Global(), 0, NULL); 3084 CHECK_EQ(1, exception_hit_count); 3085 CHECK_EQ(1, uncaught_exception_hit_count); 3086 CHECK_EQ(1, message_callback_count); 3087 3088 // Break on exception and uncaught exception 3089 DebugEventCounterClear(); 3090 MessageCallbackCountClear(); 3091 ChangeBreakOnException(true, true); 3092 caught->Call(env->Global(), 0, NULL); 3093 CHECK_EQ(1, exception_hit_count); 3094 CHECK_EQ(0, uncaught_exception_hit_count); 3095 CHECK_EQ(0, message_callback_count); 3096 notCaught->Call(env->Global(), 0, NULL); 3097 CHECK_EQ(2, exception_hit_count); 3098 CHECK_EQ(1, uncaught_exception_hit_count); 3099 CHECK_EQ(1, message_callback_count); 3100 3101 // Break on exception 3102 DebugEventCounterClear(); 3103 MessageCallbackCountClear(); 3104 ChangeBreakOnException(true, false); 3105 caught->Call(env->Global(), 0, NULL); 3106 CHECK_EQ(1, exception_hit_count); 3107 CHECK_EQ(0, uncaught_exception_hit_count); 3108 CHECK_EQ(0, message_callback_count); 3109 notCaught->Call(env->Global(), 0, NULL); 3110 CHECK_EQ(2, exception_hit_count); 3111 CHECK_EQ(1, uncaught_exception_hit_count); 3112 CHECK_EQ(1, message_callback_count); 3113 3114 // No break on exception using JavaScript 3115 DebugEventCounterClear(); 3116 MessageCallbackCountClear(); 3117 ChangeBreakOnExceptionFromJS(false, false); 3118 caught->Call(env->Global(), 0, NULL); 3119 CHECK_EQ(0, exception_hit_count); 3120 CHECK_EQ(0, uncaught_exception_hit_count); 3121 CHECK_EQ(0, message_callback_count); 3122 notCaught->Call(env->Global(), 0, NULL); 3123 CHECK_EQ(0, exception_hit_count); 3124 CHECK_EQ(0, uncaught_exception_hit_count); 3125 CHECK_EQ(1, message_callback_count); 3126 3127 // Break on uncaught exception using JavaScript 3128 DebugEventCounterClear(); 3129 MessageCallbackCountClear(); 3130 ChangeBreakOnExceptionFromJS(false, true); 3131 caught->Call(env->Global(), 0, NULL); 3132 CHECK_EQ(0, exception_hit_count); 3133 CHECK_EQ(0, uncaught_exception_hit_count); 3134 CHECK_EQ(0, message_callback_count); 3135 notCaught->Call(env->Global(), 0, NULL); 3136 CHECK_EQ(1, exception_hit_count); 3137 CHECK_EQ(1, uncaught_exception_hit_count); 3138 CHECK_EQ(1, message_callback_count); 3139 3140 // Break on exception and uncaught exception using JavaScript 3141 DebugEventCounterClear(); 3142 MessageCallbackCountClear(); 3143 ChangeBreakOnExceptionFromJS(true, true); 3144 caught->Call(env->Global(), 0, NULL); 3145 CHECK_EQ(1, exception_hit_count); 3146 CHECK_EQ(0, message_callback_count); 3147 CHECK_EQ(0, uncaught_exception_hit_count); 3148 notCaught->Call(env->Global(), 0, NULL); 3149 CHECK_EQ(2, exception_hit_count); 3150 CHECK_EQ(1, uncaught_exception_hit_count); 3151 CHECK_EQ(1, message_callback_count); 3152 3153 // Break on exception using JavaScript 3154 DebugEventCounterClear(); 3155 MessageCallbackCountClear(); 3156 ChangeBreakOnExceptionFromJS(true, false); 3157 caught->Call(env->Global(), 0, NULL); 3158 CHECK_EQ(1, exception_hit_count); 3159 CHECK_EQ(0, uncaught_exception_hit_count); 3160 CHECK_EQ(0, message_callback_count); 3161 notCaught->Call(env->Global(), 0, NULL); 3162 CHECK_EQ(2, exception_hit_count); 3163 CHECK_EQ(1, uncaught_exception_hit_count); 3164 CHECK_EQ(1, message_callback_count); 3165 3166 v8::Debug::SetDebugEventListener(NULL); 3167 CheckDebuggerUnloaded(); 3168 v8::V8::RemoveMessageListeners(MessageCallbackCount); 3169} 3170 3171 3172// Test break on exception from compiler errors. When compiling using 3173// v8::Script::Compile there is no JavaScript stack whereas when compiling using 3174// eval there are JavaScript frames. 3175TEST(BreakOnCompileException) { 3176 v8::HandleScope scope; 3177 DebugLocalContext env; 3178 3179 v8::internal::Top::TraceException(false); 3180 3181 // Create a function for checking the function when hitting a break point. 3182 frame_count = CompileFunction(&env, frame_count_source, "frame_count"); 3183 3184 v8::V8::AddMessageListener(MessageCallbackCount); 3185 v8::Debug::SetDebugEventListener(DebugEventCounter); 3186 3187 DebugEventCounterClear(); 3188 MessageCallbackCountClear(); 3189 3190 // Check initial state. 3191 CHECK_EQ(0, exception_hit_count); 3192 CHECK_EQ(0, uncaught_exception_hit_count); 3193 CHECK_EQ(0, message_callback_count); 3194 CHECK_EQ(-1, last_js_stack_height); 3195 3196 // Throws SyntaxError: Unexpected end of input 3197 v8::Script::Compile(v8::String::New("+++")); 3198 CHECK_EQ(1, exception_hit_count); 3199 CHECK_EQ(1, uncaught_exception_hit_count); 3200 CHECK_EQ(1, message_callback_count); 3201 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack. 3202 3203 // Throws SyntaxError: Unexpected identifier 3204 v8::Script::Compile(v8::String::New("x x")); 3205 CHECK_EQ(2, exception_hit_count); 3206 CHECK_EQ(2, uncaught_exception_hit_count); 3207 CHECK_EQ(2, message_callback_count); 3208 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack. 3209 3210 // Throws SyntaxError: Unexpected end of input 3211 v8::Script::Compile(v8::String::New("eval('+++')"))->Run(); 3212 CHECK_EQ(3, exception_hit_count); 3213 CHECK_EQ(3, uncaught_exception_hit_count); 3214 CHECK_EQ(3, message_callback_count); 3215 CHECK_EQ(1, last_js_stack_height); 3216 3217 // Throws SyntaxError: Unexpected identifier 3218 v8::Script::Compile(v8::String::New("eval('x x')"))->Run(); 3219 CHECK_EQ(4, exception_hit_count); 3220 CHECK_EQ(4, uncaught_exception_hit_count); 3221 CHECK_EQ(4, message_callback_count); 3222 CHECK_EQ(1, last_js_stack_height); 3223} 3224 3225 3226TEST(StepWithException) { 3227 v8::HandleScope scope; 3228 DebugLocalContext env; 3229 3230 // Create a function for checking the function when hitting a break point. 3231 frame_function_name = CompileFunction(&env, 3232 frame_function_name_source, 3233 "frame_function_name"); 3234 3235 // Register a debug event listener which steps and counts. 3236 v8::Debug::SetDebugEventListener(DebugEventStepSequence); 3237 3238 // Create functions for testing stepping. 3239 const char* src = "function a() { n(); }; " 3240 "function b() { c(); }; " 3241 "function c() { n(); }; " 3242 "function d() { x = 1; try { e(); } catch(x) { x = 2; } }; " 3243 "function e() { n(); }; " 3244 "function f() { x = 1; try { g(); } catch(x) { x = 2; } }; " 3245 "function g() { h(); }; " 3246 "function h() { x = 1; throw 1; }; "; 3247 3248 // Step through invocation of a. 3249 v8::Local<v8::Function> a = CompileFunction(&env, src, "a"); 3250 SetBreakPoint(a, 0); 3251 step_action = StepIn; 3252 break_point_hit_count = 0; 3253 expected_step_sequence = "aa"; 3254 a->Call(env->Global(), 0, NULL); 3255 CHECK_EQ(StrLength(expected_step_sequence), 3256 break_point_hit_count); 3257 3258 // Step through invocation of b + c. 3259 v8::Local<v8::Function> b = CompileFunction(&env, src, "b"); 3260 SetBreakPoint(b, 0); 3261 step_action = StepIn; 3262 break_point_hit_count = 0; 3263 expected_step_sequence = "bcc"; 3264 b->Call(env->Global(), 0, NULL); 3265 CHECK_EQ(StrLength(expected_step_sequence), 3266 break_point_hit_count); 3267 3268 // Step through invocation of d + e. 3269 v8::Local<v8::Function> d = CompileFunction(&env, src, "d"); 3270 SetBreakPoint(d, 0); 3271 ChangeBreakOnException(false, true); 3272 step_action = StepIn; 3273 break_point_hit_count = 0; 3274 expected_step_sequence = "dded"; 3275 d->Call(env->Global(), 0, NULL); 3276 CHECK_EQ(StrLength(expected_step_sequence), 3277 break_point_hit_count); 3278 3279 // Step through invocation of d + e now with break on caught exceptions. 3280 ChangeBreakOnException(true, true); 3281 step_action = StepIn; 3282 break_point_hit_count = 0; 3283 expected_step_sequence = "ddeed"; 3284 d->Call(env->Global(), 0, NULL); 3285 CHECK_EQ(StrLength(expected_step_sequence), 3286 break_point_hit_count); 3287 3288 // Step through invocation of f + g + h. 3289 v8::Local<v8::Function> f = CompileFunction(&env, src, "f"); 3290 SetBreakPoint(f, 0); 3291 ChangeBreakOnException(false, true); 3292 step_action = StepIn; 3293 break_point_hit_count = 0; 3294 expected_step_sequence = "ffghf"; 3295 f->Call(env->Global(), 0, NULL); 3296 CHECK_EQ(StrLength(expected_step_sequence), 3297 break_point_hit_count); 3298 3299 // Step through invocation of f + g + h now with break on caught exceptions. 3300 ChangeBreakOnException(true, true); 3301 step_action = StepIn; 3302 break_point_hit_count = 0; 3303 expected_step_sequence = "ffghhf"; 3304 f->Call(env->Global(), 0, NULL); 3305 CHECK_EQ(StrLength(expected_step_sequence), 3306 break_point_hit_count); 3307 3308 // Get rid of the debug event listener. 3309 v8::Debug::SetDebugEventListener(NULL); 3310 CheckDebuggerUnloaded(); 3311} 3312 3313 3314TEST(DebugBreak) { 3315 v8::HandleScope scope; 3316 DebugLocalContext env; 3317 3318 // This test should be run with option --verify-heap. As --verify-heap is 3319 // only available in debug mode only check for it in that case. 3320#ifdef DEBUG 3321 CHECK(v8::internal::FLAG_verify_heap); 3322#endif 3323 3324 // Register a debug event listener which sets the break flag and counts. 3325 v8::Debug::SetDebugEventListener(DebugEventBreak); 3326 3327 // Create a function for testing stepping. 3328 const char* src = "function f0() {}" 3329 "function f1(x1) {}" 3330 "function f2(x1,x2) {}" 3331 "function f3(x1,x2,x3) {}"; 3332 v8::Local<v8::Function> f0 = CompileFunction(&env, src, "f0"); 3333 v8::Local<v8::Function> f1 = CompileFunction(&env, src, "f1"); 3334 v8::Local<v8::Function> f2 = CompileFunction(&env, src, "f2"); 3335 v8::Local<v8::Function> f3 = CompileFunction(&env, src, "f3"); 3336 3337 // Call the function to make sure it is compiled. 3338 v8::Handle<v8::Value> argv[] = { v8::Number::New(1), 3339 v8::Number::New(1), 3340 v8::Number::New(1), 3341 v8::Number::New(1) }; 3342 3343 // Call all functions to make sure that they are compiled. 3344 f0->Call(env->Global(), 0, NULL); 3345 f1->Call(env->Global(), 0, NULL); 3346 f2->Call(env->Global(), 0, NULL); 3347 f3->Call(env->Global(), 0, NULL); 3348 3349 // Set the debug break flag. 3350 v8::Debug::DebugBreak(); 3351 3352 // Call all functions with different argument count. 3353 break_point_hit_count = 0; 3354 for (unsigned int i = 0; i < ARRAY_SIZE(argv); i++) { 3355 f0->Call(env->Global(), i, argv); 3356 f1->Call(env->Global(), i, argv); 3357 f2->Call(env->Global(), i, argv); 3358 f3->Call(env->Global(), i, argv); 3359 } 3360 3361 // One break for each function called. 3362 CHECK_EQ(4 * ARRAY_SIZE(argv), break_point_hit_count); 3363 3364 // Get rid of the debug event listener. 3365 v8::Debug::SetDebugEventListener(NULL); 3366 CheckDebuggerUnloaded(); 3367} 3368 3369 3370// Test to ensure that JavaScript code keeps running while the debug break 3371// through the stack limit flag is set but breaks are disabled. 3372TEST(DisableBreak) { 3373 v8::HandleScope scope; 3374 DebugLocalContext env; 3375 3376 // Register a debug event listener which sets the break flag and counts. 3377 v8::Debug::SetDebugEventListener(DebugEventCounter); 3378 3379 // Create a function for testing stepping. 3380 const char* src = "function f() {g()};function g(){i=0; while(i<10){i++}}"; 3381 v8::Local<v8::Function> f = CompileFunction(&env, src, "f"); 3382 3383 // Set the debug break flag. 3384 v8::Debug::DebugBreak(); 3385 3386 // Call all functions with different argument count. 3387 break_point_hit_count = 0; 3388 f->Call(env->Global(), 0, NULL); 3389 CHECK_EQ(1, break_point_hit_count); 3390 3391 { 3392 v8::Debug::DebugBreak(); 3393 v8::internal::DisableBreak disable_break(true); 3394 f->Call(env->Global(), 0, NULL); 3395 CHECK_EQ(1, break_point_hit_count); 3396 } 3397 3398 f->Call(env->Global(), 0, NULL); 3399 CHECK_EQ(2, break_point_hit_count); 3400 3401 // Get rid of the debug event listener. 3402 v8::Debug::SetDebugEventListener(NULL); 3403 CheckDebuggerUnloaded(); 3404} 3405 3406static const char* kSimpleExtensionSource = 3407 "(function Foo() {" 3408 " return 4;" 3409 "})() "; 3410 3411// http://crbug.com/28933 3412// Test that debug break is disabled when bootstrapper is active. 3413TEST(NoBreakWhenBootstrapping) { 3414 v8::HandleScope scope; 3415 3416 // Register a debug event listener which sets the break flag and counts. 3417 v8::Debug::SetDebugEventListener(DebugEventCounter); 3418 3419 // Set the debug break flag. 3420 v8::Debug::DebugBreak(); 3421 break_point_hit_count = 0; 3422 { 3423 // Create a context with an extension to make sure that some JavaScript 3424 // code is executed during bootstrapping. 3425 v8::RegisterExtension(new v8::Extension("simpletest", 3426 kSimpleExtensionSource)); 3427 const char* extension_names[] = { "simpletest" }; 3428 v8::ExtensionConfiguration extensions(1, extension_names); 3429 v8::Persistent<v8::Context> context = v8::Context::New(&extensions); 3430 context.Dispose(); 3431 } 3432 // Check that no DebugBreak events occured during the context creation. 3433 CHECK_EQ(0, break_point_hit_count); 3434 3435 // Get rid of the debug event listener. 3436 v8::Debug::SetDebugEventListener(NULL); 3437 CheckDebuggerUnloaded(); 3438} 3439 3440static v8::Handle<v8::Array> NamedEnum(const v8::AccessorInfo&) { 3441 v8::Handle<v8::Array> result = v8::Array::New(3); 3442 result->Set(v8::Integer::New(0), v8::String::New("a")); 3443 result->Set(v8::Integer::New(1), v8::String::New("b")); 3444 result->Set(v8::Integer::New(2), v8::String::New("c")); 3445 return result; 3446} 3447 3448 3449static v8::Handle<v8::Array> IndexedEnum(const v8::AccessorInfo&) { 3450 v8::Handle<v8::Array> result = v8::Array::New(2); 3451 result->Set(v8::Integer::New(0), v8::Number::New(1)); 3452 result->Set(v8::Integer::New(1), v8::Number::New(10)); 3453 return result; 3454} 3455 3456 3457static v8::Handle<v8::Value> NamedGetter(v8::Local<v8::String> name, 3458 const v8::AccessorInfo& info) { 3459 v8::String::AsciiValue n(name); 3460 if (strcmp(*n, "a") == 0) { 3461 return v8::String::New("AA"); 3462 } else if (strcmp(*n, "b") == 0) { 3463 return v8::String::New("BB"); 3464 } else if (strcmp(*n, "c") == 0) { 3465 return v8::String::New("CC"); 3466 } else { 3467 return v8::Undefined(); 3468 } 3469 3470 return name; 3471} 3472 3473 3474static v8::Handle<v8::Value> IndexedGetter(uint32_t index, 3475 const v8::AccessorInfo& info) { 3476 return v8::Number::New(index + 1); 3477} 3478 3479 3480TEST(InterceptorPropertyMirror) { 3481 // Create a V8 environment with debug access. 3482 v8::HandleScope scope; 3483 DebugLocalContext env; 3484 env.ExposeDebug(); 3485 3486 // Create object with named interceptor. 3487 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(); 3488 named->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum); 3489 env->Global()->Set(v8::String::New("intercepted_named"), 3490 named->NewInstance()); 3491 3492 // Create object with indexed interceptor. 3493 v8::Handle<v8::ObjectTemplate> indexed = v8::ObjectTemplate::New(); 3494 indexed->SetIndexedPropertyHandler(IndexedGetter, 3495 NULL, 3496 NULL, 3497 NULL, 3498 IndexedEnum); 3499 env->Global()->Set(v8::String::New("intercepted_indexed"), 3500 indexed->NewInstance()); 3501 3502 // Create object with both named and indexed interceptor. 3503 v8::Handle<v8::ObjectTemplate> both = v8::ObjectTemplate::New(); 3504 both->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum); 3505 both->SetIndexedPropertyHandler(IndexedGetter, NULL, NULL, NULL, IndexedEnum); 3506 env->Global()->Set(v8::String::New("intercepted_both"), both->NewInstance()); 3507 3508 // Get mirrors for the three objects with interceptor. 3509 CompileRun( 3510 "named_mirror = debug.MakeMirror(intercepted_named);" 3511 "indexed_mirror = debug.MakeMirror(intercepted_indexed);" 3512 "both_mirror = debug.MakeMirror(intercepted_both)"); 3513 CHECK(CompileRun( 3514 "named_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3515 CHECK(CompileRun( 3516 "indexed_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3517 CHECK(CompileRun( 3518 "both_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3519 3520 // Get the property names from the interceptors 3521 CompileRun( 3522 "named_names = named_mirror.propertyNames();" 3523 "indexed_names = indexed_mirror.propertyNames();" 3524 "both_names = both_mirror.propertyNames()"); 3525 CHECK_EQ(3, CompileRun("named_names.length")->Int32Value()); 3526 CHECK_EQ(2, CompileRun("indexed_names.length")->Int32Value()); 3527 CHECK_EQ(5, CompileRun("both_names.length")->Int32Value()); 3528 3529 // Check the expected number of properties. 3530 const char* source; 3531 source = "named_mirror.properties().length"; 3532 CHECK_EQ(3, CompileRun(source)->Int32Value()); 3533 3534 source = "indexed_mirror.properties().length"; 3535 CHECK_EQ(2, CompileRun(source)->Int32Value()); 3536 3537 source = "both_mirror.properties().length"; 3538 CHECK_EQ(5, CompileRun(source)->Int32Value()); 3539 3540 // 1 is PropertyKind.Named; 3541 source = "both_mirror.properties(1).length"; 3542 CHECK_EQ(3, CompileRun(source)->Int32Value()); 3543 3544 // 2 is PropertyKind.Indexed; 3545 source = "both_mirror.properties(2).length"; 3546 CHECK_EQ(2, CompileRun(source)->Int32Value()); 3547 3548 // 3 is PropertyKind.Named | PropertyKind.Indexed; 3549 source = "both_mirror.properties(3).length"; 3550 CHECK_EQ(5, CompileRun(source)->Int32Value()); 3551 3552 // Get the interceptor properties for the object with only named interceptor. 3553 CompileRun("named_values = named_mirror.properties()"); 3554 3555 // Check that the properties are interceptor properties. 3556 for (int i = 0; i < 3; i++) { 3557 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 3558 OS::SNPrintF(buffer, 3559 "named_values[%d] instanceof debug.PropertyMirror", i); 3560 CHECK(CompileRun(buffer.start())->BooleanValue()); 3561 3562 // 4 is PropertyType.Interceptor 3563 OS::SNPrintF(buffer, "named_values[%d].propertyType()", i); 3564 CHECK_EQ(4, CompileRun(buffer.start())->Int32Value()); 3565 3566 OS::SNPrintF(buffer, "named_values[%d].isNative()", i); 3567 CHECK(CompileRun(buffer.start())->BooleanValue()); 3568 } 3569 3570 // Get the interceptor properties for the object with only indexed 3571 // interceptor. 3572 CompileRun("indexed_values = indexed_mirror.properties()"); 3573 3574 // Check that the properties are interceptor properties. 3575 for (int i = 0; i < 2; i++) { 3576 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 3577 OS::SNPrintF(buffer, 3578 "indexed_values[%d] instanceof debug.PropertyMirror", i); 3579 CHECK(CompileRun(buffer.start())->BooleanValue()); 3580 } 3581 3582 // Get the interceptor properties for the object with both types of 3583 // interceptors. 3584 CompileRun("both_values = both_mirror.properties()"); 3585 3586 // Check that the properties are interceptor properties. 3587 for (int i = 0; i < 5; i++) { 3588 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer; 3589 OS::SNPrintF(buffer, "both_values[%d] instanceof debug.PropertyMirror", i); 3590 CHECK(CompileRun(buffer.start())->BooleanValue()); 3591 } 3592 3593 // Check the property names. 3594 source = "both_values[0].name() == 'a'"; 3595 CHECK(CompileRun(source)->BooleanValue()); 3596 3597 source = "both_values[1].name() == 'b'"; 3598 CHECK(CompileRun(source)->BooleanValue()); 3599 3600 source = "both_values[2].name() == 'c'"; 3601 CHECK(CompileRun(source)->BooleanValue()); 3602 3603 source = "both_values[3].name() == 1"; 3604 CHECK(CompileRun(source)->BooleanValue()); 3605 3606 source = "both_values[4].name() == 10"; 3607 CHECK(CompileRun(source)->BooleanValue()); 3608} 3609 3610 3611TEST(HiddenPrototypePropertyMirror) { 3612 // Create a V8 environment with debug access. 3613 v8::HandleScope scope; 3614 DebugLocalContext env; 3615 env.ExposeDebug(); 3616 3617 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New(); 3618 t0->InstanceTemplate()->Set(v8::String::New("x"), v8::Number::New(0)); 3619 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New(); 3620 t1->SetHiddenPrototype(true); 3621 t1->InstanceTemplate()->Set(v8::String::New("y"), v8::Number::New(1)); 3622 v8::Handle<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New(); 3623 t2->SetHiddenPrototype(true); 3624 t2->InstanceTemplate()->Set(v8::String::New("z"), v8::Number::New(2)); 3625 v8::Handle<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New(); 3626 t3->InstanceTemplate()->Set(v8::String::New("u"), v8::Number::New(3)); 3627 3628 // Create object and set them on the global object. 3629 v8::Handle<v8::Object> o0 = t0->GetFunction()->NewInstance(); 3630 env->Global()->Set(v8::String::New("o0"), o0); 3631 v8::Handle<v8::Object> o1 = t1->GetFunction()->NewInstance(); 3632 env->Global()->Set(v8::String::New("o1"), o1); 3633 v8::Handle<v8::Object> o2 = t2->GetFunction()->NewInstance(); 3634 env->Global()->Set(v8::String::New("o2"), o2); 3635 v8::Handle<v8::Object> o3 = t3->GetFunction()->NewInstance(); 3636 env->Global()->Set(v8::String::New("o3"), o3); 3637 3638 // Get mirrors for the four objects. 3639 CompileRun( 3640 "o0_mirror = debug.MakeMirror(o0);" 3641 "o1_mirror = debug.MakeMirror(o1);" 3642 "o2_mirror = debug.MakeMirror(o2);" 3643 "o3_mirror = debug.MakeMirror(o3)"); 3644 CHECK(CompileRun("o0_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3645 CHECK(CompileRun("o1_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3646 CHECK(CompileRun("o2_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3647 CHECK(CompileRun("o3_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3648 3649 // Check that each object has one property. 3650 CHECK_EQ(1, CompileRun( 3651 "o0_mirror.propertyNames().length")->Int32Value()); 3652 CHECK_EQ(1, CompileRun( 3653 "o1_mirror.propertyNames().length")->Int32Value()); 3654 CHECK_EQ(1, CompileRun( 3655 "o2_mirror.propertyNames().length")->Int32Value()); 3656 CHECK_EQ(1, CompileRun( 3657 "o3_mirror.propertyNames().length")->Int32Value()); 3658 3659 // Set o1 as prototype for o0. o1 has the hidden prototype flag so all 3660 // properties on o1 should be seen on o0. 3661 o0->Set(v8::String::New("__proto__"), o1); 3662 CHECK_EQ(2, CompileRun( 3663 "o0_mirror.propertyNames().length")->Int32Value()); 3664 CHECK_EQ(0, CompileRun( 3665 "o0_mirror.property('x').value().value()")->Int32Value()); 3666 CHECK_EQ(1, CompileRun( 3667 "o0_mirror.property('y').value().value()")->Int32Value()); 3668 3669 // Set o2 as prototype for o0 (it will end up after o1 as o1 has the hidden 3670 // prototype flag. o2 also has the hidden prototype flag so all properties 3671 // on o2 should be seen on o0 as well as properties on o1. 3672 o0->Set(v8::String::New("__proto__"), o2); 3673 CHECK_EQ(3, CompileRun( 3674 "o0_mirror.propertyNames().length")->Int32Value()); 3675 CHECK_EQ(0, CompileRun( 3676 "o0_mirror.property('x').value().value()")->Int32Value()); 3677 CHECK_EQ(1, CompileRun( 3678 "o0_mirror.property('y').value().value()")->Int32Value()); 3679 CHECK_EQ(2, CompileRun( 3680 "o0_mirror.property('z').value().value()")->Int32Value()); 3681 3682 // Set o3 as prototype for o0 (it will end up after o1 and o2 as both o1 and 3683 // o2 has the hidden prototype flag. o3 does not have the hidden prototype 3684 // flag so properties on o3 should not be seen on o0 whereas the properties 3685 // from o1 and o2 should still be seen on o0. 3686 // Final prototype chain: o0 -> o1 -> o2 -> o3 3687 // Hidden prototypes: ^^ ^^ 3688 o0->Set(v8::String::New("__proto__"), o3); 3689 CHECK_EQ(3, CompileRun( 3690 "o0_mirror.propertyNames().length")->Int32Value()); 3691 CHECK_EQ(1, CompileRun( 3692 "o3_mirror.propertyNames().length")->Int32Value()); 3693 CHECK_EQ(0, CompileRun( 3694 "o0_mirror.property('x').value().value()")->Int32Value()); 3695 CHECK_EQ(1, CompileRun( 3696 "o0_mirror.property('y').value().value()")->Int32Value()); 3697 CHECK_EQ(2, CompileRun( 3698 "o0_mirror.property('z').value().value()")->Int32Value()); 3699 CHECK(CompileRun("o0_mirror.property('u').isUndefined()")->BooleanValue()); 3700 3701 // The prototype (__proto__) for o0 should be o3 as o1 and o2 are hidden. 3702 CHECK(CompileRun("o0_mirror.protoObject() == o3_mirror")->BooleanValue()); 3703} 3704 3705 3706static v8::Handle<v8::Value> ProtperyXNativeGetter( 3707 v8::Local<v8::String> property, const v8::AccessorInfo& info) { 3708 return v8::Integer::New(10); 3709} 3710 3711 3712TEST(NativeGetterPropertyMirror) { 3713 // Create a V8 environment with debug access. 3714 v8::HandleScope scope; 3715 DebugLocalContext env; 3716 env.ExposeDebug(); 3717 3718 v8::Handle<v8::String> name = v8::String::New("x"); 3719 // Create object with named accessor. 3720 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(); 3721 named->SetAccessor(name, &ProtperyXNativeGetter, NULL, 3722 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None); 3723 3724 // Create object with named property getter. 3725 env->Global()->Set(v8::String::New("instance"), named->NewInstance()); 3726 CHECK_EQ(10, CompileRun("instance.x")->Int32Value()); 3727 3728 // Get mirror for the object with property getter. 3729 CompileRun("instance_mirror = debug.MakeMirror(instance);"); 3730 CHECK(CompileRun( 3731 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3732 3733 CompileRun("named_names = instance_mirror.propertyNames();"); 3734 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value()); 3735 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue()); 3736 CHECK(CompileRun( 3737 "instance_mirror.property('x').value().isNumber()")->BooleanValue()); 3738 CHECK(CompileRun( 3739 "instance_mirror.property('x').value().value() == 10")->BooleanValue()); 3740} 3741 3742 3743static v8::Handle<v8::Value> ProtperyXNativeGetterThrowingError( 3744 v8::Local<v8::String> property, const v8::AccessorInfo& info) { 3745 return CompileRun("throw new Error('Error message');"); 3746} 3747 3748 3749TEST(NativeGetterThrowingErrorPropertyMirror) { 3750 // Create a V8 environment with debug access. 3751 v8::HandleScope scope; 3752 DebugLocalContext env; 3753 env.ExposeDebug(); 3754 3755 v8::Handle<v8::String> name = v8::String::New("x"); 3756 // Create object with named accessor. 3757 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(); 3758 named->SetAccessor(name, &ProtperyXNativeGetterThrowingError, NULL, 3759 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None); 3760 3761 // Create object with named property getter. 3762 env->Global()->Set(v8::String::New("instance"), named->NewInstance()); 3763 3764 // Get mirror for the object with property getter. 3765 CompileRun("instance_mirror = debug.MakeMirror(instance);"); 3766 CHECK(CompileRun( 3767 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3768 CompileRun("named_names = instance_mirror.propertyNames();"); 3769 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value()); 3770 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue()); 3771 CHECK(CompileRun( 3772 "instance_mirror.property('x').value().isError()")->BooleanValue()); 3773 3774 // Check that the message is that passed to the Error constructor. 3775 CHECK(CompileRun( 3776 "instance_mirror.property('x').value().message() == 'Error message'")-> 3777 BooleanValue()); 3778} 3779 3780 3781// Test that hidden properties object is not returned as an unnamed property 3782// among regular properties. 3783// See http://crbug.com/26491 3784TEST(NoHiddenProperties) { 3785 // Create a V8 environment with debug access. 3786 v8::HandleScope scope; 3787 DebugLocalContext env; 3788 env.ExposeDebug(); 3789 3790 // Create an object in the global scope. 3791 const char* source = "var obj = {a: 1};"; 3792 v8::Script::Compile(v8::String::New(source))->Run(); 3793 v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast( 3794 env->Global()->Get(v8::String::New("obj"))); 3795 // Set a hidden property on the object. 3796 obj->SetHiddenValue(v8::String::New("v8::test-debug::a"), 3797 v8::Int32::New(11)); 3798 3799 // Get mirror for the object with property getter. 3800 CompileRun("var obj_mirror = debug.MakeMirror(obj);"); 3801 CHECK(CompileRun( 3802 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3803 CompileRun("var named_names = obj_mirror.propertyNames();"); 3804 // There should be exactly one property. But there is also an unnamed 3805 // property whose value is hidden properties dictionary. The latter 3806 // property should not be in the list of reguar properties. 3807 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value()); 3808 CHECK(CompileRun("named_names[0] == 'a'")->BooleanValue()); 3809 CHECK(CompileRun( 3810 "obj_mirror.property('a').value().value() == 1")->BooleanValue()); 3811 3812 // Object created by t0 will become hidden prototype of object 'obj'. 3813 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New(); 3814 t0->InstanceTemplate()->Set(v8::String::New("b"), v8::Number::New(2)); 3815 t0->SetHiddenPrototype(true); 3816 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New(); 3817 t1->InstanceTemplate()->Set(v8::String::New("c"), v8::Number::New(3)); 3818 3819 // Create proto objects, add hidden properties to them and set them on 3820 // the global object. 3821 v8::Handle<v8::Object> protoObj = t0->GetFunction()->NewInstance(); 3822 protoObj->SetHiddenValue(v8::String::New("v8::test-debug::b"), 3823 v8::Int32::New(12)); 3824 env->Global()->Set(v8::String::New("protoObj"), protoObj); 3825 v8::Handle<v8::Object> grandProtoObj = t1->GetFunction()->NewInstance(); 3826 grandProtoObj->SetHiddenValue(v8::String::New("v8::test-debug::c"), 3827 v8::Int32::New(13)); 3828 env->Global()->Set(v8::String::New("grandProtoObj"), grandProtoObj); 3829 3830 // Setting prototypes: obj->protoObj->grandProtoObj 3831 protoObj->Set(v8::String::New("__proto__"), grandProtoObj); 3832 obj->Set(v8::String::New("__proto__"), protoObj); 3833 3834 // Get mirror for the object with property getter. 3835 CompileRun("var obj_mirror = debug.MakeMirror(obj);"); 3836 CHECK(CompileRun( 3837 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue()); 3838 CompileRun("var named_names = obj_mirror.propertyNames();"); 3839 // There should be exactly two properties - one from the object itself and 3840 // another from its hidden prototype. 3841 CHECK_EQ(2, CompileRun("named_names.length")->Int32Value()); 3842 CHECK(CompileRun("named_names.sort(); named_names[0] == 'a' &&" 3843 "named_names[1] == 'b'")->BooleanValue()); 3844 CHECK(CompileRun( 3845 "obj_mirror.property('a').value().value() == 1")->BooleanValue()); 3846 CHECK(CompileRun( 3847 "obj_mirror.property('b').value().value() == 2")->BooleanValue()); 3848} 3849 3850 3851// Multithreaded tests of JSON debugger protocol 3852 3853// Support classes 3854 3855// Provides synchronization between k threads, where k is an input to the 3856// constructor. The Wait() call blocks a thread until it is called for the 3857// k'th time, then all calls return. Each ThreadBarrier object can only 3858// be used once. 3859class ThreadBarrier { 3860 public: 3861 explicit ThreadBarrier(int num_threads); 3862 ~ThreadBarrier(); 3863 void Wait(); 3864 private: 3865 int num_threads_; 3866 int num_blocked_; 3867 v8::internal::Mutex* lock_; 3868 v8::internal::Semaphore* sem_; 3869 bool invalid_; 3870}; 3871 3872ThreadBarrier::ThreadBarrier(int num_threads) 3873 : num_threads_(num_threads), num_blocked_(0) { 3874 lock_ = OS::CreateMutex(); 3875 sem_ = OS::CreateSemaphore(0); 3876 invalid_ = false; // A barrier may only be used once. Then it is invalid. 3877} 3878 3879// Do not call, due to race condition with Wait(). 3880// Could be resolved with Pthread condition variables. 3881ThreadBarrier::~ThreadBarrier() { 3882 lock_->Lock(); 3883 delete lock_; 3884 delete sem_; 3885} 3886 3887void ThreadBarrier::Wait() { 3888 lock_->Lock(); 3889 CHECK(!invalid_); 3890 if (num_blocked_ == num_threads_ - 1) { 3891 // Signal and unblock all waiting threads. 3892 for (int i = 0; i < num_threads_ - 1; ++i) { 3893 sem_->Signal(); 3894 } 3895 invalid_ = true; 3896 printf("BARRIER\n\n"); 3897 fflush(stdout); 3898 lock_->Unlock(); 3899 } else { // Wait for the semaphore. 3900 ++num_blocked_; 3901 lock_->Unlock(); // Potential race condition with destructor because 3902 sem_->Wait(); // these two lines are not atomic. 3903 } 3904} 3905 3906// A set containing enough barriers and semaphores for any of the tests. 3907class Barriers { 3908 public: 3909 Barriers(); 3910 void Initialize(); 3911 ThreadBarrier barrier_1; 3912 ThreadBarrier barrier_2; 3913 ThreadBarrier barrier_3; 3914 ThreadBarrier barrier_4; 3915 ThreadBarrier barrier_5; 3916 v8::internal::Semaphore* semaphore_1; 3917 v8::internal::Semaphore* semaphore_2; 3918}; 3919 3920Barriers::Barriers() : barrier_1(2), barrier_2(2), 3921 barrier_3(2), barrier_4(2), barrier_5(2) {} 3922 3923void Barriers::Initialize() { 3924 semaphore_1 = OS::CreateSemaphore(0); 3925 semaphore_2 = OS::CreateSemaphore(0); 3926} 3927 3928 3929// We match parts of the message to decide if it is a break message. 3930bool IsBreakEventMessage(char *message) { 3931 const char* type_event = "\"type\":\"event\""; 3932 const char* event_break = "\"event\":\"break\""; 3933 // Does the message contain both type:event and event:break? 3934 return strstr(message, type_event) != NULL && 3935 strstr(message, event_break) != NULL; 3936} 3937 3938 3939// We match parts of the message to decide if it is a exception message. 3940bool IsExceptionEventMessage(char *message) { 3941 const char* type_event = "\"type\":\"event\""; 3942 const char* event_exception = "\"event\":\"exception\""; 3943 // Does the message contain both type:event and event:exception? 3944 return strstr(message, type_event) != NULL && 3945 strstr(message, event_exception) != NULL; 3946} 3947 3948 3949// We match the message wether it is an evaluate response message. 3950bool IsEvaluateResponseMessage(char* message) { 3951 const char* type_response = "\"type\":\"response\""; 3952 const char* command_evaluate = "\"command\":\"evaluate\""; 3953 // Does the message contain both type:response and command:evaluate? 3954 return strstr(message, type_response) != NULL && 3955 strstr(message, command_evaluate) != NULL; 3956} 3957 3958 3959static int StringToInt(const char* s) { 3960 return atoi(s); // NOLINT 3961} 3962 3963 3964// We match parts of the message to get evaluate result int value. 3965int GetEvaluateIntResult(char *message) { 3966 const char* value = "\"value\":"; 3967 char* pos = strstr(message, value); 3968 if (pos == NULL) { 3969 return -1; 3970 } 3971 int res = -1; 3972 res = StringToInt(pos + strlen(value)); 3973 return res; 3974} 3975 3976 3977// We match parts of the message to get hit breakpoint id. 3978int GetBreakpointIdFromBreakEventMessage(char *message) { 3979 const char* breakpoints = "\"breakpoints\":["; 3980 char* pos = strstr(message, breakpoints); 3981 if (pos == NULL) { 3982 return -1; 3983 } 3984 int res = -1; 3985 res = StringToInt(pos + strlen(breakpoints)); 3986 return res; 3987} 3988 3989 3990// We match parts of the message to get total frames number. 3991int GetTotalFramesInt(char *message) { 3992 const char* prefix = "\"totalFrames\":"; 3993 char* pos = strstr(message, prefix); 3994 if (pos == NULL) { 3995 return -1; 3996 } 3997 pos += strlen(prefix); 3998 int res = StringToInt(pos); 3999 return res; 4000} 4001 4002 4003/* Test MessageQueues */ 4004/* Tests the message queues that hold debugger commands and 4005 * response messages to the debugger. Fills queues and makes 4006 * them grow. 4007 */ 4008Barriers message_queue_barriers; 4009 4010// This is the debugger thread, that executes no v8 calls except 4011// placing JSON debugger commands in the queue. 4012class MessageQueueDebuggerThread : public v8::internal::Thread { 4013 public: 4014 void Run(); 4015}; 4016 4017static void MessageHandler(const uint16_t* message, int length, 4018 v8::Debug::ClientData* client_data) { 4019 static char print_buffer[1000]; 4020 Utf16ToAscii(message, length, print_buffer); 4021 if (IsBreakEventMessage(print_buffer)) { 4022 // Lets test script wait until break occurs to send commands. 4023 // Signals when a break is reported. 4024 message_queue_barriers.semaphore_2->Signal(); 4025 } 4026 4027 // Allow message handler to block on a semaphore, to test queueing of 4028 // messages while blocked. 4029 message_queue_barriers.semaphore_1->Wait(); 4030} 4031 4032void MessageQueueDebuggerThread::Run() { 4033 const int kBufferSize = 1000; 4034 uint16_t buffer_1[kBufferSize]; 4035 uint16_t buffer_2[kBufferSize]; 4036 const char* command_1 = 4037 "{\"seq\":117," 4038 "\"type\":\"request\"," 4039 "\"command\":\"evaluate\"," 4040 "\"arguments\":{\"expression\":\"1+2\"}}"; 4041 const char* command_2 = 4042 "{\"seq\":118," 4043 "\"type\":\"request\"," 4044 "\"command\":\"evaluate\"," 4045 "\"arguments\":{\"expression\":\"1+a\"}}"; 4046 const char* command_3 = 4047 "{\"seq\":119," 4048 "\"type\":\"request\"," 4049 "\"command\":\"evaluate\"," 4050 "\"arguments\":{\"expression\":\"c.d * b\"}}"; 4051 const char* command_continue = 4052 "{\"seq\":106," 4053 "\"type\":\"request\"," 4054 "\"command\":\"continue\"}"; 4055 const char* command_single_step = 4056 "{\"seq\":107," 4057 "\"type\":\"request\"," 4058 "\"command\":\"continue\"," 4059 "\"arguments\":{\"stepaction\":\"next\"}}"; 4060 4061 /* Interleaved sequence of actions by the two threads:*/ 4062 // Main thread compiles and runs source_1 4063 message_queue_barriers.semaphore_1->Signal(); 4064 message_queue_barriers.barrier_1.Wait(); 4065 // Post 6 commands, filling the command queue and making it expand. 4066 // These calls return immediately, but the commands stay on the queue 4067 // until the execution of source_2. 4068 // Note: AsciiToUtf16 executes before SendCommand, so command is copied 4069 // to buffer before buffer is sent to SendCommand. 4070 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1)); 4071 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2)); 4072 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2)); 4073 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2)); 4074 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2)); 4075 message_queue_barriers.barrier_2.Wait(); 4076 // Main thread compiles and runs source_2. 4077 // Queued commands are executed at the start of compilation of source_2( 4078 // beforeCompile event). 4079 // Free the message handler to process all the messages from the queue. 7 4080 // messages are expected: 2 afterCompile events and 5 responses. 4081 // All the commands added so far will fail to execute as long as call stack 4082 // is empty on beforeCompile event. 4083 for (int i = 0; i < 6 ; ++i) { 4084 message_queue_barriers.semaphore_1->Signal(); 4085 } 4086 message_queue_barriers.barrier_3.Wait(); 4087 // Main thread compiles and runs source_3. 4088 // Don't stop in the afterCompile handler. 4089 message_queue_barriers.semaphore_1->Signal(); 4090 // source_3 includes a debugger statement, which causes a break event. 4091 // Wait on break event from hitting "debugger" statement 4092 message_queue_barriers.semaphore_2->Wait(); 4093 // These should execute after the "debugger" statement in source_2 4094 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1)); 4095 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2)); 4096 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2)); 4097 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_single_step, buffer_2)); 4098 // Run after 2 break events, 4 responses. 4099 for (int i = 0; i < 6 ; ++i) { 4100 message_queue_barriers.semaphore_1->Signal(); 4101 } 4102 // Wait on break event after a single step executes. 4103 message_queue_barriers.semaphore_2->Wait(); 4104 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_2, buffer_1)); 4105 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_continue, buffer_2)); 4106 // Run after 2 responses. 4107 for (int i = 0; i < 2 ; ++i) { 4108 message_queue_barriers.semaphore_1->Signal(); 4109 } 4110 // Main thread continues running source_3 to end, waits for this thread. 4111} 4112 4113MessageQueueDebuggerThread message_queue_debugger_thread; 4114 4115// This thread runs the v8 engine. 4116TEST(MessageQueues) { 4117 // Create a V8 environment 4118 v8::HandleScope scope; 4119 DebugLocalContext env; 4120 message_queue_barriers.Initialize(); 4121 v8::Debug::SetMessageHandler(MessageHandler); 4122 message_queue_debugger_thread.Start(); 4123 4124 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;"; 4125 const char* source_2 = "e = 17;"; 4126 const char* source_3 = "a = 4; debugger; a = 5; a = 6; a = 7;"; 4127 4128 // See MessageQueueDebuggerThread::Run for interleaved sequence of 4129 // API calls and events in the two threads. 4130 CompileRun(source_1); 4131 message_queue_barriers.barrier_1.Wait(); 4132 message_queue_barriers.barrier_2.Wait(); 4133 CompileRun(source_2); 4134 message_queue_barriers.barrier_3.Wait(); 4135 CompileRun(source_3); 4136 message_queue_debugger_thread.Join(); 4137 fflush(stdout); 4138} 4139 4140 4141class TestClientData : public v8::Debug::ClientData { 4142 public: 4143 TestClientData() { 4144 constructor_call_counter++; 4145 } 4146 virtual ~TestClientData() { 4147 destructor_call_counter++; 4148 } 4149 4150 static void ResetCounters() { 4151 constructor_call_counter = 0; 4152 destructor_call_counter = 0; 4153 } 4154 4155 static int constructor_call_counter; 4156 static int destructor_call_counter; 4157}; 4158 4159int TestClientData::constructor_call_counter = 0; 4160int TestClientData::destructor_call_counter = 0; 4161 4162 4163// Tests that MessageQueue doesn't destroy client data when expands and 4164// does destroy when it dies. 4165TEST(MessageQueueExpandAndDestroy) { 4166 TestClientData::ResetCounters(); 4167 { // Create a scope for the queue. 4168 CommandMessageQueue queue(1); 4169 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4170 new TestClientData())); 4171 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4172 new TestClientData())); 4173 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4174 new TestClientData())); 4175 CHECK_EQ(0, TestClientData::destructor_call_counter); 4176 queue.Get().Dispose(); 4177 CHECK_EQ(1, TestClientData::destructor_call_counter); 4178 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4179 new TestClientData())); 4180 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4181 new TestClientData())); 4182 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4183 new TestClientData())); 4184 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4185 new TestClientData())); 4186 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(), 4187 new TestClientData())); 4188 CHECK_EQ(1, TestClientData::destructor_call_counter); 4189 queue.Get().Dispose(); 4190 CHECK_EQ(2, TestClientData::destructor_call_counter); 4191 } 4192 // All the client data should be destroyed when the queue is destroyed. 4193 CHECK_EQ(TestClientData::destructor_call_counter, 4194 TestClientData::destructor_call_counter); 4195} 4196 4197 4198static int handled_client_data_instances_count = 0; 4199static void MessageHandlerCountingClientData( 4200 const v8::Debug::Message& message) { 4201 if (message.GetClientData() != NULL) { 4202 handled_client_data_instances_count++; 4203 } 4204} 4205 4206 4207// Tests that all client data passed to the debugger are sent to the handler. 4208TEST(SendClientDataToHandler) { 4209 // Create a V8 environment 4210 v8::HandleScope scope; 4211 DebugLocalContext env; 4212 TestClientData::ResetCounters(); 4213 handled_client_data_instances_count = 0; 4214 v8::Debug::SetMessageHandler2(MessageHandlerCountingClientData); 4215 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;"; 4216 const int kBufferSize = 1000; 4217 uint16_t buffer[kBufferSize]; 4218 const char* command_1 = 4219 "{\"seq\":117," 4220 "\"type\":\"request\"," 4221 "\"command\":\"evaluate\"," 4222 "\"arguments\":{\"expression\":\"1+2\"}}"; 4223 const char* command_2 = 4224 "{\"seq\":118," 4225 "\"type\":\"request\"," 4226 "\"command\":\"evaluate\"," 4227 "\"arguments\":{\"expression\":\"1+a\"}}"; 4228 const char* command_continue = 4229 "{\"seq\":106," 4230 "\"type\":\"request\"," 4231 "\"command\":\"continue\"}"; 4232 4233 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer), 4234 new TestClientData()); 4235 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer), NULL); 4236 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer), 4237 new TestClientData()); 4238 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer), 4239 new TestClientData()); 4240 // All the messages will be processed on beforeCompile event. 4241 CompileRun(source_1); 4242 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer)); 4243 CHECK_EQ(3, TestClientData::constructor_call_counter); 4244 CHECK_EQ(TestClientData::constructor_call_counter, 4245 handled_client_data_instances_count); 4246 CHECK_EQ(TestClientData::constructor_call_counter, 4247 TestClientData::destructor_call_counter); 4248} 4249 4250 4251/* Test ThreadedDebugging */ 4252/* This test interrupts a running infinite loop that is 4253 * occupying the v8 thread by a break command from the 4254 * debugger thread. It then changes the value of a 4255 * global object, to make the loop terminate. 4256 */ 4257 4258Barriers threaded_debugging_barriers; 4259 4260class V8Thread : public v8::internal::Thread { 4261 public: 4262 void Run(); 4263}; 4264 4265class DebuggerThread : public v8::internal::Thread { 4266 public: 4267 void Run(); 4268}; 4269 4270 4271static v8::Handle<v8::Value> ThreadedAtBarrier1(const v8::Arguments& args) { 4272 threaded_debugging_barriers.barrier_1.Wait(); 4273 return v8::Undefined(); 4274} 4275 4276 4277static void ThreadedMessageHandler(const v8::Debug::Message& message) { 4278 static char print_buffer[1000]; 4279 v8::String::Value json(message.GetJSON()); 4280 Utf16ToAscii(*json, json.length(), print_buffer); 4281 if (IsBreakEventMessage(print_buffer)) { 4282 threaded_debugging_barriers.barrier_2.Wait(); 4283 } 4284} 4285 4286 4287void V8Thread::Run() { 4288 const char* source = 4289 "flag = true;\n" 4290 "function bar( new_value ) {\n" 4291 " flag = new_value;\n" 4292 " return \"Return from bar(\" + new_value + \")\";\n" 4293 "}\n" 4294 "\n" 4295 "function foo() {\n" 4296 " var x = 1;\n" 4297 " while ( flag == true ) {\n" 4298 " if ( x == 1 ) {\n" 4299 " ThreadedAtBarrier1();\n" 4300 " }\n" 4301 " x = x + 1;\n" 4302 " }\n" 4303 "}\n" 4304 "\n" 4305 "foo();\n"; 4306 4307 v8::HandleScope scope; 4308 DebugLocalContext env; 4309 v8::Debug::SetMessageHandler2(&ThreadedMessageHandler); 4310 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New(); 4311 global_template->Set(v8::String::New("ThreadedAtBarrier1"), 4312 v8::FunctionTemplate::New(ThreadedAtBarrier1)); 4313 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template); 4314 v8::Context::Scope context_scope(context); 4315 4316 CompileRun(source); 4317} 4318 4319void DebuggerThread::Run() { 4320 const int kBufSize = 1000; 4321 uint16_t buffer[kBufSize]; 4322 4323 const char* command_1 = "{\"seq\":102," 4324 "\"type\":\"request\"," 4325 "\"command\":\"evaluate\"," 4326 "\"arguments\":{\"expression\":\"bar(false)\"}}"; 4327 const char* command_2 = "{\"seq\":103," 4328 "\"type\":\"request\"," 4329 "\"command\":\"continue\"}"; 4330 4331 threaded_debugging_barriers.barrier_1.Wait(); 4332 v8::Debug::DebugBreak(); 4333 threaded_debugging_barriers.barrier_2.Wait(); 4334 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer)); 4335 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer)); 4336} 4337 4338DebuggerThread debugger_thread; 4339V8Thread v8_thread; 4340 4341TEST(ThreadedDebugging) { 4342 // Create a V8 environment 4343 threaded_debugging_barriers.Initialize(); 4344 4345 v8_thread.Start(); 4346 debugger_thread.Start(); 4347 4348 v8_thread.Join(); 4349 debugger_thread.Join(); 4350} 4351 4352/* Test RecursiveBreakpoints */ 4353/* In this test, the debugger evaluates a function with a breakpoint, after 4354 * hitting a breakpoint in another function. We do this with both values 4355 * of the flag enabling recursive breakpoints, and verify that the second 4356 * breakpoint is hit when enabled, and missed when disabled. 4357 */ 4358 4359class BreakpointsV8Thread : public v8::internal::Thread { 4360 public: 4361 void Run(); 4362}; 4363 4364class BreakpointsDebuggerThread : public v8::internal::Thread { 4365 public: 4366 explicit BreakpointsDebuggerThread(bool global_evaluate) 4367 : global_evaluate_(global_evaluate) {} 4368 void Run(); 4369 4370 private: 4371 bool global_evaluate_; 4372}; 4373 4374 4375Barriers* breakpoints_barriers; 4376int break_event_breakpoint_id; 4377int evaluate_int_result; 4378 4379static void BreakpointsMessageHandler(const v8::Debug::Message& message) { 4380 static char print_buffer[1000]; 4381 v8::String::Value json(message.GetJSON()); 4382 Utf16ToAscii(*json, json.length(), print_buffer); 4383 4384 if (IsBreakEventMessage(print_buffer)) { 4385 break_event_breakpoint_id = 4386 GetBreakpointIdFromBreakEventMessage(print_buffer); 4387 breakpoints_barriers->semaphore_1->Signal(); 4388 } else if (IsEvaluateResponseMessage(print_buffer)) { 4389 evaluate_int_result = GetEvaluateIntResult(print_buffer); 4390 breakpoints_barriers->semaphore_1->Signal(); 4391 } 4392} 4393 4394 4395void BreakpointsV8Thread::Run() { 4396 const char* source_1 = "var y_global = 3;\n" 4397 "function cat( new_value ) {\n" 4398 " var x = new_value;\n" 4399 " y_global = y_global + 4;\n" 4400 " x = 3 * x + 1;\n" 4401 " y_global = y_global + 5;\n" 4402 " return x;\n" 4403 "}\n" 4404 "\n" 4405 "function dog() {\n" 4406 " var x = 1;\n" 4407 " x = y_global;" 4408 " var z = 3;" 4409 " x += 100;\n" 4410 " return x;\n" 4411 "}\n" 4412 "\n"; 4413 const char* source_2 = "cat(17);\n" 4414 "cat(19);\n"; 4415 4416 v8::HandleScope scope; 4417 DebugLocalContext env; 4418 v8::Debug::SetMessageHandler2(&BreakpointsMessageHandler); 4419 4420 CompileRun(source_1); 4421 breakpoints_barriers->barrier_1.Wait(); 4422 breakpoints_barriers->barrier_2.Wait(); 4423 CompileRun(source_2); 4424} 4425 4426 4427void BreakpointsDebuggerThread::Run() { 4428 const int kBufSize = 1000; 4429 uint16_t buffer[kBufSize]; 4430 4431 const char* command_1 = "{\"seq\":101," 4432 "\"type\":\"request\"," 4433 "\"command\":\"setbreakpoint\"," 4434 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}"; 4435 const char* command_2 = "{\"seq\":102," 4436 "\"type\":\"request\"," 4437 "\"command\":\"setbreakpoint\"," 4438 "\"arguments\":{\"type\":\"function\",\"target\":\"dog\",\"line\":3}}"; 4439 const char* command_3; 4440 if (this->global_evaluate_) { 4441 command_3 = "{\"seq\":103," 4442 "\"type\":\"request\"," 4443 "\"command\":\"evaluate\"," 4444 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false," 4445 "\"global\":true}}"; 4446 } else { 4447 command_3 = "{\"seq\":103," 4448 "\"type\":\"request\"," 4449 "\"command\":\"evaluate\"," 4450 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false}}"; 4451 } 4452 const char* command_4; 4453 if (this->global_evaluate_) { 4454 command_4 = "{\"seq\":104," 4455 "\"type\":\"request\"," 4456 "\"command\":\"evaluate\"," 4457 "\"arguments\":{\"expression\":\"100 + 8\",\"disable_break\":true," 4458 "\"global\":true}}"; 4459 } else { 4460 command_4 = "{\"seq\":104," 4461 "\"type\":\"request\"," 4462 "\"command\":\"evaluate\"," 4463 "\"arguments\":{\"expression\":\"x + 1\",\"disable_break\":true}}"; 4464 } 4465 const char* command_5 = "{\"seq\":105," 4466 "\"type\":\"request\"," 4467 "\"command\":\"continue\"}"; 4468 const char* command_6 = "{\"seq\":106," 4469 "\"type\":\"request\"," 4470 "\"command\":\"continue\"}"; 4471 const char* command_7; 4472 if (this->global_evaluate_) { 4473 command_7 = "{\"seq\":107," 4474 "\"type\":\"request\"," 4475 "\"command\":\"evaluate\"," 4476 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true," 4477 "\"global\":true}}"; 4478 } else { 4479 command_7 = "{\"seq\":107," 4480 "\"type\":\"request\"," 4481 "\"command\":\"evaluate\"," 4482 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true}}"; 4483 } 4484 const char* command_8 = "{\"seq\":108," 4485 "\"type\":\"request\"," 4486 "\"command\":\"continue\"}"; 4487 4488 4489 // v8 thread initializes, runs source_1 4490 breakpoints_barriers->barrier_1.Wait(); 4491 // 1:Set breakpoint in cat() (will get id 1). 4492 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer)); 4493 // 2:Set breakpoint in dog() (will get id 2). 4494 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer)); 4495 breakpoints_barriers->barrier_2.Wait(); 4496 // V8 thread starts compiling source_2. 4497 // Automatic break happens, to run queued commands 4498 // breakpoints_barriers->semaphore_1->Wait(); 4499 // Commands 1 through 3 run, thread continues. 4500 // v8 thread runs source_2 to breakpoint in cat(). 4501 // message callback receives break event. 4502 breakpoints_barriers->semaphore_1->Wait(); 4503 // Must have hit breakpoint #1. 4504 CHECK_EQ(1, break_event_breakpoint_id); 4505 // 4:Evaluate dog() (which has a breakpoint). 4506 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_3, buffer)); 4507 // V8 thread hits breakpoint in dog(). 4508 breakpoints_barriers->semaphore_1->Wait(); // wait for break event 4509 // Must have hit breakpoint #2. 4510 CHECK_EQ(2, break_event_breakpoint_id); 4511 // 5:Evaluate (x + 1). 4512 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_4, buffer)); 4513 // Evaluate (x + 1) finishes. 4514 breakpoints_barriers->semaphore_1->Wait(); 4515 // Must have result 108. 4516 CHECK_EQ(108, evaluate_int_result); 4517 // 6:Continue evaluation of dog(). 4518 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_5, buffer)); 4519 // Evaluate dog() finishes. 4520 breakpoints_barriers->semaphore_1->Wait(); 4521 // Must have result 107. 4522 CHECK_EQ(107, evaluate_int_result); 4523 // 7:Continue evaluation of source_2, finish cat(17), hit breakpoint 4524 // in cat(19). 4525 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_6, buffer)); 4526 // Message callback gets break event. 4527 breakpoints_barriers->semaphore_1->Wait(); // wait for break event 4528 // Must have hit breakpoint #1. 4529 CHECK_EQ(1, break_event_breakpoint_id); 4530 // 8: Evaluate dog() with breaks disabled. 4531 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_7, buffer)); 4532 // Evaluate dog() finishes. 4533 breakpoints_barriers->semaphore_1->Wait(); 4534 // Must have result 116. 4535 CHECK_EQ(116, evaluate_int_result); 4536 // 9: Continue evaluation of source2, reach end. 4537 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_8, buffer)); 4538} 4539 4540void TestRecursiveBreakpointsGeneric(bool global_evaluate) { 4541 i::FLAG_debugger_auto_break = true; 4542 4543 BreakpointsDebuggerThread breakpoints_debugger_thread(global_evaluate); 4544 BreakpointsV8Thread breakpoints_v8_thread; 4545 4546 // Create a V8 environment 4547 Barriers stack_allocated_breakpoints_barriers; 4548 stack_allocated_breakpoints_barriers.Initialize(); 4549 breakpoints_barriers = &stack_allocated_breakpoints_barriers; 4550 4551 breakpoints_v8_thread.Start(); 4552 breakpoints_debugger_thread.Start(); 4553 4554 breakpoints_v8_thread.Join(); 4555 breakpoints_debugger_thread.Join(); 4556} 4557 4558TEST(RecursiveBreakpoints) { 4559 TestRecursiveBreakpointsGeneric(false); 4560} 4561 4562TEST(RecursiveBreakpointsGlobal) { 4563 TestRecursiveBreakpointsGeneric(true); 4564} 4565 4566 4567static void DummyDebugEventListener(v8::DebugEvent event, 4568 v8::Handle<v8::Object> exec_state, 4569 v8::Handle<v8::Object> event_data, 4570 v8::Handle<v8::Value> data) { 4571} 4572 4573 4574TEST(SetDebugEventListenerOnUninitializedVM) { 4575 v8::Debug::SetDebugEventListener(DummyDebugEventListener); 4576} 4577 4578 4579static void DummyMessageHandler(const v8::Debug::Message& message) { 4580} 4581 4582 4583TEST(SetMessageHandlerOnUninitializedVM) { 4584 v8::Debug::SetMessageHandler2(DummyMessageHandler); 4585} 4586 4587 4588TEST(DebugBreakOnUninitializedVM) { 4589 v8::Debug::DebugBreak(); 4590} 4591 4592 4593TEST(SendCommandToUninitializedVM) { 4594 const char* dummy_command = "{}"; 4595 uint16_t dummy_buffer[80]; 4596 int dummy_length = AsciiToUtf16(dummy_command, dummy_buffer); 4597 v8::Debug::SendCommand(dummy_buffer, dummy_length); 4598} 4599 4600 4601// Source for a JavaScript function which returns the data parameter of a 4602// function called in the context of the debugger. If no data parameter is 4603// passed it throws an exception. 4604static const char* debugger_call_with_data_source = 4605 "function debugger_call_with_data(exec_state, data) {" 4606 " if (data) return data;" 4607 " throw 'No data!'" 4608 "}"; 4609v8::Handle<v8::Function> debugger_call_with_data; 4610 4611 4612// Source for a JavaScript function which returns the data parameter of a 4613// function called in the context of the debugger. If no data parameter is 4614// passed it throws an exception. 4615static const char* debugger_call_with_closure_source = 4616 "var x = 3;" 4617 "(function (exec_state) {" 4618 " if (exec_state.y) return x - 1;" 4619 " exec_state.y = x;" 4620 " return exec_state.y" 4621 "})"; 4622v8::Handle<v8::Function> debugger_call_with_closure; 4623 4624// Function to retrieve the number of JavaScript frames by calling a JavaScript 4625// in the debugger. 4626static v8::Handle<v8::Value> CheckFrameCount(const v8::Arguments& args) { 4627 CHECK(v8::Debug::Call(frame_count)->IsNumber()); 4628 CHECK_EQ(args[0]->Int32Value(), 4629 v8::Debug::Call(frame_count)->Int32Value()); 4630 return v8::Undefined(); 4631} 4632 4633 4634// Function to retrieve the source line of the top JavaScript frame by calling a 4635// JavaScript function in the debugger. 4636static v8::Handle<v8::Value> CheckSourceLine(const v8::Arguments& args) { 4637 CHECK(v8::Debug::Call(frame_source_line)->IsNumber()); 4638 CHECK_EQ(args[0]->Int32Value(), 4639 v8::Debug::Call(frame_source_line)->Int32Value()); 4640 return v8::Undefined(); 4641} 4642 4643 4644// Function to test passing an additional parameter to a JavaScript function 4645// called in the debugger. It also tests that functions called in the debugger 4646// can throw exceptions. 4647static v8::Handle<v8::Value> CheckDataParameter(const v8::Arguments& args) { 4648 v8::Handle<v8::String> data = v8::String::New("Test"); 4649 CHECK(v8::Debug::Call(debugger_call_with_data, data)->IsString()); 4650 4651 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty()); 4652 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty()); 4653 4654 v8::TryCatch catcher; 4655 v8::Debug::Call(debugger_call_with_data); 4656 CHECK(catcher.HasCaught()); 4657 CHECK(catcher.Exception()->IsString()); 4658 4659 return v8::Undefined(); 4660} 4661 4662 4663// Function to test using a JavaScript with closure in the debugger. 4664static v8::Handle<v8::Value> CheckClosure(const v8::Arguments& args) { 4665 CHECK(v8::Debug::Call(debugger_call_with_closure)->IsNumber()); 4666 CHECK_EQ(3, v8::Debug::Call(debugger_call_with_closure)->Int32Value()); 4667 return v8::Undefined(); 4668} 4669 4670 4671// Test functions called through the debugger. 4672TEST(CallFunctionInDebugger) { 4673 // Create and enter a context with the functions CheckFrameCount, 4674 // CheckSourceLine and CheckDataParameter installed. 4675 v8::HandleScope scope; 4676 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New(); 4677 global_template->Set(v8::String::New("CheckFrameCount"), 4678 v8::FunctionTemplate::New(CheckFrameCount)); 4679 global_template->Set(v8::String::New("CheckSourceLine"), 4680 v8::FunctionTemplate::New(CheckSourceLine)); 4681 global_template->Set(v8::String::New("CheckDataParameter"), 4682 v8::FunctionTemplate::New(CheckDataParameter)); 4683 global_template->Set(v8::String::New("CheckClosure"), 4684 v8::FunctionTemplate::New(CheckClosure)); 4685 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template); 4686 v8::Context::Scope context_scope(context); 4687 4688 // Compile a function for checking the number of JavaScript frames. 4689 v8::Script::Compile(v8::String::New(frame_count_source))->Run(); 4690 frame_count = v8::Local<v8::Function>::Cast( 4691 context->Global()->Get(v8::String::New("frame_count"))); 4692 4693 // Compile a function for returning the source line for the top frame. 4694 v8::Script::Compile(v8::String::New(frame_source_line_source))->Run(); 4695 frame_source_line = v8::Local<v8::Function>::Cast( 4696 context->Global()->Get(v8::String::New("frame_source_line"))); 4697 4698 // Compile a function returning the data parameter. 4699 v8::Script::Compile(v8::String::New(debugger_call_with_data_source))->Run(); 4700 debugger_call_with_data = v8::Local<v8::Function>::Cast( 4701 context->Global()->Get(v8::String::New("debugger_call_with_data"))); 4702 4703 // Compile a function capturing closure. 4704 debugger_call_with_closure = v8::Local<v8::Function>::Cast( 4705 v8::Script::Compile( 4706 v8::String::New(debugger_call_with_closure_source))->Run()); 4707 4708 // Calling a function through the debugger returns 0 frames if there are 4709 // no JavaScript frames. 4710 CHECK_EQ(v8::Integer::New(0), v8::Debug::Call(frame_count)); 4711 4712 // Test that the number of frames can be retrieved. 4713 v8::Script::Compile(v8::String::New("CheckFrameCount(1)"))->Run(); 4714 v8::Script::Compile(v8::String::New("function f() {" 4715 " CheckFrameCount(2);" 4716 "}; f()"))->Run(); 4717 4718 // Test that the source line can be retrieved. 4719 v8::Script::Compile(v8::String::New("CheckSourceLine(0)"))->Run(); 4720 v8::Script::Compile(v8::String::New("function f() {\n" 4721 " CheckSourceLine(1)\n" 4722 " CheckSourceLine(2)\n" 4723 " CheckSourceLine(3)\n" 4724 "}; f()"))->Run(); 4725 4726 // Test that a parameter can be passed to a function called in the debugger. 4727 v8::Script::Compile(v8::String::New("CheckDataParameter()"))->Run(); 4728 4729 // Test that a function with closure can be run in the debugger. 4730 v8::Script::Compile(v8::String::New("CheckClosure()"))->Run(); 4731 4732 4733 // Test that the source line is correct when there is a line offset. 4734 v8::ScriptOrigin origin(v8::String::New("test"), 4735 v8::Integer::New(7)); 4736 v8::Script::Compile(v8::String::New("CheckSourceLine(7)"), &origin)->Run(); 4737 v8::Script::Compile(v8::String::New("function f() {\n" 4738 " CheckSourceLine(8)\n" 4739 " CheckSourceLine(9)\n" 4740 " CheckSourceLine(10)\n" 4741 "}; f()"), &origin)->Run(); 4742} 4743 4744 4745// Debugger message handler which counts the number of breaks. 4746static void SendContinueCommand(); 4747static void MessageHandlerBreakPointHitCount( 4748 const v8::Debug::Message& message) { 4749 if (message.IsEvent() && message.GetEvent() == v8::Break) { 4750 // Count the number of breaks. 4751 break_point_hit_count++; 4752 4753 SendContinueCommand(); 4754 } 4755} 4756 4757 4758// Test that clearing the debug event listener actually clears all break points 4759// and related information. 4760TEST(DebuggerUnload) { 4761 DebugLocalContext env; 4762 4763 // Check debugger is unloaded before it is used. 4764 CheckDebuggerUnloaded(); 4765 4766 // Set a debug event listener. 4767 break_point_hit_count = 0; 4768 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 4769 v8::Undefined()); 4770 { 4771 v8::HandleScope scope; 4772 // Create a couple of functions for the test. 4773 v8::Local<v8::Function> foo = 4774 CompileFunction(&env, "function foo(){x=1}", "foo"); 4775 v8::Local<v8::Function> bar = 4776 CompileFunction(&env, "function bar(){y=2}", "bar"); 4777 4778 // Set some break points. 4779 SetBreakPoint(foo, 0); 4780 SetBreakPoint(foo, 4); 4781 SetBreakPoint(bar, 0); 4782 SetBreakPoint(bar, 4); 4783 4784 // Make sure that the break points are there. 4785 break_point_hit_count = 0; 4786 foo->Call(env->Global(), 0, NULL); 4787 CHECK_EQ(2, break_point_hit_count); 4788 bar->Call(env->Global(), 0, NULL); 4789 CHECK_EQ(4, break_point_hit_count); 4790 } 4791 4792 // Remove the debug event listener without clearing breakpoints. Do this 4793 // outside a handle scope. 4794 v8::Debug::SetDebugEventListener(NULL); 4795 CheckDebuggerUnloaded(true); 4796 4797 // Now set a debug message handler. 4798 break_point_hit_count = 0; 4799 v8::Debug::SetMessageHandler2(MessageHandlerBreakPointHitCount); 4800 { 4801 v8::HandleScope scope; 4802 4803 // Get the test functions again. 4804 v8::Local<v8::Function> foo = 4805 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 4806 v8::Local<v8::Function> bar = 4807 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo"))); 4808 4809 foo->Call(env->Global(), 0, NULL); 4810 CHECK_EQ(0, break_point_hit_count); 4811 4812 // Set break points and run again. 4813 SetBreakPoint(foo, 0); 4814 SetBreakPoint(foo, 4); 4815 foo->Call(env->Global(), 0, NULL); 4816 CHECK_EQ(2, break_point_hit_count); 4817 } 4818 4819 // Remove the debug message handler without clearing breakpoints. Do this 4820 // outside a handle scope. 4821 v8::Debug::SetMessageHandler2(NULL); 4822 CheckDebuggerUnloaded(true); 4823} 4824 4825 4826// Sends continue command to the debugger. 4827static void SendContinueCommand() { 4828 const int kBufferSize = 1000; 4829 uint16_t buffer[kBufferSize]; 4830 const char* command_continue = 4831 "{\"seq\":0," 4832 "\"type\":\"request\"," 4833 "\"command\":\"continue\"}"; 4834 4835 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer)); 4836} 4837 4838 4839// Debugger message handler which counts the number of times it is called. 4840static int message_handler_hit_count = 0; 4841static void MessageHandlerHitCount(const v8::Debug::Message& message) { 4842 message_handler_hit_count++; 4843 4844 static char print_buffer[1000]; 4845 v8::String::Value json(message.GetJSON()); 4846 Utf16ToAscii(*json, json.length(), print_buffer); 4847 if (IsExceptionEventMessage(print_buffer)) { 4848 // Send a continue command for exception events. 4849 SendContinueCommand(); 4850 } 4851} 4852 4853 4854// Test clearing the debug message handler. 4855TEST(DebuggerClearMessageHandler) { 4856 v8::HandleScope scope; 4857 DebugLocalContext env; 4858 4859 // Check debugger is unloaded before it is used. 4860 CheckDebuggerUnloaded(); 4861 4862 // Set a debug message handler. 4863 v8::Debug::SetMessageHandler2(MessageHandlerHitCount); 4864 4865 // Run code to throw a unhandled exception. This should end up in the message 4866 // handler. 4867 CompileRun("throw 1"); 4868 4869 // The message handler should be called. 4870 CHECK_GT(message_handler_hit_count, 0); 4871 4872 // Clear debug message handler. 4873 message_handler_hit_count = 0; 4874 v8::Debug::SetMessageHandler(NULL); 4875 4876 // Run code to throw a unhandled exception. This should end up in the message 4877 // handler. 4878 CompileRun("throw 1"); 4879 4880 // The message handler should not be called more. 4881 CHECK_EQ(0, message_handler_hit_count); 4882 4883 CheckDebuggerUnloaded(true); 4884} 4885 4886 4887// Debugger message handler which clears the message handler while active. 4888static void MessageHandlerClearingMessageHandler( 4889 const v8::Debug::Message& message) { 4890 message_handler_hit_count++; 4891 4892 // Clear debug message handler. 4893 v8::Debug::SetMessageHandler(NULL); 4894} 4895 4896 4897// Test clearing the debug message handler while processing a debug event. 4898TEST(DebuggerClearMessageHandlerWhileActive) { 4899 v8::HandleScope scope; 4900 DebugLocalContext env; 4901 4902 // Check debugger is unloaded before it is used. 4903 CheckDebuggerUnloaded(); 4904 4905 // Set a debug message handler. 4906 v8::Debug::SetMessageHandler2(MessageHandlerClearingMessageHandler); 4907 4908 // Run code to throw a unhandled exception. This should end up in the message 4909 // handler. 4910 CompileRun("throw 1"); 4911 4912 // The message handler should be called. 4913 CHECK_EQ(1, message_handler_hit_count); 4914 4915 CheckDebuggerUnloaded(true); 4916} 4917 4918 4919/* Test DebuggerHostDispatch */ 4920/* In this test, the debugger waits for a command on a breakpoint 4921 * and is dispatching host commands while in the infinite loop. 4922 */ 4923 4924class HostDispatchV8Thread : public v8::internal::Thread { 4925 public: 4926 void Run(); 4927}; 4928 4929class HostDispatchDebuggerThread : public v8::internal::Thread { 4930 public: 4931 void Run(); 4932}; 4933 4934Barriers* host_dispatch_barriers; 4935 4936static void HostDispatchMessageHandler(const v8::Debug::Message& message) { 4937 static char print_buffer[1000]; 4938 v8::String::Value json(message.GetJSON()); 4939 Utf16ToAscii(*json, json.length(), print_buffer); 4940} 4941 4942 4943static void HostDispatchDispatchHandler() { 4944 host_dispatch_barriers->semaphore_1->Signal(); 4945} 4946 4947 4948void HostDispatchV8Thread::Run() { 4949 const char* source_1 = "var y_global = 3;\n" 4950 "function cat( new_value ) {\n" 4951 " var x = new_value;\n" 4952 " y_global = 4;\n" 4953 " x = 3 * x + 1;\n" 4954 " y_global = 5;\n" 4955 " return x;\n" 4956 "}\n" 4957 "\n"; 4958 const char* source_2 = "cat(17);\n"; 4959 4960 v8::HandleScope scope; 4961 DebugLocalContext env; 4962 4963 // Setup message and host dispatch handlers. 4964 v8::Debug::SetMessageHandler2(HostDispatchMessageHandler); 4965 v8::Debug::SetHostDispatchHandler(HostDispatchDispatchHandler, 10 /* ms */); 4966 4967 CompileRun(source_1); 4968 host_dispatch_barriers->barrier_1.Wait(); 4969 host_dispatch_barriers->barrier_2.Wait(); 4970 CompileRun(source_2); 4971} 4972 4973 4974void HostDispatchDebuggerThread::Run() { 4975 const int kBufSize = 1000; 4976 uint16_t buffer[kBufSize]; 4977 4978 const char* command_1 = "{\"seq\":101," 4979 "\"type\":\"request\"," 4980 "\"command\":\"setbreakpoint\"," 4981 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}"; 4982 const char* command_2 = "{\"seq\":102," 4983 "\"type\":\"request\"," 4984 "\"command\":\"continue\"}"; 4985 4986 // v8 thread initializes, runs source_1 4987 host_dispatch_barriers->barrier_1.Wait(); 4988 // 1: Set breakpoint in cat(). 4989 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer)); 4990 4991 host_dispatch_barriers->barrier_2.Wait(); 4992 // v8 thread starts compiling source_2. 4993 // Break happens, to run queued commands and host dispatches. 4994 // Wait for host dispatch to be processed. 4995 host_dispatch_barriers->semaphore_1->Wait(); 4996 // 2: Continue evaluation 4997 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer)); 4998} 4999 5000HostDispatchDebuggerThread host_dispatch_debugger_thread; 5001HostDispatchV8Thread host_dispatch_v8_thread; 5002 5003 5004TEST(DebuggerHostDispatch) { 5005 i::FLAG_debugger_auto_break = true; 5006 5007 // Create a V8 environment 5008 Barriers stack_allocated_host_dispatch_barriers; 5009 stack_allocated_host_dispatch_barriers.Initialize(); 5010 host_dispatch_barriers = &stack_allocated_host_dispatch_barriers; 5011 5012 host_dispatch_v8_thread.Start(); 5013 host_dispatch_debugger_thread.Start(); 5014 5015 host_dispatch_v8_thread.Join(); 5016 host_dispatch_debugger_thread.Join(); 5017} 5018 5019 5020/* Test DebugMessageDispatch */ 5021/* In this test, the V8 thread waits for a message from the debug thread. 5022 * The DebugMessageDispatchHandler is executed from the debugger thread 5023 * which signals the V8 thread to wake up. 5024 */ 5025 5026class DebugMessageDispatchV8Thread : public v8::internal::Thread { 5027 public: 5028 void Run(); 5029}; 5030 5031class DebugMessageDispatchDebuggerThread : public v8::internal::Thread { 5032 public: 5033 void Run(); 5034}; 5035 5036Barriers* debug_message_dispatch_barriers; 5037 5038 5039static void DebugMessageHandler() { 5040 debug_message_dispatch_barriers->semaphore_1->Signal(); 5041} 5042 5043 5044void DebugMessageDispatchV8Thread::Run() { 5045 v8::HandleScope scope; 5046 DebugLocalContext env; 5047 5048 // Setup debug message dispatch handler. 5049 v8::Debug::SetDebugMessageDispatchHandler(DebugMessageHandler); 5050 5051 CompileRun("var y = 1 + 2;\n"); 5052 debug_message_dispatch_barriers->barrier_1.Wait(); 5053 debug_message_dispatch_barriers->semaphore_1->Wait(); 5054 debug_message_dispatch_barriers->barrier_2.Wait(); 5055} 5056 5057 5058void DebugMessageDispatchDebuggerThread::Run() { 5059 debug_message_dispatch_barriers->barrier_1.Wait(); 5060 SendContinueCommand(); 5061 debug_message_dispatch_barriers->barrier_2.Wait(); 5062} 5063 5064DebugMessageDispatchDebuggerThread debug_message_dispatch_debugger_thread; 5065DebugMessageDispatchV8Thread debug_message_dispatch_v8_thread; 5066 5067 5068TEST(DebuggerDebugMessageDispatch) { 5069 i::FLAG_debugger_auto_break = true; 5070 5071 // Create a V8 environment 5072 Barriers stack_allocated_debug_message_dispatch_barriers; 5073 stack_allocated_debug_message_dispatch_barriers.Initialize(); 5074 debug_message_dispatch_barriers = 5075 &stack_allocated_debug_message_dispatch_barriers; 5076 5077 debug_message_dispatch_v8_thread.Start(); 5078 debug_message_dispatch_debugger_thread.Start(); 5079 5080 debug_message_dispatch_v8_thread.Join(); 5081 debug_message_dispatch_debugger_thread.Join(); 5082} 5083 5084 5085TEST(DebuggerAgent) { 5086 // Make sure these ports is not used by other tests to allow tests to run in 5087 // parallel. 5088 const int kPort1 = 5858; 5089 const int kPort2 = 5857; 5090 const int kPort3 = 5856; 5091 5092 // Make a string with the port2 number. 5093 const int kPortBufferLen = 6; 5094 char port2_str[kPortBufferLen]; 5095 OS::SNPrintF(i::Vector<char>(port2_str, kPortBufferLen), "%d", kPort2); 5096 5097 bool ok; 5098 5099 // Initialize the socket library. 5100 i::Socket::Setup(); 5101 5102 // Test starting and stopping the agent without any client connection. 5103 i::Debugger::StartAgent("test", kPort1); 5104 i::Debugger::StopAgent(); 5105 5106 // Test starting the agent, connecting a client and shutting down the agent 5107 // with the client connected. 5108 ok = i::Debugger::StartAgent("test", kPort2); 5109 CHECK(ok); 5110 i::Debugger::WaitForAgent(); 5111 i::Socket* client = i::OS::CreateSocket(); 5112 ok = client->Connect("localhost", port2_str); 5113 CHECK(ok); 5114 i::Debugger::StopAgent(); 5115 delete client; 5116 5117 // Test starting and stopping the agent with the required port already 5118 // occoupied. 5119 i::Socket* server = i::OS::CreateSocket(); 5120 server->Bind(kPort3); 5121 5122 i::Debugger::StartAgent("test", kPort3); 5123 i::Debugger::StopAgent(); 5124 5125 delete server; 5126} 5127 5128 5129class DebuggerAgentProtocolServerThread : public i::Thread { 5130 public: 5131 explicit DebuggerAgentProtocolServerThread(int port) 5132 : port_(port), server_(NULL), client_(NULL), 5133 listening_(OS::CreateSemaphore(0)) { 5134 } 5135 ~DebuggerAgentProtocolServerThread() { 5136 // Close both sockets. 5137 delete client_; 5138 delete server_; 5139 delete listening_; 5140 } 5141 5142 void Run(); 5143 void WaitForListening() { listening_->Wait(); } 5144 char* body() { return *body_; } 5145 5146 private: 5147 int port_; 5148 i::SmartPointer<char> body_; 5149 i::Socket* server_; // Server socket used for bind/accept. 5150 i::Socket* client_; // Single client connection used by the test. 5151 i::Semaphore* listening_; // Signalled when the server is in listen mode. 5152}; 5153 5154 5155void DebuggerAgentProtocolServerThread::Run() { 5156 bool ok; 5157 5158 // Create the server socket and bind it to the requested port. 5159 server_ = i::OS::CreateSocket(); 5160 CHECK(server_ != NULL); 5161 ok = server_->Bind(port_); 5162 CHECK(ok); 5163 5164 // Listen for new connections. 5165 ok = server_->Listen(1); 5166 CHECK(ok); 5167 listening_->Signal(); 5168 5169 // Accept a connection. 5170 client_ = server_->Accept(); 5171 CHECK(client_ != NULL); 5172 5173 // Receive a debugger agent protocol message. 5174 i::DebuggerAgentUtil::ReceiveMessage(client_); 5175} 5176 5177 5178TEST(DebuggerAgentProtocolOverflowHeader) { 5179 // Make sure this port is not used by other tests to allow tests to run in 5180 // parallel. 5181 const int kPort = 5860; 5182 static const char* kLocalhost = "localhost"; 5183 5184 // Make a string with the port number. 5185 const int kPortBufferLen = 6; 5186 char port_str[kPortBufferLen]; 5187 OS::SNPrintF(i::Vector<char>(port_str, kPortBufferLen), "%d", kPort); 5188 5189 // Initialize the socket library. 5190 i::Socket::Setup(); 5191 5192 // Create a socket server to receive a debugger agent message. 5193 DebuggerAgentProtocolServerThread* server = 5194 new DebuggerAgentProtocolServerThread(kPort); 5195 server->Start(); 5196 server->WaitForListening(); 5197 5198 // Connect. 5199 i::Socket* client = i::OS::CreateSocket(); 5200 CHECK(client != NULL); 5201 bool ok = client->Connect(kLocalhost, port_str); 5202 CHECK(ok); 5203 5204 // Send headers which overflow the receive buffer. 5205 static const int kBufferSize = 1000; 5206 char buffer[kBufferSize]; 5207 5208 // Long key and short value: XXXX....XXXX:0\r\n. 5209 for (int i = 0; i < kBufferSize - 4; i++) { 5210 buffer[i] = 'X'; 5211 } 5212 buffer[kBufferSize - 4] = ':'; 5213 buffer[kBufferSize - 3] = '0'; 5214 buffer[kBufferSize - 2] = '\r'; 5215 buffer[kBufferSize - 1] = '\n'; 5216 client->Send(buffer, kBufferSize); 5217 5218 // Short key and long value: X:XXXX....XXXX\r\n. 5219 buffer[0] = 'X'; 5220 buffer[1] = ':'; 5221 for (int i = 2; i < kBufferSize - 2; i++) { 5222 buffer[i] = 'X'; 5223 } 5224 buffer[kBufferSize - 2] = '\r'; 5225 buffer[kBufferSize - 1] = '\n'; 5226 client->Send(buffer, kBufferSize); 5227 5228 // Add empty body to request. 5229 const char* content_length_zero_header = "Content-Length:0\r\n"; 5230 client->Send(content_length_zero_header, 5231 StrLength(content_length_zero_header)); 5232 client->Send("\r\n", 2); 5233 5234 // Wait until data is received. 5235 server->Join(); 5236 5237 // Check for empty body. 5238 CHECK(server->body() == NULL); 5239 5240 // Close the client before the server to avoid TIME_WAIT issues. 5241 client->Shutdown(); 5242 delete client; 5243 delete server; 5244} 5245 5246 5247// Test for issue http://code.google.com/p/v8/issues/detail?id=289. 5248// Make sure that DebugGetLoadedScripts doesn't return scripts 5249// with disposed external source. 5250class EmptyExternalStringResource : public v8::String::ExternalStringResource { 5251 public: 5252 EmptyExternalStringResource() { empty_[0] = 0; } 5253 virtual ~EmptyExternalStringResource() {} 5254 virtual size_t length() const { return empty_.length(); } 5255 virtual const uint16_t* data() const { return empty_.start(); } 5256 private: 5257 ::v8::internal::EmbeddedVector<uint16_t, 1> empty_; 5258}; 5259 5260 5261TEST(DebugGetLoadedScripts) { 5262 v8::HandleScope scope; 5263 DebugLocalContext env; 5264 env.ExposeDebug(); 5265 5266 EmptyExternalStringResource source_ext_str; 5267 v8::Local<v8::String> source = v8::String::NewExternal(&source_ext_str); 5268 v8::Handle<v8::Script> evil_script = v8::Script::Compile(source); 5269 Handle<i::ExternalTwoByteString> i_source( 5270 i::ExternalTwoByteString::cast(*v8::Utils::OpenHandle(*source))); 5271 // This situation can happen if source was an external string disposed 5272 // by its owner. 5273 i_source->set_resource(0); 5274 5275 bool allow_natives_syntax = i::FLAG_allow_natives_syntax; 5276 i::FLAG_allow_natives_syntax = true; 5277 CompileRun( 5278 "var scripts = %DebugGetLoadedScripts();" 5279 "var count = scripts.length;" 5280 "for (var i = 0; i < count; ++i) {" 5281 " scripts[i].line_ends;" 5282 "}"); 5283 // Must not crash while accessing line_ends. 5284 i::FLAG_allow_natives_syntax = allow_natives_syntax; 5285 5286 // Some scripts are retrieved - at least the number of native scripts. 5287 CHECK_GT((*env)->Global()->Get(v8::String::New("count"))->Int32Value(), 8); 5288} 5289 5290 5291// Test script break points set on lines. 5292TEST(ScriptNameAndData) { 5293 v8::HandleScope scope; 5294 DebugLocalContext env; 5295 env.ExposeDebug(); 5296 5297 // Create functions for retrieving script name and data for the function on 5298 // the top frame when hitting a break point. 5299 frame_script_name = CompileFunction(&env, 5300 frame_script_name_source, 5301 "frame_script_name"); 5302 frame_script_data = CompileFunction(&env, 5303 frame_script_data_source, 5304 "frame_script_data"); 5305 compiled_script_data = CompileFunction(&env, 5306 compiled_script_data_source, 5307 "compiled_script_data"); 5308 5309 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount, 5310 v8::Undefined()); 5311 5312 // Test function source. 5313 v8::Local<v8::String> script = v8::String::New( 5314 "function f() {\n" 5315 " debugger;\n" 5316 "}\n"); 5317 5318 v8::ScriptOrigin origin1 = v8::ScriptOrigin(v8::String::New("name")); 5319 v8::Handle<v8::Script> script1 = v8::Script::Compile(script, &origin1); 5320 script1->SetData(v8::String::New("data")); 5321 script1->Run(); 5322 v8::Local<v8::Function> f; 5323 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5324 5325 f->Call(env->Global(), 0, NULL); 5326 CHECK_EQ(1, break_point_hit_count); 5327 CHECK_EQ("name", last_script_name_hit); 5328 CHECK_EQ("data", last_script_data_hit); 5329 5330 // Compile the same script again without setting data. As the compilation 5331 // cache is disabled when debugging expect the data to be missing. 5332 v8::Script::Compile(script, &origin1)->Run(); 5333 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5334 f->Call(env->Global(), 0, NULL); 5335 CHECK_EQ(2, break_point_hit_count); 5336 CHECK_EQ("name", last_script_name_hit); 5337 CHECK_EQ("", last_script_data_hit); // Undefined results in empty string. 5338 5339 v8::Local<v8::String> data_obj_source = v8::String::New( 5340 "({ a: 'abc',\n" 5341 " b: 123,\n" 5342 " toString: function() { return this.a + ' ' + this.b; }\n" 5343 "})\n"); 5344 v8::Local<v8::Value> data_obj = v8::Script::Compile(data_obj_source)->Run(); 5345 v8::ScriptOrigin origin2 = v8::ScriptOrigin(v8::String::New("new name")); 5346 v8::Handle<v8::Script> script2 = v8::Script::Compile(script, &origin2); 5347 script2->Run(); 5348 script2->SetData(data_obj->ToString()); 5349 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5350 f->Call(env->Global(), 0, NULL); 5351 CHECK_EQ(3, break_point_hit_count); 5352 CHECK_EQ("new name", last_script_name_hit); 5353 CHECK_EQ("abc 123", last_script_data_hit); 5354 5355 v8::Handle<v8::Script> script3 = 5356 v8::Script::Compile(script, &origin2, NULL, 5357 v8::String::New("in compile")); 5358 CHECK_EQ("in compile", last_script_data_hit); 5359 script3->Run(); 5360 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5361 f->Call(env->Global(), 0, NULL); 5362 CHECK_EQ(4, break_point_hit_count); 5363 CHECK_EQ("in compile", last_script_data_hit); 5364} 5365 5366 5367static v8::Persistent<v8::Context> expected_context; 5368static v8::Handle<v8::Value> expected_context_data; 5369 5370 5371// Check that the expected context is the one generating the debug event. 5372static void ContextCheckMessageHandler(const v8::Debug::Message& message) { 5373 CHECK(message.GetEventContext() == expected_context); 5374 CHECK(message.GetEventContext()->GetData()->StrictEquals( 5375 expected_context_data)); 5376 message_handler_hit_count++; 5377 5378 static char print_buffer[1000]; 5379 v8::String::Value json(message.GetJSON()); 5380 Utf16ToAscii(*json, json.length(), print_buffer); 5381 5382 // Send a continue command for break events. 5383 if (IsBreakEventMessage(print_buffer)) { 5384 SendContinueCommand(); 5385 } 5386} 5387 5388 5389// Test which creates two contexts and sets different embedder data on each. 5390// Checks that this data is set correctly and that when the debug message 5391// handler is called the expected context is the one active. 5392TEST(ContextData) { 5393 v8::HandleScope scope; 5394 5395 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler); 5396 5397 // Create two contexts. 5398 v8::Persistent<v8::Context> context_1; 5399 v8::Persistent<v8::Context> context_2; 5400 v8::Handle<v8::ObjectTemplate> global_template = 5401 v8::Handle<v8::ObjectTemplate>(); 5402 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>(); 5403 context_1 = v8::Context::New(NULL, global_template, global_object); 5404 context_2 = v8::Context::New(NULL, global_template, global_object); 5405 5406 // Default data value is undefined. 5407 CHECK(context_1->GetData()->IsUndefined()); 5408 CHECK(context_2->GetData()->IsUndefined()); 5409 5410 // Set and check different data values. 5411 v8::Handle<v8::String> data_1 = v8::String::New("1"); 5412 v8::Handle<v8::String> data_2 = v8::String::New("2"); 5413 context_1->SetData(data_1); 5414 context_2->SetData(data_2); 5415 CHECK(context_1->GetData()->StrictEquals(data_1)); 5416 CHECK(context_2->GetData()->StrictEquals(data_2)); 5417 5418 // Simple test function which causes a break. 5419 const char* source = "function f() { debugger; }"; 5420 5421 // Enter and run function in the first context. 5422 { 5423 v8::Context::Scope context_scope(context_1); 5424 expected_context = context_1; 5425 expected_context_data = data_1; 5426 v8::Local<v8::Function> f = CompileFunction(source, "f"); 5427 f->Call(context_1->Global(), 0, NULL); 5428 } 5429 5430 5431 // Enter and run function in the second context. 5432 { 5433 v8::Context::Scope context_scope(context_2); 5434 expected_context = context_2; 5435 expected_context_data = data_2; 5436 v8::Local<v8::Function> f = CompileFunction(source, "f"); 5437 f->Call(context_2->Global(), 0, NULL); 5438 } 5439 5440 // Two times compile event and two times break event. 5441 CHECK_GT(message_handler_hit_count, 4); 5442 5443 v8::Debug::SetMessageHandler2(NULL); 5444 CheckDebuggerUnloaded(); 5445} 5446 5447 5448// Debug message handler which issues a debug break when it hits a break event. 5449static int message_handler_break_hit_count = 0; 5450static void DebugBreakMessageHandler(const v8::Debug::Message& message) { 5451 // Schedule a debug break for break events. 5452 if (message.IsEvent() && message.GetEvent() == v8::Break) { 5453 message_handler_break_hit_count++; 5454 if (message_handler_break_hit_count == 1) { 5455 v8::Debug::DebugBreak(); 5456 } 5457 } 5458 5459 // Issue a continue command if this event will not cause the VM to start 5460 // running. 5461 if (!message.WillStartRunning()) { 5462 SendContinueCommand(); 5463 } 5464} 5465 5466 5467// Test that a debug break can be scheduled while in a message handler. 5468TEST(DebugBreakInMessageHandler) { 5469 v8::HandleScope scope; 5470 DebugLocalContext env; 5471 5472 v8::Debug::SetMessageHandler2(DebugBreakMessageHandler); 5473 5474 // Test functions. 5475 const char* script = "function f() { debugger; g(); } function g() { }"; 5476 CompileRun(script); 5477 v8::Local<v8::Function> f = 5478 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5479 v8::Local<v8::Function> g = 5480 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g"))); 5481 5482 // Call f then g. The debugger statement in f will casue a break which will 5483 // cause another break. 5484 f->Call(env->Global(), 0, NULL); 5485 CHECK_EQ(2, message_handler_break_hit_count); 5486 // Calling g will not cause any additional breaks. 5487 g->Call(env->Global(), 0, NULL); 5488 CHECK_EQ(2, message_handler_break_hit_count); 5489} 5490 5491 5492#ifndef V8_INTERPRETED_REGEXP 5493// Debug event handler which gets the function on the top frame and schedules a 5494// break a number of times. 5495static void DebugEventDebugBreak( 5496 v8::DebugEvent event, 5497 v8::Handle<v8::Object> exec_state, 5498 v8::Handle<v8::Object> event_data, 5499 v8::Handle<v8::Value> data) { 5500 5501 if (event == v8::Break) { 5502 break_point_hit_count++; 5503 5504 // Get the name of the top frame function. 5505 if (!frame_function_name.IsEmpty()) { 5506 // Get the name of the function. 5507 const int argc = 1; 5508 v8::Handle<v8::Value> argv[argc] = { exec_state }; 5509 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state, 5510 argc, argv); 5511 if (result->IsUndefined()) { 5512 last_function_hit[0] = '\0'; 5513 } else { 5514 CHECK(result->IsString()); 5515 v8::Handle<v8::String> function_name(result->ToString()); 5516 function_name->WriteAscii(last_function_hit); 5517 } 5518 } 5519 5520 // Keep forcing breaks. 5521 if (break_point_hit_count < 20) { 5522 v8::Debug::DebugBreak(); 5523 } 5524 } 5525} 5526 5527 5528TEST(RegExpDebugBreak) { 5529 // This test only applies to native regexps. 5530 v8::HandleScope scope; 5531 DebugLocalContext env; 5532 5533 // Create a function for checking the function when hitting a break point. 5534 frame_function_name = CompileFunction(&env, 5535 frame_function_name_source, 5536 "frame_function_name"); 5537 5538 // Test RegExp which matches white spaces and comments at the begining of a 5539 // source line. 5540 const char* script = 5541 "var sourceLineBeginningSkip = /^(?:[ \\v\\h]*(?:\\/\\*.*?\\*\\/)*)*/;\n" 5542 "function f(s) { return s.match(sourceLineBeginningSkip)[0].length; }"; 5543 5544 v8::Local<v8::Function> f = CompileFunction(script, "f"); 5545 const int argc = 1; 5546 v8::Handle<v8::Value> argv[argc] = { v8::String::New(" /* xxx */ a=0;") }; 5547 v8::Local<v8::Value> result = f->Call(env->Global(), argc, argv); 5548 CHECK_EQ(12, result->Int32Value()); 5549 5550 v8::Debug::SetDebugEventListener(DebugEventDebugBreak); 5551 v8::Debug::DebugBreak(); 5552 result = f->Call(env->Global(), argc, argv); 5553 5554 // Check that there was only one break event. Matching RegExp should not 5555 // cause Break events. 5556 CHECK_EQ(1, break_point_hit_count); 5557 CHECK_EQ("f", last_function_hit); 5558} 5559#endif // V8_INTERPRETED_REGEXP 5560 5561 5562// Common part of EvalContextData and NestedBreakEventContextData tests. 5563static void ExecuteScriptForContextCheck() { 5564 // Create a context. 5565 v8::Persistent<v8::Context> context_1; 5566 v8::Handle<v8::ObjectTemplate> global_template = 5567 v8::Handle<v8::ObjectTemplate>(); 5568 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>(); 5569 context_1 = v8::Context::New(NULL, global_template, global_object); 5570 5571 // Default data value is undefined. 5572 CHECK(context_1->GetData()->IsUndefined()); 5573 5574 // Set and check a data value. 5575 v8::Handle<v8::String> data_1 = v8::String::New("1"); 5576 context_1->SetData(data_1); 5577 CHECK(context_1->GetData()->StrictEquals(data_1)); 5578 5579 // Simple test function with eval that causes a break. 5580 const char* source = "function f() { eval('debugger;'); }"; 5581 5582 // Enter and run function in the context. 5583 { 5584 v8::Context::Scope context_scope(context_1); 5585 expected_context = context_1; 5586 expected_context_data = data_1; 5587 v8::Local<v8::Function> f = CompileFunction(source, "f"); 5588 f->Call(context_1->Global(), 0, NULL); 5589 } 5590} 5591 5592 5593// Test which creates a context and sets embedder data on it. Checks that this 5594// data is set correctly and that when the debug message handler is called for 5595// break event in an eval statement the expected context is the one returned by 5596// Message.GetEventContext. 5597TEST(EvalContextData) { 5598 v8::HandleScope scope; 5599 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler); 5600 5601 ExecuteScriptForContextCheck(); 5602 5603 // One time compile event and one time break event. 5604 CHECK_GT(message_handler_hit_count, 2); 5605 v8::Debug::SetMessageHandler2(NULL); 5606 CheckDebuggerUnloaded(); 5607} 5608 5609 5610static bool sent_eval = false; 5611static int break_count = 0; 5612static int continue_command_send_count = 0; 5613// Check that the expected context is the one generating the debug event 5614// including the case of nested break event. 5615static void DebugEvalContextCheckMessageHandler( 5616 const v8::Debug::Message& message) { 5617 CHECK(message.GetEventContext() == expected_context); 5618 CHECK(message.GetEventContext()->GetData()->StrictEquals( 5619 expected_context_data)); 5620 message_handler_hit_count++; 5621 5622 static char print_buffer[1000]; 5623 v8::String::Value json(message.GetJSON()); 5624 Utf16ToAscii(*json, json.length(), print_buffer); 5625 5626 if (IsBreakEventMessage(print_buffer)) { 5627 break_count++; 5628 if (!sent_eval) { 5629 sent_eval = true; 5630 5631 const int kBufferSize = 1000; 5632 uint16_t buffer[kBufferSize]; 5633 const char* eval_command = 5634 "{\"seq\":0," 5635 "\"type\":\"request\"," 5636 "\"command\":\"evaluate\"," 5637 "arguments:{\"expression\":\"debugger;\"," 5638 "\"global\":true,\"disable_break\":false}}"; 5639 5640 // Send evaluate command. 5641 v8::Debug::SendCommand(buffer, AsciiToUtf16(eval_command, buffer)); 5642 return; 5643 } else { 5644 // It's a break event caused by the evaluation request above. 5645 SendContinueCommand(); 5646 continue_command_send_count++; 5647 } 5648 } else if (IsEvaluateResponseMessage(print_buffer) && 5649 continue_command_send_count < 2) { 5650 // Response to the evaluation request. We're still on the breakpoint so 5651 // send continue. 5652 SendContinueCommand(); 5653 continue_command_send_count++; 5654 } 5655} 5656 5657 5658// Tests that context returned for break event is correct when the event occurs 5659// in 'evaluate' debugger request. 5660TEST(NestedBreakEventContextData) { 5661 v8::HandleScope scope; 5662 break_count = 0; 5663 message_handler_hit_count = 0; 5664 v8::Debug::SetMessageHandler2(DebugEvalContextCheckMessageHandler); 5665 5666 ExecuteScriptForContextCheck(); 5667 5668 // One time compile event and two times break event. 5669 CHECK_GT(message_handler_hit_count, 3); 5670 5671 // One break from the source and another from the evaluate request. 5672 CHECK_EQ(break_count, 2); 5673 v8::Debug::SetMessageHandler2(NULL); 5674 CheckDebuggerUnloaded(); 5675} 5676 5677 5678// Debug event listener which counts the script collected events. 5679int script_collected_count = 0; 5680static void DebugEventScriptCollectedEvent(v8::DebugEvent event, 5681 v8::Handle<v8::Object> exec_state, 5682 v8::Handle<v8::Object> event_data, 5683 v8::Handle<v8::Value> data) { 5684 // Count the number of breaks. 5685 if (event == v8::ScriptCollected) { 5686 script_collected_count++; 5687 } 5688} 5689 5690 5691// Test that scripts collected are reported through the debug event listener. 5692TEST(ScriptCollectedEvent) { 5693 break_point_hit_count = 0; 5694 script_collected_count = 0; 5695 v8::HandleScope scope; 5696 DebugLocalContext env; 5697 5698 // Request the loaded scripts to initialize the debugger script cache. 5699 Debug::GetLoadedScripts(); 5700 5701 // Do garbage collection to ensure that only the script in this test will be 5702 // collected afterwards. 5703 Heap::CollectAllGarbage(false); 5704 5705 script_collected_count = 0; 5706 v8::Debug::SetDebugEventListener(DebugEventScriptCollectedEvent, 5707 v8::Undefined()); 5708 { 5709 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run(); 5710 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run(); 5711 } 5712 5713 // Do garbage collection to collect the script above which is no longer 5714 // referenced. 5715 Heap::CollectAllGarbage(false); 5716 5717 CHECK_EQ(2, script_collected_count); 5718 5719 v8::Debug::SetDebugEventListener(NULL); 5720 CheckDebuggerUnloaded(); 5721} 5722 5723 5724// Debug event listener which counts the script collected events. 5725int script_collected_message_count = 0; 5726static void ScriptCollectedMessageHandler(const v8::Debug::Message& message) { 5727 // Count the number of scripts collected. 5728 if (message.IsEvent() && message.GetEvent() == v8::ScriptCollected) { 5729 script_collected_message_count++; 5730 v8::Handle<v8::Context> context = message.GetEventContext(); 5731 CHECK(context.IsEmpty()); 5732 } 5733} 5734 5735 5736// Test that GetEventContext doesn't fail and return empty handle for 5737// ScriptCollected events. 5738TEST(ScriptCollectedEventContext) { 5739 script_collected_message_count = 0; 5740 v8::HandleScope scope; 5741 5742 { // Scope for the DebugLocalContext. 5743 DebugLocalContext env; 5744 5745 // Request the loaded scripts to initialize the debugger script cache. 5746 Debug::GetLoadedScripts(); 5747 5748 // Do garbage collection to ensure that only the script in this test will be 5749 // collected afterwards. 5750 Heap::CollectAllGarbage(false); 5751 5752 v8::Debug::SetMessageHandler2(ScriptCollectedMessageHandler); 5753 { 5754 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run(); 5755 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run(); 5756 } 5757 } 5758 5759 // Do garbage collection to collect the script above which is no longer 5760 // referenced. 5761 Heap::CollectAllGarbage(false); 5762 5763 CHECK_EQ(2, script_collected_message_count); 5764 5765 v8::Debug::SetMessageHandler2(NULL); 5766} 5767 5768 5769// Debug event listener which counts the after compile events. 5770int after_compile_message_count = 0; 5771static void AfterCompileMessageHandler(const v8::Debug::Message& message) { 5772 // Count the number of scripts collected. 5773 if (message.IsEvent()) { 5774 if (message.GetEvent() == v8::AfterCompile) { 5775 after_compile_message_count++; 5776 } else if (message.GetEvent() == v8::Break) { 5777 SendContinueCommand(); 5778 } 5779 } 5780} 5781 5782 5783// Tests that after compile event is sent as many times as there are scripts 5784// compiled. 5785TEST(AfterCompileMessageWhenMessageHandlerIsReset) { 5786 v8::HandleScope scope; 5787 DebugLocalContext env; 5788 after_compile_message_count = 0; 5789 const char* script = "var a=1"; 5790 5791 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler); 5792 v8::Script::Compile(v8::String::New(script))->Run(); 5793 v8::Debug::SetMessageHandler2(NULL); 5794 5795 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler); 5796 v8::Debug::DebugBreak(); 5797 v8::Script::Compile(v8::String::New(script))->Run(); 5798 5799 // Setting listener to NULL should cause debugger unload. 5800 v8::Debug::SetMessageHandler2(NULL); 5801 CheckDebuggerUnloaded(); 5802 5803 // Compilation cache should be disabled when debugger is active. 5804 CHECK_EQ(2, after_compile_message_count); 5805} 5806 5807 5808// Tests that break event is sent when message handler is reset. 5809TEST(BreakMessageWhenMessageHandlerIsReset) { 5810 v8::HandleScope scope; 5811 DebugLocalContext env; 5812 after_compile_message_count = 0; 5813 const char* script = "function f() {};"; 5814 5815 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler); 5816 v8::Script::Compile(v8::String::New(script))->Run(); 5817 v8::Debug::SetMessageHandler2(NULL); 5818 5819 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler); 5820 v8::Debug::DebugBreak(); 5821 v8::Local<v8::Function> f = 5822 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5823 f->Call(env->Global(), 0, NULL); 5824 5825 // Setting message handler to NULL should cause debugger unload. 5826 v8::Debug::SetMessageHandler2(NULL); 5827 CheckDebuggerUnloaded(); 5828 5829 // Compilation cache should be disabled when debugger is active. 5830 CHECK_EQ(1, after_compile_message_count); 5831} 5832 5833 5834static int exception_event_count = 0; 5835static void ExceptionMessageHandler(const v8::Debug::Message& message) { 5836 if (message.IsEvent() && message.GetEvent() == v8::Exception) { 5837 exception_event_count++; 5838 SendContinueCommand(); 5839 } 5840} 5841 5842 5843// Tests that exception event is sent when message handler is reset. 5844TEST(ExceptionMessageWhenMessageHandlerIsReset) { 5845 v8::HandleScope scope; 5846 DebugLocalContext env; 5847 exception_event_count = 0; 5848 const char* script = "function f() {throw new Error()};"; 5849 5850 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler); 5851 v8::Script::Compile(v8::String::New(script))->Run(); 5852 v8::Debug::SetMessageHandler2(NULL); 5853 5854 v8::Debug::SetMessageHandler2(ExceptionMessageHandler); 5855 v8::Local<v8::Function> f = 5856 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f"))); 5857 f->Call(env->Global(), 0, NULL); 5858 5859 // Setting message handler to NULL should cause debugger unload. 5860 v8::Debug::SetMessageHandler2(NULL); 5861 CheckDebuggerUnloaded(); 5862 5863 CHECK_EQ(1, exception_event_count); 5864} 5865 5866 5867// Tests after compile event is sent when there are some provisional 5868// breakpoints out of the scripts lines range. 5869TEST(ProvisionalBreakpointOnLineOutOfRange) { 5870 v8::HandleScope scope; 5871 DebugLocalContext env; 5872 env.ExposeDebug(); 5873 const char* script = "function f() {};"; 5874 const char* resource_name = "test_resource"; 5875 5876 // Set a couple of provisional breakpoint on lines out of the script lines 5877 // range. 5878 int sbp1 = SetScriptBreakPointByNameFromJS(resource_name, 3, 5879 -1 /* no column */); 5880 int sbp2 = SetScriptBreakPointByNameFromJS(resource_name, 5, 5); 5881 5882 after_compile_message_count = 0; 5883 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler); 5884 5885 v8::ScriptOrigin origin( 5886 v8::String::New(resource_name), 5887 v8::Integer::New(10), 5888 v8::Integer::New(1)); 5889 // Compile a script whose first line number is greater than the breakpoints' 5890 // lines. 5891 v8::Script::Compile(v8::String::New(script), &origin)->Run(); 5892 5893 // If the script is compiled successfully there is exactly one after compile 5894 // event. In case of an exception in debugger code after compile event is not 5895 // sent. 5896 CHECK_EQ(1, after_compile_message_count); 5897 5898 ClearBreakPointFromJS(sbp1); 5899 ClearBreakPointFromJS(sbp2); 5900 v8::Debug::SetMessageHandler2(NULL); 5901} 5902 5903 5904static void BreakMessageHandler(const v8::Debug::Message& message) { 5905 if (message.IsEvent() && message.GetEvent() == v8::Break) { 5906 // Count the number of breaks. 5907 break_point_hit_count++; 5908 5909 v8::HandleScope scope; 5910 v8::Handle<v8::String> json = message.GetJSON(); 5911 5912 SendContinueCommand(); 5913 } else if (message.IsEvent() && message.GetEvent() == v8::AfterCompile) { 5914 v8::HandleScope scope; 5915 5916 bool is_debug_break = i::StackGuard::IsDebugBreak(); 5917 // Force DebugBreak flag while serializer is working. 5918 i::StackGuard::DebugBreak(); 5919 5920 // Force serialization to trigger some internal JS execution. 5921 v8::Handle<v8::String> json = message.GetJSON(); 5922 5923 // Restore previous state. 5924 if (is_debug_break) { 5925 i::StackGuard::DebugBreak(); 5926 } else { 5927 i::StackGuard::Continue(i::DEBUGBREAK); 5928 } 5929 } 5930} 5931 5932 5933// Test that if DebugBreak is forced it is ignored when code from 5934// debug-delay.js is executed. 5935TEST(NoDebugBreakInAfterCompileMessageHandler) { 5936 v8::HandleScope scope; 5937 DebugLocalContext env; 5938 5939 // Register a debug event listener which sets the break flag and counts. 5940 v8::Debug::SetMessageHandler2(BreakMessageHandler); 5941 5942 // Set the debug break flag. 5943 v8::Debug::DebugBreak(); 5944 5945 // Create a function for testing stepping. 5946 const char* src = "function f() { eval('var x = 10;'); } "; 5947 v8::Local<v8::Function> f = CompileFunction(&env, src, "f"); 5948 5949 // There should be only one break event. 5950 CHECK_EQ(1, break_point_hit_count); 5951 5952 // Set the debug break flag again. 5953 v8::Debug::DebugBreak(); 5954 f->Call(env->Global(), 0, NULL); 5955 // There should be one more break event when the script is evaluated in 'f'. 5956 CHECK_EQ(2, break_point_hit_count); 5957 5958 // Get rid of the debug message handler. 5959 v8::Debug::SetMessageHandler2(NULL); 5960 CheckDebuggerUnloaded(); 5961} 5962 5963 5964static int counting_message_handler_counter; 5965 5966static void CountingMessageHandler(const v8::Debug::Message& message) { 5967 counting_message_handler_counter++; 5968} 5969 5970// Test that debug messages get processed when ProcessDebugMessages is called. 5971TEST(ProcessDebugMessages) { 5972 v8::HandleScope scope; 5973 DebugLocalContext env; 5974 5975 counting_message_handler_counter = 0; 5976 5977 v8::Debug::SetMessageHandler2(CountingMessageHandler); 5978 5979 const int kBufferSize = 1000; 5980 uint16_t buffer[kBufferSize]; 5981 const char* scripts_command = 5982 "{\"seq\":0," 5983 "\"type\":\"request\"," 5984 "\"command\":\"scripts\"}"; 5985 5986 // Send scripts command. 5987 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer)); 5988 5989 CHECK_EQ(0, counting_message_handler_counter); 5990 v8::Debug::ProcessDebugMessages(); 5991 // At least one message should come 5992 CHECK_GE(counting_message_handler_counter, 1); 5993 5994 counting_message_handler_counter = 0; 5995 5996 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer)); 5997 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer)); 5998 CHECK_EQ(0, counting_message_handler_counter); 5999 v8::Debug::ProcessDebugMessages(); 6000 // At least two messages should come 6001 CHECK_GE(counting_message_handler_counter, 2); 6002 6003 // Get rid of the debug message handler. 6004 v8::Debug::SetMessageHandler2(NULL); 6005 CheckDebuggerUnloaded(); 6006} 6007 6008 6009struct BacktraceData { 6010 static int frame_counter; 6011 static void MessageHandler(const v8::Debug::Message& message) { 6012 char print_buffer[1000]; 6013 v8::String::Value json(message.GetJSON()); 6014 Utf16ToAscii(*json, json.length(), print_buffer, 1000); 6015 6016 if (strstr(print_buffer, "backtrace") == NULL) { 6017 return; 6018 } 6019 frame_counter = GetTotalFramesInt(print_buffer); 6020 } 6021}; 6022 6023int BacktraceData::frame_counter; 6024 6025 6026// Test that debug messages get processed when ProcessDebugMessages is called. 6027TEST(Backtrace) { 6028 v8::HandleScope scope; 6029 DebugLocalContext env; 6030 6031 v8::Debug::SetMessageHandler2(BacktraceData::MessageHandler); 6032 6033 const int kBufferSize = 1000; 6034 uint16_t buffer[kBufferSize]; 6035 const char* scripts_command = 6036 "{\"seq\":0," 6037 "\"type\":\"request\"," 6038 "\"command\":\"backtrace\"}"; 6039 6040 // Check backtrace from ProcessDebugMessages. 6041 BacktraceData::frame_counter = -10; 6042 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer)); 6043 v8::Debug::ProcessDebugMessages(); 6044 CHECK_EQ(BacktraceData::frame_counter, 0); 6045 6046 v8::Handle<v8::String> void0 = v8::String::New("void(0)"); 6047 v8::Handle<v8::Script> script = v8::Script::Compile(void0, void0); 6048 6049 // Check backtrace from "void(0)" script. 6050 BacktraceData::frame_counter = -10; 6051 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer)); 6052 script->Run(); 6053 CHECK_EQ(BacktraceData::frame_counter, 1); 6054 6055 // Get rid of the debug message handler. 6056 v8::Debug::SetMessageHandler2(NULL); 6057 CheckDebuggerUnloaded(); 6058} 6059 6060 6061TEST(GetMirror) { 6062 v8::HandleScope scope; 6063 DebugLocalContext env; 6064 v8::Handle<v8::Value> obj = v8::Debug::GetMirror(v8::String::New("hodja")); 6065 v8::Handle<v8::Function> run_test = v8::Handle<v8::Function>::Cast( 6066 v8::Script::New( 6067 v8::String::New( 6068 "function runTest(mirror) {" 6069 " return mirror.isString() && (mirror.length() == 5);" 6070 "}" 6071 "" 6072 "runTest;"))->Run()); 6073 v8::Handle<v8::Value> result = run_test->Call(env->Global(), 1, &obj); 6074 CHECK(result->IsTrue()); 6075} 6076 6077 6078// Test that the debug break flag works with function.apply. 6079TEST(DebugBreakFunctionApply) { 6080 v8::HandleScope scope; 6081 DebugLocalContext env; 6082 6083 // Create a function for testing breaking in apply. 6084 v8::Local<v8::Function> foo = CompileFunction( 6085 &env, 6086 "function baz(x) { }" 6087 "function bar(x) { baz(); }" 6088 "function foo(){ bar.apply(this, [1]); }", 6089 "foo"); 6090 6091 // Register a debug event listener which steps and counts. 6092 v8::Debug::SetDebugEventListener(DebugEventBreakMax); 6093 6094 // Set the debug break flag before calling the code using function.apply. 6095 v8::Debug::DebugBreak(); 6096 6097 // Limit the number of debug breaks. This is a regression test for issue 493 6098 // where this test would enter an infinite loop. 6099 break_point_hit_count = 0; 6100 max_break_point_hit_count = 10000; // 10000 => infinite loop. 6101 foo->Call(env->Global(), 0, NULL); 6102 6103 // When keeping the debug break several break will happen. 6104 CHECK_EQ(3, break_point_hit_count); 6105 6106 v8::Debug::SetDebugEventListener(NULL); 6107 CheckDebuggerUnloaded(); 6108} 6109 6110 6111v8::Handle<v8::Context> debugee_context; 6112v8::Handle<v8::Context> debugger_context; 6113 6114 6115// Property getter that checks that current and calling contexts 6116// are both the debugee contexts. 6117static v8::Handle<v8::Value> NamedGetterWithCallingContextCheck( 6118 v8::Local<v8::String> name, 6119 const v8::AccessorInfo& info) { 6120 CHECK_EQ(0, strcmp(*v8::String::AsciiValue(name), "a")); 6121 v8::Handle<v8::Context> current = v8::Context::GetCurrent(); 6122 CHECK(current == debugee_context); 6123 CHECK(current != debugger_context); 6124 v8::Handle<v8::Context> calling = v8::Context::GetCalling(); 6125 CHECK(calling == debugee_context); 6126 CHECK(calling != debugger_context); 6127 return v8::Int32::New(1); 6128} 6129 6130 6131// Debug event listener that checks if the first argument of a function is 6132// an object with property 'a' == 1. If the property has custom accessor 6133// this handler will eventually invoke it. 6134static void DebugEventGetAtgumentPropertyValue( 6135 v8::DebugEvent event, 6136 v8::Handle<v8::Object> exec_state, 6137 v8::Handle<v8::Object> event_data, 6138 v8::Handle<v8::Value> data) { 6139 if (event == v8::Break) { 6140 break_point_hit_count++; 6141 CHECK(debugger_context == v8::Context::GetCurrent()); 6142 v8::Handle<v8::Function> func(v8::Function::Cast(*CompileRun( 6143 "(function(exec_state) {\n" 6144 " return (exec_state.frame(0).argumentValue(0).property('a').\n" 6145 " value().value() == 1);\n" 6146 "})"))); 6147 const int argc = 1; 6148 v8::Handle<v8::Value> argv[argc] = { exec_state }; 6149 v8::Handle<v8::Value> result = func->Call(exec_state, argc, argv); 6150 CHECK(result->IsTrue()); 6151 } 6152} 6153 6154 6155TEST(CallingContextIsNotDebugContext) { 6156 // Create and enter a debugee context. 6157 v8::HandleScope scope; 6158 DebugLocalContext env; 6159 env.ExposeDebug(); 6160 6161 // Save handles to the debugger and debugee contexts to be used in 6162 // NamedGetterWithCallingContextCheck. 6163 debugee_context = v8::Local<v8::Context>(*env); 6164 debugger_context = v8::Utils::ToLocal(Debug::debug_context()); 6165 6166 // Create object with 'a' property accessor. 6167 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(); 6168 named->SetAccessor(v8::String::New("a"), 6169 NamedGetterWithCallingContextCheck); 6170 env->Global()->Set(v8::String::New("obj"), 6171 named->NewInstance()); 6172 6173 // Register the debug event listener 6174 v8::Debug::SetDebugEventListener(DebugEventGetAtgumentPropertyValue); 6175 6176 // Create a function that invokes debugger. 6177 v8::Local<v8::Function> foo = CompileFunction( 6178 &env, 6179 "function bar(x) { debugger; }" 6180 "function foo(){ bar(obj); }", 6181 "foo"); 6182 6183 break_point_hit_count = 0; 6184 foo->Call(env->Global(), 0, NULL); 6185 CHECK_EQ(1, break_point_hit_count); 6186 6187 v8::Debug::SetDebugEventListener(NULL); 6188 debugee_context = v8::Handle<v8::Context>(); 6189 debugger_context = v8::Handle<v8::Context>(); 6190 CheckDebuggerUnloaded(); 6191} 6192 6193 6194TEST(DebugContextIsPreservedBetweenAccesses) { 6195 v8::HandleScope scope; 6196 v8::Local<v8::Context> context1 = v8::Debug::GetDebugContext(); 6197 v8::Local<v8::Context> context2 = v8::Debug::GetDebugContext(); 6198 CHECK_EQ(*context1, *context2); 6199} 6200 6201 6202static v8::Handle<v8::Value> expected_callback_data; 6203static void DebugEventContextChecker(const v8::Debug::EventDetails& details) { 6204 CHECK(details.GetEventContext() == expected_context); 6205 CHECK_EQ(expected_callback_data, details.GetCallbackData()); 6206} 6207 6208// Check that event details contain context where debug event occured. 6209TEST(DebugEventContext) { 6210 v8::HandleScope scope; 6211 expected_callback_data = v8::Int32::New(2010); 6212 v8::Debug::SetDebugEventListener2(DebugEventContextChecker, 6213 expected_callback_data); 6214 expected_context = v8::Context::New(); 6215 v8::Context::Scope context_scope(expected_context); 6216 v8::Script::Compile(v8::String::New("(function(){debugger;})();"))->Run(); 6217 expected_context.Dispose(); 6218 expected_context.Clear(); 6219 v8::Debug::SetDebugEventListener(NULL); 6220 expected_context_data = v8::Handle<v8::Value>(); 6221 CheckDebuggerUnloaded(); 6222} 6223 6224