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