1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Redistribution and use in source and binary forms, with or without
3 // modification, are permitted provided that the following conditions are
6 // * Redistributions of source code must retain the above copyright
7 // notice, this list of conditions and the following disclaimer.
8 // * Redistributions in binary form must reproduce the above
9 // copyright notice, this list of conditions and the following
10 // disclaimer in the documentation and/or other materials provided
11 // with the distribution.
12 // * Neither the name of Google Inc. nor the names of its
13 // contributors may be used to endorse or promote products derived
14 // from this software without specific prior written permission.
16 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 #include "src/base/platform/condition-variable.h"
34 #include "src/base/platform/platform.h"
35 #include "src/compilation-cache.h"
36 #include "src/debug.h"
37 #include "src/deoptimizer.h"
38 #include "src/frames.h"
39 #include "src/utils.h"
40 #include "test/cctest/cctest.h"
43 using ::v8::base::Mutex;
44 using ::v8::base::LockGuard;
45 using ::v8::base::ConditionVariable;
47 using ::v8::base::Semaphore;
48 using ::v8::internal::EmbeddedVector;
49 using ::v8::internal::Object;
50 using ::v8::internal::Handle;
51 using ::v8::internal::Heap;
52 using ::v8::internal::JSGlobalProxy;
53 using ::v8::internal::Code;
54 using ::v8::internal::Debug;
55 using ::v8::internal::Debugger;
56 using ::v8::internal::CommandMessage;
57 using ::v8::internal::CommandMessageQueue;
58 using ::v8::internal::StackFrame;
59 using ::v8::internal::StepAction;
60 using ::v8::internal::StepIn; // From StepAction enum
61 using ::v8::internal::StepNext; // From StepAction enum
62 using ::v8::internal::StepOut; // From StepAction enum
63 using ::v8::internal::Vector;
64 using ::v8::internal::StrLength;
66 // Size of temp buffer for formatting small strings.
67 #define SMALL_STRING_BUFFER_SIZE 80
69 // --- H e l p e r C l a s s e s
72 // Helper class for creating a V8 enviromnent for running tests
73 class DebugLocalContext {
75 inline DebugLocalContext(
76 v8::ExtensionConfiguration* extensions = 0,
77 v8::Handle<v8::ObjectTemplate> global_template =
78 v8::Handle<v8::ObjectTemplate>(),
79 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>())
80 : scope_(CcTest::isolate()),
82 v8::Context::New(CcTest::isolate(),
88 inline ~DebugLocalContext() {
91 inline v8::Local<v8::Context> context() { return context_; }
92 inline v8::Context* operator->() { return *context_; }
93 inline v8::Context* operator*() { return *context_; }
94 inline v8::Isolate* GetIsolate() { return context_->GetIsolate(); }
95 inline bool IsReady() { return !context_.IsEmpty(); }
97 v8::internal::Isolate* isolate =
98 reinterpret_cast<v8::internal::Isolate*>(context_->GetIsolate());
99 v8::internal::Factory* factory = isolate->factory();
100 // Expose the debug context global object in the global object for testing.
101 CHECK(isolate->debug()->Load());
102 Handle<v8::internal::Context> debug_context =
103 isolate->debug()->debug_context();
104 debug_context->set_security_token(
105 v8::Utils::OpenHandle(*context_)->security_token());
107 Handle<JSGlobalProxy> global(Handle<JSGlobalProxy>::cast(
108 v8::Utils::OpenHandle(*context_->Global())));
109 Handle<v8::internal::String> debug_string =
110 factory->InternalizeOneByteString(STATIC_ASCII_VECTOR("debug"));
111 v8::internal::Runtime::DefineObjectProperty(global, debug_string,
112 handle(debug_context->global_proxy(), isolate), DONT_ENUM).Check();
116 v8::HandleScope scope_;
117 v8::Local<v8::Context> context_;
121 // --- H e l p e r F u n c t i o n s
124 // Compile and run the supplied source and return the fequested function.
125 static v8::Local<v8::Function> CompileFunction(DebugLocalContext* env,
127 const char* function_name) {
128 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), source))
130 return v8::Local<v8::Function>::Cast((*env)->Global()->Get(
131 v8::String::NewFromUtf8(env->GetIsolate(), function_name)));
135 // Compile and run the supplied source and return the requested function.
136 static v8::Local<v8::Function> CompileFunction(v8::Isolate* isolate,
138 const char* function_name) {
139 v8::Script::Compile(v8::String::NewFromUtf8(isolate, source))->Run();
140 v8::Local<v8::Object> global =
141 CcTest::isolate()->GetCurrentContext()->Global();
142 return v8::Local<v8::Function>::Cast(
143 global->Get(v8::String::NewFromUtf8(isolate, function_name)));
147 // Is there any debug info for the function?
148 static bool HasDebugInfo(v8::Handle<v8::Function> fun) {
149 Handle<v8::internal::JSFunction> f = v8::Utils::OpenHandle(*fun);
150 Handle<v8::internal::SharedFunctionInfo> shared(f->shared());
151 return Debug::HasDebugInfo(shared);
155 // Set a break point in a function and return the associated break point
157 static int SetBreakPoint(Handle<v8::internal::JSFunction> fun, int position) {
158 static int break_point = 0;
159 v8::internal::Isolate* isolate = fun->GetIsolate();
160 v8::internal::Debug* debug = isolate->debug();
161 debug->SetBreakPoint(
163 Handle<Object>(v8::internal::Smi::FromInt(++break_point), isolate),
169 // Set a break point in a function and return the associated break point
171 static int SetBreakPoint(v8::Handle<v8::Function> fun, int position) {
172 return SetBreakPoint(v8::Utils::OpenHandle(*fun), position);
176 // Set a break point in a function using the Debug object and return the
177 // associated break point number.
178 static int SetBreakPointFromJS(v8::Isolate* isolate,
179 const char* function_name,
180 int line, int position) {
181 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
183 "debug.Debug.setBreakPoint(%s,%d,%d)",
184 function_name, line, position);
185 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
186 v8::Handle<v8::String> str = v8::String::NewFromUtf8(isolate, buffer.start());
187 return v8::Script::Compile(str)->Run()->Int32Value();
191 // Set a break point in a script identified by id using the global Debug object.
192 static int SetScriptBreakPointByIdFromJS(v8::Isolate* isolate, int script_id,
193 int line, int column) {
194 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
196 // Column specified set script break point on precise location.
198 "debug.Debug.setScriptBreakPointById(%d,%d,%d)",
199 script_id, line, column);
201 // Column not specified set script break point on line.
203 "debug.Debug.setScriptBreakPointById(%d,%d)",
206 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
208 v8::TryCatch try_catch;
209 v8::Handle<v8::String> str =
210 v8::String::NewFromUtf8(isolate, buffer.start());
211 v8::Handle<v8::Value> value = v8::Script::Compile(str)->Run();
212 CHECK(!try_catch.HasCaught());
213 return value->Int32Value();
218 // Set a break point in a script identified by name using the global Debug
220 static int SetScriptBreakPointByNameFromJS(v8::Isolate* isolate,
221 const char* script_name, int line,
223 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
225 // Column specified set script break point on precise location.
227 "debug.Debug.setScriptBreakPointByName(\"%s\",%d,%d)",
228 script_name, line, column);
230 // Column not specified set script break point on line.
232 "debug.Debug.setScriptBreakPointByName(\"%s\",%d)",
235 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
237 v8::TryCatch try_catch;
238 v8::Handle<v8::String> str =
239 v8::String::NewFromUtf8(isolate, buffer.start());
240 v8::Handle<v8::Value> value = v8::Script::Compile(str)->Run();
241 CHECK(!try_catch.HasCaught());
242 return value->Int32Value();
247 // Clear a break point.
248 static void ClearBreakPoint(int break_point) {
249 v8::internal::Isolate* isolate = CcTest::i_isolate();
250 v8::internal::Debug* debug = isolate->debug();
251 debug->ClearBreakPoint(
252 Handle<Object>(v8::internal::Smi::FromInt(break_point), isolate));
256 // Clear a break point using the global Debug object.
257 static void ClearBreakPointFromJS(v8::Isolate* isolate,
258 int break_point_number) {
259 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
261 "debug.Debug.clearBreakPoint(%d)",
263 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
264 v8::Script::Compile(v8::String::NewFromUtf8(isolate, buffer.start()))->Run();
268 static void EnableScriptBreakPointFromJS(v8::Isolate* isolate,
269 int break_point_number) {
270 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
272 "debug.Debug.enableScriptBreakPoint(%d)",
274 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
275 v8::Script::Compile(v8::String::NewFromUtf8(isolate, buffer.start()))->Run();
279 static void DisableScriptBreakPointFromJS(v8::Isolate* isolate,
280 int break_point_number) {
281 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
283 "debug.Debug.disableScriptBreakPoint(%d)",
285 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
286 v8::Script::Compile(v8::String::NewFromUtf8(isolate, buffer.start()))->Run();
290 static void ChangeScriptBreakPointConditionFromJS(v8::Isolate* isolate,
291 int break_point_number,
292 const char* condition) {
293 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
295 "debug.Debug.changeScriptBreakPointCondition(%d, \"%s\")",
296 break_point_number, condition);
297 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
298 v8::Script::Compile(v8::String::NewFromUtf8(isolate, buffer.start()))->Run();
302 static void ChangeScriptBreakPointIgnoreCountFromJS(v8::Isolate* isolate,
303 int break_point_number,
305 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
307 "debug.Debug.changeScriptBreakPointIgnoreCount(%d, %d)",
308 break_point_number, ignoreCount);
309 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
310 v8::Script::Compile(v8::String::NewFromUtf8(isolate, buffer.start()))->Run();
314 // Change break on exception.
315 static void ChangeBreakOnException(bool caught, bool uncaught) {
316 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
317 debug->ChangeBreakOnException(v8::internal::BreakException, caught);
318 debug->ChangeBreakOnException(v8::internal::BreakUncaughtException, uncaught);
322 // Change break on exception using the global Debug object.
323 static void ChangeBreakOnExceptionFromJS(v8::Isolate* isolate, bool caught,
327 v8::String::NewFromUtf8(isolate, "debug.Debug.setBreakOnException()"))
331 v8::String::NewFromUtf8(isolate, "debug.Debug.clearBreakOnException()"))
336 v8::String::NewFromUtf8(
337 isolate, "debug.Debug.setBreakOnUncaughtException()"))->Run();
340 v8::String::NewFromUtf8(
341 isolate, "debug.Debug.clearBreakOnUncaughtException()"))->Run();
346 // Prepare to step to next break location.
347 static void PrepareStep(StepAction step_action) {
348 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
349 debug->PrepareStep(step_action, 1, StackFrame::NO_ID);
353 // This function is in namespace v8::internal to be friend with class
354 // v8::internal::Debug.
358 // Collect the currently debugged functions.
359 Handle<FixedArray> GetDebuggedFunctions() {
360 Debug* debug = CcTest::i_isolate()->debug();
362 v8::internal::DebugInfoListNode* node = debug->debug_info_list_;
364 // Find the number of debugged functions.
371 // Allocate array for the debugged functions
372 Handle<FixedArray> debugged_functions =
373 CcTest::i_isolate()->factory()->NewFixedArray(count);
375 // Run through the debug info objects and collect all functions.
378 debugged_functions->set(count++, *node->debug_info());
382 return debugged_functions;
386 // Check that the debugger has been fully unloaded.
387 void CheckDebuggerUnloaded(bool check_functions) {
388 // Check that the debugger context is cleared and that there is no debug
389 // information stored for the debugger.
390 CHECK(CcTest::i_isolate()->debug()->debug_context().is_null());
391 CHECK_EQ(NULL, CcTest::i_isolate()->debug()->debug_info_list_);
393 // Collect garbage to ensure weak handles are cleared.
394 CcTest::heap()->CollectAllGarbage(Heap::kNoGCFlags);
395 CcTest::heap()->CollectAllGarbage(Heap::kMakeHeapIterableMask);
397 // Iterate the head and check that there are no debugger related objects left.
398 HeapIterator iterator(CcTest::heap());
399 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
400 CHECK(!obj->IsDebugInfo());
401 CHECK(!obj->IsBreakPointInfo());
403 // If deep check of functions is requested check that no debug break code
404 // is left in all functions.
405 if (check_functions) {
406 if (obj->IsJSFunction()) {
407 JSFunction* fun = JSFunction::cast(obj);
408 for (RelocIterator it(fun->shared()->code()); !it.done(); it.next()) {
409 RelocInfo::Mode rmode = it.rinfo()->rmode();
410 if (RelocInfo::IsCodeTarget(rmode)) {
411 CHECK(!Debug::IsDebugBreak(it.rinfo()->target_address()));
412 } else if (RelocInfo::IsJSReturn(rmode)) {
413 CHECK(!Debug::IsDebugBreakAtReturn(it.rinfo()));
422 } } // namespace v8::internal
425 // Check that the debugger has been fully unloaded.
426 static void CheckDebuggerUnloaded(bool check_functions = false) {
427 // Let debugger to unload itself synchronously
428 v8::Debug::ProcessDebugMessages();
430 v8::internal::CheckDebuggerUnloaded(check_functions);
434 // Inherit from BreakLocationIterator to get access to protected parts for
436 class TestBreakLocationIterator: public v8::internal::BreakLocationIterator {
438 explicit TestBreakLocationIterator(Handle<v8::internal::DebugInfo> debug_info)
439 : BreakLocationIterator(debug_info, v8::internal::SOURCE_BREAK_LOCATIONS) {}
440 v8::internal::RelocIterator* it() { return reloc_iterator_; }
441 v8::internal::RelocIterator* it_original() {
442 return reloc_iterator_original_;
447 // Compile a function, set a break point and check that the call at the break
448 // location in the code is the expected debug_break function.
449 void CheckDebugBreakFunction(DebugLocalContext* env,
450 const char* source, const char* name,
451 int position, v8::internal::RelocInfo::Mode mode,
453 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
455 // Create function and set the break point.
456 Handle<v8::internal::JSFunction> fun = v8::Utils::OpenHandle(
457 *CompileFunction(env, source, name));
458 int bp = SetBreakPoint(fun, position);
460 // Check that the debug break function is as expected.
461 Handle<v8::internal::SharedFunctionInfo> shared(fun->shared());
462 CHECK(Debug::HasDebugInfo(shared));
463 TestBreakLocationIterator it1(Debug::GetDebugInfo(shared));
464 it1.FindBreakLocationFromPosition(position, v8::internal::STATEMENT_ALIGNED);
465 v8::internal::RelocInfo::Mode actual_mode = it1.it()->rinfo()->rmode();
466 if (actual_mode == v8::internal::RelocInfo::CODE_TARGET_WITH_ID) {
467 actual_mode = v8::internal::RelocInfo::CODE_TARGET;
469 CHECK_EQ(mode, actual_mode);
470 if (mode != v8::internal::RelocInfo::JS_RETURN) {
471 CHECK_EQ(debug_break,
472 Code::GetCodeFromTargetAddress(it1.it()->rinfo()->target_address()));
474 CHECK(Debug::IsDebugBreakAtReturn(it1.it()->rinfo()));
477 // Clear the break point and check that the debug break function is no longer
480 CHECK(!debug->HasDebugInfo(shared));
481 CHECK(debug->EnsureDebugInfo(shared, fun));
482 TestBreakLocationIterator it2(Debug::GetDebugInfo(shared));
483 it2.FindBreakLocationFromPosition(position, v8::internal::STATEMENT_ALIGNED);
484 actual_mode = it2.it()->rinfo()->rmode();
485 if (actual_mode == v8::internal::RelocInfo::CODE_TARGET_WITH_ID) {
486 actual_mode = v8::internal::RelocInfo::CODE_TARGET;
488 CHECK_EQ(mode, actual_mode);
489 if (mode == v8::internal::RelocInfo::JS_RETURN) {
490 CHECK(!Debug::IsDebugBreakAtReturn(it2.it()->rinfo()));
495 // --- D e b u g E v e n t H a n d l e r s
497 // --- The different tests uses a number of debug event handlers.
501 // Source for the JavaScript function which picks out the function
503 const char* frame_function_name_source =
504 "function frame_function_name(exec_state, frame_number) {"
505 " return exec_state.frame(frame_number).func().name();"
507 v8::Local<v8::Function> frame_function_name;
510 // Source for the JavaScript function which pick out the name of the
511 // first argument of a frame.
512 const char* frame_argument_name_source =
513 "function frame_argument_name(exec_state, frame_number) {"
514 " return exec_state.frame(frame_number).argumentName(0);"
516 v8::Local<v8::Function> frame_argument_name;
519 // Source for the JavaScript function which pick out the value of the
520 // first argument of a frame.
521 const char* frame_argument_value_source =
522 "function frame_argument_value(exec_state, frame_number) {"
523 " return exec_state.frame(frame_number).argumentValue(0).value_;"
525 v8::Local<v8::Function> frame_argument_value;
528 // Source for the JavaScript function which pick out the name of the
529 // first argument of a frame.
530 const char* frame_local_name_source =
531 "function frame_local_name(exec_state, frame_number) {"
532 " return exec_state.frame(frame_number).localName(0);"
534 v8::Local<v8::Function> frame_local_name;
537 // Source for the JavaScript function which pick out the value of the
538 // first argument of a frame.
539 const char* frame_local_value_source =
540 "function frame_local_value(exec_state, frame_number) {"
541 " return exec_state.frame(frame_number).localValue(0).value_;"
543 v8::Local<v8::Function> frame_local_value;
546 // Source for the JavaScript function which picks out the source line for the
548 const char* frame_source_line_source =
549 "function frame_source_line(exec_state) {"
550 " return exec_state.frame(0).sourceLine();"
552 v8::Local<v8::Function> frame_source_line;
555 // Source for the JavaScript function which picks out the source column for the
557 const char* frame_source_column_source =
558 "function frame_source_column(exec_state) {"
559 " return exec_state.frame(0).sourceColumn();"
561 v8::Local<v8::Function> frame_source_column;
564 // Source for the JavaScript function which picks out the script name for the
566 const char* frame_script_name_source =
567 "function frame_script_name(exec_state) {"
568 " return exec_state.frame(0).func().script().name();"
570 v8::Local<v8::Function> frame_script_name;
573 // Source for the JavaScript function which returns the number of frames.
574 static const char* frame_count_source =
575 "function frame_count(exec_state) {"
576 " return exec_state.frameCount();"
578 v8::Handle<v8::Function> frame_count;
581 // Global variable to store the last function hit - used by some tests.
582 char last_function_hit[80];
584 // Global variable to store the name for last script hit - used by some tests.
585 char last_script_name_hit[80];
587 // Global variables to store the last source position - used by some tests.
588 int last_source_line = -1;
589 int last_source_column = -1;
591 // Debug event handler which counts the break points which have been hit.
592 int break_point_hit_count = 0;
593 int break_point_hit_count_deoptimize = 0;
594 static void DebugEventBreakPointHitCount(
595 const v8::Debug::EventDetails& event_details) {
596 v8::DebugEvent event = event_details.GetEvent();
597 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
598 v8::internal::Isolate* isolate = CcTest::i_isolate();
599 Debug* debug = isolate->debug();
600 // When hitting a debug event listener there must be a break set.
601 CHECK_NE(debug->break_id(), 0);
603 // Count the number of breaks.
604 if (event == v8::Break) {
605 break_point_hit_count++;
606 if (!frame_function_name.IsEmpty()) {
607 // Get the name of the function.
609 v8::Handle<v8::Value> argv[argc] = {
610 exec_state, v8::Integer::New(CcTest::isolate(), 0)
612 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
614 if (result->IsUndefined()) {
615 last_function_hit[0] = '\0';
617 CHECK(result->IsString());
618 v8::Handle<v8::String> function_name(result->ToString());
619 function_name->WriteUtf8(last_function_hit);
623 if (!frame_source_line.IsEmpty()) {
624 // Get the source line.
626 v8::Handle<v8::Value> argv[argc] = { exec_state };
627 v8::Handle<v8::Value> result = frame_source_line->Call(exec_state,
629 CHECK(result->IsNumber());
630 last_source_line = result->Int32Value();
633 if (!frame_source_column.IsEmpty()) {
634 // Get the source column.
636 v8::Handle<v8::Value> argv[argc] = { exec_state };
637 v8::Handle<v8::Value> result = frame_source_column->Call(exec_state,
639 CHECK(result->IsNumber());
640 last_source_column = result->Int32Value();
643 if (!frame_script_name.IsEmpty()) {
644 // Get the script name of the function script.
646 v8::Handle<v8::Value> argv[argc] = { exec_state };
647 v8::Handle<v8::Value> result = frame_script_name->Call(exec_state,
649 if (result->IsUndefined()) {
650 last_script_name_hit[0] = '\0';
652 CHECK(result->IsString());
653 v8::Handle<v8::String> script_name(result->ToString());
654 script_name->WriteUtf8(last_script_name_hit);
658 // Perform a full deoptimization when the specified number of
659 // breaks have been hit.
660 if (break_point_hit_count == break_point_hit_count_deoptimize) {
661 i::Deoptimizer::DeoptimizeAll(isolate);
667 // Debug event handler which counts a number of events and collects the stack
668 // height if there is a function compiled for that.
669 int exception_hit_count = 0;
670 int uncaught_exception_hit_count = 0;
671 int last_js_stack_height = -1;
673 static void DebugEventCounterClear() {
674 break_point_hit_count = 0;
675 exception_hit_count = 0;
676 uncaught_exception_hit_count = 0;
679 static void DebugEventCounter(
680 const v8::Debug::EventDetails& event_details) {
681 v8::DebugEvent event = event_details.GetEvent();
682 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
683 v8::Handle<v8::Object> event_data = event_details.GetEventData();
684 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
686 // When hitting a debug event listener there must be a break set.
687 CHECK_NE(debug->break_id(), 0);
689 // Count the number of breaks.
690 if (event == v8::Break) {
691 break_point_hit_count++;
692 } else if (event == v8::Exception) {
693 exception_hit_count++;
695 // Check whether the exception was uncaught.
696 v8::Local<v8::String> fun_name =
697 v8::String::NewFromUtf8(CcTest::isolate(), "uncaught");
698 v8::Local<v8::Function> fun =
699 v8::Local<v8::Function>::Cast(event_data->Get(fun_name));
700 v8::Local<v8::Value> result = fun->Call(event_data, 0, NULL);
701 if (result->IsTrue()) {
702 uncaught_exception_hit_count++;
706 // Collect the JavsScript stack height if the function frame_count is
708 if (!frame_count.IsEmpty()) {
709 static const int kArgc = 1;
710 v8::Handle<v8::Value> argv[kArgc] = { exec_state };
711 // Using exec_state as receiver is just to have a receiver.
712 v8::Handle<v8::Value> result = frame_count->Call(exec_state, kArgc, argv);
713 last_js_stack_height = result->Int32Value();
718 // Debug event handler which evaluates a number of expressions when a break
719 // point is hit. Each evaluated expression is compared with an expected value.
720 // For this debug event handler to work the following two global varaibles
721 // must be initialized.
722 // checks: An array of expressions and expected results
723 // evaluate_check_function: A JavaScript function (see below)
725 // Structure for holding checks to do.
726 struct EvaluateCheck {
727 const char* expr; // An expression to evaluate when a break point is hit.
728 v8::Handle<v8::Value> expected; // The expected result.
732 // Array of checks to do.
733 struct EvaluateCheck* checks = NULL;
734 // Source for The JavaScript function which can do the evaluation when a break
736 const char* evaluate_check_source =
737 "function evaluate_check(exec_state, expr, expected) {"
738 " return exec_state.frame(0).evaluate(expr).value() === expected;"
740 v8::Local<v8::Function> evaluate_check_function;
742 // The actual debug event described by the longer comment above.
743 static void DebugEventEvaluate(
744 const v8::Debug::EventDetails& event_details) {
745 v8::DebugEvent event = event_details.GetEvent();
746 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
747 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
748 // When hitting a debug event listener there must be a break set.
749 CHECK_NE(debug->break_id(), 0);
751 if (event == v8::Break) {
752 for (int i = 0; checks[i].expr != NULL; i++) {
754 v8::Handle<v8::Value> argv[argc] = {
756 v8::String::NewFromUtf8(CcTest::isolate(), checks[i].expr),
758 v8::Handle<v8::Value> result =
759 evaluate_check_function->Call(exec_state, argc, argv);
760 if (!result->IsTrue()) {
761 v8::String::Utf8Value utf8(checks[i].expected->ToString());
762 V8_Fatal(__FILE__, __LINE__, "%s != %s", checks[i].expr, *utf8);
769 // This debug event listener removes a breakpoint in a function
770 int debug_event_remove_break_point = 0;
771 static void DebugEventRemoveBreakPoint(
772 const v8::Debug::EventDetails& event_details) {
773 v8::DebugEvent event = event_details.GetEvent();
774 v8::Handle<v8::Value> data = event_details.GetCallbackData();
775 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
776 // When hitting a debug event listener there must be a break set.
777 CHECK_NE(debug->break_id(), 0);
779 if (event == v8::Break) {
780 break_point_hit_count++;
781 CHECK(data->IsFunction());
782 ClearBreakPoint(debug_event_remove_break_point);
787 // Debug event handler which counts break points hit and performs a step
789 StepAction step_action = StepIn; // Step action to perform when stepping.
790 static void DebugEventStep(
791 const v8::Debug::EventDetails& event_details) {
792 v8::DebugEvent event = event_details.GetEvent();
793 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
794 // When hitting a debug event listener there must be a break set.
795 CHECK_NE(debug->break_id(), 0);
797 if (event == v8::Break) {
798 break_point_hit_count++;
799 PrepareStep(step_action);
804 // Debug event handler which counts break points hit and performs a step
805 // afterwards. For each call the expected function is checked.
806 // For this debug event handler to work the following two global varaibles
807 // must be initialized.
808 // expected_step_sequence: An array of the expected function call sequence.
809 // frame_function_name: A JavaScript function (see below).
811 // String containing the expected function call sequence. Note: this only works
812 // if functions have name length of one.
813 const char* expected_step_sequence = NULL;
815 // The actual debug event described by the longer comment above.
816 static void DebugEventStepSequence(
817 const v8::Debug::EventDetails& event_details) {
818 v8::DebugEvent event = event_details.GetEvent();
819 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
820 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
821 // When hitting a debug event listener there must be a break set.
822 CHECK_NE(debug->break_id(), 0);
824 if (event == v8::Break || event == v8::Exception) {
825 // Check that the current function is the expected.
826 CHECK(break_point_hit_count <
827 StrLength(expected_step_sequence));
829 v8::Handle<v8::Value> argv[argc] = {
830 exec_state, v8::Integer::New(CcTest::isolate(), 0)
832 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
834 CHECK(result->IsString());
835 v8::String::Utf8Value function_name(result->ToString());
836 CHECK_EQ(1, StrLength(*function_name));
837 CHECK_EQ((*function_name)[0],
838 expected_step_sequence[break_point_hit_count]);
841 break_point_hit_count++;
842 PrepareStep(step_action);
847 // Debug event handler which performs a garbage collection.
848 static void DebugEventBreakPointCollectGarbage(
849 const v8::Debug::EventDetails& event_details) {
850 v8::DebugEvent event = event_details.GetEvent();
851 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
852 // When hitting a debug event listener there must be a break set.
853 CHECK_NE(debug->break_id(), 0);
855 // Perform a garbage collection when break point is hit and continue. Based
856 // on the number of break points hit either scavenge or mark compact
857 // collector is used.
858 if (event == v8::Break) {
859 break_point_hit_count++;
860 if (break_point_hit_count % 2 == 0) {
862 CcTest::heap()->CollectGarbage(v8::internal::NEW_SPACE);
864 // Mark sweep compact.
865 CcTest::heap()->CollectAllGarbage(Heap::kNoGCFlags);
871 // Debug event handler which re-issues a debug break and calls the garbage
872 // collector to have the heap verified.
873 static void DebugEventBreak(
874 const v8::Debug::EventDetails& event_details) {
875 v8::DebugEvent event = event_details.GetEvent();
876 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
877 // When hitting a debug event listener there must be a break set.
878 CHECK_NE(debug->break_id(), 0);
880 if (event == v8::Break) {
881 // Count the number of breaks.
882 break_point_hit_count++;
884 // Run the garbage collector to enforce heap verification if option
885 // --verify-heap is set.
886 CcTest::heap()->CollectGarbage(v8::internal::NEW_SPACE);
888 // Set the break flag again to come back here as soon as possible.
889 v8::Debug::DebugBreak(CcTest::isolate());
894 // Debug event handler which re-issues a debug break until a limit has been
896 int max_break_point_hit_count = 0;
897 bool terminate_after_max_break_point_hit = false;
898 static void DebugEventBreakMax(
899 const v8::Debug::EventDetails& event_details) {
900 v8::DebugEvent event = event_details.GetEvent();
901 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
902 v8::Isolate* v8_isolate = CcTest::isolate();
903 v8::internal::Isolate* isolate = CcTest::i_isolate();
904 v8::internal::Debug* debug = isolate->debug();
905 // When hitting a debug event listener there must be a break set.
906 CHECK_NE(debug->break_id(), 0);
908 if (event == v8::Break) {
909 if (break_point_hit_count < max_break_point_hit_count) {
910 // Count the number of breaks.
911 break_point_hit_count++;
913 // Collect the JavsScript stack height if the function frame_count is
915 if (!frame_count.IsEmpty()) {
916 static const int kArgc = 1;
917 v8::Handle<v8::Value> argv[kArgc] = { exec_state };
918 // Using exec_state as receiver is just to have a receiver.
919 v8::Handle<v8::Value> result =
920 frame_count->Call(exec_state, kArgc, argv);
921 last_js_stack_height = result->Int32Value();
924 // Set the break flag again to come back here as soon as possible.
925 v8::Debug::DebugBreak(v8_isolate);
927 } else if (terminate_after_max_break_point_hit) {
928 // Terminate execution after the last break if requested.
929 v8::V8::TerminateExecution(v8_isolate);
932 // Perform a full deoptimization when the specified number of
933 // breaks have been hit.
934 if (break_point_hit_count == break_point_hit_count_deoptimize) {
935 i::Deoptimizer::DeoptimizeAll(isolate);
941 // --- M e s s a g e C a l l b a c k
944 // Message callback which counts the number of messages.
945 int message_callback_count = 0;
947 static void MessageCallbackCountClear() {
948 message_callback_count = 0;
951 static void MessageCallbackCount(v8::Handle<v8::Message> message,
952 v8::Handle<v8::Value> data) {
953 message_callback_count++;
957 // --- T h e A c t u a l T e s t s
960 // Test that the debug break function is the expected one for different kinds
961 // of break locations.
963 using ::v8::internal::Builtins;
964 using ::v8::internal::Isolate;
965 DebugLocalContext env;
966 v8::HandleScope scope(env->GetIsolate());
968 CheckDebugBreakFunction(&env,
969 "function f1(){}", "f1",
971 v8::internal::RelocInfo::JS_RETURN,
973 CheckDebugBreakFunction(&env,
974 "function f2(){x=1;}", "f2",
976 v8::internal::RelocInfo::CODE_TARGET,
977 CcTest::i_isolate()->builtins()->builtin(
978 Builtins::kStoreIC_DebugBreak));
979 CheckDebugBreakFunction(&env,
980 "function f3(){var a=x;}", "f3",
982 v8::internal::RelocInfo::CODE_TARGET,
983 CcTest::i_isolate()->builtins()->builtin(
984 Builtins::kLoadIC_DebugBreak));
986 // TODO(1240753): Make the test architecture independent or split
987 // parts of the debugger into architecture dependent files. This
988 // part currently disabled as it is not portable between IA32/ARM.
989 // Currently on ICs for keyed store/load on ARM.
990 #if !defined (__arm__) && !defined(__thumb__)
991 CheckDebugBreakFunction(
993 "function f4(){var index='propertyName'; var a={}; a[index] = 'x';}",
996 v8::internal::RelocInfo::CODE_TARGET,
997 CcTest::i_isolate()->builtins()->builtin(
998 Builtins::kKeyedStoreIC_DebugBreak));
999 CheckDebugBreakFunction(
1001 "function f5(){var index='propertyName'; var a={}; return a[index];}",
1004 v8::internal::RelocInfo::CODE_TARGET,
1005 CcTest::i_isolate()->builtins()->builtin(
1006 Builtins::kKeyedLoadIC_DebugBreak));
1009 CheckDebugBreakFunction(
1011 "function f6(a){return a==null;}",
1014 v8::internal::RelocInfo::CODE_TARGET,
1015 CcTest::i_isolate()->builtins()->builtin(
1016 Builtins::kCompareNilIC_DebugBreak));
1018 // Check the debug break code stubs for call ICs with different number of
1020 // TODO(verwaest): XXX update test.
1021 // Handle<Code> debug_break_0 = v8::internal::ComputeCallDebugBreak(0);
1022 // Handle<Code> debug_break_1 = v8::internal::ComputeCallDebugBreak(1);
1023 // Handle<Code> debug_break_4 = v8::internal::ComputeCallDebugBreak(4);
1025 // CheckDebugBreakFunction(&env,
1026 // "function f4_0(){x();}", "f4_0",
1028 // v8::internal::RelocInfo::CODE_TARGET,
1031 // CheckDebugBreakFunction(&env,
1032 // "function f4_1(){x(1);}", "f4_1",
1034 // v8::internal::RelocInfo::CODE_TARGET,
1037 // CheckDebugBreakFunction(&env,
1038 // "function f4_4(){x(1,2,3,4);}", "f4_4",
1040 // v8::internal::RelocInfo::CODE_TARGET,
1045 // Test that the debug info in the VM is in sync with the functions being
1048 DebugLocalContext env;
1049 v8::HandleScope scope(env->GetIsolate());
1050 // Create a couple of functions for the test.
1051 v8::Local<v8::Function> foo =
1052 CompileFunction(&env, "function foo(){}", "foo");
1053 v8::Local<v8::Function> bar =
1054 CompileFunction(&env, "function bar(){}", "bar");
1055 // Initially no functions are debugged.
1056 CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length());
1057 CHECK(!HasDebugInfo(foo));
1058 CHECK(!HasDebugInfo(bar));
1059 // One function (foo) is debugged.
1060 int bp1 = SetBreakPoint(foo, 0);
1061 CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length());
1062 CHECK(HasDebugInfo(foo));
1063 CHECK(!HasDebugInfo(bar));
1064 // Two functions are debugged.
1065 int bp2 = SetBreakPoint(bar, 0);
1066 CHECK_EQ(2, v8::internal::GetDebuggedFunctions()->length());
1067 CHECK(HasDebugInfo(foo));
1068 CHECK(HasDebugInfo(bar));
1069 // One function (bar) is debugged.
1070 ClearBreakPoint(bp1);
1071 CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length());
1072 CHECK(!HasDebugInfo(foo));
1073 CHECK(HasDebugInfo(bar));
1074 // No functions are debugged.
1075 ClearBreakPoint(bp2);
1076 CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length());
1077 CHECK(!HasDebugInfo(foo));
1078 CHECK(!HasDebugInfo(bar));
1082 // Test that a break point can be set at an IC store location.
1083 TEST(BreakPointICStore) {
1084 break_point_hit_count = 0;
1085 DebugLocalContext env;
1086 v8::HandleScope scope(env->GetIsolate());
1088 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1089 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
1090 "function foo(){bar=0;}"))->Run();
1091 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1092 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
1094 // Run without breakpoints.
1095 foo->Call(env->Global(), 0, NULL);
1096 CHECK_EQ(0, break_point_hit_count);
1098 // Run with breakpoint
1099 int bp = SetBreakPoint(foo, 0);
1100 foo->Call(env->Global(), 0, NULL);
1101 CHECK_EQ(1, break_point_hit_count);
1102 foo->Call(env->Global(), 0, NULL);
1103 CHECK_EQ(2, break_point_hit_count);
1105 // Run without breakpoints.
1106 ClearBreakPoint(bp);
1107 foo->Call(env->Global(), 0, NULL);
1108 CHECK_EQ(2, break_point_hit_count);
1110 v8::Debug::SetDebugEventListener(NULL);
1111 CheckDebuggerUnloaded();
1115 // Test that a break point can be set at an IC load location.
1116 TEST(BreakPointICLoad) {
1117 break_point_hit_count = 0;
1118 DebugLocalContext env;
1119 v8::HandleScope scope(env->GetIsolate());
1120 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1121 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "bar=1"))
1123 v8::Script::Compile(
1124 v8::String::NewFromUtf8(env->GetIsolate(), "function foo(){var x=bar;}"))
1126 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1127 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
1129 // Run without breakpoints.
1130 foo->Call(env->Global(), 0, NULL);
1131 CHECK_EQ(0, break_point_hit_count);
1133 // Run with breakpoint.
1134 int bp = SetBreakPoint(foo, 0);
1135 foo->Call(env->Global(), 0, NULL);
1136 CHECK_EQ(1, break_point_hit_count);
1137 foo->Call(env->Global(), 0, NULL);
1138 CHECK_EQ(2, break_point_hit_count);
1140 // Run without breakpoints.
1141 ClearBreakPoint(bp);
1142 foo->Call(env->Global(), 0, NULL);
1143 CHECK_EQ(2, break_point_hit_count);
1145 v8::Debug::SetDebugEventListener(NULL);
1146 CheckDebuggerUnloaded();
1150 // Test that a break point can be set at an IC call location.
1151 TEST(BreakPointICCall) {
1152 break_point_hit_count = 0;
1153 DebugLocalContext env;
1154 v8::HandleScope scope(env->GetIsolate());
1155 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1156 v8::Script::Compile(
1157 v8::String::NewFromUtf8(env->GetIsolate(), "function bar(){}"))->Run();
1158 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
1159 "function foo(){bar();}"))->Run();
1160 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1161 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
1163 // Run without breakpoints.
1164 foo->Call(env->Global(), 0, NULL);
1165 CHECK_EQ(0, break_point_hit_count);
1167 // Run with breakpoint
1168 int bp = SetBreakPoint(foo, 0);
1169 foo->Call(env->Global(), 0, NULL);
1170 CHECK_EQ(1, break_point_hit_count);
1171 foo->Call(env->Global(), 0, NULL);
1172 CHECK_EQ(2, break_point_hit_count);
1174 // Run without breakpoints.
1175 ClearBreakPoint(bp);
1176 foo->Call(env->Global(), 0, NULL);
1177 CHECK_EQ(2, break_point_hit_count);
1179 v8::Debug::SetDebugEventListener(NULL);
1180 CheckDebuggerUnloaded();
1184 // Test that a break point can be set at an IC call location and survive a GC.
1185 TEST(BreakPointICCallWithGC) {
1186 break_point_hit_count = 0;
1187 DebugLocalContext env;
1188 v8::HandleScope scope(env->GetIsolate());
1189 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage);
1190 v8::Script::Compile(
1191 v8::String::NewFromUtf8(env->GetIsolate(), "function bar(){return 1;}"))
1193 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
1194 "function foo(){return bar();}"))
1196 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1197 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
1199 // Run without breakpoints.
1200 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1201 CHECK_EQ(0, break_point_hit_count);
1203 // Run with breakpoint.
1204 int bp = SetBreakPoint(foo, 0);
1205 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1206 CHECK_EQ(1, break_point_hit_count);
1207 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1208 CHECK_EQ(2, break_point_hit_count);
1210 // Run without breakpoints.
1211 ClearBreakPoint(bp);
1212 foo->Call(env->Global(), 0, NULL);
1213 CHECK_EQ(2, break_point_hit_count);
1215 v8::Debug::SetDebugEventListener(NULL);
1216 CheckDebuggerUnloaded();
1220 // Test that a break point can be set at an IC call location and survive a GC.
1221 TEST(BreakPointConstructCallWithGC) {
1222 break_point_hit_count = 0;
1223 DebugLocalContext env;
1224 v8::HandleScope scope(env->GetIsolate());
1225 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage);
1226 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
1227 "function bar(){ this.x = 1;}"))
1229 v8::Script::Compile(
1230 v8::String::NewFromUtf8(env->GetIsolate(),
1231 "function foo(){return new bar(1).x;}"))->Run();
1232 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1233 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
1235 // Run without breakpoints.
1236 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1237 CHECK_EQ(0, break_point_hit_count);
1239 // Run with breakpoint.
1240 int bp = SetBreakPoint(foo, 0);
1241 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1242 CHECK_EQ(1, break_point_hit_count);
1243 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1244 CHECK_EQ(2, break_point_hit_count);
1246 // Run without breakpoints.
1247 ClearBreakPoint(bp);
1248 foo->Call(env->Global(), 0, NULL);
1249 CHECK_EQ(2, break_point_hit_count);
1251 v8::Debug::SetDebugEventListener(NULL);
1252 CheckDebuggerUnloaded();
1256 // Test that a break point can be set at a return store location.
1257 TEST(BreakPointReturn) {
1258 break_point_hit_count = 0;
1259 DebugLocalContext env;
1260 v8::HandleScope scope(env->GetIsolate());
1262 // Create a functions for checking the source line and column when hitting
1264 frame_source_line = CompileFunction(&env,
1265 frame_source_line_source,
1266 "frame_source_line");
1267 frame_source_column = CompileFunction(&env,
1268 frame_source_column_source,
1269 "frame_source_column");
1272 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1273 v8::Script::Compile(
1274 v8::String::NewFromUtf8(env->GetIsolate(), "function foo(){}"))->Run();
1275 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
1276 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
1278 // Run without breakpoints.
1279 foo->Call(env->Global(), 0, NULL);
1280 CHECK_EQ(0, break_point_hit_count);
1282 // Run with breakpoint
1283 int bp = SetBreakPoint(foo, 0);
1284 foo->Call(env->Global(), 0, NULL);
1285 CHECK_EQ(1, break_point_hit_count);
1286 CHECK_EQ(0, last_source_line);
1287 CHECK_EQ(15, last_source_column);
1288 foo->Call(env->Global(), 0, NULL);
1289 CHECK_EQ(2, break_point_hit_count);
1290 CHECK_EQ(0, last_source_line);
1291 CHECK_EQ(15, last_source_column);
1293 // Run without breakpoints.
1294 ClearBreakPoint(bp);
1295 foo->Call(env->Global(), 0, NULL);
1296 CHECK_EQ(2, break_point_hit_count);
1298 v8::Debug::SetDebugEventListener(NULL);
1299 CheckDebuggerUnloaded();
1303 static void CallWithBreakPoints(v8::Local<v8::Object> recv,
1304 v8::Local<v8::Function> f,
1305 int break_point_count,
1307 break_point_hit_count = 0;
1308 for (int i = 0; i < call_count; i++) {
1309 f->Call(recv, 0, NULL);
1310 CHECK_EQ((i + 1) * break_point_count, break_point_hit_count);
1315 // Test GC during break point processing.
1316 TEST(GCDuringBreakPointProcessing) {
1317 break_point_hit_count = 0;
1318 DebugLocalContext env;
1319 v8::HandleScope scope(env->GetIsolate());
1321 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage);
1322 v8::Local<v8::Function> foo;
1324 // Test IC store break point with garbage collection.
1325 foo = CompileFunction(&env, "function foo(){bar=0;}", "foo");
1326 SetBreakPoint(foo, 0);
1327 CallWithBreakPoints(env->Global(), foo, 1, 10);
1329 // Test IC load break point with garbage collection.
1330 foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo");
1331 SetBreakPoint(foo, 0);
1332 CallWithBreakPoints(env->Global(), foo, 1, 10);
1334 // Test IC call break point with garbage collection.
1335 foo = CompileFunction(&env, "function bar(){};function foo(){bar();}", "foo");
1336 SetBreakPoint(foo, 0);
1337 CallWithBreakPoints(env->Global(), foo, 1, 10);
1339 // Test return break point with garbage collection.
1340 foo = CompileFunction(&env, "function foo(){}", "foo");
1341 SetBreakPoint(foo, 0);
1342 CallWithBreakPoints(env->Global(), foo, 1, 25);
1344 // Test debug break slot break point with garbage collection.
1345 foo = CompileFunction(&env, "function foo(){var a;}", "foo");
1346 SetBreakPoint(foo, 0);
1347 CallWithBreakPoints(env->Global(), foo, 1, 25);
1349 v8::Debug::SetDebugEventListener(NULL);
1350 CheckDebuggerUnloaded();
1354 // Call the function three times with different garbage collections in between
1355 // and make sure that the break point survives.
1356 static void CallAndGC(v8::Local<v8::Object> recv,
1357 v8::Local<v8::Function> f) {
1358 break_point_hit_count = 0;
1360 for (int i = 0; i < 3; i++) {
1362 f->Call(recv, 0, NULL);
1363 CHECK_EQ(1 + i * 3, break_point_hit_count);
1365 // Scavenge and call function.
1366 CcTest::heap()->CollectGarbage(v8::internal::NEW_SPACE);
1367 f->Call(recv, 0, NULL);
1368 CHECK_EQ(2 + i * 3, break_point_hit_count);
1370 // Mark sweep (and perhaps compact) and call function.
1371 CcTest::heap()->CollectAllGarbage(Heap::kNoGCFlags);
1372 f->Call(recv, 0, NULL);
1373 CHECK_EQ(3 + i * 3, break_point_hit_count);
1378 // Test that a break point can be set at a return store location.
1379 TEST(BreakPointSurviveGC) {
1380 break_point_hit_count = 0;
1381 DebugLocalContext env;
1382 v8::HandleScope scope(env->GetIsolate());
1384 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1385 v8::Local<v8::Function> foo;
1387 // Test IC store break point with garbage collection.
1389 CompileFunction(&env, "function foo(){}", "foo");
1390 foo = CompileFunction(&env, "function foo(){bar=0;}", "foo");
1391 SetBreakPoint(foo, 0);
1393 CallAndGC(env->Global(), foo);
1395 // Test IC load break point with garbage collection.
1397 CompileFunction(&env, "function foo(){}", "foo");
1398 foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo");
1399 SetBreakPoint(foo, 0);
1401 CallAndGC(env->Global(), foo);
1403 // Test IC call break point with garbage collection.
1405 CompileFunction(&env, "function foo(){}", "foo");
1406 foo = CompileFunction(&env,
1407 "function bar(){};function foo(){bar();}",
1409 SetBreakPoint(foo, 0);
1411 CallAndGC(env->Global(), foo);
1413 // Test return break point with garbage collection.
1415 CompileFunction(&env, "function foo(){}", "foo");
1416 foo = CompileFunction(&env, "function foo(){}", "foo");
1417 SetBreakPoint(foo, 0);
1419 CallAndGC(env->Global(), foo);
1421 // Test non IC break point with garbage collection.
1423 CompileFunction(&env, "function foo(){}", "foo");
1424 foo = CompileFunction(&env, "function foo(){var bar=0;}", "foo");
1425 SetBreakPoint(foo, 0);
1427 CallAndGC(env->Global(), foo);
1430 v8::Debug::SetDebugEventListener(NULL);
1431 CheckDebuggerUnloaded();
1435 // Test that break points can be set using the global Debug object.
1436 TEST(BreakPointThroughJavaScript) {
1437 break_point_hit_count = 0;
1438 DebugLocalContext env;
1439 v8::HandleScope scope(env->GetIsolate());
1442 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1443 v8::Script::Compile(
1444 v8::String::NewFromUtf8(env->GetIsolate(), "function bar(){}"))->Run();
1445 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
1446 "function foo(){bar();bar();}"))
1448 // 012345678901234567890
1450 // Break points are set at position 3 and 9
1451 v8::Local<v8::Script> foo =
1452 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "foo()"));
1454 // Run without breakpoints.
1456 CHECK_EQ(0, break_point_hit_count);
1458 // Run with one breakpoint
1459 int bp1 = SetBreakPointFromJS(env->GetIsolate(), "foo", 0, 3);
1461 CHECK_EQ(1, break_point_hit_count);
1463 CHECK_EQ(2, break_point_hit_count);
1465 // Run with two breakpoints
1466 int bp2 = SetBreakPointFromJS(env->GetIsolate(), "foo", 0, 9);
1468 CHECK_EQ(4, break_point_hit_count);
1470 CHECK_EQ(6, break_point_hit_count);
1472 // Run with one breakpoint
1473 ClearBreakPointFromJS(env->GetIsolate(), bp2);
1475 CHECK_EQ(7, break_point_hit_count);
1477 CHECK_EQ(8, break_point_hit_count);
1479 // Run without breakpoints.
1480 ClearBreakPointFromJS(env->GetIsolate(), bp1);
1482 CHECK_EQ(8, break_point_hit_count);
1484 v8::Debug::SetDebugEventListener(NULL);
1485 CheckDebuggerUnloaded();
1487 // Make sure that the break point numbers are consecutive.
1493 // Test that break points on scripts identified by name can be set using the
1494 // global Debug object.
1495 TEST(ScriptBreakPointByNameThroughJavaScript) {
1496 break_point_hit_count = 0;
1497 DebugLocalContext env;
1498 v8::HandleScope scope(env->GetIsolate());
1501 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1503 v8::Local<v8::String> script = v8::String::NewFromUtf8(
1507 " a = 0; // line 2\n"
1509 " b = 1; // line 4\n"
1517 " b = 2; // line 12\n"
1519 " b = 3; // line 14\n"
1520 " f(); // line 15\n"
1523 // Compile the script and get the two functions.
1524 v8::ScriptOrigin origin =
1525 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "test"));
1526 v8::Script::Compile(script, &origin)->Run();
1527 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
1528 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1529 v8::Local<v8::Function> g = v8::Local<v8::Function>::Cast(
1530 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "g")));
1532 // Call f and g without break points.
1533 break_point_hit_count = 0;
1534 f->Call(env->Global(), 0, NULL);
1535 CHECK_EQ(0, break_point_hit_count);
1536 g->Call(env->Global(), 0, NULL);
1537 CHECK_EQ(0, break_point_hit_count);
1539 // Call f and g with break point on line 12.
1540 int sbp1 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 12, 0);
1541 break_point_hit_count = 0;
1542 f->Call(env->Global(), 0, NULL);
1543 CHECK_EQ(0, break_point_hit_count);
1544 g->Call(env->Global(), 0, NULL);
1545 CHECK_EQ(1, break_point_hit_count);
1547 // Remove the break point again.
1548 break_point_hit_count = 0;
1549 ClearBreakPointFromJS(env->GetIsolate(), sbp1);
1550 f->Call(env->Global(), 0, NULL);
1551 CHECK_EQ(0, break_point_hit_count);
1552 g->Call(env->Global(), 0, NULL);
1553 CHECK_EQ(0, break_point_hit_count);
1555 // Call f and g with break point on line 2.
1556 int sbp2 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 2, 0);
1557 break_point_hit_count = 0;
1558 f->Call(env->Global(), 0, NULL);
1559 CHECK_EQ(1, break_point_hit_count);
1560 g->Call(env->Global(), 0, NULL);
1561 CHECK_EQ(2, break_point_hit_count);
1563 // Call f and g with break point on line 2, 4, 12, 14 and 15.
1564 int sbp3 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 4, 0);
1565 int sbp4 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 12, 0);
1566 int sbp5 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 14, 0);
1567 int sbp6 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 15, 0);
1568 break_point_hit_count = 0;
1569 f->Call(env->Global(), 0, NULL);
1570 CHECK_EQ(2, break_point_hit_count);
1571 g->Call(env->Global(), 0, NULL);
1572 CHECK_EQ(7, break_point_hit_count);
1574 // Remove all the break points again.
1575 break_point_hit_count = 0;
1576 ClearBreakPointFromJS(env->GetIsolate(), sbp2);
1577 ClearBreakPointFromJS(env->GetIsolate(), sbp3);
1578 ClearBreakPointFromJS(env->GetIsolate(), sbp4);
1579 ClearBreakPointFromJS(env->GetIsolate(), sbp5);
1580 ClearBreakPointFromJS(env->GetIsolate(), sbp6);
1581 f->Call(env->Global(), 0, NULL);
1582 CHECK_EQ(0, break_point_hit_count);
1583 g->Call(env->Global(), 0, NULL);
1584 CHECK_EQ(0, break_point_hit_count);
1586 v8::Debug::SetDebugEventListener(NULL);
1587 CheckDebuggerUnloaded();
1589 // Make sure that the break point numbers are consecutive.
1599 TEST(ScriptBreakPointByIdThroughJavaScript) {
1600 break_point_hit_count = 0;
1601 DebugLocalContext env;
1602 v8::HandleScope scope(env->GetIsolate());
1605 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1607 v8::Local<v8::String> source = v8::String::NewFromUtf8(
1611 " a = 0; // line 2\n"
1613 " b = 1; // line 4\n"
1621 " b = 2; // line 12\n"
1623 " b = 3; // line 14\n"
1624 " f(); // line 15\n"
1627 // Compile the script and get the two functions.
1628 v8::ScriptOrigin origin =
1629 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "test"));
1630 v8::Local<v8::Script> script = v8::Script::Compile(source, &origin);
1632 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
1633 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1634 v8::Local<v8::Function> g = v8::Local<v8::Function>::Cast(
1635 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "g")));
1637 // Get the script id knowing that internally it is a 32 integer.
1638 int script_id = script->GetUnboundScript()->GetId();
1640 // Call f and g without break points.
1641 break_point_hit_count = 0;
1642 f->Call(env->Global(), 0, NULL);
1643 CHECK_EQ(0, break_point_hit_count);
1644 g->Call(env->Global(), 0, NULL);
1645 CHECK_EQ(0, break_point_hit_count);
1647 // Call f and g with break point on line 12.
1648 int sbp1 = SetScriptBreakPointByIdFromJS(env->GetIsolate(), script_id, 12, 0);
1649 break_point_hit_count = 0;
1650 f->Call(env->Global(), 0, NULL);
1651 CHECK_EQ(0, break_point_hit_count);
1652 g->Call(env->Global(), 0, NULL);
1653 CHECK_EQ(1, break_point_hit_count);
1655 // Remove the break point again.
1656 break_point_hit_count = 0;
1657 ClearBreakPointFromJS(env->GetIsolate(), sbp1);
1658 f->Call(env->Global(), 0, NULL);
1659 CHECK_EQ(0, break_point_hit_count);
1660 g->Call(env->Global(), 0, NULL);
1661 CHECK_EQ(0, break_point_hit_count);
1663 // Call f and g with break point on line 2.
1664 int sbp2 = SetScriptBreakPointByIdFromJS(env->GetIsolate(), script_id, 2, 0);
1665 break_point_hit_count = 0;
1666 f->Call(env->Global(), 0, NULL);
1667 CHECK_EQ(1, break_point_hit_count);
1668 g->Call(env->Global(), 0, NULL);
1669 CHECK_EQ(2, break_point_hit_count);
1671 // Call f and g with break point on line 2, 4, 12, 14 and 15.
1672 int sbp3 = SetScriptBreakPointByIdFromJS(env->GetIsolate(), script_id, 4, 0);
1673 int sbp4 = SetScriptBreakPointByIdFromJS(env->GetIsolate(), script_id, 12, 0);
1674 int sbp5 = SetScriptBreakPointByIdFromJS(env->GetIsolate(), script_id, 14, 0);
1675 int sbp6 = SetScriptBreakPointByIdFromJS(env->GetIsolate(), script_id, 15, 0);
1676 break_point_hit_count = 0;
1677 f->Call(env->Global(), 0, NULL);
1678 CHECK_EQ(2, break_point_hit_count);
1679 g->Call(env->Global(), 0, NULL);
1680 CHECK_EQ(7, break_point_hit_count);
1682 // Remove all the break points again.
1683 break_point_hit_count = 0;
1684 ClearBreakPointFromJS(env->GetIsolate(), sbp2);
1685 ClearBreakPointFromJS(env->GetIsolate(), sbp3);
1686 ClearBreakPointFromJS(env->GetIsolate(), sbp4);
1687 ClearBreakPointFromJS(env->GetIsolate(), sbp5);
1688 ClearBreakPointFromJS(env->GetIsolate(), sbp6);
1689 f->Call(env->Global(), 0, NULL);
1690 CHECK_EQ(0, break_point_hit_count);
1691 g->Call(env->Global(), 0, NULL);
1692 CHECK_EQ(0, break_point_hit_count);
1694 v8::Debug::SetDebugEventListener(NULL);
1695 CheckDebuggerUnloaded();
1697 // Make sure that the break point numbers are consecutive.
1707 // Test conditional script break points.
1708 TEST(EnableDisableScriptBreakPoint) {
1709 break_point_hit_count = 0;
1710 DebugLocalContext env;
1711 v8::HandleScope scope(env->GetIsolate());
1714 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1716 v8::Local<v8::String> script = v8::String::NewFromUtf8(
1719 " a = 0; // line 1\n"
1722 // Compile the script and get function f.
1723 v8::ScriptOrigin origin =
1724 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "test"));
1725 v8::Script::Compile(script, &origin)->Run();
1726 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
1727 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1729 // Set script break point on line 1 (in function f).
1730 int sbp = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 1, 0);
1732 // Call f while enabeling and disabling the script break point.
1733 break_point_hit_count = 0;
1734 f->Call(env->Global(), 0, NULL);
1735 CHECK_EQ(1, break_point_hit_count);
1737 DisableScriptBreakPointFromJS(env->GetIsolate(), sbp);
1738 f->Call(env->Global(), 0, NULL);
1739 CHECK_EQ(1, break_point_hit_count);
1741 EnableScriptBreakPointFromJS(env->GetIsolate(), sbp);
1742 f->Call(env->Global(), 0, NULL);
1743 CHECK_EQ(2, break_point_hit_count);
1745 DisableScriptBreakPointFromJS(env->GetIsolate(), sbp);
1746 f->Call(env->Global(), 0, NULL);
1747 CHECK_EQ(2, break_point_hit_count);
1749 // Reload the script and get f again checking that the disabeling survives.
1750 v8::Script::Compile(script, &origin)->Run();
1751 f = v8::Local<v8::Function>::Cast(
1752 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1753 f->Call(env->Global(), 0, NULL);
1754 CHECK_EQ(2, break_point_hit_count);
1756 EnableScriptBreakPointFromJS(env->GetIsolate(), sbp);
1757 f->Call(env->Global(), 0, NULL);
1758 CHECK_EQ(3, break_point_hit_count);
1760 v8::Debug::SetDebugEventListener(NULL);
1761 CheckDebuggerUnloaded();
1765 // Test conditional script break points.
1766 TEST(ConditionalScriptBreakPoint) {
1767 break_point_hit_count = 0;
1768 DebugLocalContext env;
1769 v8::HandleScope scope(env->GetIsolate());
1772 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1774 v8::Local<v8::String> script = v8::String::NewFromUtf8(
1778 " g(count++); // line 2\n"
1781 " var a=x; // line 5\n"
1784 // Compile the script and get function f.
1785 v8::ScriptOrigin origin =
1786 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "test"));
1787 v8::Script::Compile(script, &origin)->Run();
1788 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
1789 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1791 // Set script break point on line 5 (in function g).
1792 int sbp1 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 5, 0);
1794 // Call f with different conditions on the script break point.
1795 break_point_hit_count = 0;
1796 ChangeScriptBreakPointConditionFromJS(env->GetIsolate(), sbp1, "false");
1797 f->Call(env->Global(), 0, NULL);
1798 CHECK_EQ(0, break_point_hit_count);
1800 ChangeScriptBreakPointConditionFromJS(env->GetIsolate(), sbp1, "true");
1801 break_point_hit_count = 0;
1802 f->Call(env->Global(), 0, NULL);
1803 CHECK_EQ(1, break_point_hit_count);
1805 ChangeScriptBreakPointConditionFromJS(env->GetIsolate(), sbp1, "x % 2 == 0");
1806 break_point_hit_count = 0;
1807 for (int i = 0; i < 10; i++) {
1808 f->Call(env->Global(), 0, NULL);
1810 CHECK_EQ(5, break_point_hit_count);
1812 // Reload the script and get f again checking that the condition survives.
1813 v8::Script::Compile(script, &origin)->Run();
1814 f = v8::Local<v8::Function>::Cast(
1815 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1817 break_point_hit_count = 0;
1818 for (int i = 0; i < 10; i++) {
1819 f->Call(env->Global(), 0, NULL);
1821 CHECK_EQ(5, break_point_hit_count);
1823 v8::Debug::SetDebugEventListener(NULL);
1824 CheckDebuggerUnloaded();
1828 // Test ignore count on script break points.
1829 TEST(ScriptBreakPointIgnoreCount) {
1830 break_point_hit_count = 0;
1831 DebugLocalContext env;
1832 v8::HandleScope scope(env->GetIsolate());
1835 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1837 v8::Local<v8::String> script = v8::String::NewFromUtf8(
1840 " a = 0; // line 1\n"
1843 // Compile the script and get function f.
1844 v8::ScriptOrigin origin =
1845 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "test"));
1846 v8::Script::Compile(script, &origin)->Run();
1847 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
1848 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1850 // Set script break point on line 1 (in function f).
1851 int sbp = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 1, 0);
1853 // Call f with different ignores on the script break point.
1854 break_point_hit_count = 0;
1855 ChangeScriptBreakPointIgnoreCountFromJS(env->GetIsolate(), sbp, 1);
1856 f->Call(env->Global(), 0, NULL);
1857 CHECK_EQ(0, break_point_hit_count);
1858 f->Call(env->Global(), 0, NULL);
1859 CHECK_EQ(1, break_point_hit_count);
1861 ChangeScriptBreakPointIgnoreCountFromJS(env->GetIsolate(), sbp, 5);
1862 break_point_hit_count = 0;
1863 for (int i = 0; i < 10; i++) {
1864 f->Call(env->Global(), 0, NULL);
1866 CHECK_EQ(5, break_point_hit_count);
1868 // Reload the script and get f again checking that the ignore survives.
1869 v8::Script::Compile(script, &origin)->Run();
1870 f = v8::Local<v8::Function>::Cast(
1871 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1873 break_point_hit_count = 0;
1874 for (int i = 0; i < 10; i++) {
1875 f->Call(env->Global(), 0, NULL);
1877 CHECK_EQ(5, break_point_hit_count);
1879 v8::Debug::SetDebugEventListener(NULL);
1880 CheckDebuggerUnloaded();
1884 // Test that script break points survive when a script is reloaded.
1885 TEST(ScriptBreakPointReload) {
1886 break_point_hit_count = 0;
1887 DebugLocalContext env;
1888 v8::HandleScope scope(env->GetIsolate());
1891 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1893 v8::Local<v8::Function> f;
1894 v8::Local<v8::String> script = v8::String::NewFromUtf8(
1898 " a = 0; // line 2\n"
1900 " b = 1; // line 4\n"
1904 v8::ScriptOrigin origin_1 =
1905 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "1"));
1906 v8::ScriptOrigin origin_2 =
1907 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "2"));
1909 // Set a script break point before the script is loaded.
1910 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "1", 2, 0);
1912 // Compile the script and get the function.
1913 v8::Script::Compile(script, &origin_1)->Run();
1914 f = v8::Local<v8::Function>::Cast(
1915 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1917 // Call f and check that the script break point is active.
1918 break_point_hit_count = 0;
1919 f->Call(env->Global(), 0, NULL);
1920 CHECK_EQ(1, break_point_hit_count);
1922 // Compile the script again with a different script data and get the
1924 v8::Script::Compile(script, &origin_2)->Run();
1925 f = v8::Local<v8::Function>::Cast(
1926 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1928 // Call f and check that no break points are set.
1929 break_point_hit_count = 0;
1930 f->Call(env->Global(), 0, NULL);
1931 CHECK_EQ(0, break_point_hit_count);
1933 // Compile the script again and get the function.
1934 v8::Script::Compile(script, &origin_1)->Run();
1935 f = v8::Local<v8::Function>::Cast(
1936 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1938 // Call f and check that the script break point is active.
1939 break_point_hit_count = 0;
1940 f->Call(env->Global(), 0, NULL);
1941 CHECK_EQ(1, break_point_hit_count);
1943 v8::Debug::SetDebugEventListener(NULL);
1944 CheckDebuggerUnloaded();
1948 // Test when several scripts has the same script data
1949 TEST(ScriptBreakPointMultiple) {
1950 break_point_hit_count = 0;
1951 DebugLocalContext env;
1952 v8::HandleScope scope(env->GetIsolate());
1955 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
1957 v8::Local<v8::Function> f;
1958 v8::Local<v8::String> script_f =
1959 v8::String::NewFromUtf8(env->GetIsolate(),
1961 " a = 0; // line 1\n"
1964 v8::Local<v8::Function> g;
1965 v8::Local<v8::String> script_g =
1966 v8::String::NewFromUtf8(env->GetIsolate(),
1968 " b = 0; // line 1\n"
1971 v8::ScriptOrigin origin =
1972 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "test"));
1974 // Set a script break point before the scripts are loaded.
1975 int sbp = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 1, 0);
1977 // Compile the scripts with same script data and get the functions.
1978 v8::Script::Compile(script_f, &origin)->Run();
1979 f = v8::Local<v8::Function>::Cast(
1980 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
1981 v8::Script::Compile(script_g, &origin)->Run();
1982 g = v8::Local<v8::Function>::Cast(
1983 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "g")));
1985 // Call f and g and check that the script break point is active.
1986 break_point_hit_count = 0;
1987 f->Call(env->Global(), 0, NULL);
1988 CHECK_EQ(1, break_point_hit_count);
1989 g->Call(env->Global(), 0, NULL);
1990 CHECK_EQ(2, break_point_hit_count);
1992 // Clear the script break point.
1993 ClearBreakPointFromJS(env->GetIsolate(), sbp);
1995 // Call f and g and check that the script break point is no longer active.
1996 break_point_hit_count = 0;
1997 f->Call(env->Global(), 0, NULL);
1998 CHECK_EQ(0, break_point_hit_count);
1999 g->Call(env->Global(), 0, NULL);
2000 CHECK_EQ(0, break_point_hit_count);
2002 // Set script break point with the scripts loaded.
2003 sbp = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test", 1, 0);
2005 // Call f and g and check that the script break point is active.
2006 break_point_hit_count = 0;
2007 f->Call(env->Global(), 0, NULL);
2008 CHECK_EQ(1, break_point_hit_count);
2009 g->Call(env->Global(), 0, NULL);
2010 CHECK_EQ(2, break_point_hit_count);
2012 v8::Debug::SetDebugEventListener(NULL);
2013 CheckDebuggerUnloaded();
2017 // Test the script origin which has both name and line offset.
2018 TEST(ScriptBreakPointLineOffset) {
2019 break_point_hit_count = 0;
2020 DebugLocalContext env;
2021 v8::HandleScope scope(env->GetIsolate());
2024 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2026 v8::Local<v8::Function> f;
2027 v8::Local<v8::String> script = v8::String::NewFromUtf8(
2030 " a = 0; // line 8 as this script has line offset 7\n"
2031 " b = 0; // line 9 as this script has line offset 7\n"
2034 // Create script origin both name and line offset.
2035 v8::ScriptOrigin origin(
2036 v8::String::NewFromUtf8(env->GetIsolate(), "test.html"),
2037 v8::Integer::New(env->GetIsolate(), 7));
2039 // Set two script break points before the script is loaded.
2041 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 8, 0);
2043 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 9, 0);
2045 // Compile the script and get the function.
2046 v8::Script::Compile(script, &origin)->Run();
2047 f = v8::Local<v8::Function>::Cast(
2048 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
2050 // Call f and check that the script break point is active.
2051 break_point_hit_count = 0;
2052 f->Call(env->Global(), 0, NULL);
2053 CHECK_EQ(2, break_point_hit_count);
2055 // Clear the script break points.
2056 ClearBreakPointFromJS(env->GetIsolate(), sbp1);
2057 ClearBreakPointFromJS(env->GetIsolate(), sbp2);
2059 // Call f and check that no script break points are active.
2060 break_point_hit_count = 0;
2061 f->Call(env->Global(), 0, NULL);
2062 CHECK_EQ(0, break_point_hit_count);
2064 // Set a script break point with the script loaded.
2065 sbp1 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 9, 0);
2067 // Call f and check that the script break point is active.
2068 break_point_hit_count = 0;
2069 f->Call(env->Global(), 0, NULL);
2070 CHECK_EQ(1, break_point_hit_count);
2072 v8::Debug::SetDebugEventListener(NULL);
2073 CheckDebuggerUnloaded();
2077 // Test script break points set on lines.
2078 TEST(ScriptBreakPointLine) {
2079 DebugLocalContext env;
2080 v8::HandleScope scope(env->GetIsolate());
2083 // Create a function for checking the function when hitting a break point.
2084 frame_function_name = CompileFunction(&env,
2085 frame_function_name_source,
2086 "frame_function_name");
2088 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2090 v8::Local<v8::Function> f;
2091 v8::Local<v8::Function> g;
2092 v8::Local<v8::String> script =
2093 v8::String::NewFromUtf8(env->GetIsolate(),
2096 " a = 1; // line 2\n"
2098 " a = 2; // line 4\n"
2099 " /* xx */ function g() { // line 5\n"
2100 " function h() { // line 6\n"
2101 " a = 3; // line 7\n"
2104 " a = 4; // line 10\n"
2106 " a=5; // line 12");
2108 // Set a couple script break point before the script is loaded.
2110 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 0, -1);
2112 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 1, -1);
2114 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 5, -1);
2116 // Compile the script and get the function.
2117 break_point_hit_count = 0;
2118 v8::ScriptOrigin origin(
2119 v8::String::NewFromUtf8(env->GetIsolate(), "test.html"),
2120 v8::Integer::New(env->GetIsolate(), 0));
2121 v8::Script::Compile(script, &origin)->Run();
2122 f = v8::Local<v8::Function>::Cast(
2123 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
2124 g = v8::Local<v8::Function>::Cast(
2125 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "g")));
2127 // Check that a break point was hit when the script was run.
2128 CHECK_EQ(1, break_point_hit_count);
2129 CHECK_EQ(0, StrLength(last_function_hit));
2131 // Call f and check that the script break point.
2132 f->Call(env->Global(), 0, NULL);
2133 CHECK_EQ(2, break_point_hit_count);
2134 CHECK_EQ("f", last_function_hit);
2136 // Call g and check that the script break point.
2137 g->Call(env->Global(), 0, NULL);
2138 CHECK_EQ(3, break_point_hit_count);
2139 CHECK_EQ("g", last_function_hit);
2141 // Clear the script break point on g and set one on h.
2142 ClearBreakPointFromJS(env->GetIsolate(), sbp3);
2144 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 6, -1);
2146 // Call g and check that the script break point in h is hit.
2147 g->Call(env->Global(), 0, NULL);
2148 CHECK_EQ(4, break_point_hit_count);
2149 CHECK_EQ("h", last_function_hit);
2151 // Clear break points in f and h. Set a new one in the script between
2152 // functions f and g and test that there is no break points in f and g any
2154 ClearBreakPointFromJS(env->GetIsolate(), sbp2);
2155 ClearBreakPointFromJS(env->GetIsolate(), sbp4);
2157 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 4, -1);
2158 break_point_hit_count = 0;
2159 f->Call(env->Global(), 0, NULL);
2160 g->Call(env->Global(), 0, NULL);
2161 CHECK_EQ(0, break_point_hit_count);
2163 // Reload the script which should hit two break points.
2164 break_point_hit_count = 0;
2165 v8::Script::Compile(script, &origin)->Run();
2166 CHECK_EQ(2, break_point_hit_count);
2167 CHECK_EQ(0, StrLength(last_function_hit));
2169 // Set a break point in the code after the last function decleration.
2171 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 12, -1);
2173 // Reload the script which should hit three break points.
2174 break_point_hit_count = 0;
2175 v8::Script::Compile(script, &origin)->Run();
2176 CHECK_EQ(3, break_point_hit_count);
2177 CHECK_EQ(0, StrLength(last_function_hit));
2179 // Clear the last break points, and reload the script which should not hit any
2181 ClearBreakPointFromJS(env->GetIsolate(), sbp1);
2182 ClearBreakPointFromJS(env->GetIsolate(), sbp5);
2183 ClearBreakPointFromJS(env->GetIsolate(), sbp6);
2184 break_point_hit_count = 0;
2185 v8::Script::Compile(script, &origin)->Run();
2186 CHECK_EQ(0, break_point_hit_count);
2188 v8::Debug::SetDebugEventListener(NULL);
2189 CheckDebuggerUnloaded();
2193 // Test top level script break points set on lines.
2194 TEST(ScriptBreakPointLineTopLevel) {
2195 DebugLocalContext env;
2196 v8::HandleScope scope(env->GetIsolate());
2199 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2201 v8::Local<v8::String> script =
2202 v8::String::NewFromUtf8(env->GetIsolate(),
2204 " a = 1; // line 1\n"
2206 "a = 2; // line 3\n");
2207 v8::Local<v8::Function> f;
2209 v8::HandleScope scope(env->GetIsolate());
2210 CompileRunWithOrigin(script, "test.html");
2212 f = v8::Local<v8::Function>::Cast(
2213 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
2215 CcTest::heap()->CollectAllGarbage(Heap::kNoGCFlags);
2217 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 3, -1);
2219 // Call f and check that there was no break points.
2220 break_point_hit_count = 0;
2221 f->Call(env->Global(), 0, NULL);
2222 CHECK_EQ(0, break_point_hit_count);
2224 // Recompile and run script and check that break point was hit.
2225 break_point_hit_count = 0;
2226 CompileRunWithOrigin(script, "test.html");
2227 CHECK_EQ(1, break_point_hit_count);
2229 // Call f and check that there are still no break points.
2230 break_point_hit_count = 0;
2231 f = v8::Local<v8::Function>::Cast(
2232 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
2233 CHECK_EQ(0, break_point_hit_count);
2235 v8::Debug::SetDebugEventListener(NULL);
2236 CheckDebuggerUnloaded();
2240 // Test that it is possible to add and remove break points in a top level
2241 // function which has no references but has not been collected yet.
2242 TEST(ScriptBreakPointTopLevelCrash) {
2243 DebugLocalContext env;
2244 v8::HandleScope scope(env->GetIsolate());
2247 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2249 v8::Local<v8::String> script_source =
2250 v8::String::NewFromUtf8(env->GetIsolate(),
2257 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 3, -1);
2259 v8::HandleScope scope(env->GetIsolate());
2260 break_point_hit_count = 0;
2261 CompileRunWithOrigin(script_source, "test.html");
2262 CHECK_EQ(1, break_point_hit_count);
2266 SetScriptBreakPointByNameFromJS(env->GetIsolate(), "test.html", 3, -1);
2267 ClearBreakPointFromJS(env->GetIsolate(), sbp1);
2268 ClearBreakPointFromJS(env->GetIsolate(), sbp2);
2270 v8::Debug::SetDebugEventListener(NULL);
2271 CheckDebuggerUnloaded();
2275 // Test that it is possible to remove the last break point for a function
2276 // inside the break handling of that break point.
2277 TEST(RemoveBreakPointInBreak) {
2278 DebugLocalContext env;
2279 v8::HandleScope scope(env->GetIsolate());
2281 v8::Local<v8::Function> foo =
2282 CompileFunction(&env, "function foo(){a=1;}", "foo");
2283 debug_event_remove_break_point = SetBreakPoint(foo, 0);
2285 // Register the debug event listener pasing the function
2286 v8::Debug::SetDebugEventListener(DebugEventRemoveBreakPoint, foo);
2288 break_point_hit_count = 0;
2289 foo->Call(env->Global(), 0, NULL);
2290 CHECK_EQ(1, break_point_hit_count);
2292 break_point_hit_count = 0;
2293 foo->Call(env->Global(), 0, NULL);
2294 CHECK_EQ(0, break_point_hit_count);
2296 v8::Debug::SetDebugEventListener(NULL);
2297 CheckDebuggerUnloaded();
2301 // Test that the debugger statement causes a break.
2302 TEST(DebuggerStatement) {
2303 break_point_hit_count = 0;
2304 DebugLocalContext env;
2305 v8::HandleScope scope(env->GetIsolate());
2306 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2307 v8::Script::Compile(
2308 v8::String::NewFromUtf8(env->GetIsolate(), "function bar(){debugger}"))
2310 v8::Script::Compile(
2311 v8::String::NewFromUtf8(env->GetIsolate(),
2312 "function foo(){debugger;debugger;}"))->Run();
2313 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
2314 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
2315 v8::Local<v8::Function> bar = v8::Local<v8::Function>::Cast(
2316 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "bar")));
2318 // Run function with debugger statement
2319 bar->Call(env->Global(), 0, NULL);
2320 CHECK_EQ(1, break_point_hit_count);
2322 // Run function with two debugger statement
2323 foo->Call(env->Global(), 0, NULL);
2324 CHECK_EQ(3, break_point_hit_count);
2326 v8::Debug::SetDebugEventListener(NULL);
2327 CheckDebuggerUnloaded();
2331 // Test setting a breakpoint on the debugger statement.
2332 TEST(DebuggerStatementBreakpoint) {
2333 break_point_hit_count = 0;
2334 DebugLocalContext env;
2335 v8::HandleScope scope(env->GetIsolate());
2336 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2337 v8::Script::Compile(
2338 v8::String::NewFromUtf8(env->GetIsolate(), "function foo(){debugger;}"))
2340 v8::Local<v8::Function> foo = v8::Local<v8::Function>::Cast(
2341 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo")));
2343 // The debugger statement triggers breakpint hit
2344 foo->Call(env->Global(), 0, NULL);
2345 CHECK_EQ(1, break_point_hit_count);
2347 int bp = SetBreakPoint(foo, 0);
2349 // Set breakpoint does not duplicate hits
2350 foo->Call(env->Global(), 0, NULL);
2351 CHECK_EQ(2, break_point_hit_count);
2353 ClearBreakPoint(bp);
2354 v8::Debug::SetDebugEventListener(NULL);
2355 CheckDebuggerUnloaded();
2359 // Test that the evaluation of expressions when a break point is hit generates
2360 // the correct results.
2361 TEST(DebugEvaluate) {
2362 DebugLocalContext env;
2363 v8::Isolate* isolate = env->GetIsolate();
2364 v8::HandleScope scope(isolate);
2367 // Create a function for checking the evaluation when hitting a break point.
2368 evaluate_check_function = CompileFunction(&env,
2369 evaluate_check_source,
2371 // Register the debug event listener
2372 v8::Debug::SetDebugEventListener(DebugEventEvaluate);
2374 // Different expected vaules of x and a when in a break point (u = undefined,
2375 // d = Hello, world!).
2376 struct EvaluateCheck checks_uu[] = {
2377 {"x", v8::Undefined(isolate)},
2378 {"a", v8::Undefined(isolate)},
2379 {NULL, v8::Handle<v8::Value>()}
2381 struct EvaluateCheck checks_hu[] = {
2382 {"x", v8::String::NewFromUtf8(env->GetIsolate(), "Hello, world!")},
2383 {"a", v8::Undefined(isolate)},
2384 {NULL, v8::Handle<v8::Value>()}
2386 struct EvaluateCheck checks_hh[] = {
2387 {"x", v8::String::NewFromUtf8(env->GetIsolate(), "Hello, world!")},
2388 {"a", v8::String::NewFromUtf8(env->GetIsolate(), "Hello, world!")},
2389 {NULL, v8::Handle<v8::Value>()}
2392 // Simple test function. The "y=0" is in the function foo to provide a break
2393 // location. For "y=0" the "y" is at position 15 in the barbar function
2394 // therefore setting breakpoint at position 15 will break at "y=0" and
2395 // setting it higher will break after.
2396 v8::Local<v8::Function> foo = CompileFunction(&env,
2399 " y=0;" // To ensure break location 1.
2401 " y=0;" // To ensure break location 2.
2404 const int foo_break_position_1 = 15;
2405 const int foo_break_position_2 = 29;
2407 // Arguments with one parameter "Hello, world!"
2408 v8::Handle<v8::Value> argv_foo[1] = {
2409 v8::String::NewFromUtf8(env->GetIsolate(), "Hello, world!")};
2411 // Call foo with breakpoint set before a=x and undefined as parameter.
2412 int bp = SetBreakPoint(foo, foo_break_position_1);
2414 foo->Call(env->Global(), 0, NULL);
2416 // Call foo with breakpoint set before a=x and parameter "Hello, world!".
2418 foo->Call(env->Global(), 1, argv_foo);
2420 // Call foo with breakpoint set after a=x and parameter "Hello, world!".
2421 ClearBreakPoint(bp);
2422 SetBreakPoint(foo, foo_break_position_2);
2424 foo->Call(env->Global(), 1, argv_foo);
2426 // Test function with an inner function. The "y=0" is in function barbar
2427 // to provide a break location. For "y=0" the "y" is at position 8 in the
2428 // barbar function therefore setting breakpoint at position 8 will break at
2429 // "y=0" and setting it higher will break after.
2430 v8::Local<v8::Function> bar = CompileFunction(&env,
2432 "x = 'Goodbye, world!';"
2433 "function bar(x, b) {"
2435 " function barbar() {"
2436 " y=0; /* To ensure break location.*/"
2439 " debug.Debug.clearAllBreakPoints();"
2444 const int barbar_break_position = 8;
2446 // Call bar setting breakpoint before a=x in barbar and undefined as
2449 v8::Handle<v8::Value> argv_bar_1[2] = {
2450 v8::Undefined(isolate),
2451 v8::Number::New(isolate, barbar_break_position)
2453 bar->Call(env->Global(), 2, argv_bar_1);
2455 // Call bar setting breakpoint before a=x in barbar and parameter
2458 v8::Handle<v8::Value> argv_bar_2[2] = {
2459 v8::String::NewFromUtf8(env->GetIsolate(), "Hello, world!"),
2460 v8::Number::New(env->GetIsolate(), barbar_break_position)
2462 bar->Call(env->Global(), 2, argv_bar_2);
2464 // Call bar setting breakpoint after a=x in barbar and parameter
2467 v8::Handle<v8::Value> argv_bar_3[2] = {
2468 v8::String::NewFromUtf8(env->GetIsolate(), "Hello, world!"),
2469 v8::Number::New(env->GetIsolate(), barbar_break_position + 1)
2471 bar->Call(env->Global(), 2, argv_bar_3);
2473 v8::Debug::SetDebugEventListener(NULL);
2474 CheckDebuggerUnloaded();
2478 int debugEventCount = 0;
2479 static void CheckDebugEvent(const v8::Debug::EventDetails& eventDetails) {
2480 if (eventDetails.GetEvent() == v8::Break) ++debugEventCount;
2484 // Test that the conditional breakpoints work event if code generation from
2485 // strings is prohibited in the debugee context.
2486 TEST(ConditionalBreakpointWithCodeGenerationDisallowed) {
2487 DebugLocalContext env;
2488 v8::HandleScope scope(env->GetIsolate());
2491 v8::Debug::SetDebugEventListener(CheckDebugEvent);
2493 v8::Local<v8::Function> foo = CompileFunction(&env,
2494 "function foo(x) {\n"
2495 " var s = 'String value2';\n"
2500 // Set conditional breakpoint with condition 'true'.
2501 CompileRun("debug.Debug.setBreakPoint(foo, 2, 0, 'true')");
2503 debugEventCount = 0;
2504 env->AllowCodeGenerationFromStrings(false);
2505 foo->Call(env->Global(), 0, NULL);
2506 CHECK_EQ(1, debugEventCount);
2508 v8::Debug::SetDebugEventListener(NULL);
2509 CheckDebuggerUnloaded();
2513 bool checkedDebugEvals = true;
2514 v8::Handle<v8::Function> checkGlobalEvalFunction;
2515 v8::Handle<v8::Function> checkFrameEvalFunction;
2516 static void CheckDebugEval(const v8::Debug::EventDetails& eventDetails) {
2517 if (eventDetails.GetEvent() == v8::Break) {
2519 v8::HandleScope handleScope(CcTest::isolate());
2521 v8::Handle<v8::Value> args[] = { eventDetails.GetExecutionState() };
2522 CHECK(checkGlobalEvalFunction->Call(
2523 eventDetails.GetEventContext()->Global(), 1, args)->IsTrue());
2524 CHECK(checkFrameEvalFunction->Call(
2525 eventDetails.GetEventContext()->Global(), 1, args)->IsTrue());
2530 // Test that the evaluation of expressions when a break point is hit generates
2531 // the correct results in case code generation from strings is disallowed in the
2533 TEST(DebugEvaluateWithCodeGenerationDisallowed) {
2534 DebugLocalContext env;
2535 v8::HandleScope scope(env->GetIsolate());
2538 v8::Debug::SetDebugEventListener(CheckDebugEval);
2540 v8::Local<v8::Function> foo = CompileFunction(&env,
2541 "var global = 'Global';\n"
2542 "function foo(x) {\n"
2543 " var local = 'Local';\n"
2545 " return local + x;\n"
2548 checkGlobalEvalFunction = CompileFunction(&env,
2549 "function checkGlobalEval(exec_state) {\n"
2550 " return exec_state.evaluateGlobal('global').value() === 'Global';\n"
2554 checkFrameEvalFunction = CompileFunction(&env,
2555 "function checkFrameEval(exec_state) {\n"
2556 " return exec_state.frame(0).evaluate('local').value() === 'Local';\n"
2559 debugEventCount = 0;
2560 env->AllowCodeGenerationFromStrings(false);
2561 foo->Call(env->Global(), 0, NULL);
2562 CHECK_EQ(1, debugEventCount);
2564 checkGlobalEvalFunction.Clear();
2565 checkFrameEvalFunction.Clear();
2566 v8::Debug::SetDebugEventListener(NULL);
2567 CheckDebuggerUnloaded();
2571 // Copies a C string to a 16-bit string. Does not check for buffer overflow.
2572 // Does not use the V8 engine to convert strings, so it can be used
2573 // in any thread. Returns the length of the string.
2574 int AsciiToUtf16(const char* input_buffer, uint16_t* output_buffer) {
2576 for (i = 0; input_buffer[i] != '\0'; ++i) {
2577 // ASCII does not use chars > 127, but be careful anyway.
2578 output_buffer[i] = static_cast<unsigned char>(input_buffer[i]);
2580 output_buffer[i] = 0;
2585 // Copies a 16-bit string to a C string by dropping the high byte of
2586 // each character. Does not check for buffer overflow.
2587 // Can be used in any thread. Requires string length as an input.
2588 int Utf16ToAscii(const uint16_t* input_buffer, int length,
2589 char* output_buffer, int output_len = -1) {
2590 if (output_len >= 0) {
2591 if (length > output_len - 1) {
2592 length = output_len - 1;
2596 for (int i = 0; i < length; ++i) {
2597 output_buffer[i] = static_cast<char>(input_buffer[i]);
2599 output_buffer[length] = '\0';
2604 // We match parts of the message to get evaluate result int value.
2605 bool GetEvaluateStringResult(char *message, char* buffer, int buffer_size) {
2606 if (strstr(message, "\"command\":\"evaluate\"") == NULL) {
2609 const char* prefix = "\"text\":\"";
2610 char* pos1 = strstr(message, prefix);
2614 pos1 += strlen(prefix);
2615 char* pos2 = strchr(pos1, '"');
2619 Vector<char> buf(buffer, buffer_size);
2620 int len = static_cast<int>(pos2 - pos1);
2621 if (len > buffer_size - 1) {
2622 len = buffer_size - 1;
2624 StrNCpy(buf, pos1, len);
2625 buffer[buffer_size - 1] = '\0';
2630 struct EvaluateResult {
2631 static const int kBufferSize = 20;
2632 char buffer[kBufferSize];
2635 struct DebugProcessDebugMessagesData {
2636 static const int kArraySize = 5;
2638 EvaluateResult results[kArraySize];
2643 EvaluateResult* current() {
2644 return &results[counter % kArraySize];
2651 DebugProcessDebugMessagesData process_debug_messages_data;
2653 static void DebugProcessDebugMessagesHandler(
2654 const v8::Debug::Message& message) {
2655 v8::Handle<v8::String> json = message.GetJSON();
2656 v8::String::Utf8Value utf8(json);
2657 EvaluateResult* array_item = process_debug_messages_data.current();
2659 bool res = GetEvaluateStringResult(*utf8,
2661 EvaluateResult::kBufferSize);
2663 process_debug_messages_data.next();
2668 // Test that the evaluation of expressions works even from ProcessDebugMessages
2669 // i.e. with empty stack.
2670 TEST(DebugEvaluateWithoutStack) {
2671 v8::Debug::SetMessageHandler(DebugProcessDebugMessagesHandler);
2673 DebugLocalContext env;
2674 v8::HandleScope scope(env->GetIsolate());
2676 const char* source =
2677 "var v1 = 'Pinguin';\n function getAnimal() { return 'Capy' + 'bara'; }";
2679 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), source))
2682 v8::Debug::ProcessDebugMessages();
2684 const int kBufferSize = 1000;
2685 uint16_t buffer[kBufferSize];
2687 const char* command_111 = "{\"seq\":111,"
2688 "\"type\":\"request\","
2689 "\"command\":\"evaluate\","
2692 " \"expression\":\"v1\",\"disable_break\":true"
2695 v8::Isolate* isolate = CcTest::isolate();
2696 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_111, buffer));
2698 const char* command_112 = "{\"seq\":112,"
2699 "\"type\":\"request\","
2700 "\"command\":\"evaluate\","
2703 " \"expression\":\"getAnimal()\",\"disable_break\":true"
2706 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_112, buffer));
2708 const char* command_113 = "{\"seq\":113,"
2709 "\"type\":\"request\","
2710 "\"command\":\"evaluate\","
2713 " \"expression\":\"239 + 566\",\"disable_break\":true"
2716 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_113, buffer));
2718 v8::Debug::ProcessDebugMessages();
2720 CHECK_EQ(3, process_debug_messages_data.counter);
2722 CHECK_EQ(strcmp("Pinguin", process_debug_messages_data.results[0].buffer), 0);
2723 CHECK_EQ(strcmp("Capybara", process_debug_messages_data.results[1].buffer),
2725 CHECK_EQ(strcmp("805", process_debug_messages_data.results[2].buffer), 0);
2727 v8::Debug::SetMessageHandler(NULL);
2728 v8::Debug::SetDebugEventListener(NULL);
2729 CheckDebuggerUnloaded();
2733 // Simple test of the stepping mechanism using only store ICs.
2734 TEST(DebugStepLinear) {
2735 DebugLocalContext env;
2736 v8::HandleScope scope(env->GetIsolate());
2738 // Create a function for testing stepping.
2739 v8::Local<v8::Function> foo = CompileFunction(&env,
2740 "function foo(){a=1;b=1;c=1;}",
2743 // Run foo to allow it to get optimized.
2744 CompileRun("a=0; b=0; c=0; foo();");
2746 SetBreakPoint(foo, 3);
2748 // Register a debug event listener which steps and counts.
2749 v8::Debug::SetDebugEventListener(DebugEventStep);
2751 step_action = StepIn;
2752 break_point_hit_count = 0;
2753 foo->Call(env->Global(), 0, NULL);
2755 // With stepping all break locations are hit.
2756 CHECK_EQ(4, break_point_hit_count);
2758 v8::Debug::SetDebugEventListener(NULL);
2759 CheckDebuggerUnloaded();
2761 // Register a debug event listener which just counts.
2762 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2764 SetBreakPoint(foo, 3);
2765 break_point_hit_count = 0;
2766 foo->Call(env->Global(), 0, NULL);
2768 // Without stepping only active break points are hit.
2769 CHECK_EQ(1, break_point_hit_count);
2771 v8::Debug::SetDebugEventListener(NULL);
2772 CheckDebuggerUnloaded();
2776 // Test of the stepping mechanism for keyed load in a loop.
2777 TEST(DebugStepKeyedLoadLoop) {
2778 DebugLocalContext env;
2779 v8::HandleScope scope(env->GetIsolate());
2781 // Register a debug event listener which steps and counts.
2782 v8::Debug::SetDebugEventListener(DebugEventStep);
2784 // Create a function for testing stepping of keyed load. The statement 'y=1'
2785 // is there to have more than one breakable statement in the loop, TODO(315).
2786 v8::Local<v8::Function> foo = CompileFunction(
2788 "function foo(a) {\n"
2790 " var len = a.length;\n"
2791 " for (var i = 0; i < len; i++) {\n"
2799 // Create array [0,1,2,3,4,5,6,7,8,9]
2800 v8::Local<v8::Array> a = v8::Array::New(env->GetIsolate(), 10);
2801 for (int i = 0; i < 10; i++) {
2802 a->Set(v8::Number::New(env->GetIsolate(), i),
2803 v8::Number::New(env->GetIsolate(), i));
2806 // Call function without any break points to ensure inlining is in place.
2807 const int kArgc = 1;
2808 v8::Handle<v8::Value> args[kArgc] = { a };
2809 foo->Call(env->Global(), kArgc, args);
2811 // Set up break point and step through the function.
2812 SetBreakPoint(foo, 3);
2813 step_action = StepNext;
2814 break_point_hit_count = 0;
2815 foo->Call(env->Global(), kArgc, args);
2817 // With stepping all break locations are hit.
2818 CHECK_EQ(35, break_point_hit_count);
2820 v8::Debug::SetDebugEventListener(NULL);
2821 CheckDebuggerUnloaded();
2825 // Test of the stepping mechanism for keyed store in a loop.
2826 TEST(DebugStepKeyedStoreLoop) {
2827 DebugLocalContext env;
2828 v8::HandleScope scope(env->GetIsolate());
2830 // Register a debug event listener which steps and counts.
2831 v8::Debug::SetDebugEventListener(DebugEventStep);
2833 // Create a function for testing stepping of keyed store. The statement 'y=1'
2834 // is there to have more than one breakable statement in the loop, TODO(315).
2835 v8::Local<v8::Function> foo = CompileFunction(
2837 "function foo(a) {\n"
2838 " var len = a.length;\n"
2839 " for (var i = 0; i < len; i++) {\n"
2847 // Create array [0,1,2,3,4,5,6,7,8,9]
2848 v8::Local<v8::Array> a = v8::Array::New(env->GetIsolate(), 10);
2849 for (int i = 0; i < 10; i++) {
2850 a->Set(v8::Number::New(env->GetIsolate(), i),
2851 v8::Number::New(env->GetIsolate(), i));
2854 // Call function without any break points to ensure inlining is in place.
2855 const int kArgc = 1;
2856 v8::Handle<v8::Value> args[kArgc] = { a };
2857 foo->Call(env->Global(), kArgc, args);
2859 // Set up break point and step through the function.
2860 SetBreakPoint(foo, 3);
2861 step_action = StepNext;
2862 break_point_hit_count = 0;
2863 foo->Call(env->Global(), kArgc, args);
2865 // With stepping all break locations are hit.
2866 CHECK_EQ(34, break_point_hit_count);
2868 v8::Debug::SetDebugEventListener(NULL);
2869 CheckDebuggerUnloaded();
2873 // Test of the stepping mechanism for named load in a loop.
2874 TEST(DebugStepNamedLoadLoop) {
2875 DebugLocalContext env;
2876 v8::HandleScope scope(env->GetIsolate());
2878 // Register a debug event listener which steps and counts.
2879 v8::Debug::SetDebugEventListener(DebugEventStep);
2881 // Create a function for testing stepping of named load.
2882 v8::Local<v8::Function> foo = CompileFunction(
2884 "function foo() {\n"
2887 " for (var i = 0; i < 10; i++) {\n"
2888 " var v = new V(i, i + 1);\n"
2890 " a.length;\n" // Special case: array length.
2891 " s.length;\n" // Special case: string length.
2894 "function V(x, y) {\n"
2900 // Call function without any break points to ensure inlining is in place.
2901 foo->Call(env->Global(), 0, NULL);
2903 // Set up break point and step through the function.
2904 SetBreakPoint(foo, 4);
2905 step_action = StepNext;
2906 break_point_hit_count = 0;
2907 foo->Call(env->Global(), 0, NULL);
2909 // With stepping all break locations are hit.
2910 CHECK_EQ(55, break_point_hit_count);
2912 v8::Debug::SetDebugEventListener(NULL);
2913 CheckDebuggerUnloaded();
2917 static void DoDebugStepNamedStoreLoop(int expected) {
2918 DebugLocalContext env;
2919 v8::HandleScope scope(env->GetIsolate());
2921 // Register a debug event listener which steps and counts.
2922 v8::Debug::SetDebugEventListener(DebugEventStep);
2924 // Create a function for testing stepping of named store.
2925 v8::Local<v8::Function> foo = CompileFunction(
2927 "function foo() {\n"
2929 " for (var i = 0; i < 10; i++) {\n"
2935 // Call function without any break points to ensure inlining is in place.
2936 foo->Call(env->Global(), 0, NULL);
2938 // Set up break point and step through the function.
2939 SetBreakPoint(foo, 3);
2940 step_action = StepNext;
2941 break_point_hit_count = 0;
2942 foo->Call(env->Global(), 0, NULL);
2944 // With stepping all expected break locations are hit.
2945 CHECK_EQ(expected, break_point_hit_count);
2947 v8::Debug::SetDebugEventListener(NULL);
2948 CheckDebuggerUnloaded();
2952 // Test of the stepping mechanism for named load in a loop.
2953 TEST(DebugStepNamedStoreLoop) {
2954 DoDebugStepNamedStoreLoop(24);
2958 // Test the stepping mechanism with different ICs.
2959 TEST(DebugStepLinearMixedICs) {
2960 DebugLocalContext env;
2961 v8::HandleScope scope(env->GetIsolate());
2963 // Register a debug event listener which steps and counts.
2964 v8::Debug::SetDebugEventListener(DebugEventStep);
2966 // Create a function for testing stepping.
2967 v8::Local<v8::Function> foo = CompileFunction(&env,
2968 "function bar() {};"
2971 " var index='name';"
2973 " a=1;b=2;x=a;y[index]=3;x=y[index];bar();}", "foo");
2975 // Run functions to allow them to get optimized.
2976 CompileRun("a=0; b=0; bar(); foo();");
2978 SetBreakPoint(foo, 0);
2980 step_action = StepIn;
2981 break_point_hit_count = 0;
2982 foo->Call(env->Global(), 0, NULL);
2984 // With stepping all break locations are hit.
2985 CHECK_EQ(11, break_point_hit_count);
2987 v8::Debug::SetDebugEventListener(NULL);
2988 CheckDebuggerUnloaded();
2990 // Register a debug event listener which just counts.
2991 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2993 SetBreakPoint(foo, 0);
2994 break_point_hit_count = 0;
2995 foo->Call(env->Global(), 0, NULL);
2997 // Without stepping only active break points are hit.
2998 CHECK_EQ(1, break_point_hit_count);
3000 v8::Debug::SetDebugEventListener(NULL);
3001 CheckDebuggerUnloaded();
3005 TEST(DebugStepDeclarations) {
3006 DebugLocalContext env;
3007 v8::HandleScope scope(env->GetIsolate());
3009 // Register a debug event listener which steps and counts.
3010 v8::Debug::SetDebugEventListener(DebugEventStep);
3012 // Create a function for testing stepping. Run it to allow it to get
3014 const char* src = "function foo() { "
3018 " var d = Math.floor;"
3019 " var e = b + d(1.2);"
3022 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3024 SetBreakPoint(foo, 0);
3026 // Stepping through the declarations.
3027 step_action = StepIn;
3028 break_point_hit_count = 0;
3029 foo->Call(env->Global(), 0, NULL);
3030 CHECK_EQ(6, break_point_hit_count);
3032 // Get rid of the debug event listener.
3033 v8::Debug::SetDebugEventListener(NULL);
3034 CheckDebuggerUnloaded();
3038 TEST(DebugStepLocals) {
3039 DebugLocalContext env;
3040 v8::HandleScope scope(env->GetIsolate());
3042 // Register a debug event listener which steps and counts.
3043 v8::Debug::SetDebugEventListener(DebugEventStep);
3045 // Create a function for testing stepping. Run it to allow it to get
3047 const char* src = "function foo() { "
3052 " a = Math.floor(b);"
3055 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3057 SetBreakPoint(foo, 0);
3059 // Stepping through the declarations.
3060 step_action = StepIn;
3061 break_point_hit_count = 0;
3062 foo->Call(env->Global(), 0, NULL);
3063 CHECK_EQ(6, break_point_hit_count);
3065 // Get rid of the debug event listener.
3066 v8::Debug::SetDebugEventListener(NULL);
3067 CheckDebuggerUnloaded();
3072 DebugLocalContext env;
3073 v8::Isolate* isolate = env->GetIsolate();
3074 v8::HandleScope scope(isolate);
3076 // Register a debug event listener which steps and counts.
3077 v8::Debug::SetDebugEventListener(DebugEventStep);
3079 // Create a function for testing stepping. Run it to allow it to get
3082 const char* src = "function foo(x) { "
3091 "a=0; b=0; c=0; d=0; foo()";
3092 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3093 SetBreakPoint(foo, 0);
3095 // Stepping through the true part.
3096 step_action = StepIn;
3097 break_point_hit_count = 0;
3098 v8::Handle<v8::Value> argv_true[argc] = { v8::True(isolate) };
3099 foo->Call(env->Global(), argc, argv_true);
3100 CHECK_EQ(4, break_point_hit_count);
3102 // Stepping through the false part.
3103 step_action = StepIn;
3104 break_point_hit_count = 0;
3105 v8::Handle<v8::Value> argv_false[argc] = { v8::False(isolate) };
3106 foo->Call(env->Global(), argc, argv_false);
3107 CHECK_EQ(5, break_point_hit_count);
3109 // Get rid of the debug event listener.
3110 v8::Debug::SetDebugEventListener(NULL);
3111 CheckDebuggerUnloaded();
3115 TEST(DebugStepSwitch) {
3116 DebugLocalContext env;
3117 v8::Isolate* isolate = env->GetIsolate();
3118 v8::HandleScope scope(isolate);
3120 // Register a debug event listener which steps and counts.
3121 v8::Debug::SetDebugEventListener(DebugEventStep);
3123 // Create a function for testing stepping. Run it to allow it to get
3126 const char* src = "function foo(x) { "
3141 "a=0; b=0; c=0; d=0; e=0; f=0; foo()";
3142 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3143 SetBreakPoint(foo, 0);
3145 // One case with fall-through.
3146 step_action = StepIn;
3147 break_point_hit_count = 0;
3148 v8::Handle<v8::Value> argv_1[argc] = { v8::Number::New(isolate, 1) };
3149 foo->Call(env->Global(), argc, argv_1);
3150 CHECK_EQ(6, break_point_hit_count);
3153 step_action = StepIn;
3154 break_point_hit_count = 0;
3155 v8::Handle<v8::Value> argv_2[argc] = { v8::Number::New(isolate, 2) };
3156 foo->Call(env->Global(), argc, argv_2);
3157 CHECK_EQ(5, break_point_hit_count);
3160 step_action = StepIn;
3161 break_point_hit_count = 0;
3162 v8::Handle<v8::Value> argv_3[argc] = { v8::Number::New(isolate, 3) };
3163 foo->Call(env->Global(), argc, argv_3);
3164 CHECK_EQ(7, break_point_hit_count);
3166 // Get rid of the debug event listener.
3167 v8::Debug::SetDebugEventListener(NULL);
3168 CheckDebuggerUnloaded();
3172 TEST(DebugStepWhile) {
3173 DebugLocalContext env;
3174 v8::Isolate* isolate = env->GetIsolate();
3175 v8::HandleScope scope(isolate);
3177 // Register a debug event listener which steps and counts.
3178 v8::Debug::SetDebugEventListener(DebugEventStep);
3180 // Create a function for testing stepping. Run it to allow it to get
3183 const char* src = "function foo(x) { "
3190 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3191 SetBreakPoint(foo, 8); // "var a = 0;"
3193 // Looping 0 times. We still should break at the while-condition once.
3194 step_action = StepIn;
3195 break_point_hit_count = 0;
3196 v8::Handle<v8::Value> argv_0[argc] = { v8::Number::New(isolate, 0) };
3197 foo->Call(env->Global(), argc, argv_0);
3198 CHECK_EQ(3, break_point_hit_count);
3200 // Looping 10 times.
3201 step_action = StepIn;
3202 break_point_hit_count = 0;
3203 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(isolate, 10) };
3204 foo->Call(env->Global(), argc, argv_10);
3205 CHECK_EQ(23, break_point_hit_count);
3207 // Looping 100 times.
3208 step_action = StepIn;
3209 break_point_hit_count = 0;
3210 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(isolate, 100) };
3211 foo->Call(env->Global(), argc, argv_100);
3212 CHECK_EQ(203, break_point_hit_count);
3214 // Get rid of the debug event listener.
3215 v8::Debug::SetDebugEventListener(NULL);
3216 CheckDebuggerUnloaded();
3220 TEST(DebugStepDoWhile) {
3221 DebugLocalContext env;
3222 v8::Isolate* isolate = env->GetIsolate();
3223 v8::HandleScope scope(isolate);
3225 // Register a debug event listener which steps and counts.
3226 v8::Debug::SetDebugEventListener(DebugEventStep);
3228 // Create a function for testing stepping. Run it to allow it to get
3231 const char* src = "function foo(x) { "
3238 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3239 SetBreakPoint(foo, 8); // "var a = 0;"
3241 // Looping 10 times.
3242 step_action = StepIn;
3243 break_point_hit_count = 0;
3244 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(isolate, 10) };
3245 foo->Call(env->Global(), argc, argv_10);
3246 CHECK_EQ(22, break_point_hit_count);
3248 // Looping 100 times.
3249 step_action = StepIn;
3250 break_point_hit_count = 0;
3251 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(isolate, 100) };
3252 foo->Call(env->Global(), argc, argv_100);
3253 CHECK_EQ(202, break_point_hit_count);
3255 // Get rid of the debug event listener.
3256 v8::Debug::SetDebugEventListener(NULL);
3257 CheckDebuggerUnloaded();
3261 TEST(DebugStepFor) {
3262 DebugLocalContext env;
3263 v8::Isolate* isolate = env->GetIsolate();
3264 v8::HandleScope scope(isolate);
3266 // Register a debug event listener which steps and counts.
3267 v8::Debug::SetDebugEventListener(DebugEventStep);
3269 // Create a function for testing stepping. Run it to allow it to get
3272 const char* src = "function foo(x) { "
3274 " for (i = 0; i < x; i++) {"
3278 "a=0; b=0; i=0; foo()";
3279 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3281 SetBreakPoint(foo, 8); // "a = 1;"
3283 // Looping 10 times.
3284 step_action = StepIn;
3285 break_point_hit_count = 0;
3286 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(isolate, 10) };
3287 foo->Call(env->Global(), argc, argv_10);
3288 CHECK_EQ(23, break_point_hit_count);
3290 // Looping 100 times.
3291 step_action = StepIn;
3292 break_point_hit_count = 0;
3293 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(isolate, 100) };
3294 foo->Call(env->Global(), argc, argv_100);
3295 CHECK_EQ(203, break_point_hit_count);
3297 // Get rid of the debug event listener.
3298 v8::Debug::SetDebugEventListener(NULL);
3299 CheckDebuggerUnloaded();
3303 TEST(DebugStepForContinue) {
3304 DebugLocalContext env;
3305 v8::Isolate* isolate = env->GetIsolate();
3306 v8::HandleScope scope(isolate);
3308 // Register a debug event listener which steps and counts.
3309 v8::Debug::SetDebugEventListener(DebugEventStep);
3311 // Create a function for testing stepping. Run it to allow it to get
3314 const char* src = "function foo(x) { "
3318 " for (var i = 0; i < x; i++) {"
3320 " if (a % 2 == 0) continue;"
3327 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3328 v8::Handle<v8::Value> result;
3329 SetBreakPoint(foo, 8); // "var a = 0;"
3331 // Each loop generates 4 or 5 steps depending on whether a is equal.
3333 // Looping 10 times.
3334 step_action = StepIn;
3335 break_point_hit_count = 0;
3336 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(isolate, 10) };
3337 result = foo->Call(env->Global(), argc, argv_10);
3338 CHECK_EQ(5, result->Int32Value());
3339 CHECK_EQ(52, break_point_hit_count);
3341 // Looping 100 times.
3342 step_action = StepIn;
3343 break_point_hit_count = 0;
3344 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(isolate, 100) };
3345 result = foo->Call(env->Global(), argc, argv_100);
3346 CHECK_EQ(50, result->Int32Value());
3347 CHECK_EQ(457, break_point_hit_count);
3349 // Get rid of the debug event listener.
3350 v8::Debug::SetDebugEventListener(NULL);
3351 CheckDebuggerUnloaded();
3355 TEST(DebugStepForBreak) {
3356 DebugLocalContext env;
3357 v8::Isolate* isolate = env->GetIsolate();
3358 v8::HandleScope scope(isolate);
3360 // Register a debug event listener which steps and counts.
3361 v8::Debug::SetDebugEventListener(DebugEventStep);
3363 // Create a function for testing stepping. Run it to allow it to get
3366 const char* src = "function foo(x) { "
3370 " for (var i = 0; i < 1000; i++) {"
3372 " if (a == x) break;"
3379 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3380 v8::Handle<v8::Value> result;
3381 SetBreakPoint(foo, 8); // "var a = 0;"
3383 // Each loop generates 5 steps except for the last (when break is executed)
3384 // which only generates 4.
3386 // Looping 10 times.
3387 step_action = StepIn;
3388 break_point_hit_count = 0;
3389 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(isolate, 10) };
3390 result = foo->Call(env->Global(), argc, argv_10);
3391 CHECK_EQ(9, result->Int32Value());
3392 CHECK_EQ(55, break_point_hit_count);
3394 // Looping 100 times.
3395 step_action = StepIn;
3396 break_point_hit_count = 0;
3397 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(isolate, 100) };
3398 result = foo->Call(env->Global(), argc, argv_100);
3399 CHECK_EQ(99, result->Int32Value());
3400 CHECK_EQ(505, break_point_hit_count);
3402 // Get rid of the debug event listener.
3403 v8::Debug::SetDebugEventListener(NULL);
3404 CheckDebuggerUnloaded();
3408 TEST(DebugStepForIn) {
3409 DebugLocalContext env;
3410 v8::HandleScope scope(env->GetIsolate());
3412 // Register a debug event listener which steps and counts.
3413 v8::Debug::SetDebugEventListener(DebugEventStep);
3415 // Create a function for testing stepping. Run it to allow it to get
3417 v8::Local<v8::Function> foo;
3418 const char* src_1 = "function foo() { "
3425 foo = CompileFunction(&env, src_1, "foo");
3426 SetBreakPoint(foo, 0); // "var a = ..."
3428 step_action = StepIn;
3429 break_point_hit_count = 0;
3430 foo->Call(env->Global(), 0, NULL);
3431 CHECK_EQ(6, break_point_hit_count);
3433 // Create a function for testing stepping. Run it to allow it to get
3435 const char* src_2 = "function foo() { "
3436 " var a = {a:[1, 2, 3]};"
3442 foo = CompileFunction(&env, src_2, "foo");
3443 SetBreakPoint(foo, 0); // "var a = ..."
3445 step_action = StepIn;
3446 break_point_hit_count = 0;
3447 foo->Call(env->Global(), 0, NULL);
3448 CHECK_EQ(8, break_point_hit_count);
3450 // Get rid of the debug event listener.
3451 v8::Debug::SetDebugEventListener(NULL);
3452 CheckDebuggerUnloaded();
3456 TEST(DebugStepWith) {
3457 DebugLocalContext env;
3458 v8::HandleScope scope(env->GetIsolate());
3460 // Register a debug event listener which steps and counts.
3461 v8::Debug::SetDebugEventListener(DebugEventStep);
3463 // Create a function for testing stepping. Run it to allow it to get
3465 const char* src = "function foo(x) { "
3471 env->Global()->Set(v8::String::NewFromUtf8(env->GetIsolate(), "b"),
3472 v8::Object::New(env->GetIsolate()));
3473 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3474 v8::Handle<v8::Value> result;
3475 SetBreakPoint(foo, 8); // "var a = {};"
3477 step_action = StepIn;
3478 break_point_hit_count = 0;
3479 foo->Call(env->Global(), 0, NULL);
3480 CHECK_EQ(4, break_point_hit_count);
3482 // Get rid of the debug event listener.
3483 v8::Debug::SetDebugEventListener(NULL);
3484 CheckDebuggerUnloaded();
3488 TEST(DebugConditional) {
3489 DebugLocalContext env;
3490 v8::Isolate* isolate = env->GetIsolate();
3491 v8::HandleScope scope(isolate);
3493 // Register a debug event listener which steps and counts.
3494 v8::Debug::SetDebugEventListener(DebugEventStep);
3496 // Create a function for testing stepping. Run it to allow it to get
3498 const char* src = "function foo(x) { "
3504 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3505 SetBreakPoint(foo, 0); // "var a;"
3507 step_action = StepIn;
3508 break_point_hit_count = 0;
3509 foo->Call(env->Global(), 0, NULL);
3510 CHECK_EQ(5, break_point_hit_count);
3512 step_action = StepIn;
3513 break_point_hit_count = 0;
3515 v8::Handle<v8::Value> argv_true[argc] = { v8::True(isolate) };
3516 foo->Call(env->Global(), argc, argv_true);
3517 CHECK_EQ(5, break_point_hit_count);
3519 // Get rid of the debug event listener.
3520 v8::Debug::SetDebugEventListener(NULL);
3521 CheckDebuggerUnloaded();
3525 TEST(StepInOutSimple) {
3526 DebugLocalContext env;
3527 v8::HandleScope scope(env->GetIsolate());
3529 // Create a function for checking the function when hitting a break point.
3530 frame_function_name = CompileFunction(&env,
3531 frame_function_name_source,
3532 "frame_function_name");
3534 // Register a debug event listener which steps and counts.
3535 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3537 // Create a function for testing stepping. Run it to allow it to get
3539 const char* src = "function a() {b();c();}; "
3540 "function b() {c();}; "
3543 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3544 SetBreakPoint(a, 0);
3546 // Step through invocation of a with step in.
3547 step_action = StepIn;
3548 break_point_hit_count = 0;
3549 expected_step_sequence = "abcbaca";
3550 a->Call(env->Global(), 0, NULL);
3551 CHECK_EQ(StrLength(expected_step_sequence),
3552 break_point_hit_count);
3554 // Step through invocation of a with step next.
3555 step_action = StepNext;
3556 break_point_hit_count = 0;
3557 expected_step_sequence = "aaa";
3558 a->Call(env->Global(), 0, NULL);
3559 CHECK_EQ(StrLength(expected_step_sequence),
3560 break_point_hit_count);
3562 // Step through invocation of a with step out.
3563 step_action = StepOut;
3564 break_point_hit_count = 0;
3565 expected_step_sequence = "a";
3566 a->Call(env->Global(), 0, NULL);
3567 CHECK_EQ(StrLength(expected_step_sequence),
3568 break_point_hit_count);
3570 // Get rid of the debug event listener.
3571 v8::Debug::SetDebugEventListener(NULL);
3572 CheckDebuggerUnloaded();
3576 TEST(StepInOutTree) {
3577 DebugLocalContext env;
3578 v8::HandleScope scope(env->GetIsolate());
3580 // Create a function for checking the function when hitting a break point.
3581 frame_function_name = CompileFunction(&env,
3582 frame_function_name_source,
3583 "frame_function_name");
3585 // Register a debug event listener which steps and counts.
3586 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3588 // Create a function for testing stepping. Run it to allow it to get
3590 const char* src = "function a() {b(c(d()),d());c(d());d()}; "
3591 "function b(x,y) {c();}; "
3592 "function c(x) {}; "
3594 "a(); b(); c(); d()";
3595 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3596 SetBreakPoint(a, 0);
3598 // Step through invocation of a with step in.
3599 step_action = StepIn;
3600 break_point_hit_count = 0;
3601 expected_step_sequence = "adacadabcbadacada";
3602 a->Call(env->Global(), 0, NULL);
3603 CHECK_EQ(StrLength(expected_step_sequence),
3604 break_point_hit_count);
3606 // Step through invocation of a with step next.
3607 step_action = StepNext;
3608 break_point_hit_count = 0;
3609 expected_step_sequence = "aaaa";
3610 a->Call(env->Global(), 0, NULL);
3611 CHECK_EQ(StrLength(expected_step_sequence),
3612 break_point_hit_count);
3614 // Step through invocation of a with step out.
3615 step_action = StepOut;
3616 break_point_hit_count = 0;
3617 expected_step_sequence = "a";
3618 a->Call(env->Global(), 0, NULL);
3619 CHECK_EQ(StrLength(expected_step_sequence),
3620 break_point_hit_count);
3622 // Get rid of the debug event listener.
3623 v8::Debug::SetDebugEventListener(NULL);
3624 CheckDebuggerUnloaded(true);
3628 TEST(StepInOutBranch) {
3629 DebugLocalContext env;
3630 v8::HandleScope scope(env->GetIsolate());
3632 // Create a function for checking the function when hitting a break point.
3633 frame_function_name = CompileFunction(&env,
3634 frame_function_name_source,
3635 "frame_function_name");
3637 // Register a debug event listener which steps and counts.
3638 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3640 // Create a function for testing stepping. Run it to allow it to get
3642 const char* src = "function a() {b(false);c();}; "
3643 "function b(x) {if(x){c();};}; "
3646 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3647 SetBreakPoint(a, 0);
3649 // Step through invocation of a.
3650 step_action = StepIn;
3651 break_point_hit_count = 0;
3652 expected_step_sequence = "abbaca";
3653 a->Call(env->Global(), 0, NULL);
3654 CHECK_EQ(StrLength(expected_step_sequence),
3655 break_point_hit_count);
3657 // Get rid of the debug event listener.
3658 v8::Debug::SetDebugEventListener(NULL);
3659 CheckDebuggerUnloaded();
3663 // Test that step in does not step into native functions.
3664 TEST(DebugStepNatives) {
3665 DebugLocalContext env;
3666 v8::HandleScope scope(env->GetIsolate());
3668 // Create a function for testing stepping.
3669 v8::Local<v8::Function> foo = CompileFunction(
3671 "function foo(){debugger;Math.sin(1);}",
3674 // Register a debug event listener which steps and counts.
3675 v8::Debug::SetDebugEventListener(DebugEventStep);
3677 step_action = StepIn;
3678 break_point_hit_count = 0;
3679 foo->Call(env->Global(), 0, NULL);
3681 // With stepping all break locations are hit.
3682 CHECK_EQ(3, break_point_hit_count);
3684 v8::Debug::SetDebugEventListener(NULL);
3685 CheckDebuggerUnloaded();
3687 // Register a debug event listener which just counts.
3688 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
3690 break_point_hit_count = 0;
3691 foo->Call(env->Global(), 0, NULL);
3693 // Without stepping only active break points are hit.
3694 CHECK_EQ(1, break_point_hit_count);
3696 v8::Debug::SetDebugEventListener(NULL);
3697 CheckDebuggerUnloaded();
3701 // Test that step in works with function.apply.
3702 TEST(DebugStepFunctionApply) {
3703 DebugLocalContext env;
3704 v8::HandleScope scope(env->GetIsolate());
3706 // Create a function for testing stepping.
3707 v8::Local<v8::Function> foo = CompileFunction(
3709 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
3710 "function foo(){ debugger; bar.apply(this, [1,2,3]); }",
3713 // Register a debug event listener which steps and counts.
3714 v8::Debug::SetDebugEventListener(DebugEventStep);
3716 step_action = StepIn;
3717 break_point_hit_count = 0;
3718 foo->Call(env->Global(), 0, NULL);
3720 // With stepping all break locations are hit.
3721 CHECK_EQ(7, break_point_hit_count);
3723 v8::Debug::SetDebugEventListener(NULL);
3724 CheckDebuggerUnloaded();
3726 // Register a debug event listener which just counts.
3727 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
3729 break_point_hit_count = 0;
3730 foo->Call(env->Global(), 0, NULL);
3732 // Without stepping only the debugger statement is hit.
3733 CHECK_EQ(1, break_point_hit_count);
3735 v8::Debug::SetDebugEventListener(NULL);
3736 CheckDebuggerUnloaded();
3740 // Test that step in works with function.call.
3741 TEST(DebugStepFunctionCall) {
3742 DebugLocalContext env;
3743 v8::Isolate* isolate = env->GetIsolate();
3744 v8::HandleScope scope(isolate);
3746 // Create a function for testing stepping.
3747 v8::Local<v8::Function> foo = CompileFunction(
3749 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
3750 "function foo(a){ debugger;"
3752 " bar.call(this, 1, 2, 3);"
3754 " bar.call(this, 0);"
3759 // Register a debug event listener which steps and counts.
3760 v8::Debug::SetDebugEventListener(DebugEventStep);
3761 step_action = StepIn;
3763 // Check stepping where the if condition in bar is false.
3764 break_point_hit_count = 0;
3765 foo->Call(env->Global(), 0, NULL);
3766 CHECK_EQ(6, break_point_hit_count);
3768 // Check stepping where the if condition in bar is true.
3769 break_point_hit_count = 0;
3771 v8::Handle<v8::Value> argv[argc] = { v8::True(isolate) };
3772 foo->Call(env->Global(), argc, argv);
3773 CHECK_EQ(8, break_point_hit_count);
3775 v8::Debug::SetDebugEventListener(NULL);
3776 CheckDebuggerUnloaded();
3778 // Register a debug event listener which just counts.
3779 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
3781 break_point_hit_count = 0;
3782 foo->Call(env->Global(), 0, NULL);
3784 // Without stepping only the debugger statement is hit.
3785 CHECK_EQ(1, break_point_hit_count);
3787 v8::Debug::SetDebugEventListener(NULL);
3788 CheckDebuggerUnloaded();
3792 // Tests that breakpoint will be hit if it's set in script.
3793 TEST(PauseInScript) {
3794 DebugLocalContext env;
3795 v8::HandleScope scope(env->GetIsolate());
3798 // Register a debug event listener which counts.
3799 v8::Debug::SetDebugEventListener(DebugEventCounter);
3801 // Create a script that returns a function.
3802 const char* src = "(function (evt) {})";
3803 const char* script_name = "StepInHandlerTest";
3805 // Set breakpoint in the script.
3806 SetScriptBreakPointByNameFromJS(env->GetIsolate(), script_name, 0, -1);
3807 break_point_hit_count = 0;
3809 v8::ScriptOrigin origin(
3810 v8::String::NewFromUtf8(env->GetIsolate(), script_name),
3811 v8::Integer::New(env->GetIsolate(), 0));
3812 v8::Handle<v8::Script> script = v8::Script::Compile(
3813 v8::String::NewFromUtf8(env->GetIsolate(), src), &origin);
3814 v8::Local<v8::Value> r = script->Run();
3816 CHECK(r->IsFunction());
3817 CHECK_EQ(1, break_point_hit_count);
3819 // Get rid of the debug event listener.
3820 v8::Debug::SetDebugEventListener(NULL);
3821 CheckDebuggerUnloaded();
3825 // Test break on exceptions. For each exception break combination the number
3826 // of debug event exception callbacks and message callbacks are collected. The
3827 // number of debug event exception callbacks are used to check that the
3828 // debugger is called correctly and the number of message callbacks is used to
3829 // check that uncaught exceptions are still returned even if there is a break
3831 TEST(BreakOnException) {
3832 DebugLocalContext env;
3833 v8::HandleScope scope(env->GetIsolate());
3836 // Create functions for testing break on exception.
3837 CompileFunction(&env, "function throws(){throw 1;}", "throws");
3838 v8::Local<v8::Function> caught =
3839 CompileFunction(&env,
3840 "function caught(){try {throws();} catch(e) {};}",
3842 v8::Local<v8::Function> notCaught =
3843 CompileFunction(&env, "function notCaught(){throws();}", "notCaught");
3845 v8::V8::AddMessageListener(MessageCallbackCount);
3846 v8::Debug::SetDebugEventListener(DebugEventCounter);
3848 // Initial state should be no break on exceptions.
3849 DebugEventCounterClear();
3850 MessageCallbackCountClear();
3851 caught->Call(env->Global(), 0, NULL);
3852 CHECK_EQ(0, exception_hit_count);
3853 CHECK_EQ(0, uncaught_exception_hit_count);
3854 CHECK_EQ(0, message_callback_count);
3855 notCaught->Call(env->Global(), 0, NULL);
3856 CHECK_EQ(0, exception_hit_count);
3857 CHECK_EQ(0, uncaught_exception_hit_count);
3858 CHECK_EQ(1, message_callback_count);
3860 // No break on exception
3861 DebugEventCounterClear();
3862 MessageCallbackCountClear();
3863 ChangeBreakOnException(false, false);
3864 caught->Call(env->Global(), 0, NULL);
3865 CHECK_EQ(0, exception_hit_count);
3866 CHECK_EQ(0, uncaught_exception_hit_count);
3867 CHECK_EQ(0, message_callback_count);
3868 notCaught->Call(env->Global(), 0, NULL);
3869 CHECK_EQ(0, exception_hit_count);
3870 CHECK_EQ(0, uncaught_exception_hit_count);
3871 CHECK_EQ(1, message_callback_count);
3873 // Break on uncaught exception
3874 DebugEventCounterClear();
3875 MessageCallbackCountClear();
3876 ChangeBreakOnException(false, true);
3877 caught->Call(env->Global(), 0, NULL);
3878 CHECK_EQ(0, exception_hit_count);
3879 CHECK_EQ(0, uncaught_exception_hit_count);
3880 CHECK_EQ(0, message_callback_count);
3881 notCaught->Call(env->Global(), 0, NULL);
3882 CHECK_EQ(1, exception_hit_count);
3883 CHECK_EQ(1, uncaught_exception_hit_count);
3884 CHECK_EQ(1, message_callback_count);
3886 // Break on exception and uncaught exception
3887 DebugEventCounterClear();
3888 MessageCallbackCountClear();
3889 ChangeBreakOnException(true, true);
3890 caught->Call(env->Global(), 0, NULL);
3891 CHECK_EQ(1, exception_hit_count);
3892 CHECK_EQ(0, uncaught_exception_hit_count);
3893 CHECK_EQ(0, message_callback_count);
3894 notCaught->Call(env->Global(), 0, NULL);
3895 CHECK_EQ(2, exception_hit_count);
3896 CHECK_EQ(1, uncaught_exception_hit_count);
3897 CHECK_EQ(1, message_callback_count);
3899 // Break on exception
3900 DebugEventCounterClear();
3901 MessageCallbackCountClear();
3902 ChangeBreakOnException(true, false);
3903 caught->Call(env->Global(), 0, NULL);
3904 CHECK_EQ(1, exception_hit_count);
3905 CHECK_EQ(0, uncaught_exception_hit_count);
3906 CHECK_EQ(0, message_callback_count);
3907 notCaught->Call(env->Global(), 0, NULL);
3908 CHECK_EQ(2, exception_hit_count);
3909 CHECK_EQ(1, uncaught_exception_hit_count);
3910 CHECK_EQ(1, message_callback_count);
3912 // No break on exception using JavaScript
3913 DebugEventCounterClear();
3914 MessageCallbackCountClear();
3915 ChangeBreakOnExceptionFromJS(env->GetIsolate(), false, false);
3916 caught->Call(env->Global(), 0, NULL);
3917 CHECK_EQ(0, exception_hit_count);
3918 CHECK_EQ(0, uncaught_exception_hit_count);
3919 CHECK_EQ(0, message_callback_count);
3920 notCaught->Call(env->Global(), 0, NULL);
3921 CHECK_EQ(0, exception_hit_count);
3922 CHECK_EQ(0, uncaught_exception_hit_count);
3923 CHECK_EQ(1, message_callback_count);
3925 // Break on uncaught exception using JavaScript
3926 DebugEventCounterClear();
3927 MessageCallbackCountClear();
3928 ChangeBreakOnExceptionFromJS(env->GetIsolate(), false, true);
3929 caught->Call(env->Global(), 0, NULL);
3930 CHECK_EQ(0, exception_hit_count);
3931 CHECK_EQ(0, uncaught_exception_hit_count);
3932 CHECK_EQ(0, message_callback_count);
3933 notCaught->Call(env->Global(), 0, NULL);
3934 CHECK_EQ(1, exception_hit_count);
3935 CHECK_EQ(1, uncaught_exception_hit_count);
3936 CHECK_EQ(1, message_callback_count);
3938 // Break on exception and uncaught exception using JavaScript
3939 DebugEventCounterClear();
3940 MessageCallbackCountClear();
3941 ChangeBreakOnExceptionFromJS(env->GetIsolate(), true, true);
3942 caught->Call(env->Global(), 0, NULL);
3943 CHECK_EQ(1, exception_hit_count);
3944 CHECK_EQ(0, message_callback_count);
3945 CHECK_EQ(0, uncaught_exception_hit_count);
3946 notCaught->Call(env->Global(), 0, NULL);
3947 CHECK_EQ(2, exception_hit_count);
3948 CHECK_EQ(1, uncaught_exception_hit_count);
3949 CHECK_EQ(1, message_callback_count);
3951 // Break on exception using JavaScript
3952 DebugEventCounterClear();
3953 MessageCallbackCountClear();
3954 ChangeBreakOnExceptionFromJS(env->GetIsolate(), true, false);
3955 caught->Call(env->Global(), 0, NULL);
3956 CHECK_EQ(1, exception_hit_count);
3957 CHECK_EQ(0, uncaught_exception_hit_count);
3958 CHECK_EQ(0, message_callback_count);
3959 notCaught->Call(env->Global(), 0, NULL);
3960 CHECK_EQ(2, exception_hit_count);
3961 CHECK_EQ(1, uncaught_exception_hit_count);
3962 CHECK_EQ(1, message_callback_count);
3964 v8::Debug::SetDebugEventListener(NULL);
3965 CheckDebuggerUnloaded();
3966 v8::V8::RemoveMessageListeners(MessageCallbackCount);
3970 // Test break on exception from compiler errors. When compiling using
3971 // v8::Script::Compile there is no JavaScript stack whereas when compiling using
3972 // eval there are JavaScript frames.
3973 TEST(BreakOnCompileException) {
3974 DebugLocalContext env;
3975 v8::HandleScope scope(env->GetIsolate());
3977 // For this test, we want to break on uncaught exceptions:
3978 ChangeBreakOnException(false, true);
3980 // Create a function for checking the function when hitting a break point.
3981 frame_count = CompileFunction(&env, frame_count_source, "frame_count");
3983 v8::V8::AddMessageListener(MessageCallbackCount);
3984 v8::Debug::SetDebugEventListener(DebugEventCounter);
3986 DebugEventCounterClear();
3987 MessageCallbackCountClear();
3989 // Check initial state.
3990 CHECK_EQ(0, exception_hit_count);
3991 CHECK_EQ(0, uncaught_exception_hit_count);
3992 CHECK_EQ(0, message_callback_count);
3993 CHECK_EQ(-1, last_js_stack_height);
3995 // Throws SyntaxError: Unexpected end of input
3996 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "+++"));
3997 CHECK_EQ(1, exception_hit_count);
3998 CHECK_EQ(1, uncaught_exception_hit_count);
3999 CHECK_EQ(1, message_callback_count);
4000 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack.
4002 // Throws SyntaxError: Unexpected identifier
4003 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "x x"));
4004 CHECK_EQ(2, exception_hit_count);
4005 CHECK_EQ(2, uncaught_exception_hit_count);
4006 CHECK_EQ(2, message_callback_count);
4007 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack.
4009 // Throws SyntaxError: Unexpected end of input
4010 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "eval('+++')"))
4012 CHECK_EQ(3, exception_hit_count);
4013 CHECK_EQ(3, uncaught_exception_hit_count);
4014 CHECK_EQ(3, message_callback_count);
4015 CHECK_EQ(1, last_js_stack_height);
4017 // Throws SyntaxError: Unexpected identifier
4018 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "eval('x x')"))
4020 CHECK_EQ(4, exception_hit_count);
4021 CHECK_EQ(4, uncaught_exception_hit_count);
4022 CHECK_EQ(4, message_callback_count);
4023 CHECK_EQ(1, last_js_stack_height);
4027 TEST(StepWithException) {
4028 DebugLocalContext env;
4029 v8::HandleScope scope(env->GetIsolate());
4031 // For this test, we want to break on uncaught exceptions:
4032 ChangeBreakOnException(false, true);
4034 // Create a function for checking the function when hitting a break point.
4035 frame_function_name = CompileFunction(&env,
4036 frame_function_name_source,
4037 "frame_function_name");
4039 // Register a debug event listener which steps and counts.
4040 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
4042 // Create functions for testing stepping.
4043 const char* src = "function a() { n(); }; "
4044 "function b() { c(); }; "
4045 "function c() { n(); }; "
4046 "function d() { x = 1; try { e(); } catch(x) { x = 2; } }; "
4047 "function e() { n(); }; "
4048 "function f() { x = 1; try { g(); } catch(x) { x = 2; } }; "
4049 "function g() { h(); }; "
4050 "function h() { x = 1; throw 1; }; ";
4052 // Step through invocation of a.
4053 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
4054 SetBreakPoint(a, 0);
4055 step_action = StepIn;
4056 break_point_hit_count = 0;
4057 expected_step_sequence = "aa";
4058 a->Call(env->Global(), 0, NULL);
4059 CHECK_EQ(StrLength(expected_step_sequence),
4060 break_point_hit_count);
4062 // Step through invocation of b + c.
4063 v8::Local<v8::Function> b = CompileFunction(&env, src, "b");
4064 SetBreakPoint(b, 0);
4065 step_action = StepIn;
4066 break_point_hit_count = 0;
4067 expected_step_sequence = "bcc";
4068 b->Call(env->Global(), 0, NULL);
4069 CHECK_EQ(StrLength(expected_step_sequence),
4070 break_point_hit_count);
4071 // Step through invocation of d + e.
4072 v8::Local<v8::Function> d = CompileFunction(&env, src, "d");
4073 SetBreakPoint(d, 0);
4074 ChangeBreakOnException(false, true);
4075 step_action = StepIn;
4076 break_point_hit_count = 0;
4077 expected_step_sequence = "ddedd";
4078 d->Call(env->Global(), 0, NULL);
4079 CHECK_EQ(StrLength(expected_step_sequence),
4080 break_point_hit_count);
4082 // Step through invocation of d + e now with break on caught exceptions.
4083 ChangeBreakOnException(true, true);
4084 step_action = StepIn;
4085 break_point_hit_count = 0;
4086 expected_step_sequence = "ddeedd";
4087 d->Call(env->Global(), 0, NULL);
4088 CHECK_EQ(StrLength(expected_step_sequence),
4089 break_point_hit_count);
4091 // Step through invocation of f + g + h.
4092 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
4093 SetBreakPoint(f, 0);
4094 ChangeBreakOnException(false, true);
4095 step_action = StepIn;
4096 break_point_hit_count = 0;
4097 expected_step_sequence = "ffghhff";
4098 f->Call(env->Global(), 0, NULL);
4099 CHECK_EQ(StrLength(expected_step_sequence),
4100 break_point_hit_count);
4102 // Step through invocation of f + g + h now with break on caught exceptions.
4103 ChangeBreakOnException(true, true);
4104 step_action = StepIn;
4105 break_point_hit_count = 0;
4106 expected_step_sequence = "ffghhhff";
4107 f->Call(env->Global(), 0, NULL);
4108 CHECK_EQ(StrLength(expected_step_sequence),
4109 break_point_hit_count);
4111 // Get rid of the debug event listener.
4112 v8::Debug::SetDebugEventListener(NULL);
4113 CheckDebuggerUnloaded();
4118 i::FLAG_stress_compaction = false;
4120 i::FLAG_verify_heap = true;
4122 DebugLocalContext env;
4123 v8::Isolate* isolate = env->GetIsolate();
4124 v8::HandleScope scope(isolate);
4126 // Register a debug event listener which sets the break flag and counts.
4127 v8::Debug::SetDebugEventListener(DebugEventBreak);
4129 // Create a function for testing stepping.
4130 const char* src = "function f0() {}"
4131 "function f1(x1) {}"
4132 "function f2(x1,x2) {}"
4133 "function f3(x1,x2,x3) {}";
4134 v8::Local<v8::Function> f0 = CompileFunction(&env, src, "f0");
4135 v8::Local<v8::Function> f1 = CompileFunction(&env, src, "f1");
4136 v8::Local<v8::Function> f2 = CompileFunction(&env, src, "f2");
4137 v8::Local<v8::Function> f3 = CompileFunction(&env, src, "f3");
4139 // Call the function to make sure it is compiled.
4140 v8::Handle<v8::Value> argv[] = { v8::Number::New(isolate, 1),
4141 v8::Number::New(isolate, 1),
4142 v8::Number::New(isolate, 1),
4143 v8::Number::New(isolate, 1) };
4145 // Call all functions to make sure that they are compiled.
4146 f0->Call(env->Global(), 0, NULL);
4147 f1->Call(env->Global(), 0, NULL);
4148 f2->Call(env->Global(), 0, NULL);
4149 f3->Call(env->Global(), 0, NULL);
4151 // Set the debug break flag.
4152 v8::Debug::DebugBreak(env->GetIsolate());
4153 CHECK(v8::Debug::CheckDebugBreak(env->GetIsolate()));
4155 // Call all functions with different argument count.
4156 break_point_hit_count = 0;
4157 for (unsigned int i = 0; i < ARRAY_SIZE(argv); i++) {
4158 f0->Call(env->Global(), i, argv);
4159 f1->Call(env->Global(), i, argv);
4160 f2->Call(env->Global(), i, argv);
4161 f3->Call(env->Global(), i, argv);
4164 // One break for each function called.
4165 CHECK_EQ(4 * ARRAY_SIZE(argv), break_point_hit_count);
4167 // Get rid of the debug event listener.
4168 v8::Debug::SetDebugEventListener(NULL);
4169 CheckDebuggerUnloaded();
4173 // Test to ensure that JavaScript code keeps running while the debug break
4174 // through the stack limit flag is set but breaks are disabled.
4175 TEST(DisableBreak) {
4176 DebugLocalContext env;
4177 v8::HandleScope scope(env->GetIsolate());
4179 // Register a debug event listener which sets the break flag and counts.
4180 v8::Debug::SetDebugEventListener(DebugEventCounter);
4182 // Create a function for testing stepping.
4183 const char* src = "function f() {g()};function g(){i=0; while(i<10){i++}}";
4184 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
4186 // Set, test and cancel debug break.
4187 v8::Debug::DebugBreak(env->GetIsolate());
4188 CHECK(v8::Debug::CheckDebugBreak(env->GetIsolate()));
4189 v8::Debug::CancelDebugBreak(env->GetIsolate());
4190 CHECK(!v8::Debug::CheckDebugBreak(env->GetIsolate()));
4192 // Set the debug break flag.
4193 v8::Debug::DebugBreak(env->GetIsolate());
4195 // Call all functions with different argument count.
4196 break_point_hit_count = 0;
4197 f->Call(env->Global(), 0, NULL);
4198 CHECK_EQ(1, break_point_hit_count);
4201 v8::Debug::DebugBreak(env->GetIsolate());
4202 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(env->GetIsolate());
4203 v8::internal::DisableBreak disable_break(isolate->debug(), true);
4204 f->Call(env->Global(), 0, NULL);
4205 CHECK_EQ(1, break_point_hit_count);
4208 f->Call(env->Global(), 0, NULL);
4209 CHECK_EQ(2, break_point_hit_count);
4211 // Get rid of the debug event listener.
4212 v8::Debug::SetDebugEventListener(NULL);
4213 CheckDebuggerUnloaded();
4216 static const char* kSimpleExtensionSource =
4221 // http://crbug.com/28933
4222 // Test that debug break is disabled when bootstrapper is active.
4223 TEST(NoBreakWhenBootstrapping) {
4224 v8::Isolate* isolate = CcTest::isolate();
4225 v8::HandleScope scope(isolate);
4227 // Register a debug event listener which sets the break flag and counts.
4228 v8::Debug::SetDebugEventListener(DebugEventCounter);
4230 // Set the debug break flag.
4231 v8::Debug::DebugBreak(isolate);
4232 break_point_hit_count = 0;
4234 // Create a context with an extension to make sure that some JavaScript
4235 // code is executed during bootstrapping.
4236 v8::RegisterExtension(new v8::Extension("simpletest",
4237 kSimpleExtensionSource));
4238 const char* extension_names[] = { "simpletest" };
4239 v8::ExtensionConfiguration extensions(1, extension_names);
4240 v8::HandleScope handle_scope(isolate);
4241 v8::Context::New(isolate, &extensions);
4243 // Check that no DebugBreak events occured during the context creation.
4244 CHECK_EQ(0, break_point_hit_count);
4246 // Get rid of the debug event listener.
4247 v8::Debug::SetDebugEventListener(NULL);
4248 CheckDebuggerUnloaded();
4252 static void NamedEnum(const v8::PropertyCallbackInfo<v8::Array>& info) {
4253 v8::Handle<v8::Array> result = v8::Array::New(info.GetIsolate(), 3);
4254 result->Set(v8::Integer::New(info.GetIsolate(), 0),
4255 v8::String::NewFromUtf8(info.GetIsolate(), "a"));
4256 result->Set(v8::Integer::New(info.GetIsolate(), 1),
4257 v8::String::NewFromUtf8(info.GetIsolate(), "b"));
4258 result->Set(v8::Integer::New(info.GetIsolate(), 2),
4259 v8::String::NewFromUtf8(info.GetIsolate(), "c"));
4260 info.GetReturnValue().Set(result);
4264 static void IndexedEnum(const v8::PropertyCallbackInfo<v8::Array>& info) {
4265 v8::Isolate* isolate = info.GetIsolate();
4266 v8::Handle<v8::Array> result = v8::Array::New(isolate, 2);
4267 result->Set(v8::Integer::New(isolate, 0), v8::Number::New(isolate, 1));
4268 result->Set(v8::Integer::New(isolate, 1), v8::Number::New(isolate, 10));
4269 info.GetReturnValue().Set(result);
4273 static void NamedGetter(v8::Local<v8::String> name,
4274 const v8::PropertyCallbackInfo<v8::Value>& info) {
4275 v8::String::Utf8Value n(name);
4276 if (strcmp(*n, "a") == 0) {
4277 info.GetReturnValue().Set(v8::String::NewFromUtf8(info.GetIsolate(), "AA"));
4279 } else if (strcmp(*n, "b") == 0) {
4280 info.GetReturnValue().Set(v8::String::NewFromUtf8(info.GetIsolate(), "BB"));
4282 } else if (strcmp(*n, "c") == 0) {
4283 info.GetReturnValue().Set(v8::String::NewFromUtf8(info.GetIsolate(), "CC"));
4286 info.GetReturnValue().SetUndefined();
4289 info.GetReturnValue().Set(name);
4293 static void IndexedGetter(uint32_t index,
4294 const v8::PropertyCallbackInfo<v8::Value>& info) {
4295 info.GetReturnValue().Set(static_cast<double>(index + 1));
4299 TEST(InterceptorPropertyMirror) {
4300 // Create a V8 environment with debug access.
4301 DebugLocalContext env;
4302 v8::Isolate* isolate = env->GetIsolate();
4303 v8::HandleScope scope(isolate);
4306 // Create object with named interceptor.
4307 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(isolate);
4308 named->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum);
4310 v8::String::NewFromUtf8(isolate, "intercepted_named"),
4311 named->NewInstance());
4313 // Create object with indexed interceptor.
4314 v8::Handle<v8::ObjectTemplate> indexed = v8::ObjectTemplate::New(isolate);
4315 indexed->SetIndexedPropertyHandler(IndexedGetter,
4321 v8::String::NewFromUtf8(isolate, "intercepted_indexed"),
4322 indexed->NewInstance());
4324 // Create object with both named and indexed interceptor.
4325 v8::Handle<v8::ObjectTemplate> both = v8::ObjectTemplate::New(isolate);
4326 both->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum);
4327 both->SetIndexedPropertyHandler(IndexedGetter, NULL, NULL, NULL, IndexedEnum);
4329 v8::String::NewFromUtf8(isolate, "intercepted_both"),
4330 both->NewInstance());
4332 // Get mirrors for the three objects with interceptor.
4334 "var named_mirror = debug.MakeMirror(intercepted_named);"
4335 "var indexed_mirror = debug.MakeMirror(intercepted_indexed);"
4336 "var both_mirror = debug.MakeMirror(intercepted_both)");
4338 "named_mirror instanceof debug.ObjectMirror")->BooleanValue());
4340 "indexed_mirror instanceof debug.ObjectMirror")->BooleanValue());
4342 "both_mirror instanceof debug.ObjectMirror")->BooleanValue());
4344 // Get the property names from the interceptors
4346 "named_names = named_mirror.propertyNames();"
4347 "indexed_names = indexed_mirror.propertyNames();"
4348 "both_names = both_mirror.propertyNames()");
4349 CHECK_EQ(3, CompileRun("named_names.length")->Int32Value());
4350 CHECK_EQ(2, CompileRun("indexed_names.length")->Int32Value());
4351 CHECK_EQ(5, CompileRun("both_names.length")->Int32Value());
4353 // Check the expected number of properties.
4355 source = "named_mirror.properties().length";
4356 CHECK_EQ(3, CompileRun(source)->Int32Value());
4358 source = "indexed_mirror.properties().length";
4359 CHECK_EQ(2, CompileRun(source)->Int32Value());
4361 source = "both_mirror.properties().length";
4362 CHECK_EQ(5, CompileRun(source)->Int32Value());
4364 // 1 is PropertyKind.Named;
4365 source = "both_mirror.properties(1).length";
4366 CHECK_EQ(3, CompileRun(source)->Int32Value());
4368 // 2 is PropertyKind.Indexed;
4369 source = "both_mirror.properties(2).length";
4370 CHECK_EQ(2, CompileRun(source)->Int32Value());
4372 // 3 is PropertyKind.Named | PropertyKind.Indexed;
4373 source = "both_mirror.properties(3).length";
4374 CHECK_EQ(5, CompileRun(source)->Int32Value());
4376 // Get the interceptor properties for the object with only named interceptor.
4377 CompileRun("var named_values = named_mirror.properties()");
4379 // Check that the properties are interceptor properties.
4380 for (int i = 0; i < 3; i++) {
4381 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
4383 "named_values[%d] instanceof debug.PropertyMirror", i);
4384 CHECK(CompileRun(buffer.start())->BooleanValue());
4386 SNPrintF(buffer, "named_values[%d].propertyType()", i);
4387 CHECK_EQ(v8::internal::INTERCEPTOR,
4388 CompileRun(buffer.start())->Int32Value());
4390 SNPrintF(buffer, "named_values[%d].isNative()", i);
4391 CHECK(CompileRun(buffer.start())->BooleanValue());
4394 // Get the interceptor properties for the object with only indexed
4396 CompileRun("var indexed_values = indexed_mirror.properties()");
4398 // Check that the properties are interceptor properties.
4399 for (int i = 0; i < 2; i++) {
4400 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
4402 "indexed_values[%d] instanceof debug.PropertyMirror", i);
4403 CHECK(CompileRun(buffer.start())->BooleanValue());
4406 // Get the interceptor properties for the object with both types of
4408 CompileRun("var both_values = both_mirror.properties()");
4410 // Check that the properties are interceptor properties.
4411 for (int i = 0; i < 5; i++) {
4412 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
4413 SNPrintF(buffer, "both_values[%d] instanceof debug.PropertyMirror", i);
4414 CHECK(CompileRun(buffer.start())->BooleanValue());
4417 // Check the property names.
4418 source = "both_values[0].name() == 'a'";
4419 CHECK(CompileRun(source)->BooleanValue());
4421 source = "both_values[1].name() == 'b'";
4422 CHECK(CompileRun(source)->BooleanValue());
4424 source = "both_values[2].name() == 'c'";
4425 CHECK(CompileRun(source)->BooleanValue());
4427 source = "both_values[3].name() == 1";
4428 CHECK(CompileRun(source)->BooleanValue());
4430 source = "both_values[4].name() == 10";
4431 CHECK(CompileRun(source)->BooleanValue());
4435 TEST(HiddenPrototypePropertyMirror) {
4436 // Create a V8 environment with debug access.
4437 DebugLocalContext env;
4438 v8::Isolate* isolate = env->GetIsolate();
4439 v8::HandleScope scope(isolate);
4442 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New(isolate);
4443 t0->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "x"),
4444 v8::Number::New(isolate, 0));
4445 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New(isolate);
4446 t1->SetHiddenPrototype(true);
4447 t1->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "y"),
4448 v8::Number::New(isolate, 1));
4449 v8::Handle<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New(isolate);
4450 t2->SetHiddenPrototype(true);
4451 t2->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "z"),
4452 v8::Number::New(isolate, 2));
4453 v8::Handle<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New(isolate);
4454 t3->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "u"),
4455 v8::Number::New(isolate, 3));
4457 // Create object and set them on the global object.
4458 v8::Handle<v8::Object> o0 = t0->GetFunction()->NewInstance();
4459 env->Global()->Set(v8::String::NewFromUtf8(isolate, "o0"), o0);
4460 v8::Handle<v8::Object> o1 = t1->GetFunction()->NewInstance();
4461 env->Global()->Set(v8::String::NewFromUtf8(isolate, "o1"), o1);
4462 v8::Handle<v8::Object> o2 = t2->GetFunction()->NewInstance();
4463 env->Global()->Set(v8::String::NewFromUtf8(isolate, "o2"), o2);
4464 v8::Handle<v8::Object> o3 = t3->GetFunction()->NewInstance();
4465 env->Global()->Set(v8::String::NewFromUtf8(isolate, "o3"), o3);
4467 // Get mirrors for the four objects.
4469 "var o0_mirror = debug.MakeMirror(o0);"
4470 "var o1_mirror = debug.MakeMirror(o1);"
4471 "var o2_mirror = debug.MakeMirror(o2);"
4472 "var o3_mirror = debug.MakeMirror(o3)");
4473 CHECK(CompileRun("o0_mirror instanceof debug.ObjectMirror")->BooleanValue());
4474 CHECK(CompileRun("o1_mirror instanceof debug.ObjectMirror")->BooleanValue());
4475 CHECK(CompileRun("o2_mirror instanceof debug.ObjectMirror")->BooleanValue());
4476 CHECK(CompileRun("o3_mirror instanceof debug.ObjectMirror")->BooleanValue());
4478 // Check that each object has one property.
4479 CHECK_EQ(1, CompileRun(
4480 "o0_mirror.propertyNames().length")->Int32Value());
4481 CHECK_EQ(1, CompileRun(
4482 "o1_mirror.propertyNames().length")->Int32Value());
4483 CHECK_EQ(1, CompileRun(
4484 "o2_mirror.propertyNames().length")->Int32Value());
4485 CHECK_EQ(1, CompileRun(
4486 "o3_mirror.propertyNames().length")->Int32Value());
4488 // Set o1 as prototype for o0. o1 has the hidden prototype flag so all
4489 // properties on o1 should be seen on o0.
4490 o0->Set(v8::String::NewFromUtf8(isolate, "__proto__"), o1);
4491 CHECK_EQ(2, CompileRun(
4492 "o0_mirror.propertyNames().length")->Int32Value());
4493 CHECK_EQ(0, CompileRun(
4494 "o0_mirror.property('x').value().value()")->Int32Value());
4495 CHECK_EQ(1, CompileRun(
4496 "o0_mirror.property('y').value().value()")->Int32Value());
4498 // Set o2 as prototype for o0 (it will end up after o1 as o1 has the hidden
4499 // prototype flag. o2 also has the hidden prototype flag so all properties
4500 // on o2 should be seen on o0 as well as properties on o1.
4501 o0->Set(v8::String::NewFromUtf8(isolate, "__proto__"), o2);
4502 CHECK_EQ(3, CompileRun(
4503 "o0_mirror.propertyNames().length")->Int32Value());
4504 CHECK_EQ(0, CompileRun(
4505 "o0_mirror.property('x').value().value()")->Int32Value());
4506 CHECK_EQ(1, CompileRun(
4507 "o0_mirror.property('y').value().value()")->Int32Value());
4508 CHECK_EQ(2, CompileRun(
4509 "o0_mirror.property('z').value().value()")->Int32Value());
4511 // Set o3 as prototype for o0 (it will end up after o1 and o2 as both o1 and
4512 // o2 has the hidden prototype flag. o3 does not have the hidden prototype
4513 // flag so properties on o3 should not be seen on o0 whereas the properties
4514 // from o1 and o2 should still be seen on o0.
4515 // Final prototype chain: o0 -> o1 -> o2 -> o3
4516 // Hidden prototypes: ^^ ^^
4517 o0->Set(v8::String::NewFromUtf8(isolate, "__proto__"), o3);
4518 CHECK_EQ(3, CompileRun(
4519 "o0_mirror.propertyNames().length")->Int32Value());
4520 CHECK_EQ(1, CompileRun(
4521 "o3_mirror.propertyNames().length")->Int32Value());
4522 CHECK_EQ(0, CompileRun(
4523 "o0_mirror.property('x').value().value()")->Int32Value());
4524 CHECK_EQ(1, CompileRun(
4525 "o0_mirror.property('y').value().value()")->Int32Value());
4526 CHECK_EQ(2, CompileRun(
4527 "o0_mirror.property('z').value().value()")->Int32Value());
4528 CHECK(CompileRun("o0_mirror.property('u').isUndefined()")->BooleanValue());
4530 // The prototype (__proto__) for o0 should be o3 as o1 and o2 are hidden.
4531 CHECK(CompileRun("o0_mirror.protoObject() == o3_mirror")->BooleanValue());
4535 static void ProtperyXNativeGetter(
4536 v8::Local<v8::String> property,
4537 const v8::PropertyCallbackInfo<v8::Value>& info) {
4538 info.GetReturnValue().Set(10);
4542 TEST(NativeGetterPropertyMirror) {
4543 // Create a V8 environment with debug access.
4544 DebugLocalContext env;
4545 v8::Isolate* isolate = env->GetIsolate();
4546 v8::HandleScope scope(isolate);
4549 v8::Handle<v8::String> name = v8::String::NewFromUtf8(isolate, "x");
4550 // Create object with named accessor.
4551 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(isolate);
4552 named->SetAccessor(name, &ProtperyXNativeGetter, NULL,
4553 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None);
4555 // Create object with named property getter.
4556 env->Global()->Set(v8::String::NewFromUtf8(isolate, "instance"),
4557 named->NewInstance());
4558 CHECK_EQ(10, CompileRun("instance.x")->Int32Value());
4560 // Get mirror for the object with property getter.
4561 CompileRun("var instance_mirror = debug.MakeMirror(instance);");
4563 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue());
4565 CompileRun("var named_names = instance_mirror.propertyNames();");
4566 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
4567 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue());
4569 "instance_mirror.property('x').value().isNumber()")->BooleanValue());
4571 "instance_mirror.property('x').value().value() == 10")->BooleanValue());
4575 static void ProtperyXNativeGetterThrowingError(
4576 v8::Local<v8::String> property,
4577 const v8::PropertyCallbackInfo<v8::Value>& info) {
4578 CompileRun("throw new Error('Error message');");
4582 TEST(NativeGetterThrowingErrorPropertyMirror) {
4583 // Create a V8 environment with debug access.
4584 DebugLocalContext env;
4585 v8::Isolate* isolate = env->GetIsolate();
4586 v8::HandleScope scope(isolate);
4589 v8::Handle<v8::String> name = v8::String::NewFromUtf8(isolate, "x");
4590 // Create object with named accessor.
4591 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(isolate);
4592 named->SetAccessor(name, &ProtperyXNativeGetterThrowingError, NULL,
4593 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None);
4595 // Create object with named property getter.
4596 env->Global()->Set(v8::String::NewFromUtf8(isolate, "instance"),
4597 named->NewInstance());
4599 // Get mirror for the object with property getter.
4600 CompileRun("var instance_mirror = debug.MakeMirror(instance);");
4602 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue());
4603 CompileRun("named_names = instance_mirror.propertyNames();");
4604 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
4605 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue());
4607 "instance_mirror.property('x').value().isError()")->BooleanValue());
4609 // Check that the message is that passed to the Error constructor.
4611 "instance_mirror.property('x').value().message() == 'Error message'")->
4616 // Test that hidden properties object is not returned as an unnamed property
4617 // among regular properties.
4618 // See http://crbug.com/26491
4619 TEST(NoHiddenProperties) {
4620 // Create a V8 environment with debug access.
4621 DebugLocalContext env;
4622 v8::Isolate* isolate = env->GetIsolate();
4623 v8::HandleScope scope(isolate);
4626 // Create an object in the global scope.
4627 const char* source = "var obj = {a: 1};";
4628 v8::Script::Compile(v8::String::NewFromUtf8(isolate, source))
4630 v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(
4631 env->Global()->Get(v8::String::NewFromUtf8(isolate, "obj")));
4632 // Set a hidden property on the object.
4633 obj->SetHiddenValue(
4634 v8::String::NewFromUtf8(isolate, "v8::test-debug::a"),
4635 v8::Int32::New(isolate, 11));
4637 // Get mirror for the object with property getter.
4638 CompileRun("var obj_mirror = debug.MakeMirror(obj);");
4640 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue());
4641 CompileRun("var named_names = obj_mirror.propertyNames();");
4642 // There should be exactly one property. But there is also an unnamed
4643 // property whose value is hidden properties dictionary. The latter
4644 // property should not be in the list of reguar properties.
4645 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
4646 CHECK(CompileRun("named_names[0] == 'a'")->BooleanValue());
4648 "obj_mirror.property('a').value().value() == 1")->BooleanValue());
4650 // Object created by t0 will become hidden prototype of object 'obj'.
4651 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New(isolate);
4652 t0->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "b"),
4653 v8::Number::New(isolate, 2));
4654 t0->SetHiddenPrototype(true);
4655 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New(isolate);
4656 t1->InstanceTemplate()->Set(v8::String::NewFromUtf8(isolate, "c"),
4657 v8::Number::New(isolate, 3));
4659 // Create proto objects, add hidden properties to them and set them on
4660 // the global object.
4661 v8::Handle<v8::Object> protoObj = t0->GetFunction()->NewInstance();
4662 protoObj->SetHiddenValue(
4663 v8::String::NewFromUtf8(isolate, "v8::test-debug::b"),
4664 v8::Int32::New(isolate, 12));
4665 env->Global()->Set(v8::String::NewFromUtf8(isolate, "protoObj"),
4667 v8::Handle<v8::Object> grandProtoObj = t1->GetFunction()->NewInstance();
4668 grandProtoObj->SetHiddenValue(
4669 v8::String::NewFromUtf8(isolate, "v8::test-debug::c"),
4670 v8::Int32::New(isolate, 13));
4672 v8::String::NewFromUtf8(isolate, "grandProtoObj"),
4675 // Setting prototypes: obj->protoObj->grandProtoObj
4676 protoObj->Set(v8::String::NewFromUtf8(isolate, "__proto__"),
4678 obj->Set(v8::String::NewFromUtf8(isolate, "__proto__"), protoObj);
4680 // Get mirror for the object with property getter.
4681 CompileRun("var obj_mirror = debug.MakeMirror(obj);");
4683 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue());
4684 CompileRun("var named_names = obj_mirror.propertyNames();");
4685 // There should be exactly two properties - one from the object itself and
4686 // another from its hidden prototype.
4687 CHECK_EQ(2, CompileRun("named_names.length")->Int32Value());
4688 CHECK(CompileRun("named_names.sort(); named_names[0] == 'a' &&"
4689 "named_names[1] == 'b'")->BooleanValue());
4691 "obj_mirror.property('a').value().value() == 1")->BooleanValue());
4693 "obj_mirror.property('b').value().value() == 2")->BooleanValue());
4697 // Multithreaded tests of JSON debugger protocol
4701 // Provides synchronization between N threads, where N is a template parameter.
4702 // The Wait() call blocks a thread until it is called for the Nth time, then all
4703 // calls return. Each ThreadBarrier object can only be used once.
4705 class ThreadBarrier V8_FINAL {
4707 ThreadBarrier() : num_blocked_(0) {}
4710 LockGuard<Mutex> lock_guard(&mutex_);
4711 if (num_blocked_ != 0) {
4712 CHECK_EQ(N, num_blocked_);
4717 LockGuard<Mutex> lock_guard(&mutex_);
4718 CHECK_LT(num_blocked_, N);
4720 if (N == num_blocked_) {
4721 // Signal and unblock all waiting threads.
4723 printf("BARRIER\n\n");
4725 } else { // Wait for the semaphore.
4726 while (num_blocked_ < N) {
4730 CHECK_EQ(N, num_blocked_);
4734 ConditionVariable cv_;
4738 STATIC_ASSERT(N > 0);
4740 DISALLOW_COPY_AND_ASSIGN(ThreadBarrier);
4744 // A set containing enough barriers and semaphores for any of the tests.
4747 Barriers() : semaphore_1(0), semaphore_2(0) {}
4748 ThreadBarrier<2> barrier_1;
4749 ThreadBarrier<2> barrier_2;
4750 ThreadBarrier<2> barrier_3;
4751 ThreadBarrier<2> barrier_4;
4752 ThreadBarrier<2> barrier_5;
4753 v8::base::Semaphore semaphore_1;
4754 v8::base::Semaphore semaphore_2;
4758 // We match parts of the message to decide if it is a break message.
4759 bool IsBreakEventMessage(char *message) {
4760 const char* type_event = "\"type\":\"event\"";
4761 const char* event_break = "\"event\":\"break\"";
4762 // Does the message contain both type:event and event:break?
4763 return strstr(message, type_event) != NULL &&
4764 strstr(message, event_break) != NULL;
4768 // We match parts of the message to decide if it is a exception message.
4769 bool IsExceptionEventMessage(char *message) {
4770 const char* type_event = "\"type\":\"event\"";
4771 const char* event_exception = "\"event\":\"exception\"";
4772 // Does the message contain both type:event and event:exception?
4773 return strstr(message, type_event) != NULL &&
4774 strstr(message, event_exception) != NULL;
4778 // We match the message wether it is an evaluate response message.
4779 bool IsEvaluateResponseMessage(char* message) {
4780 const char* type_response = "\"type\":\"response\"";
4781 const char* command_evaluate = "\"command\":\"evaluate\"";
4782 // Does the message contain both type:response and command:evaluate?
4783 return strstr(message, type_response) != NULL &&
4784 strstr(message, command_evaluate) != NULL;
4788 static int StringToInt(const char* s) {
4789 return atoi(s); // NOLINT
4793 // We match parts of the message to get evaluate result int value.
4794 int GetEvaluateIntResult(char *message) {
4795 const char* value = "\"value\":";
4796 char* pos = strstr(message, value);
4801 res = StringToInt(pos + strlen(value));
4806 // We match parts of the message to get hit breakpoint id.
4807 int GetBreakpointIdFromBreakEventMessage(char *message) {
4808 const char* breakpoints = "\"breakpoints\":[";
4809 char* pos = strstr(message, breakpoints);
4814 res = StringToInt(pos + strlen(breakpoints));
4819 // We match parts of the message to get total frames number.
4820 int GetTotalFramesInt(char *message) {
4821 const char* prefix = "\"totalFrames\":";
4822 char* pos = strstr(message, prefix);
4826 pos += strlen(prefix);
4827 int res = StringToInt(pos);
4832 // We match parts of the message to get source line.
4833 int GetSourceLineFromBreakEventMessage(char *message) {
4834 const char* source_line = "\"sourceLine\":";
4835 char* pos = strstr(message, source_line);
4840 res = StringToInt(pos + strlen(source_line));
4845 /* Test MessageQueues */
4846 /* Tests the message queues that hold debugger commands and
4847 * response messages to the debugger. Fills queues and makes
4850 Barriers message_queue_barriers;
4852 // This is the debugger thread, that executes no v8 calls except
4853 // placing JSON debugger commands in the queue.
4854 class MessageQueueDebuggerThread : public v8::base::Thread {
4856 MessageQueueDebuggerThread()
4857 : Thread(Options("MessageQueueDebuggerThread")) {}
4862 static void MessageHandler(const v8::Debug::Message& message) {
4863 v8::Handle<v8::String> json = message.GetJSON();
4864 v8::String::Utf8Value utf8(json);
4865 if (IsBreakEventMessage(*utf8)) {
4866 // Lets test script wait until break occurs to send commands.
4867 // Signals when a break is reported.
4868 message_queue_barriers.semaphore_2.Signal();
4871 // Allow message handler to block on a semaphore, to test queueing of
4872 // messages while blocked.
4873 message_queue_barriers.semaphore_1.Wait();
4877 void MessageQueueDebuggerThread::Run() {
4878 const int kBufferSize = 1000;
4879 uint16_t buffer_1[kBufferSize];
4880 uint16_t buffer_2[kBufferSize];
4881 const char* command_1 =
4883 "\"type\":\"request\","
4884 "\"command\":\"evaluate\","
4885 "\"arguments\":{\"expression\":\"1+2\"}}";
4886 const char* command_2 =
4888 "\"type\":\"request\","
4889 "\"command\":\"evaluate\","
4890 "\"arguments\":{\"expression\":\"1+a\"}}";
4891 const char* command_3 =
4893 "\"type\":\"request\","
4894 "\"command\":\"evaluate\","
4895 "\"arguments\":{\"expression\":\"c.d * b\"}}";
4896 const char* command_continue =
4898 "\"type\":\"request\","
4899 "\"command\":\"continue\"}";
4900 const char* command_single_step =
4902 "\"type\":\"request\","
4903 "\"command\":\"continue\","
4904 "\"arguments\":{\"stepaction\":\"next\"}}";
4906 /* Interleaved sequence of actions by the two threads:*/
4907 // Main thread compiles and runs source_1
4908 message_queue_barriers.semaphore_1.Signal();
4909 message_queue_barriers.barrier_1.Wait();
4910 // Post 6 commands, filling the command queue and making it expand.
4911 // These calls return immediately, but the commands stay on the queue
4912 // until the execution of source_2.
4913 // Note: AsciiToUtf16 executes before SendCommand, so command is copied
4914 // to buffer before buffer is sent to SendCommand.
4915 v8::Isolate* isolate = CcTest::isolate();
4916 v8::Debug::SendCommand(isolate, buffer_1, AsciiToUtf16(command_1, buffer_1));
4917 v8::Debug::SendCommand(isolate, buffer_2, AsciiToUtf16(command_2, buffer_2));
4918 v8::Debug::SendCommand(isolate, buffer_2, AsciiToUtf16(command_3, buffer_2));
4919 v8::Debug::SendCommand(isolate, buffer_2, AsciiToUtf16(command_3, buffer_2));
4920 v8::Debug::SendCommand(isolate, buffer_2, AsciiToUtf16(command_3, buffer_2));
4921 message_queue_barriers.barrier_2.Wait();
4922 // Main thread compiles and runs source_2.
4923 // Queued commands are executed at the start of compilation of source_2(
4924 // beforeCompile event).
4925 // Free the message handler to process all the messages from the queue. 7
4926 // messages are expected: 2 afterCompile events and 5 responses.
4927 // All the commands added so far will fail to execute as long as call stack
4928 // is empty on beforeCompile event.
4929 for (int i = 0; i < 6 ; ++i) {
4930 message_queue_barriers.semaphore_1.Signal();
4932 message_queue_barriers.barrier_3.Wait();
4933 // Main thread compiles and runs source_3.
4934 // Don't stop in the afterCompile handler.
4935 message_queue_barriers.semaphore_1.Signal();
4936 // source_3 includes a debugger statement, which causes a break event.
4937 // Wait on break event from hitting "debugger" statement
4938 message_queue_barriers.semaphore_2.Wait();
4939 // These should execute after the "debugger" statement in source_2
4940 v8::Debug::SendCommand(isolate, buffer_1, AsciiToUtf16(command_1, buffer_1));
4941 v8::Debug::SendCommand(isolate, buffer_2, AsciiToUtf16(command_2, buffer_2));
4942 v8::Debug::SendCommand(isolate, buffer_2, AsciiToUtf16(command_3, buffer_2));
4943 v8::Debug::SendCommand(
4944 isolate, buffer_2, AsciiToUtf16(command_single_step, buffer_2));
4945 // Run after 2 break events, 4 responses.
4946 for (int i = 0; i < 6 ; ++i) {
4947 message_queue_barriers.semaphore_1.Signal();
4949 // Wait on break event after a single step executes.
4950 message_queue_barriers.semaphore_2.Wait();
4951 v8::Debug::SendCommand(isolate, buffer_1, AsciiToUtf16(command_2, buffer_1));
4952 v8::Debug::SendCommand(
4953 isolate, buffer_2, AsciiToUtf16(command_continue, buffer_2));
4954 // Run after 2 responses.
4955 for (int i = 0; i < 2 ; ++i) {
4956 message_queue_barriers.semaphore_1.Signal();
4958 // Main thread continues running source_3 to end, waits for this thread.
4962 // This thread runs the v8 engine.
4963 TEST(MessageQueues) {
4964 MessageQueueDebuggerThread message_queue_debugger_thread;
4966 // Create a V8 environment
4967 DebugLocalContext env;
4968 v8::HandleScope scope(env->GetIsolate());
4969 v8::Debug::SetMessageHandler(MessageHandler);
4970 message_queue_debugger_thread.Start();
4972 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
4973 const char* source_2 = "e = 17;";
4974 const char* source_3 = "a = 4; debugger; a = 5; a = 6; a = 7;";
4976 // See MessageQueueDebuggerThread::Run for interleaved sequence of
4977 // API calls and events in the two threads.
4978 CompileRun(source_1);
4979 message_queue_barriers.barrier_1.Wait();
4980 message_queue_barriers.barrier_2.Wait();
4981 CompileRun(source_2);
4982 message_queue_barriers.barrier_3.Wait();
4983 CompileRun(source_3);
4984 message_queue_debugger_thread.Join();
4989 class TestClientData : public v8::Debug::ClientData {
4992 constructor_call_counter++;
4994 virtual ~TestClientData() {
4995 destructor_call_counter++;
4998 static void ResetCounters() {
4999 constructor_call_counter = 0;
5000 destructor_call_counter = 0;
5003 static int constructor_call_counter;
5004 static int destructor_call_counter;
5007 int TestClientData::constructor_call_counter = 0;
5008 int TestClientData::destructor_call_counter = 0;
5011 // Tests that MessageQueue doesn't destroy client data when expands and
5012 // does destroy when it dies.
5013 TEST(MessageQueueExpandAndDestroy) {
5014 TestClientData::ResetCounters();
5015 { // Create a scope for the queue.
5016 CommandMessageQueue queue(1);
5017 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5018 new TestClientData()));
5019 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5020 new TestClientData()));
5021 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5022 new TestClientData()));
5023 CHECK_EQ(0, TestClientData::destructor_call_counter);
5024 queue.Get().Dispose();
5025 CHECK_EQ(1, TestClientData::destructor_call_counter);
5026 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5027 new TestClientData()));
5028 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5029 new TestClientData()));
5030 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5031 new TestClientData()));
5032 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5033 new TestClientData()));
5034 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
5035 new TestClientData()));
5036 CHECK_EQ(1, TestClientData::destructor_call_counter);
5037 queue.Get().Dispose();
5038 CHECK_EQ(2, TestClientData::destructor_call_counter);
5040 // All the client data should be destroyed when the queue is destroyed.
5041 CHECK_EQ(TestClientData::destructor_call_counter,
5042 TestClientData::destructor_call_counter);
5046 static int handled_client_data_instances_count = 0;
5047 static void MessageHandlerCountingClientData(
5048 const v8::Debug::Message& message) {
5049 if (message.GetClientData() != NULL) {
5050 handled_client_data_instances_count++;
5055 // Tests that all client data passed to the debugger are sent to the handler.
5056 TEST(SendClientDataToHandler) {
5057 // Create a V8 environment
5058 DebugLocalContext env;
5059 v8::Isolate* isolate = env->GetIsolate();
5060 v8::HandleScope scope(isolate);
5061 TestClientData::ResetCounters();
5062 handled_client_data_instances_count = 0;
5063 v8::Debug::SetMessageHandler(MessageHandlerCountingClientData);
5064 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
5065 const int kBufferSize = 1000;
5066 uint16_t buffer[kBufferSize];
5067 const char* command_1 =
5069 "\"type\":\"request\","
5070 "\"command\":\"evaluate\","
5071 "\"arguments\":{\"expression\":\"1+2\"}}";
5072 const char* command_2 =
5074 "\"type\":\"request\","
5075 "\"command\":\"evaluate\","
5076 "\"arguments\":{\"expression\":\"1+a\"}}";
5077 const char* command_continue =
5079 "\"type\":\"request\","
5080 "\"command\":\"continue\"}";
5082 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_1, buffer),
5083 new TestClientData());
5084 v8::Debug::SendCommand(
5085 isolate, buffer, AsciiToUtf16(command_2, buffer), NULL);
5086 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_2, buffer),
5087 new TestClientData());
5088 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_2, buffer),
5089 new TestClientData());
5090 // All the messages will be processed on beforeCompile event.
5091 CompileRun(source_1);
5092 v8::Debug::SendCommand(
5093 isolate, buffer, AsciiToUtf16(command_continue, buffer));
5094 CHECK_EQ(3, TestClientData::constructor_call_counter);
5095 CHECK_EQ(TestClientData::constructor_call_counter,
5096 handled_client_data_instances_count);
5097 CHECK_EQ(TestClientData::constructor_call_counter,
5098 TestClientData::destructor_call_counter);
5102 /* Test ThreadedDebugging */
5103 /* This test interrupts a running infinite loop that is
5104 * occupying the v8 thread by a break command from the
5105 * debugger thread. It then changes the value of a
5106 * global object, to make the loop terminate.
5109 Barriers threaded_debugging_barriers;
5111 class V8Thread : public v8::base::Thread {
5113 V8Thread() : Thread(Options("V8Thread")) {}
5117 class DebuggerThread : public v8::base::Thread {
5119 DebuggerThread() : Thread(Options("DebuggerThread")) {}
5124 static void ThreadedAtBarrier1(
5125 const v8::FunctionCallbackInfo<v8::Value>& args) {
5126 threaded_debugging_barriers.barrier_1.Wait();
5130 static void ThreadedMessageHandler(const v8::Debug::Message& message) {
5131 static char print_buffer[1000];
5132 v8::String::Value json(message.GetJSON());
5133 Utf16ToAscii(*json, json.length(), print_buffer);
5134 if (IsBreakEventMessage(print_buffer)) {
5135 // Check that we are inside the while loop.
5136 int source_line = GetSourceLineFromBreakEventMessage(print_buffer);
5137 CHECK(8 <= source_line && source_line <= 13);
5138 threaded_debugging_barriers.barrier_2.Wait();
5143 void V8Thread::Run() {
5144 const char* source =
5146 "function bar( new_value ) {\n"
5147 " flag = new_value;\n"
5148 " return \"Return from bar(\" + new_value + \")\";\n"
5151 "function foo() {\n"
5153 " while ( flag == true ) {\n"
5154 " if ( x == 1 ) {\n"
5155 " ThreadedAtBarrier1();\n"
5163 v8::Isolate* isolate = CcTest::isolate();
5164 v8::Isolate::Scope isolate_scope(isolate);
5165 DebugLocalContext env;
5166 v8::HandleScope scope(env->GetIsolate());
5167 v8::Debug::SetMessageHandler(&ThreadedMessageHandler);
5168 v8::Handle<v8::ObjectTemplate> global_template =
5169 v8::ObjectTemplate::New(env->GetIsolate());
5170 global_template->Set(
5171 v8::String::NewFromUtf8(env->GetIsolate(), "ThreadedAtBarrier1"),
5172 v8::FunctionTemplate::New(isolate, ThreadedAtBarrier1));
5173 v8::Handle<v8::Context> context = v8::Context::New(isolate,
5176 v8::Context::Scope context_scope(context);
5182 void DebuggerThread::Run() {
5183 const int kBufSize = 1000;
5184 uint16_t buffer[kBufSize];
5186 const char* command_1 = "{\"seq\":102,"
5187 "\"type\":\"request\","
5188 "\"command\":\"evaluate\","
5189 "\"arguments\":{\"expression\":\"bar(false)\"}}";
5190 const char* command_2 = "{\"seq\":103,"
5191 "\"type\":\"request\","
5192 "\"command\":\"continue\"}";
5194 v8::Isolate* isolate = CcTest::isolate();
5195 threaded_debugging_barriers.barrier_1.Wait();
5196 v8::Debug::DebugBreak(isolate);
5197 threaded_debugging_barriers.barrier_2.Wait();
5198 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_1, buffer));
5199 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_2, buffer));
5203 TEST(ThreadedDebugging) {
5204 DebuggerThread debugger_thread;
5207 // Create a V8 environment
5209 debugger_thread.Start();
5212 debugger_thread.Join();
5216 /* Test RecursiveBreakpoints */
5217 /* In this test, the debugger evaluates a function with a breakpoint, after
5218 * hitting a breakpoint in another function. We do this with both values
5219 * of the flag enabling recursive breakpoints, and verify that the second
5220 * breakpoint is hit when enabled, and missed when disabled.
5223 class BreakpointsV8Thread : public v8::base::Thread {
5225 BreakpointsV8Thread() : Thread(Options("BreakpointsV8Thread")) {}
5229 class BreakpointsDebuggerThread : public v8::base::Thread {
5231 explicit BreakpointsDebuggerThread(bool global_evaluate)
5232 : Thread(Options("BreakpointsDebuggerThread")),
5233 global_evaluate_(global_evaluate) {}
5237 bool global_evaluate_;
5241 Barriers* breakpoints_barriers;
5242 int break_event_breakpoint_id;
5243 int evaluate_int_result;
5245 static void BreakpointsMessageHandler(const v8::Debug::Message& message) {
5246 static char print_buffer[1000];
5247 v8::String::Value json(message.GetJSON());
5248 Utf16ToAscii(*json, json.length(), print_buffer);
5250 if (IsBreakEventMessage(print_buffer)) {
5251 break_event_breakpoint_id =
5252 GetBreakpointIdFromBreakEventMessage(print_buffer);
5253 breakpoints_barriers->semaphore_1.Signal();
5254 } else if (IsEvaluateResponseMessage(print_buffer)) {
5255 evaluate_int_result = GetEvaluateIntResult(print_buffer);
5256 breakpoints_barriers->semaphore_1.Signal();
5261 void BreakpointsV8Thread::Run() {
5262 const char* source_1 = "var y_global = 3;\n"
5263 "function cat( new_value ) {\n"
5264 " var x = new_value;\n"
5265 " y_global = y_global + 4;\n"
5267 " y_global = y_global + 5;\n"
5271 "function dog() {\n"
5279 const char* source_2 = "cat(17);\n"
5282 v8::Isolate* isolate = CcTest::isolate();
5283 v8::Isolate::Scope isolate_scope(isolate);
5284 DebugLocalContext env;
5285 v8::HandleScope scope(isolate);
5286 v8::Debug::SetMessageHandler(&BreakpointsMessageHandler);
5288 CompileRun(source_1);
5289 breakpoints_barriers->barrier_1.Wait();
5290 breakpoints_barriers->barrier_2.Wait();
5291 CompileRun(source_2);
5295 void BreakpointsDebuggerThread::Run() {
5296 const int kBufSize = 1000;
5297 uint16_t buffer[kBufSize];
5299 const char* command_1 = "{\"seq\":101,"
5300 "\"type\":\"request\","
5301 "\"command\":\"setbreakpoint\","
5302 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
5303 const char* command_2 = "{\"seq\":102,"
5304 "\"type\":\"request\","
5305 "\"command\":\"setbreakpoint\","
5306 "\"arguments\":{\"type\":\"function\",\"target\":\"dog\",\"line\":3}}";
5307 const char* command_3;
5308 if (this->global_evaluate_) {
5309 command_3 = "{\"seq\":103,"
5310 "\"type\":\"request\","
5311 "\"command\":\"evaluate\","
5312 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false,"
5313 "\"global\":true}}";
5315 command_3 = "{\"seq\":103,"
5316 "\"type\":\"request\","
5317 "\"command\":\"evaluate\","
5318 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false}}";
5320 const char* command_4;
5321 if (this->global_evaluate_) {
5322 command_4 = "{\"seq\":104,"
5323 "\"type\":\"request\","
5324 "\"command\":\"evaluate\","
5325 "\"arguments\":{\"expression\":\"100 + 8\",\"disable_break\":true,"
5326 "\"global\":true}}";
5328 command_4 = "{\"seq\":104,"
5329 "\"type\":\"request\","
5330 "\"command\":\"evaluate\","
5331 "\"arguments\":{\"expression\":\"x + 1\",\"disable_break\":true}}";
5333 const char* command_5 = "{\"seq\":105,"
5334 "\"type\":\"request\","
5335 "\"command\":\"continue\"}";
5336 const char* command_6 = "{\"seq\":106,"
5337 "\"type\":\"request\","
5338 "\"command\":\"continue\"}";
5339 const char* command_7;
5340 if (this->global_evaluate_) {
5341 command_7 = "{\"seq\":107,"
5342 "\"type\":\"request\","
5343 "\"command\":\"evaluate\","
5344 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true,"
5345 "\"global\":true}}";
5347 command_7 = "{\"seq\":107,"
5348 "\"type\":\"request\","
5349 "\"command\":\"evaluate\","
5350 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true}}";
5352 const char* command_8 = "{\"seq\":108,"
5353 "\"type\":\"request\","
5354 "\"command\":\"continue\"}";
5357 v8::Isolate* isolate = CcTest::isolate();
5358 v8::Isolate::Scope isolate_scope(isolate);
5359 // v8 thread initializes, runs source_1
5360 breakpoints_barriers->barrier_1.Wait();
5361 // 1:Set breakpoint in cat() (will get id 1).
5362 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_1, buffer));
5363 // 2:Set breakpoint in dog() (will get id 2).
5364 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_2, buffer));
5365 breakpoints_barriers->barrier_2.Wait();
5366 // V8 thread starts compiling source_2.
5367 // Automatic break happens, to run queued commands
5368 // breakpoints_barriers->semaphore_1.Wait();
5369 // Commands 1 through 3 run, thread continues.
5370 // v8 thread runs source_2 to breakpoint in cat().
5371 // message callback receives break event.
5372 breakpoints_barriers->semaphore_1.Wait();
5373 // Must have hit breakpoint #1.
5374 CHECK_EQ(1, break_event_breakpoint_id);
5375 // 4:Evaluate dog() (which has a breakpoint).
5376 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_3, buffer));
5377 // V8 thread hits breakpoint in dog().
5378 breakpoints_barriers->semaphore_1.Wait(); // wait for break event
5379 // Must have hit breakpoint #2.
5380 CHECK_EQ(2, break_event_breakpoint_id);
5381 // 5:Evaluate (x + 1).
5382 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_4, buffer));
5383 // Evaluate (x + 1) finishes.
5384 breakpoints_barriers->semaphore_1.Wait();
5385 // Must have result 108.
5386 CHECK_EQ(108, evaluate_int_result);
5387 // 6:Continue evaluation of dog().
5388 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_5, buffer));
5389 // Evaluate dog() finishes.
5390 breakpoints_barriers->semaphore_1.Wait();
5391 // Must have result 107.
5392 CHECK_EQ(107, evaluate_int_result);
5393 // 7:Continue evaluation of source_2, finish cat(17), hit breakpoint
5395 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_6, buffer));
5396 // Message callback gets break event.
5397 breakpoints_barriers->semaphore_1.Wait(); // wait for break event
5398 // Must have hit breakpoint #1.
5399 CHECK_EQ(1, break_event_breakpoint_id);
5400 // 8: Evaluate dog() with breaks disabled.
5401 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_7, buffer));
5402 // Evaluate dog() finishes.
5403 breakpoints_barriers->semaphore_1.Wait();
5404 // Must have result 116.
5405 CHECK_EQ(116, evaluate_int_result);
5406 // 9: Continue evaluation of source2, reach end.
5407 v8::Debug::SendCommand(isolate, buffer, AsciiToUtf16(command_8, buffer));
5411 void TestRecursiveBreakpointsGeneric(bool global_evaluate) {
5412 BreakpointsDebuggerThread breakpoints_debugger_thread(global_evaluate);
5413 BreakpointsV8Thread breakpoints_v8_thread;
5415 // Create a V8 environment
5416 Barriers stack_allocated_breakpoints_barriers;
5417 breakpoints_barriers = &stack_allocated_breakpoints_barriers;
5419 breakpoints_v8_thread.Start();
5420 breakpoints_debugger_thread.Start();
5422 breakpoints_v8_thread.Join();
5423 breakpoints_debugger_thread.Join();
5427 TEST(RecursiveBreakpoints) {
5428 TestRecursiveBreakpointsGeneric(false);
5432 TEST(RecursiveBreakpointsGlobal) {
5433 TestRecursiveBreakpointsGeneric(true);
5437 static void DummyDebugEventListener(
5438 const v8::Debug::EventDetails& event_details) {
5442 TEST(SetDebugEventListenerOnUninitializedVM) {
5443 v8::Debug::SetDebugEventListener(DummyDebugEventListener);
5447 static void DummyMessageHandler(const v8::Debug::Message& message) {
5451 TEST(SetMessageHandlerOnUninitializedVM) {
5452 v8::Debug::SetMessageHandler(DummyMessageHandler);
5456 // Source for a JavaScript function which returns the data parameter of a
5457 // function called in the context of the debugger. If no data parameter is
5458 // passed it throws an exception.
5459 static const char* debugger_call_with_data_source =
5460 "function debugger_call_with_data(exec_state, data) {"
5461 " if (data) return data;"
5464 v8::Handle<v8::Function> debugger_call_with_data;
5467 // Source for a JavaScript function which returns the data parameter of a
5468 // function called in the context of the debugger. If no data parameter is
5469 // passed it throws an exception.
5470 static const char* debugger_call_with_closure_source =
5472 "(function (exec_state) {"
5473 " if (exec_state.y) return x - 1;"
5474 " exec_state.y = x;"
5475 " return exec_state.y"
5477 v8::Handle<v8::Function> debugger_call_with_closure;
5479 // Function to retrieve the number of JavaScript frames by calling a JavaScript
5481 static void CheckFrameCount(const v8::FunctionCallbackInfo<v8::Value>& args) {
5482 CHECK(v8::Debug::Call(frame_count)->IsNumber());
5483 CHECK_EQ(args[0]->Int32Value(),
5484 v8::Debug::Call(frame_count)->Int32Value());
5488 // Function to retrieve the source line of the top JavaScript frame by calling a
5489 // JavaScript function in the debugger.
5490 static void CheckSourceLine(const v8::FunctionCallbackInfo<v8::Value>& args) {
5491 CHECK(v8::Debug::Call(frame_source_line)->IsNumber());
5492 CHECK_EQ(args[0]->Int32Value(),
5493 v8::Debug::Call(frame_source_line)->Int32Value());
5497 // Function to test passing an additional parameter to a JavaScript function
5498 // called in the debugger. It also tests that functions called in the debugger
5499 // can throw exceptions.
5500 static void CheckDataParameter(
5501 const v8::FunctionCallbackInfo<v8::Value>& args) {
5502 v8::Handle<v8::String> data =
5503 v8::String::NewFromUtf8(args.GetIsolate(), "Test");
5504 CHECK(v8::Debug::Call(debugger_call_with_data, data)->IsString());
5506 for (int i = 0; i < 3; i++) {
5507 v8::TryCatch catcher;
5508 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
5509 CHECK(catcher.HasCaught());
5510 CHECK(catcher.Exception()->IsString());
5515 // Function to test using a JavaScript with closure in the debugger.
5516 static void CheckClosure(const v8::FunctionCallbackInfo<v8::Value>& args) {
5517 CHECK(v8::Debug::Call(debugger_call_with_closure)->IsNumber());
5518 CHECK_EQ(3, v8::Debug::Call(debugger_call_with_closure)->Int32Value());
5522 // Test functions called through the debugger.
5523 TEST(CallFunctionInDebugger) {
5524 // Create and enter a context with the functions CheckFrameCount,
5525 // CheckSourceLine and CheckDataParameter installed.
5526 v8::Isolate* isolate = CcTest::isolate();
5527 v8::HandleScope scope(isolate);
5528 v8::Handle<v8::ObjectTemplate> global_template =
5529 v8::ObjectTemplate::New(isolate);
5530 global_template->Set(
5531 v8::String::NewFromUtf8(isolate, "CheckFrameCount"),
5532 v8::FunctionTemplate::New(isolate, CheckFrameCount));
5533 global_template->Set(
5534 v8::String::NewFromUtf8(isolate, "CheckSourceLine"),
5535 v8::FunctionTemplate::New(isolate, CheckSourceLine));
5536 global_template->Set(
5537 v8::String::NewFromUtf8(isolate, "CheckDataParameter"),
5538 v8::FunctionTemplate::New(isolate, CheckDataParameter));
5539 global_template->Set(
5540 v8::String::NewFromUtf8(isolate, "CheckClosure"),
5541 v8::FunctionTemplate::New(isolate, CheckClosure));
5542 v8::Handle<v8::Context> context = v8::Context::New(isolate,
5545 v8::Context::Scope context_scope(context);
5547 // Compile a function for checking the number of JavaScript frames.
5548 v8::Script::Compile(
5549 v8::String::NewFromUtf8(isolate, frame_count_source))->Run();
5550 frame_count = v8::Local<v8::Function>::Cast(context->Global()->Get(
5551 v8::String::NewFromUtf8(isolate, "frame_count")));
5553 // Compile a function for returning the source line for the top frame.
5554 v8::Script::Compile(v8::String::NewFromUtf8(isolate,
5555 frame_source_line_source))->Run();
5556 frame_source_line = v8::Local<v8::Function>::Cast(context->Global()->Get(
5557 v8::String::NewFromUtf8(isolate, "frame_source_line")));
5559 // Compile a function returning the data parameter.
5560 v8::Script::Compile(v8::String::NewFromUtf8(isolate,
5561 debugger_call_with_data_source))
5563 debugger_call_with_data = v8::Local<v8::Function>::Cast(
5564 context->Global()->Get(v8::String::NewFromUtf8(
5565 isolate, "debugger_call_with_data")));
5567 // Compile a function capturing closure.
5568 debugger_call_with_closure =
5569 v8::Local<v8::Function>::Cast(v8::Script::Compile(
5570 v8::String::NewFromUtf8(isolate,
5571 debugger_call_with_closure_source))->Run());
5573 // Calling a function through the debugger returns 0 frames if there are
5574 // no JavaScript frames.
5575 CHECK_EQ(v8::Integer::New(isolate, 0),
5576 v8::Debug::Call(frame_count));
5578 // Test that the number of frames can be retrieved.
5579 v8::Script::Compile(
5580 v8::String::NewFromUtf8(isolate, "CheckFrameCount(1)"))->Run();
5581 v8::Script::Compile(v8::String::NewFromUtf8(isolate,
5583 " CheckFrameCount(2);"
5586 // Test that the source line can be retrieved.
5587 v8::Script::Compile(
5588 v8::String::NewFromUtf8(isolate, "CheckSourceLine(0)"))->Run();
5589 v8::Script::Compile(v8::String::NewFromUtf8(isolate,
5591 " CheckSourceLine(1)\n"
5592 " CheckSourceLine(2)\n"
5593 " CheckSourceLine(3)\n"
5596 // Test that a parameter can be passed to a function called in the debugger.
5597 v8::Script::Compile(v8::String::NewFromUtf8(isolate,
5598 "CheckDataParameter()"))->Run();
5600 // Test that a function with closure can be run in the debugger.
5601 v8::Script::Compile(
5602 v8::String::NewFromUtf8(isolate, "CheckClosure()"))->Run();
5604 // Test that the source line is correct when there is a line offset.
5605 v8::ScriptOrigin origin(v8::String::NewFromUtf8(isolate, "test"),
5606 v8::Integer::New(isolate, 7));
5607 v8::Script::Compile(
5608 v8::String::NewFromUtf8(isolate, "CheckSourceLine(7)"), &origin)
5610 v8::Script::Compile(v8::String::NewFromUtf8(isolate,
5612 " CheckSourceLine(8)\n"
5613 " CheckSourceLine(9)\n"
5614 " CheckSourceLine(10)\n"
5620 // Debugger message handler which counts the number of breaks.
5621 static void SendContinueCommand();
5622 static void MessageHandlerBreakPointHitCount(
5623 const v8::Debug::Message& message) {
5624 if (message.IsEvent() && message.GetEvent() == v8::Break) {
5625 // Count the number of breaks.
5626 break_point_hit_count++;
5628 SendContinueCommand();
5633 // Test that clearing the debug event listener actually clears all break points
5634 // and related information.
5635 TEST(DebuggerUnload) {
5636 DebugLocalContext env;
5638 // Check debugger is unloaded before it is used.
5639 CheckDebuggerUnloaded();
5641 // Set a debug event listener.
5642 break_point_hit_count = 0;
5643 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
5645 v8::HandleScope scope(env->GetIsolate());
5646 // Create a couple of functions for the test.
5647 v8::Local<v8::Function> foo =
5648 CompileFunction(&env, "function foo(){x=1}", "foo");
5649 v8::Local<v8::Function> bar =
5650 CompileFunction(&env, "function bar(){y=2}", "bar");
5652 // Set some break points.
5653 SetBreakPoint(foo, 0);
5654 SetBreakPoint(foo, 4);
5655 SetBreakPoint(bar, 0);
5656 SetBreakPoint(bar, 4);
5658 // Make sure that the break points are there.
5659 break_point_hit_count = 0;
5660 foo->Call(env->Global(), 0, NULL);
5661 CHECK_EQ(2, break_point_hit_count);
5662 bar->Call(env->Global(), 0, NULL);
5663 CHECK_EQ(4, break_point_hit_count);
5666 // Remove the debug event listener without clearing breakpoints. Do this
5667 // outside a handle scope.
5668 v8::Debug::SetDebugEventListener(NULL);
5669 CheckDebuggerUnloaded(true);
5671 // Now set a debug message handler.
5672 break_point_hit_count = 0;
5673 v8::Debug::SetMessageHandler(MessageHandlerBreakPointHitCount);
5675 v8::HandleScope scope(env->GetIsolate());
5677 // Get the test functions again.
5678 v8::Local<v8::Function> foo(v8::Local<v8::Function>::Cast(
5679 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "foo"))));
5681 foo->Call(env->Global(), 0, NULL);
5682 CHECK_EQ(0, break_point_hit_count);
5684 // Set break points and run again.
5685 SetBreakPoint(foo, 0);
5686 SetBreakPoint(foo, 4);
5687 foo->Call(env->Global(), 0, NULL);
5688 CHECK_EQ(2, break_point_hit_count);
5691 // Remove the debug message handler without clearing breakpoints. Do this
5692 // outside a handle scope.
5693 v8::Debug::SetMessageHandler(NULL);
5694 CheckDebuggerUnloaded(true);
5698 // Sends continue command to the debugger.
5699 static void SendContinueCommand() {
5700 const int kBufferSize = 1000;
5701 uint16_t buffer[kBufferSize];
5702 const char* command_continue =
5704 "\"type\":\"request\","
5705 "\"command\":\"continue\"}";
5707 v8::Debug::SendCommand(
5708 CcTest::isolate(), buffer, AsciiToUtf16(command_continue, buffer));
5712 // Debugger message handler which counts the number of times it is called.
5713 static int message_handler_hit_count = 0;
5714 static void MessageHandlerHitCount(const v8::Debug::Message& message) {
5715 message_handler_hit_count++;
5717 static char print_buffer[1000];
5718 v8::String::Value json(message.GetJSON());
5719 Utf16ToAscii(*json, json.length(), print_buffer);
5720 if (IsExceptionEventMessage(print_buffer)) {
5721 // Send a continue command for exception events.
5722 SendContinueCommand();
5727 // Test clearing the debug message handler.
5728 TEST(DebuggerClearMessageHandler) {
5729 DebugLocalContext env;
5730 v8::HandleScope scope(env->GetIsolate());
5732 // Check debugger is unloaded before it is used.
5733 CheckDebuggerUnloaded();
5735 // Set a debug message handler.
5736 v8::Debug::SetMessageHandler(MessageHandlerHitCount);
5738 // Run code to throw a unhandled exception. This should end up in the message
5740 CompileRun("throw 1");
5742 // The message handler should be called.
5743 CHECK_GT(message_handler_hit_count, 0);
5745 // Clear debug message handler.
5746 message_handler_hit_count = 0;
5747 v8::Debug::SetMessageHandler(NULL);
5749 // Run code to throw a unhandled exception. This should end up in the message
5751 CompileRun("throw 1");
5753 // The message handler should not be called more.
5754 CHECK_EQ(0, message_handler_hit_count);
5756 CheckDebuggerUnloaded(true);
5760 // Debugger message handler which clears the message handler while active.
5761 static void MessageHandlerClearingMessageHandler(
5762 const v8::Debug::Message& message) {
5763 message_handler_hit_count++;
5765 // Clear debug message handler.
5766 v8::Debug::SetMessageHandler(NULL);
5770 // Test clearing the debug message handler while processing a debug event.
5771 TEST(DebuggerClearMessageHandlerWhileActive) {
5772 DebugLocalContext env;
5773 v8::HandleScope scope(env->GetIsolate());
5775 // Check debugger is unloaded before it is used.
5776 CheckDebuggerUnloaded();
5778 // Set a debug message handler.
5779 v8::Debug::SetMessageHandler(MessageHandlerClearingMessageHandler);
5781 // Run code to throw a unhandled exception. This should end up in the message
5783 CompileRun("throw 1");
5785 // The message handler should be called.
5786 CHECK_EQ(1, message_handler_hit_count);
5788 CheckDebuggerUnloaded(true);
5792 // Test for issue http://code.google.com/p/v8/issues/detail?id=289.
5793 // Make sure that DebugGetLoadedScripts doesn't return scripts
5794 // with disposed external source.
5795 class EmptyExternalStringResource : public v8::String::ExternalStringResource {
5797 EmptyExternalStringResource() { empty_[0] = 0; }
5798 virtual ~EmptyExternalStringResource() {}
5799 virtual size_t length() const { return empty_.length(); }
5800 virtual const uint16_t* data() const { return empty_.start(); }
5802 ::v8::internal::EmbeddedVector<uint16_t, 1> empty_;
5806 TEST(DebugGetLoadedScripts) {
5807 DebugLocalContext env;
5808 v8::HandleScope scope(env->GetIsolate());
5811 EmptyExternalStringResource source_ext_str;
5812 v8::Local<v8::String> source =
5813 v8::String::NewExternal(env->GetIsolate(), &source_ext_str);
5814 v8::Handle<v8::Script> evil_script(v8::Script::Compile(source));
5815 // "use" evil_script to make the compiler happy.
5817 Handle<i::ExternalTwoByteString> i_source(
5818 i::ExternalTwoByteString::cast(*v8::Utils::OpenHandle(*source)));
5819 // This situation can happen if source was an external string disposed
5821 i_source->set_resource(0);
5823 bool allow_natives_syntax = i::FLAG_allow_natives_syntax;
5824 i::FLAG_allow_natives_syntax = true;
5826 "var scripts = %DebugGetLoadedScripts();"
5827 "var count = scripts.length;"
5828 "for (var i = 0; i < count; ++i) {"
5829 " scripts[i].line_ends;"
5831 // Must not crash while accessing line_ends.
5832 i::FLAG_allow_natives_syntax = allow_natives_syntax;
5834 // Some scripts are retrieved - at least the number of native scripts.
5837 ->Get(v8::String::NewFromUtf8(env->GetIsolate(), "count"))
5843 // Test script break points set on lines.
5844 TEST(ScriptNameAndData) {
5845 DebugLocalContext env;
5846 v8::HandleScope scope(env->GetIsolate());
5849 // Create functions for retrieving script name and data for the function on
5850 // the top frame when hitting a break point.
5851 frame_script_name = CompileFunction(&env,
5852 frame_script_name_source,
5853 "frame_script_name");
5855 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
5857 // Test function source.
5858 v8::Local<v8::String> script = v8::String::NewFromUtf8(env->GetIsolate(),
5863 v8::ScriptOrigin origin1 =
5864 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "name"));
5865 v8::Handle<v8::Script> script1 = v8::Script::Compile(script, &origin1);
5867 v8::Local<v8::Function> f;
5868 f = v8::Local<v8::Function>::Cast(
5869 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
5871 f->Call(env->Global(), 0, NULL);
5872 CHECK_EQ(1, break_point_hit_count);
5873 CHECK_EQ("name", last_script_name_hit);
5875 // Compile the same script again without setting data. As the compilation
5876 // cache is disabled when debugging expect the data to be missing.
5877 v8::Script::Compile(script, &origin1)->Run();
5878 f = v8::Local<v8::Function>::Cast(
5879 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
5880 f->Call(env->Global(), 0, NULL);
5881 CHECK_EQ(2, break_point_hit_count);
5882 CHECK_EQ("name", last_script_name_hit);
5884 v8::Local<v8::String> data_obj_source = v8::String::NewFromUtf8(
5888 " toString: function() { return this.a + ' ' + this.b; }\n"
5890 v8::Script::Compile(data_obj_source)->Run();
5891 v8::ScriptOrigin origin2 =
5892 v8::ScriptOrigin(v8::String::NewFromUtf8(env->GetIsolate(), "new name"));
5893 v8::Handle<v8::Script> script2 = v8::Script::Compile(script, &origin2);
5895 f = v8::Local<v8::Function>::Cast(
5896 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
5897 f->Call(env->Global(), 0, NULL);
5898 CHECK_EQ(3, break_point_hit_count);
5899 CHECK_EQ("new name", last_script_name_hit);
5901 v8::Handle<v8::Script> script3 = v8::Script::Compile(script, &origin2);
5903 f = v8::Local<v8::Function>::Cast(
5904 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
5905 f->Call(env->Global(), 0, NULL);
5906 CHECK_EQ(4, break_point_hit_count);
5910 static v8::Handle<v8::Context> expected_context;
5911 static v8::Handle<v8::Value> expected_context_data;
5914 // Check that the expected context is the one generating the debug event.
5915 static void ContextCheckMessageHandler(const v8::Debug::Message& message) {
5916 CHECK(message.GetEventContext() == expected_context);
5917 CHECK(message.GetEventContext()->GetEmbedderData(0)->StrictEquals(
5918 expected_context_data));
5919 message_handler_hit_count++;
5921 static char print_buffer[1000];
5922 v8::String::Value json(message.GetJSON());
5923 Utf16ToAscii(*json, json.length(), print_buffer);
5925 // Send a continue command for break events.
5926 if (IsBreakEventMessage(print_buffer)) {
5927 SendContinueCommand();
5932 // Test which creates two contexts and sets different embedder data on each.
5933 // Checks that this data is set correctly and that when the debug message
5934 // handler is called the expected context is the one active.
5936 v8::Isolate* isolate = CcTest::isolate();
5937 v8::HandleScope scope(isolate);
5939 // Create two contexts.
5940 v8::Handle<v8::Context> context_1;
5941 v8::Handle<v8::Context> context_2;
5942 v8::Handle<v8::ObjectTemplate> global_template =
5943 v8::Handle<v8::ObjectTemplate>();
5944 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
5945 context_1 = v8::Context::New(isolate, NULL, global_template, global_object);
5946 context_2 = v8::Context::New(isolate, NULL, global_template, global_object);
5948 v8::Debug::SetMessageHandler(ContextCheckMessageHandler);
5950 // Default data value is undefined.
5951 CHECK(context_1->GetEmbedderData(0)->IsUndefined());
5952 CHECK(context_2->GetEmbedderData(0)->IsUndefined());
5954 // Set and check different data values.
5955 v8::Handle<v8::String> data_1 = v8::String::NewFromUtf8(isolate, "1");
5956 v8::Handle<v8::String> data_2 = v8::String::NewFromUtf8(isolate, "2");
5957 context_1->SetEmbedderData(0, data_1);
5958 context_2->SetEmbedderData(0, data_2);
5959 CHECK(context_1->GetEmbedderData(0)->StrictEquals(data_1));
5960 CHECK(context_2->GetEmbedderData(0)->StrictEquals(data_2));
5962 // Simple test function which causes a break.
5963 const char* source = "function f() { debugger; }";
5965 // Enter and run function in the first context.
5967 v8::Context::Scope context_scope(context_1);
5968 expected_context = context_1;
5969 expected_context_data = data_1;
5970 v8::Local<v8::Function> f = CompileFunction(isolate, source, "f");
5971 f->Call(context_1->Global(), 0, NULL);
5975 // Enter and run function in the second context.
5977 v8::Context::Scope context_scope(context_2);
5978 expected_context = context_2;
5979 expected_context_data = data_2;
5980 v8::Local<v8::Function> f = CompileFunction(isolate, source, "f");
5981 f->Call(context_2->Global(), 0, NULL);
5984 // Two times compile event and two times break event.
5985 CHECK_GT(message_handler_hit_count, 4);
5987 v8::Debug::SetMessageHandler(NULL);
5988 CheckDebuggerUnloaded();
5992 // Debug message handler which issues a debug break when it hits a break event.
5993 static int message_handler_break_hit_count = 0;
5994 static void DebugBreakMessageHandler(const v8::Debug::Message& message) {
5995 // Schedule a debug break for break events.
5996 if (message.IsEvent() && message.GetEvent() == v8::Break) {
5997 message_handler_break_hit_count++;
5998 if (message_handler_break_hit_count == 1) {
5999 v8::Debug::DebugBreak(message.GetIsolate());
6003 // Issue a continue command if this event will not cause the VM to start
6005 if (!message.WillStartRunning()) {
6006 SendContinueCommand();
6011 // Test that a debug break can be scheduled while in a message handler.
6012 TEST(DebugBreakInMessageHandler) {
6013 DebugLocalContext env;
6014 v8::HandleScope scope(env->GetIsolate());
6016 v8::Debug::SetMessageHandler(DebugBreakMessageHandler);
6019 const char* script = "function f() { debugger; g(); } function g() { }";
6021 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
6022 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
6023 v8::Local<v8::Function> g = v8::Local<v8::Function>::Cast(
6024 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "g")));
6026 // Call f then g. The debugger statement in f will casue a break which will
6027 // cause another break.
6028 f->Call(env->Global(), 0, NULL);
6029 CHECK_EQ(2, message_handler_break_hit_count);
6030 // Calling g will not cause any additional breaks.
6031 g->Call(env->Global(), 0, NULL);
6032 CHECK_EQ(2, message_handler_break_hit_count);
6036 #ifndef V8_INTERPRETED_REGEXP
6037 // Debug event handler which gets the function on the top frame and schedules a
6038 // break a number of times.
6039 static void DebugEventDebugBreak(
6040 const v8::Debug::EventDetails& event_details) {
6041 v8::DebugEvent event = event_details.GetEvent();
6042 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
6044 if (event == v8::Break) {
6045 break_point_hit_count++;
6047 // Get the name of the top frame function.
6048 if (!frame_function_name.IsEmpty()) {
6049 // Get the name of the function.
6051 v8::Handle<v8::Value> argv[argc] = {
6052 exec_state, v8::Integer::New(CcTest::isolate(), 0)
6054 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
6056 if (result->IsUndefined()) {
6057 last_function_hit[0] = '\0';
6059 CHECK(result->IsString());
6060 v8::Handle<v8::String> function_name(result->ToString());
6061 function_name->WriteUtf8(last_function_hit);
6065 // Keep forcing breaks.
6066 if (break_point_hit_count < 20) {
6067 v8::Debug::DebugBreak(CcTest::isolate());
6073 TEST(RegExpDebugBreak) {
6074 // This test only applies to native regexps.
6075 DebugLocalContext env;
6076 v8::HandleScope scope(env->GetIsolate());
6078 // Create a function for checking the function when hitting a break point.
6079 frame_function_name = CompileFunction(&env,
6080 frame_function_name_source,
6081 "frame_function_name");
6083 // Test RegExp which matches white spaces and comments at the begining of a
6085 const char* script =
6086 "var sourceLineBeginningSkip = /^(?:[ \\v\\h]*(?:\\/\\*.*?\\*\\/)*)*/;\n"
6087 "function f(s) { return s.match(sourceLineBeginningSkip)[0].length; }";
6089 v8::Local<v8::Function> f = CompileFunction(env->GetIsolate(), script, "f");
6091 v8::Handle<v8::Value> argv[argc] = {
6092 v8::String::NewFromUtf8(env->GetIsolate(), " /* xxx */ a=0;")};
6093 v8::Local<v8::Value> result = f->Call(env->Global(), argc, argv);
6094 CHECK_EQ(12, result->Int32Value());
6096 v8::Debug::SetDebugEventListener(DebugEventDebugBreak);
6097 v8::Debug::DebugBreak(env->GetIsolate());
6098 result = f->Call(env->Global(), argc, argv);
6100 // Check that there was only one break event. Matching RegExp should not
6101 // cause Break events.
6102 CHECK_EQ(1, break_point_hit_count);
6103 CHECK_EQ("f", last_function_hit);
6105 #endif // V8_INTERPRETED_REGEXP
6108 // Common part of EvalContextData and NestedBreakEventContextData tests.
6109 static void ExecuteScriptForContextCheck(
6110 v8::Debug::MessageHandler message_handler) {
6111 // Create a context.
6112 v8::Handle<v8::Context> context_1;
6113 v8::Handle<v8::ObjectTemplate> global_template =
6114 v8::Handle<v8::ObjectTemplate>();
6116 v8::Context::New(CcTest::isolate(), NULL, global_template);
6118 v8::Debug::SetMessageHandler(message_handler);
6120 // Default data value is undefined.
6121 CHECK(context_1->GetEmbedderData(0)->IsUndefined());
6123 // Set and check a data value.
6124 v8::Handle<v8::String> data_1 =
6125 v8::String::NewFromUtf8(CcTest::isolate(), "1");
6126 context_1->SetEmbedderData(0, data_1);
6127 CHECK(context_1->GetEmbedderData(0)->StrictEquals(data_1));
6129 // Simple test function with eval that causes a break.
6130 const char* source = "function f() { eval('debugger;'); }";
6132 // Enter and run function in the context.
6134 v8::Context::Scope context_scope(context_1);
6135 expected_context = context_1;
6136 expected_context_data = data_1;
6137 v8::Local<v8::Function> f = CompileFunction(CcTest::isolate(), source, "f");
6138 f->Call(context_1->Global(), 0, NULL);
6141 v8::Debug::SetMessageHandler(NULL);
6145 // Test which creates a context and sets embedder data on it. Checks that this
6146 // data is set correctly and that when the debug message handler is called for
6147 // break event in an eval statement the expected context is the one returned by
6148 // Message.GetEventContext.
6149 TEST(EvalContextData) {
6150 v8::HandleScope scope(CcTest::isolate());
6152 ExecuteScriptForContextCheck(ContextCheckMessageHandler);
6154 // One time compile event and one time break event.
6155 CHECK_GT(message_handler_hit_count, 2);
6156 CheckDebuggerUnloaded();
6160 static bool sent_eval = false;
6161 static int break_count = 0;
6162 static int continue_command_send_count = 0;
6163 // Check that the expected context is the one generating the debug event
6164 // including the case of nested break event.
6165 static void DebugEvalContextCheckMessageHandler(
6166 const v8::Debug::Message& message) {
6167 CHECK(message.GetEventContext() == expected_context);
6168 CHECK(message.GetEventContext()->GetEmbedderData(0)->StrictEquals(
6169 expected_context_data));
6170 message_handler_hit_count++;
6172 static char print_buffer[1000];
6173 v8::String::Value json(message.GetJSON());
6174 Utf16ToAscii(*json, json.length(), print_buffer);
6176 v8::Isolate* isolate = message.GetIsolate();
6177 if (IsBreakEventMessage(print_buffer)) {
6182 const int kBufferSize = 1000;
6183 uint16_t buffer[kBufferSize];
6184 const char* eval_command =
6186 "\"type\":\"request\","
6187 "\"command\":\"evaluate\","
6188 "\"arguments\":{\"expression\":\"debugger;\","
6189 "\"global\":true,\"disable_break\":false}}";
6191 // Send evaluate command.
6192 v8::Debug::SendCommand(
6193 isolate, buffer, AsciiToUtf16(eval_command, buffer));
6196 // It's a break event caused by the evaluation request above.
6197 SendContinueCommand();
6198 continue_command_send_count++;
6200 } else if (IsEvaluateResponseMessage(print_buffer) &&
6201 continue_command_send_count < 2) {
6202 // Response to the evaluation request. We're still on the breakpoint so
6204 SendContinueCommand();
6205 continue_command_send_count++;
6210 // Tests that context returned for break event is correct when the event occurs
6211 // in 'evaluate' debugger request.
6212 TEST(NestedBreakEventContextData) {
6213 v8::HandleScope scope(CcTest::isolate());
6215 message_handler_hit_count = 0;
6217 ExecuteScriptForContextCheck(DebugEvalContextCheckMessageHandler);
6219 // One time compile event and two times break event.
6220 CHECK_GT(message_handler_hit_count, 3);
6222 // One break from the source and another from the evaluate request.
6223 CHECK_EQ(break_count, 2);
6224 CheckDebuggerUnloaded();
6228 // Debug event listener which counts the after compile events.
6229 int after_compile_message_count = 0;
6230 static void AfterCompileMessageHandler(const v8::Debug::Message& message) {
6231 // Count the number of scripts collected.
6232 if (message.IsEvent()) {
6233 if (message.GetEvent() == v8::AfterCompile) {
6234 after_compile_message_count++;
6235 } else if (message.GetEvent() == v8::Break) {
6236 SendContinueCommand();
6242 // Tests that after compile event is sent as many times as there are scripts
6244 TEST(AfterCompileMessageWhenMessageHandlerIsReset) {
6245 DebugLocalContext env;
6246 v8::HandleScope scope(env->GetIsolate());
6247 after_compile_message_count = 0;
6248 const char* script = "var a=1";
6250 v8::Debug::SetMessageHandler(AfterCompileMessageHandler);
6251 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), script))
6253 v8::Debug::SetMessageHandler(NULL);
6255 v8::Debug::SetMessageHandler(AfterCompileMessageHandler);
6256 v8::Debug::DebugBreak(env->GetIsolate());
6257 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), script))
6260 // Setting listener to NULL should cause debugger unload.
6261 v8::Debug::SetMessageHandler(NULL);
6262 CheckDebuggerUnloaded();
6264 // Compilation cache should be disabled when debugger is active.
6265 CHECK_EQ(2, after_compile_message_count);
6269 // Syntax error event handler which counts a number of events.
6270 int compile_error_event_count = 0;
6272 static void CompileErrorEventCounterClear() {
6273 compile_error_event_count = 0;
6276 static void CompileErrorEventCounter(
6277 const v8::Debug::EventDetails& event_details) {
6278 v8::DebugEvent event = event_details.GetEvent();
6280 if (event == v8::CompileError) {
6281 compile_error_event_count++;
6286 // Tests that syntax error event is sent as many times as there are scripts
6287 // with syntax error compiled.
6288 TEST(SyntaxErrorMessageOnSyntaxException) {
6289 DebugLocalContext env;
6290 v8::HandleScope scope(env->GetIsolate());
6292 // For this test, we want to break on uncaught exceptions:
6293 ChangeBreakOnException(false, true);
6295 v8::Debug::SetDebugEventListener(CompileErrorEventCounter);
6297 CompileErrorEventCounterClear();
6299 // Check initial state.
6300 CHECK_EQ(0, compile_error_event_count);
6302 // Throws SyntaxError: Unexpected end of input
6303 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "+++"));
6304 CHECK_EQ(1, compile_error_event_count);
6306 v8::Script::Compile(
6307 v8::String::NewFromUtf8(env->GetIsolate(), "/sel\\/: \\"));
6308 CHECK_EQ(2, compile_error_event_count);
6310 v8::Script::Compile(
6311 v8::String::NewFromUtf8(env->GetIsolate(), "JSON.parse('1234:')"));
6312 CHECK_EQ(2, compile_error_event_count);
6314 v8::Script::Compile(
6315 v8::String::NewFromUtf8(env->GetIsolate(), "new RegExp('/\\/\\\\');"));
6316 CHECK_EQ(2, compile_error_event_count);
6318 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "throw 1;"));
6319 CHECK_EQ(2, compile_error_event_count);
6323 // Tests that break event is sent when message handler is reset.
6324 TEST(BreakMessageWhenMessageHandlerIsReset) {
6325 DebugLocalContext env;
6326 v8::HandleScope scope(env->GetIsolate());
6327 after_compile_message_count = 0;
6328 const char* script = "function f() {};";
6330 v8::Debug::SetMessageHandler(AfterCompileMessageHandler);
6331 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), script))
6333 v8::Debug::SetMessageHandler(NULL);
6335 v8::Debug::SetMessageHandler(AfterCompileMessageHandler);
6336 v8::Debug::DebugBreak(env->GetIsolate());
6337 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
6338 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
6339 f->Call(env->Global(), 0, NULL);
6341 // Setting message handler to NULL should cause debugger unload.
6342 v8::Debug::SetMessageHandler(NULL);
6343 CheckDebuggerUnloaded();
6345 // Compilation cache should be disabled when debugger is active.
6346 CHECK_EQ(1, after_compile_message_count);
6350 static int exception_event_count = 0;
6351 static void ExceptionMessageHandler(const v8::Debug::Message& message) {
6352 if (message.IsEvent() && message.GetEvent() == v8::Exception) {
6353 exception_event_count++;
6354 SendContinueCommand();
6359 // Tests that exception event is sent when message handler is reset.
6360 TEST(ExceptionMessageWhenMessageHandlerIsReset) {
6361 DebugLocalContext env;
6362 v8::HandleScope scope(env->GetIsolate());
6364 // For this test, we want to break on uncaught exceptions:
6365 ChangeBreakOnException(false, true);
6367 exception_event_count = 0;
6368 const char* script = "function f() {throw new Error()};";
6370 v8::Debug::SetMessageHandler(AfterCompileMessageHandler);
6371 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), script))
6373 v8::Debug::SetMessageHandler(NULL);
6375 v8::Debug::SetMessageHandler(ExceptionMessageHandler);
6376 v8::Local<v8::Function> f = v8::Local<v8::Function>::Cast(
6377 env->Global()->Get(v8::String::NewFromUtf8(env->GetIsolate(), "f")));
6378 f->Call(env->Global(), 0, NULL);
6380 // Setting message handler to NULL should cause debugger unload.
6381 v8::Debug::SetMessageHandler(NULL);
6382 CheckDebuggerUnloaded();
6384 CHECK_EQ(1, exception_event_count);
6388 // Tests after compile event is sent when there are some provisional
6389 // breakpoints out of the scripts lines range.
6390 TEST(ProvisionalBreakpointOnLineOutOfRange) {
6391 DebugLocalContext env;
6392 v8::HandleScope scope(env->GetIsolate());
6394 const char* script = "function f() {};";
6395 const char* resource_name = "test_resource";
6397 // Set a couple of provisional breakpoint on lines out of the script lines
6399 int sbp1 = SetScriptBreakPointByNameFromJS(env->GetIsolate(), resource_name,
6400 3, -1 /* no column */);
6402 SetScriptBreakPointByNameFromJS(env->GetIsolate(), resource_name, 5, 5);
6404 after_compile_message_count = 0;
6405 v8::Debug::SetMessageHandler(AfterCompileMessageHandler);
6407 v8::ScriptOrigin origin(
6408 v8::String::NewFromUtf8(env->GetIsolate(), resource_name),
6409 v8::Integer::New(env->GetIsolate(), 10),
6410 v8::Integer::New(env->GetIsolate(), 1));
6411 // Compile a script whose first line number is greater than the breakpoints'
6413 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), script),
6416 // If the script is compiled successfully there is exactly one after compile
6417 // event. In case of an exception in debugger code after compile event is not
6419 CHECK_EQ(1, after_compile_message_count);
6421 ClearBreakPointFromJS(env->GetIsolate(), sbp1);
6422 ClearBreakPointFromJS(env->GetIsolate(), sbp2);
6423 v8::Debug::SetMessageHandler(NULL);
6427 static void BreakMessageHandler(const v8::Debug::Message& message) {
6428 i::Isolate* isolate = CcTest::i_isolate();
6429 if (message.IsEvent() && message.GetEvent() == v8::Break) {
6430 // Count the number of breaks.
6431 break_point_hit_count++;
6433 i::HandleScope scope(isolate);
6436 SendContinueCommand();
6437 } else if (message.IsEvent() && message.GetEvent() == v8::AfterCompile) {
6438 i::HandleScope scope(isolate);
6440 int current_count = break_point_hit_count;
6442 // Force serialization to trigger some internal JS execution.
6445 CHECK_EQ(current_count, break_point_hit_count);
6450 // Test that if DebugBreak is forced it is ignored when code from
6451 // debug-delay.js is executed.
6452 TEST(NoDebugBreakInAfterCompileMessageHandler) {
6453 DebugLocalContext env;
6454 v8::HandleScope scope(env->GetIsolate());
6456 // Register a debug event listener which sets the break flag and counts.
6457 v8::Debug::SetMessageHandler(BreakMessageHandler);
6459 // Set the debug break flag.
6460 v8::Debug::DebugBreak(env->GetIsolate());
6462 // Create a function for testing stepping.
6463 const char* src = "function f() { eval('var x = 10;'); } ";
6464 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
6466 // There should be only one break event.
6467 CHECK_EQ(1, break_point_hit_count);
6469 // Set the debug break flag again.
6470 v8::Debug::DebugBreak(env->GetIsolate());
6471 f->Call(env->Global(), 0, NULL);
6472 // There should be one more break event when the script is evaluated in 'f'.
6473 CHECK_EQ(2, break_point_hit_count);
6475 // Get rid of the debug message handler.
6476 v8::Debug::SetMessageHandler(NULL);
6477 CheckDebuggerUnloaded();
6481 static int counting_message_handler_counter;
6483 static void CountingMessageHandler(const v8::Debug::Message& message) {
6484 if (message.IsResponse()) counting_message_handler_counter++;
6488 // Test that debug messages get processed when ProcessDebugMessages is called.
6489 TEST(ProcessDebugMessages) {
6490 DebugLocalContext env;
6491 v8::Isolate* isolate = env->GetIsolate();
6492 v8::HandleScope scope(isolate);
6494 counting_message_handler_counter = 0;
6496 v8::Debug::SetMessageHandler(CountingMessageHandler);
6498 const int kBufferSize = 1000;
6499 uint16_t buffer[kBufferSize];
6500 const char* scripts_command =
6502 "\"type\":\"request\","
6503 "\"command\":\"scripts\"}";
6505 // Send scripts command.
6506 v8::Debug::SendCommand(
6507 isolate, buffer, AsciiToUtf16(scripts_command, buffer));
6509 CHECK_EQ(0, counting_message_handler_counter);
6510 v8::Debug::ProcessDebugMessages();
6511 // At least one message should come
6512 CHECK_GE(counting_message_handler_counter, 1);
6514 counting_message_handler_counter = 0;
6516 v8::Debug::SendCommand(
6517 isolate, buffer, AsciiToUtf16(scripts_command, buffer));
6518 v8::Debug::SendCommand(
6519 isolate, buffer, AsciiToUtf16(scripts_command, buffer));
6520 CHECK_EQ(0, counting_message_handler_counter);
6521 v8::Debug::ProcessDebugMessages();
6522 // At least two messages should come
6523 CHECK_GE(counting_message_handler_counter, 2);
6525 // Get rid of the debug message handler.
6526 v8::Debug::SetMessageHandler(NULL);
6527 CheckDebuggerUnloaded();
6531 class SendCommandThread : public v8::base::Thread {
6533 explicit SendCommandThread(v8::Isolate* isolate)
6534 : Thread(Options("SendCommandThread")),
6536 isolate_(isolate) {}
6538 static void ProcessDebugMessages(v8::Isolate* isolate, void* data) {
6539 v8::Debug::ProcessDebugMessages();
6540 reinterpret_cast<v8::base::Semaphore*>(data)->Signal();
6543 virtual void Run() {
6545 const int kBufferSize = 1000;
6546 uint16_t buffer[kBufferSize];
6547 const char* scripts_command =
6549 "\"type\":\"request\","
6550 "\"command\":\"scripts\"}";
6551 int length = AsciiToUtf16(scripts_command, buffer);
6552 // Send scripts command.
6554 for (int i = 0; i < 100; i++) {
6555 CHECK_EQ(i, counting_message_handler_counter);
6556 // Queue debug message.
6557 v8::Debug::SendCommand(isolate_, buffer, length);
6558 // Synchronize with the main thread to force message processing.
6559 isolate_->RequestInterrupt(ProcessDebugMessages, &semaphore_);
6563 v8::V8::TerminateExecution(isolate_);
6566 void StartSending() {
6567 semaphore_.Signal();
6571 v8::base::Semaphore semaphore_;
6572 v8::Isolate* isolate_;
6576 static SendCommandThread* send_command_thread_ = NULL;
6578 static void StartSendingCommands(
6579 const v8::FunctionCallbackInfo<v8::Value>& info) {
6580 send_command_thread_->StartSending();
6584 TEST(ProcessDebugMessagesThreaded) {
6585 DebugLocalContext env;
6586 v8::Isolate* isolate = env->GetIsolate();
6587 v8::HandleScope scope(isolate);
6589 counting_message_handler_counter = 0;
6591 v8::Debug::SetMessageHandler(CountingMessageHandler);
6592 send_command_thread_ = new SendCommandThread(isolate);
6593 send_command_thread_->Start();
6595 v8::Handle<v8::FunctionTemplate> start =
6596 v8::FunctionTemplate::New(isolate, StartSendingCommands);
6597 env->Global()->Set(v8_str("start"), start->GetFunction());
6599 CompileRun("start(); while (true) { }");
6601 CHECK_EQ(100, counting_message_handler_counter);
6603 v8::Debug::SetMessageHandler(NULL);
6604 CheckDebuggerUnloaded();
6608 struct BacktraceData {
6609 static int frame_counter;
6610 static void MessageHandler(const v8::Debug::Message& message) {
6611 char print_buffer[1000];
6612 v8::String::Value json(message.GetJSON());
6613 Utf16ToAscii(*json, json.length(), print_buffer, 1000);
6615 if (strstr(print_buffer, "backtrace") == NULL) {
6618 frame_counter = GetTotalFramesInt(print_buffer);
6622 int BacktraceData::frame_counter;
6625 // Test that debug messages get processed when ProcessDebugMessages is called.
6627 DebugLocalContext env;
6628 v8::Isolate* isolate = env->GetIsolate();
6629 v8::HandleScope scope(isolate);
6631 v8::Debug::SetMessageHandler(BacktraceData::MessageHandler);
6633 const int kBufferSize = 1000;
6634 uint16_t buffer[kBufferSize];
6635 const char* scripts_command =
6637 "\"type\":\"request\","
6638 "\"command\":\"backtrace\"}";
6640 // Check backtrace from ProcessDebugMessages.
6641 BacktraceData::frame_counter = -10;
6642 v8::Debug::SendCommand(
6645 AsciiToUtf16(scripts_command, buffer),
6647 v8::Debug::ProcessDebugMessages();
6648 CHECK_EQ(BacktraceData::frame_counter, 0);
6650 v8::Handle<v8::String> void0 =
6651 v8::String::NewFromUtf8(env->GetIsolate(), "void(0)");
6652 v8::Handle<v8::Script> script = CompileWithOrigin(void0, void0);
6654 // Check backtrace from "void(0)" script.
6655 BacktraceData::frame_counter = -10;
6656 v8::Debug::SendCommand(
6659 AsciiToUtf16(scripts_command, buffer),
6662 CHECK_EQ(BacktraceData::frame_counter, 1);
6664 // Get rid of the debug message handler.
6665 v8::Debug::SetMessageHandler(NULL);
6666 CheckDebuggerUnloaded();
6671 DebugLocalContext env;
6672 v8::Isolate* isolate = env->GetIsolate();
6673 v8::HandleScope scope(isolate);
6674 v8::Handle<v8::Value> obj =
6675 v8::Debug::GetMirror(v8::String::NewFromUtf8(isolate, "hodja"));
6676 v8::ScriptCompiler::Source source(v8_str(
6677 "function runTest(mirror) {"
6678 " return mirror.isString() && (mirror.length() == 5);"
6682 v8::Handle<v8::Function> run_test = v8::Handle<v8::Function>::Cast(
6683 v8::ScriptCompiler::CompileUnbound(isolate, &source)
6684 ->BindToCurrentContext()
6686 v8::Handle<v8::Value> result = run_test->Call(env->Global(), 1, &obj);
6687 CHECK(result->IsTrue());
6691 // Test that the debug break flag works with function.apply.
6692 TEST(DebugBreakFunctionApply) {
6693 DebugLocalContext env;
6694 v8::HandleScope scope(env->GetIsolate());
6696 // Create a function for testing breaking in apply.
6697 v8::Local<v8::Function> foo = CompileFunction(
6699 "function baz(x) { }"
6700 "function bar(x) { baz(); }"
6701 "function foo(){ bar.apply(this, [1]); }",
6704 // Register a debug event listener which steps and counts.
6705 v8::Debug::SetDebugEventListener(DebugEventBreakMax);
6707 // Set the debug break flag before calling the code using function.apply.
6708 v8::Debug::DebugBreak(env->GetIsolate());
6710 // Limit the number of debug breaks. This is a regression test for issue 493
6711 // where this test would enter an infinite loop.
6712 break_point_hit_count = 0;
6713 max_break_point_hit_count = 10000; // 10000 => infinite loop.
6714 foo->Call(env->Global(), 0, NULL);
6716 // When keeping the debug break several break will happen.
6717 CHECK_GT(break_point_hit_count, 1);
6719 v8::Debug::SetDebugEventListener(NULL);
6720 CheckDebuggerUnloaded();
6724 v8::Handle<v8::Context> debugee_context;
6725 v8::Handle<v8::Context> debugger_context;
6728 // Property getter that checks that current and calling contexts
6729 // are both the debugee contexts.
6730 static void NamedGetterWithCallingContextCheck(
6731 v8::Local<v8::String> name,
6732 const v8::PropertyCallbackInfo<v8::Value>& info) {
6733 CHECK_EQ(0, strcmp(*v8::String::Utf8Value(name), "a"));
6734 v8::Handle<v8::Context> current = info.GetIsolate()->GetCurrentContext();
6735 CHECK(current == debugee_context);
6736 CHECK(current != debugger_context);
6737 v8::Handle<v8::Context> calling = info.GetIsolate()->GetCallingContext();
6738 CHECK(calling == debugee_context);
6739 CHECK(calling != debugger_context);
6740 info.GetReturnValue().Set(1);
6744 // Debug event listener that checks if the first argument of a function is
6745 // an object with property 'a' == 1. If the property has custom accessor
6746 // this handler will eventually invoke it.
6747 static void DebugEventGetAtgumentPropertyValue(
6748 const v8::Debug::EventDetails& event_details) {
6749 v8::DebugEvent event = event_details.GetEvent();
6750 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
6751 if (event == v8::Break) {
6752 break_point_hit_count++;
6753 CHECK(debugger_context == CcTest::isolate()->GetCurrentContext());
6754 v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(CompileRun(
6755 "(function(exec_state) {\n"
6756 " return (exec_state.frame(0).argumentValue(0).property('a').\n"
6757 " value().value() == 1);\n"
6760 v8::Handle<v8::Value> argv[argc] = { exec_state };
6761 v8::Handle<v8::Value> result = func->Call(exec_state, argc, argv);
6762 CHECK(result->IsTrue());
6767 TEST(CallingContextIsNotDebugContext) {
6768 v8::internal::Debug* debug = CcTest::i_isolate()->debug();
6769 // Create and enter a debugee context.
6770 DebugLocalContext env;
6771 v8::Isolate* isolate = env->GetIsolate();
6772 v8::HandleScope scope(isolate);
6775 // Save handles to the debugger and debugee contexts to be used in
6776 // NamedGetterWithCallingContextCheck.
6777 debugee_context = env.context();
6778 debugger_context = v8::Utils::ToLocal(debug->debug_context());
6780 // Create object with 'a' property accessor.
6781 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New(isolate);
6782 named->SetAccessor(v8::String::NewFromUtf8(isolate, "a"),
6783 NamedGetterWithCallingContextCheck);
6784 env->Global()->Set(v8::String::NewFromUtf8(isolate, "obj"),
6785 named->NewInstance());
6787 // Register the debug event listener
6788 v8::Debug::SetDebugEventListener(DebugEventGetAtgumentPropertyValue);
6790 // Create a function that invokes debugger.
6791 v8::Local<v8::Function> foo = CompileFunction(
6793 "function bar(x) { debugger; }"
6794 "function foo(){ bar(obj); }",
6797 break_point_hit_count = 0;
6798 foo->Call(env->Global(), 0, NULL);
6799 CHECK_EQ(1, break_point_hit_count);
6801 v8::Debug::SetDebugEventListener(NULL);
6802 debugee_context = v8::Handle<v8::Context>();
6803 debugger_context = v8::Handle<v8::Context>();
6804 CheckDebuggerUnloaded();
6808 TEST(DebugContextIsPreservedBetweenAccesses) {
6809 v8::HandleScope scope(CcTest::isolate());
6810 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
6811 v8::Local<v8::Context> context1 = v8::Debug::GetDebugContext();
6812 v8::Local<v8::Context> context2 = v8::Debug::GetDebugContext();
6813 CHECK(v8::Utils::OpenHandle(*context1).is_identical_to(
6814 v8::Utils::OpenHandle(*context2)));
6815 v8::Debug::SetDebugEventListener(NULL);
6819 static v8::Handle<v8::Value> expected_callback_data;
6820 static void DebugEventContextChecker(const v8::Debug::EventDetails& details) {
6821 CHECK(details.GetEventContext() == expected_context);
6822 CHECK_EQ(expected_callback_data, details.GetCallbackData());
6826 // Check that event details contain context where debug event occured.
6827 TEST(DebugEventContext) {
6828 v8::Isolate* isolate = CcTest::isolate();
6829 v8::HandleScope scope(isolate);
6830 expected_context = v8::Context::New(isolate);
6831 expected_callback_data = v8::Int32::New(isolate, 2010);
6832 v8::Debug::SetDebugEventListener(DebugEventContextChecker,
6833 expected_callback_data);
6834 v8::Context::Scope context_scope(expected_context);
6835 v8::Script::Compile(
6836 v8::String::NewFromUtf8(isolate, "(function(){debugger;})();"))->Run();
6837 expected_context.Clear();
6838 v8::Debug::SetDebugEventListener(NULL);
6839 expected_context_data = v8::Handle<v8::Value>();
6840 CheckDebuggerUnloaded();
6844 static void* expected_break_data;
6845 static bool was_debug_break_called;
6846 static bool was_debug_event_called;
6847 static void DebugEventBreakDataChecker(const v8::Debug::EventDetails& details) {
6848 if (details.GetEvent() == v8::BreakForCommand) {
6849 CHECK_EQ(expected_break_data, details.GetClientData());
6850 was_debug_event_called = true;
6851 } else if (details.GetEvent() == v8::Break) {
6852 was_debug_break_called = true;
6857 // Check that event details contain context where debug event occured.
6858 TEST(DebugEventBreakData) {
6859 DebugLocalContext env;
6860 v8::Isolate* isolate = env->GetIsolate();
6861 v8::HandleScope scope(isolate);
6862 v8::Debug::SetDebugEventListener(DebugEventBreakDataChecker);
6864 TestClientData::constructor_call_counter = 0;
6865 TestClientData::destructor_call_counter = 0;
6867 expected_break_data = NULL;
6868 was_debug_event_called = false;
6869 was_debug_break_called = false;
6870 v8::Debug::DebugBreakForCommand(isolate, NULL);
6871 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
6872 "(function(x){return x;})(1);"))
6874 CHECK(was_debug_event_called);
6875 CHECK(!was_debug_break_called);
6877 TestClientData* data1 = new TestClientData();
6878 expected_break_data = data1;
6879 was_debug_event_called = false;
6880 was_debug_break_called = false;
6881 v8::Debug::DebugBreakForCommand(isolate, data1);
6882 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
6883 "(function(x){return x+1;})(1);"))
6885 CHECK(was_debug_event_called);
6886 CHECK(!was_debug_break_called);
6888 expected_break_data = NULL;
6889 was_debug_event_called = false;
6890 was_debug_break_called = false;
6891 v8::Debug::DebugBreak(isolate);
6892 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
6893 "(function(x){return x+2;})(1);"))
6895 CHECK(!was_debug_event_called);
6896 CHECK(was_debug_break_called);
6898 TestClientData* data2 = new TestClientData();
6899 expected_break_data = data2;
6900 was_debug_event_called = false;
6901 was_debug_break_called = false;
6902 v8::Debug::DebugBreak(isolate);
6903 v8::Debug::DebugBreakForCommand(isolate, data2);
6904 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(),
6905 "(function(x){return x+3;})(1);"))
6907 CHECK(was_debug_event_called);
6908 CHECK(was_debug_break_called);
6910 CHECK_EQ(2, TestClientData::constructor_call_counter);
6911 CHECK_EQ(TestClientData::constructor_call_counter,
6912 TestClientData::destructor_call_counter);
6914 v8::Debug::SetDebugEventListener(NULL);
6915 CheckDebuggerUnloaded();
6918 static bool debug_event_break_deoptimize_done = false;
6920 static void DebugEventBreakDeoptimize(
6921 const v8::Debug::EventDetails& event_details) {
6922 v8::DebugEvent event = event_details.GetEvent();
6923 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
6924 if (event == v8::Break) {
6925 if (!frame_function_name.IsEmpty()) {
6926 // Get the name of the function.
6928 v8::Handle<v8::Value> argv[argc] = {
6929 exec_state, v8::Integer::New(CcTest::isolate(), 0)
6931 v8::Handle<v8::Value> result =
6932 frame_function_name->Call(exec_state, argc, argv);
6933 if (!result->IsUndefined()) {
6935 CHECK(result->IsString());
6936 v8::Handle<v8::String> function_name(result->ToString());
6937 function_name->WriteUtf8(fn);
6938 if (strcmp(fn, "bar") == 0) {
6939 i::Deoptimizer::DeoptimizeAll(CcTest::i_isolate());
6940 debug_event_break_deoptimize_done = true;
6945 v8::Debug::DebugBreak(CcTest::isolate());
6950 // Test deoptimization when execution is broken using the debug break stack
6952 TEST(DeoptimizeDuringDebugBreak) {
6953 DebugLocalContext env;
6954 v8::HandleScope scope(env->GetIsolate());
6957 // Create a function for checking the function when hitting a break point.
6958 frame_function_name = CompileFunction(&env,
6959 frame_function_name_source,
6960 "frame_function_name");
6963 // Set a debug event listener which will keep interrupting execution until
6964 // debug break. When inside function bar it will deoptimize all functions.
6965 // This tests lazy deoptimization bailout for the stack check, as the first
6966 // time in function bar when using debug break and no break points will be at
6967 // the initial stack check.
6968 v8::Debug::SetDebugEventListener(DebugEventBreakDeoptimize);
6970 // Compile and run function bar which will optimize it for some flag settings.
6971 v8::Script::Compile(v8::String::NewFromUtf8(
6972 env->GetIsolate(), "function bar(){}; bar()"))->Run();
6974 // Set debug break and call bar again.
6975 v8::Debug::DebugBreak(env->GetIsolate());
6976 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), "bar()"))
6979 CHECK(debug_event_break_deoptimize_done);
6981 v8::Debug::SetDebugEventListener(NULL);
6985 static void DebugEventBreakWithOptimizedStack(
6986 const v8::Debug::EventDetails& event_details) {
6987 v8::Isolate* isolate = event_details.GetEventContext()->GetIsolate();
6988 v8::DebugEvent event = event_details.GetEvent();
6989 v8::Handle<v8::Object> exec_state = event_details.GetExecutionState();
6990 if (event == v8::Break) {
6991 if (!frame_function_name.IsEmpty()) {
6992 for (int i = 0; i < 2; i++) {
6994 v8::Handle<v8::Value> argv[argc] = {
6995 exec_state, v8::Integer::New(isolate, i)
6997 // Get the name of the function in frame i.
6998 v8::Handle<v8::Value> result =
6999 frame_function_name->Call(exec_state, argc, argv);
7000 CHECK(result->IsString());
7001 v8::Handle<v8::String> function_name(result->ToString());
7002 CHECK(function_name->Equals(v8::String::NewFromUtf8(isolate, "loop")));
7003 // Get the name of the first argument in frame i.
7004 result = frame_argument_name->Call(exec_state, argc, argv);
7005 CHECK(result->IsString());
7006 v8::Handle<v8::String> argument_name(result->ToString());
7007 CHECK(argument_name->Equals(v8::String::NewFromUtf8(isolate, "count")));
7008 // Get the value of the first argument in frame i. If the
7009 // funtion is optimized the value will be undefined, otherwise
7010 // the value will be '1 - i'.
7012 // TODO(3141533): We should be able to get the real value for
7013 // optimized frames.
7014 result = frame_argument_value->Call(exec_state, argc, argv);
7015 CHECK(result->IsUndefined() || (result->Int32Value() == 1 - i));
7016 // Get the name of the first local variable.
7017 result = frame_local_name->Call(exec_state, argc, argv);
7018 CHECK(result->IsString());
7019 v8::Handle<v8::String> local_name(result->ToString());
7020 CHECK(local_name->Equals(v8::String::NewFromUtf8(isolate, "local")));
7021 // Get the value of the first local variable. If the function
7022 // is optimized the value will be undefined, otherwise it will
7025 // TODO(3141533): We should be able to get the real value for
7026 // optimized frames.
7027 result = frame_local_value->Call(exec_state, argc, argv);
7028 CHECK(result->IsUndefined() || (result->Int32Value() == 42));
7035 static void ScheduleBreak(const v8::FunctionCallbackInfo<v8::Value>& args) {
7036 v8::Debug::SetDebugEventListener(DebugEventBreakWithOptimizedStack);
7037 v8::Debug::DebugBreak(args.GetIsolate());
7041 TEST(DebugBreakStackInspection) {
7042 DebugLocalContext env;
7043 v8::HandleScope scope(env->GetIsolate());
7045 frame_function_name =
7046 CompileFunction(&env, frame_function_name_source, "frame_function_name");
7047 frame_argument_name =
7048 CompileFunction(&env, frame_argument_name_source, "frame_argument_name");
7049 frame_argument_value = CompileFunction(&env,
7050 frame_argument_value_source,
7051 "frame_argument_value");
7053 CompileFunction(&env, frame_local_name_source, "frame_local_name");
7055 CompileFunction(&env, frame_local_value_source, "frame_local_value");
7057 v8::Handle<v8::FunctionTemplate> schedule_break_template =
7058 v8::FunctionTemplate::New(env->GetIsolate(), ScheduleBreak);
7059 v8::Handle<v8::Function> schedule_break =
7060 schedule_break_template->GetFunction();
7061 env->Global()->Set(v8_str("scheduleBreak"), schedule_break);
7064 "function loop(count) {"
7066 " if (count < 1) { scheduleBreak(); loop(count + 1); }"
7069 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), src))->Run();
7073 // Test that setting the terminate execution flag during debug break processing.
7074 static void TestDebugBreakInLoop(const char* loop_head,
7075 const char** loop_bodies,
7076 const char* loop_tail) {
7077 // Receive 100 breaks for each test and then terminate JavaScript execution.
7078 static const int kBreaksPerTest = 100;
7080 for (int i = 0; loop_bodies[i] != NULL; i++) {
7081 // Perform a lazy deoptimization after various numbers of breaks
7083 for (int j = 0; j < 7; j++) {
7084 break_point_hit_count_deoptimize = j;
7086 break_point_hit_count_deoptimize = kBreaksPerTest;
7089 break_point_hit_count = 0;
7090 max_break_point_hit_count = kBreaksPerTest;
7091 terminate_after_max_break_point_hit = true;
7093 EmbeddedVector<char, 1024> buffer;
7095 "function f() {%s%s%s}",
7096 loop_head, loop_bodies[i], loop_tail);
7098 // Function with infinite loop.
7099 CompileRun(buffer.start());
7101 // Set the debug break to enter the debugger as soon as possible.
7102 v8::Debug::DebugBreak(CcTest::isolate());
7104 // Call function with infinite loop.
7106 CHECK_EQ(kBreaksPerTest, break_point_hit_count);
7108 CHECK(!v8::V8::IsExecutionTerminating());
7114 TEST(DebugBreakLoop) {
7115 DebugLocalContext env;
7116 v8::HandleScope scope(env->GetIsolate());
7118 // Register a debug event listener which sets the break flag and counts.
7119 v8::Debug::SetDebugEventListener(DebugEventBreakMax);
7121 // Create a function for getting the frame count when hitting the break.
7122 frame_count = CompileFunction(&env, frame_count_source, "frame_count");
7124 CompileRun("var a = 1;");
7125 CompileRun("function g() { }");
7126 CompileRun("function h() { }");
7128 const char* loop_bodies[] = {
7131 "if (a == 0) { g() }",
7132 "if (a == 1) { g() }",
7133 "if (a == 0) { g() } else { h() }",
7134 "if (a == 0) { continue }",
7135 "if (a == 1) { continue }",
7136 "switch (a) { case 1: g(); }",
7137 "switch (a) { case 1: continue; }",
7138 "switch (a) { case 1: g(); break; default: h() }",
7139 "switch (a) { case 1: continue; break; default: h() }",
7143 TestDebugBreakInLoop("while (true) {", loop_bodies, "}");
7144 TestDebugBreakInLoop("while (a == 1) {", loop_bodies, "}");
7146 TestDebugBreakInLoop("do {", loop_bodies, "} while (true)");
7147 TestDebugBreakInLoop("do {", loop_bodies, "} while (a == 1)");
7149 TestDebugBreakInLoop("for (;;) {", loop_bodies, "}");
7150 TestDebugBreakInLoop("for (;a == 1;) {", loop_bodies, "}");
7152 // Get rid of the debug event listener.
7153 v8::Debug::SetDebugEventListener(NULL);
7154 CheckDebuggerUnloaded();
7158 v8::Local<v8::Script> inline_script;
7160 static void DebugBreakInlineListener(
7161 const v8::Debug::EventDetails& event_details) {
7162 v8::DebugEvent event = event_details.GetEvent();
7163 if (event != v8::Break) return;
7165 int expected_frame_count = 4;
7166 int expected_line_number[] = {1, 4, 7, 12};
7168 i::Handle<i::Object> compiled_script = v8::Utils::OpenHandle(*inline_script);
7169 i::Handle<i::Script> source_script = i::Handle<i::Script>(i::Script::cast(
7170 i::JSFunction::cast(*compiled_script)->shared()->script()));
7172 int break_id = CcTest::i_isolate()->debug()->break_id();
7174 i::Vector<char> script_vector(script, sizeof(script));
7175 SNPrintF(script_vector, "%%GetFrameCount(%d)", break_id);
7176 v8::Local<v8::Value> result = CompileRun(script);
7178 int frame_count = result->Int32Value();
7179 CHECK_EQ(expected_frame_count, frame_count);
7181 for (int i = 0; i < frame_count; i++) {
7182 // The 5. element in the returned array of GetFrameDetails contains the
7183 // source position of that frame.
7184 SNPrintF(script_vector, "%%GetFrameDetails(%d, %d)[5]", break_id, i);
7185 v8::Local<v8::Value> result = CompileRun(script);
7186 CHECK_EQ(expected_line_number[i],
7187 i::Script::GetLineNumber(source_script, result->Int32Value()));
7189 v8::Debug::SetDebugEventListener(NULL);
7190 v8::V8::TerminateExecution(CcTest::isolate());
7194 TEST(DebugBreakInline) {
7195 i::FLAG_allow_natives_syntax = true;
7196 DebugLocalContext env;
7197 v8::HandleScope scope(env->GetIsolate());
7198 const char* source =
7199 "function debug(b) { \n"
7200 " if (b) debugger; \n"
7202 "function f(b) { \n"
7205 "function g(b) { \n"
7210 "%OptimizeFunctionOnNextCall(g); \n"
7212 v8::Debug::SetDebugEventListener(DebugBreakInlineListener);
7214 v8::Script::Compile(v8::String::NewFromUtf8(env->GetIsolate(), source));
7215 inline_script->Run();
7219 static void DebugEventStepNext(
7220 const v8::Debug::EventDetails& event_details) {
7221 v8::DebugEvent event = event_details.GetEvent();
7222 if (event == v8::Break) {
7223 PrepareStep(StepNext);
7228 static void RunScriptInANewCFrame(const char* source) {
7229 v8::TryCatch try_catch;
7231 CHECK(try_catch.HasCaught());
7235 TEST(Regress131642) {
7237 // When doing StepNext through the first script, the debugger is not reset
7238 // after exiting through exception. A flawed implementation enabling the
7239 // debugger to step into Array.prototype.forEach breaks inside the callback
7240 // for forEach in the second script under the assumption that we are in a
7241 // recursive call. In an attempt to step out, we crawl the stack using the
7242 // recorded frame pointer from the first script and fail when not finding it
7244 DebugLocalContext env;
7245 v8::HandleScope scope(env->GetIsolate());
7246 v8::Debug::SetDebugEventListener(DebugEventStepNext);
7248 // We step through the first script. It exits through an exception. We run
7249 // this inside a new frame to record a different FP than the second script
7251 const char* script_1 = "debugger; throw new Error();";
7252 RunScriptInANewCFrame(script_1);
7254 // The second script uses forEach.
7255 const char* script_2 = "[0].forEach(function() { });";
7256 CompileRun(script_2);
7258 v8::Debug::SetDebugEventListener(NULL);
7262 // Import from test-heap.cc
7263 int CountNativeContexts();
7266 static void NopListener(const v8::Debug::EventDetails& event_details) {
7270 TEST(DebuggerCreatesContextIffActive) {
7271 DebugLocalContext env;
7272 v8::HandleScope scope(env->GetIsolate());
7273 CHECK_EQ(1, CountNativeContexts());
7275 v8::Debug::SetDebugEventListener(NULL);
7276 CompileRun("debugger;");
7277 CHECK_EQ(1, CountNativeContexts());
7279 v8::Debug::SetDebugEventListener(NopListener);
7280 CompileRun("debugger;");
7281 CHECK_EQ(2, CountNativeContexts());
7283 v8::Debug::SetDebugEventListener(NULL);
7287 TEST(LiveEditEnabled) {
7288 v8::internal::FLAG_allow_natives_syntax = true;
7290 v8::HandleScope scope(env->GetIsolate());
7291 v8::Debug::SetLiveEditEnabled(env->GetIsolate(), true);
7292 CompileRun("%LiveEditCompareStrings('', '')");
7296 TEST(LiveEditDisabled) {
7297 v8::internal::FLAG_allow_natives_syntax = true;
7299 v8::HandleScope scope(env->GetIsolate());
7300 v8::Debug::SetLiveEditEnabled(env->GetIsolate(), false);
7301 CompileRun("%LiveEditCompareStrings('', '')");
7305 TEST(PrecompiledFunction) {
7306 // Regression test for crbug.com/346207. If we have preparse data, parsing the
7307 // function in the presence of the debugger (and breakpoints) should still
7308 // succeed. The bug was that preparsing was done lazily and parsing was done
7309 // eagerly, so, the symbol streams didn't match.
7310 DebugLocalContext env;
7311 v8::HandleScope scope(env->GetIsolate());
7313 v8::Debug::SetDebugEventListener(DebugBreakInlineListener);
7315 v8::Local<v8::Function> break_here =
7316 CompileFunction(&env, "function break_here(){}", "break_here");
7317 SetBreakPoint(break_here, 0);
7319 const char* source =
7320 "var a = b = c = 1; \n"
7321 "function this_is_lazy() { \n"
7322 // This symbol won't appear in the preparse data.
7325 "function bar() { \n"
7326 " return \"bar\"; \n"
7330 v8::Local<v8::Value> result = ParserCacheCompileRun(source);
7331 CHECK(result->IsString());
7332 v8::String::Utf8Value utf8(result);
7333 CHECK_EQ("bar", *utf8);
7335 v8::Debug::SetDebugEventListener(NULL);
7336 CheckDebuggerUnloaded();
7340 static void DebugBreakStackTraceListener(
7341 const v8::Debug::EventDetails& event_details) {
7342 v8::StackTrace::CurrentStackTrace(CcTest::isolate(), 10);
7346 static void AddDebugBreak(const v8::FunctionCallbackInfo<v8::Value>& args) {
7347 v8::Debug::DebugBreak(args.GetIsolate());
7351 TEST(DebugBreakStackTrace) {
7352 DebugLocalContext env;
7353 v8::HandleScope scope(env->GetIsolate());
7354 v8::Debug::SetDebugEventListener(DebugBreakStackTraceListener);
7355 v8::Handle<v8::FunctionTemplate> add_debug_break_template =
7356 v8::FunctionTemplate::New(env->GetIsolate(), AddDebugBreak);
7357 v8::Handle<v8::Function> add_debug_break =
7358 add_debug_break_template->GetFunction();
7359 env->Global()->Set(v8_str("add_debug_break"), add_debug_break);
7361 CompileRun("(function loop() {"
7362 " for (var j = 0; j < 1000; j++) {"
7363 " for (var i = 0; i < 1000; i++) {"
7364 " if (i == 999) add_debug_break();"
7371 v8::base::Semaphore terminate_requested_semaphore(0);
7372 v8::base::Semaphore terminate_fired_semaphore(0);
7373 bool terminate_already_fired = false;
7376 static void DebugBreakTriggerTerminate(
7377 const v8::Debug::EventDetails& event_details) {
7378 if (event_details.GetEvent() != v8::Break || terminate_already_fired) return;
7379 terminate_requested_semaphore.Signal();
7380 // Wait for at most 2 seconds for the terminate request.
7381 CHECK(terminate_fired_semaphore.WaitFor(v8::base::TimeDelta::FromSeconds(2)));
7382 terminate_already_fired = true;
7386 class TerminationThread : public v8::base::Thread {
7388 explicit TerminationThread(v8::Isolate* isolate)
7389 : Thread(Options("terminator")), isolate_(isolate) {}
7391 virtual void Run() {
7392 terminate_requested_semaphore.Wait();
7393 v8::V8::TerminateExecution(isolate_);
7394 terminate_fired_semaphore.Signal();
7398 v8::Isolate* isolate_;
7402 TEST(DebugBreakOffThreadTerminate) {
7403 DebugLocalContext env;
7404 v8::Isolate* isolate = env->GetIsolate();
7405 v8::HandleScope scope(isolate);
7406 v8::Debug::SetDebugEventListener(DebugBreakTriggerTerminate);
7407 TerminationThread terminator(isolate);
7409 v8::TryCatch try_catch;
7410 v8::Debug::DebugBreak(isolate);
7411 CompileRun("while (true);");
7412 CHECK(try_catch.HasTerminated());