blob: 4ffcee3dbf64125c08e379e40a928f565f4b348d [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
Steve Block3ce2e202009-11-05 08:53:23 +00003542// We match parts of the message to decide if it is a exception message.
3543bool IsExceptionEventMessage(char *message) {
3544 const char* type_event = "\"type\":\"event\"";
3545 const char* event_exception = "\"event\":\"exception\"";
3546 // Does the message contain both type:event and event:exception?
3547 return strstr(message, type_event) != NULL &&
3548 strstr(message, event_exception) != NULL;
3549}
3550
3551
3552// We match the message wether it is an evaluate response message.
3553bool IsEvaluateResponseMessage(char* message) {
3554 const char* type_response = "\"type\":\"response\"";
3555 const char* command_evaluate = "\"command\":\"evaluate\"";
3556 // Does the message contain both type:response and command:evaluate?
3557 return strstr(message, type_response) != NULL &&
3558 strstr(message, command_evaluate) != NULL;
3559}
3560
3561
3562// We match parts of the message to get evaluate result int value.
3563int GetEvaluateIntResult(char *message) {
3564 const char* value = "\"value\":";
3565 char* pos = strstr(message, value);
3566 if (pos == NULL) {
3567 return -1;
3568 }
3569 int res = -1;
3570 res = atoi(pos + strlen(value));
3571 return res;
3572}
3573
3574
3575// We match parts of the message to get hit breakpoint id.
3576int GetBreakpointIdFromBreakEventMessage(char *message) {
3577 const char* breakpoints = "\"breakpoints\":[";
3578 char* pos = strstr(message, breakpoints);
3579 if (pos == NULL) {
3580 return -1;
3581 }
3582 int res = -1;
3583 res = atoi(pos + strlen(breakpoints));
3584 return res;
3585}
3586
3587
Steve Blocka7e24c12009-10-30 11:49:00 +00003588/* Test MessageQueues */
3589/* Tests the message queues that hold debugger commands and
3590 * response messages to the debugger. Fills queues and makes
3591 * them grow.
3592 */
3593Barriers message_queue_barriers;
3594
3595// This is the debugger thread, that executes no v8 calls except
3596// placing JSON debugger commands in the queue.
3597class MessageQueueDebuggerThread : public v8::internal::Thread {
3598 public:
3599 void Run();
3600};
3601
3602static void MessageHandler(const uint16_t* message, int length,
3603 v8::Debug::ClientData* client_data) {
3604 static char print_buffer[1000];
3605 Utf16ToAscii(message, length, print_buffer);
3606 if (IsBreakEventMessage(print_buffer)) {
3607 // Lets test script wait until break occurs to send commands.
3608 // Signals when a break is reported.
3609 message_queue_barriers.semaphore_2->Signal();
3610 }
3611
3612 // Allow message handler to block on a semaphore, to test queueing of
3613 // messages while blocked.
3614 message_queue_barriers.semaphore_1->Wait();
Steve Blocka7e24c12009-10-30 11:49:00 +00003615}
3616
3617void MessageQueueDebuggerThread::Run() {
3618 const int kBufferSize = 1000;
3619 uint16_t buffer_1[kBufferSize];
3620 uint16_t buffer_2[kBufferSize];
3621 const char* command_1 =
3622 "{\"seq\":117,"
3623 "\"type\":\"request\","
3624 "\"command\":\"evaluate\","
3625 "\"arguments\":{\"expression\":\"1+2\"}}";
3626 const char* command_2 =
3627 "{\"seq\":118,"
3628 "\"type\":\"request\","
3629 "\"command\":\"evaluate\","
3630 "\"arguments\":{\"expression\":\"1+a\"}}";
3631 const char* command_3 =
3632 "{\"seq\":119,"
3633 "\"type\":\"request\","
3634 "\"command\":\"evaluate\","
3635 "\"arguments\":{\"expression\":\"c.d * b\"}}";
3636 const char* command_continue =
3637 "{\"seq\":106,"
3638 "\"type\":\"request\","
3639 "\"command\":\"continue\"}";
3640 const char* command_single_step =
3641 "{\"seq\":107,"
3642 "\"type\":\"request\","
3643 "\"command\":\"continue\","
3644 "\"arguments\":{\"stepaction\":\"next\"}}";
3645
3646 /* Interleaved sequence of actions by the two threads:*/
3647 // Main thread compiles and runs source_1
3648 message_queue_barriers.semaphore_1->Signal();
3649 message_queue_barriers.barrier_1.Wait();
3650 // Post 6 commands, filling the command queue and making it expand.
3651 // These calls return immediately, but the commands stay on the queue
3652 // until the execution of source_2.
3653 // Note: AsciiToUtf16 executes before SendCommand, so command is copied
3654 // to buffer before buffer is sent to SendCommand.
3655 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1));
3656 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2));
3657 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3658 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3659 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3660 message_queue_barriers.barrier_2.Wait();
3661 // Main thread compiles and runs source_2.
3662 // Queued commands are executed at the start of compilation of source_2(
3663 // beforeCompile event).
3664 // Free the message handler to process all the messages from the queue. 7
3665 // messages are expected: 2 afterCompile events and 5 responses.
3666 // All the commands added so far will fail to execute as long as call stack
3667 // is empty on beforeCompile event.
3668 for (int i = 0; i < 6 ; ++i) {
3669 message_queue_barriers.semaphore_1->Signal();
3670 }
3671 message_queue_barriers.barrier_3.Wait();
3672 // Main thread compiles and runs source_3.
3673 // Don't stop in the afterCompile handler.
3674 message_queue_barriers.semaphore_1->Signal();
3675 // source_3 includes a debugger statement, which causes a break event.
3676 // Wait on break event from hitting "debugger" statement
3677 message_queue_barriers.semaphore_2->Wait();
3678 // These should execute after the "debugger" statement in source_2
3679 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1));
3680 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2));
3681 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3682 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_single_step, buffer_2));
3683 // Run after 2 break events, 4 responses.
3684 for (int i = 0; i < 6 ; ++i) {
3685 message_queue_barriers.semaphore_1->Signal();
3686 }
3687 // Wait on break event after a single step executes.
3688 message_queue_barriers.semaphore_2->Wait();
3689 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_2, buffer_1));
3690 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_continue, buffer_2));
3691 // Run after 2 responses.
3692 for (int i = 0; i < 2 ; ++i) {
3693 message_queue_barriers.semaphore_1->Signal();
3694 }
3695 // Main thread continues running source_3 to end, waits for this thread.
3696}
3697
3698MessageQueueDebuggerThread message_queue_debugger_thread;
3699
3700// This thread runs the v8 engine.
3701TEST(MessageQueues) {
3702 // Create a V8 environment
3703 v8::HandleScope scope;
3704 DebugLocalContext env;
3705 message_queue_barriers.Initialize();
3706 v8::Debug::SetMessageHandler(MessageHandler);
3707 message_queue_debugger_thread.Start();
3708
3709 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
3710 const char* source_2 = "e = 17;";
3711 const char* source_3 = "a = 4; debugger; a = 5; a = 6; a = 7;";
3712
3713 // See MessageQueueDebuggerThread::Run for interleaved sequence of
3714 // API calls and events in the two threads.
3715 CompileRun(source_1);
3716 message_queue_barriers.barrier_1.Wait();
3717 message_queue_barriers.barrier_2.Wait();
3718 CompileRun(source_2);
3719 message_queue_barriers.barrier_3.Wait();
3720 CompileRun(source_3);
3721 message_queue_debugger_thread.Join();
3722 fflush(stdout);
3723}
3724
3725
3726class TestClientData : public v8::Debug::ClientData {
3727 public:
3728 TestClientData() {
3729 constructor_call_counter++;
3730 }
3731 virtual ~TestClientData() {
3732 destructor_call_counter++;
3733 }
3734
3735 static void ResetCounters() {
3736 constructor_call_counter = 0;
3737 destructor_call_counter = 0;
3738 }
3739
3740 static int constructor_call_counter;
3741 static int destructor_call_counter;
3742};
3743
3744int TestClientData::constructor_call_counter = 0;
3745int TestClientData::destructor_call_counter = 0;
3746
3747
3748// Tests that MessageQueue doesn't destroy client data when expands and
3749// does destroy when it dies.
3750TEST(MessageQueueExpandAndDestroy) {
3751 TestClientData::ResetCounters();
3752 { // Create a scope for the queue.
3753 CommandMessageQueue queue(1);
3754 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3755 new TestClientData()));
3756 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3757 new TestClientData()));
3758 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3759 new TestClientData()));
3760 CHECK_EQ(0, TestClientData::destructor_call_counter);
3761 queue.Get().Dispose();
3762 CHECK_EQ(1, TestClientData::destructor_call_counter);
3763 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3764 new TestClientData()));
3765 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3766 new TestClientData()));
3767 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3768 new TestClientData()));
3769 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3770 new TestClientData()));
3771 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
3772 new TestClientData()));
3773 CHECK_EQ(1, TestClientData::destructor_call_counter);
3774 queue.Get().Dispose();
3775 CHECK_EQ(2, TestClientData::destructor_call_counter);
3776 }
3777 // All the client data should be destroyed when the queue is destroyed.
3778 CHECK_EQ(TestClientData::destructor_call_counter,
3779 TestClientData::destructor_call_counter);
3780}
3781
3782
3783static int handled_client_data_instances_count = 0;
3784static void MessageHandlerCountingClientData(
3785 const v8::Debug::Message& message) {
3786 if (message.GetClientData() != NULL) {
3787 handled_client_data_instances_count++;
3788 }
3789}
3790
3791
3792// Tests that all client data passed to the debugger are sent to the handler.
3793TEST(SendClientDataToHandler) {
3794 // Create a V8 environment
3795 v8::HandleScope scope;
3796 DebugLocalContext env;
3797 TestClientData::ResetCounters();
3798 handled_client_data_instances_count = 0;
3799 v8::Debug::SetMessageHandler2(MessageHandlerCountingClientData);
3800 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
3801 const int kBufferSize = 1000;
3802 uint16_t buffer[kBufferSize];
3803 const char* command_1 =
3804 "{\"seq\":117,"
3805 "\"type\":\"request\","
3806 "\"command\":\"evaluate\","
3807 "\"arguments\":{\"expression\":\"1+2\"}}";
3808 const char* command_2 =
3809 "{\"seq\":118,"
3810 "\"type\":\"request\","
3811 "\"command\":\"evaluate\","
3812 "\"arguments\":{\"expression\":\"1+a\"}}";
3813 const char* command_continue =
3814 "{\"seq\":106,"
3815 "\"type\":\"request\","
3816 "\"command\":\"continue\"}";
3817
3818 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer),
3819 new TestClientData());
3820 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer), NULL);
3821 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer),
3822 new TestClientData());
3823 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer),
3824 new TestClientData());
3825 // All the messages will be processed on beforeCompile event.
3826 CompileRun(source_1);
3827 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer));
3828 CHECK_EQ(3, TestClientData::constructor_call_counter);
3829 CHECK_EQ(TestClientData::constructor_call_counter,
3830 handled_client_data_instances_count);
3831 CHECK_EQ(TestClientData::constructor_call_counter,
3832 TestClientData::destructor_call_counter);
3833}
3834
3835
3836/* Test ThreadedDebugging */
3837/* This test interrupts a running infinite loop that is
3838 * occupying the v8 thread by a break command from the
3839 * debugger thread. It then changes the value of a
3840 * global object, to make the loop terminate.
3841 */
3842
3843Barriers threaded_debugging_barriers;
3844
3845class V8Thread : public v8::internal::Thread {
3846 public:
3847 void Run();
3848};
3849
3850class DebuggerThread : public v8::internal::Thread {
3851 public:
3852 void Run();
3853};
3854
3855
3856static v8::Handle<v8::Value> ThreadedAtBarrier1(const v8::Arguments& args) {
3857 threaded_debugging_barriers.barrier_1.Wait();
3858 return v8::Undefined();
3859}
3860
3861
3862static void ThreadedMessageHandler(const v8::Debug::Message& message) {
3863 static char print_buffer[1000];
3864 v8::String::Value json(message.GetJSON());
3865 Utf16ToAscii(*json, json.length(), print_buffer);
3866 if (IsBreakEventMessage(print_buffer)) {
3867 threaded_debugging_barriers.barrier_2.Wait();
3868 }
Steve Blocka7e24c12009-10-30 11:49:00 +00003869}
3870
3871
3872void V8Thread::Run() {
3873 const char* source =
3874 "flag = true;\n"
3875 "function bar( new_value ) {\n"
3876 " flag = new_value;\n"
3877 " return \"Return from bar(\" + new_value + \")\";\n"
3878 "}\n"
3879 "\n"
3880 "function foo() {\n"
3881 " var x = 1;\n"
3882 " while ( flag == true ) {\n"
3883 " if ( x == 1 ) {\n"
3884 " ThreadedAtBarrier1();\n"
3885 " }\n"
3886 " x = x + 1;\n"
3887 " }\n"
3888 "}\n"
3889 "\n"
3890 "foo();\n";
3891
3892 v8::HandleScope scope;
3893 DebugLocalContext env;
3894 v8::Debug::SetMessageHandler2(&ThreadedMessageHandler);
3895 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
3896 global_template->Set(v8::String::New("ThreadedAtBarrier1"),
3897 v8::FunctionTemplate::New(ThreadedAtBarrier1));
3898 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template);
3899 v8::Context::Scope context_scope(context);
3900
3901 CompileRun(source);
3902}
3903
3904void DebuggerThread::Run() {
3905 const int kBufSize = 1000;
3906 uint16_t buffer[kBufSize];
3907
3908 const char* command_1 = "{\"seq\":102,"
3909 "\"type\":\"request\","
3910 "\"command\":\"evaluate\","
3911 "\"arguments\":{\"expression\":\"bar(false)\"}}";
3912 const char* command_2 = "{\"seq\":103,"
3913 "\"type\":\"request\","
3914 "\"command\":\"continue\"}";
3915
3916 threaded_debugging_barriers.barrier_1.Wait();
3917 v8::Debug::DebugBreak();
3918 threaded_debugging_barriers.barrier_2.Wait();
3919 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
3920 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
3921}
3922
3923DebuggerThread debugger_thread;
3924V8Thread v8_thread;
3925
3926TEST(ThreadedDebugging) {
3927 // Create a V8 environment
3928 threaded_debugging_barriers.Initialize();
3929
3930 v8_thread.Start();
3931 debugger_thread.Start();
3932
3933 v8_thread.Join();
3934 debugger_thread.Join();
3935}
3936
3937/* Test RecursiveBreakpoints */
3938/* In this test, the debugger evaluates a function with a breakpoint, after
3939 * hitting a breakpoint in another function. We do this with both values
3940 * of the flag enabling recursive breakpoints, and verify that the second
3941 * breakpoint is hit when enabled, and missed when disabled.
3942 */
3943
3944class BreakpointsV8Thread : public v8::internal::Thread {
3945 public:
3946 void Run();
3947};
3948
3949class BreakpointsDebuggerThread : public v8::internal::Thread {
3950 public:
3951 void Run();
3952};
3953
3954
3955Barriers* breakpoints_barriers;
Steve Block3ce2e202009-11-05 08:53:23 +00003956int break_event_breakpoint_id;
3957int evaluate_int_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00003958
3959static void BreakpointsMessageHandler(const v8::Debug::Message& message) {
3960 static char print_buffer[1000];
3961 v8::String::Value json(message.GetJSON());
3962 Utf16ToAscii(*json, json.length(), print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00003963
Steve Blocka7e24c12009-10-30 11:49:00 +00003964 if (IsBreakEventMessage(print_buffer)) {
Steve Block3ce2e202009-11-05 08:53:23 +00003965 break_event_breakpoint_id =
3966 GetBreakpointIdFromBreakEventMessage(print_buffer);
3967 breakpoints_barriers->semaphore_1->Signal();
3968 } else if (IsEvaluateResponseMessage(print_buffer)) {
3969 evaluate_int_result = GetEvaluateIntResult(print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00003970 breakpoints_barriers->semaphore_1->Signal();
3971 }
3972}
3973
3974
3975void BreakpointsV8Thread::Run() {
3976 const char* source_1 = "var y_global = 3;\n"
3977 "function cat( new_value ) {\n"
3978 " var x = new_value;\n"
Steve Block3ce2e202009-11-05 08:53:23 +00003979 " y_global = y_global + 4;\n"
Steve Blocka7e24c12009-10-30 11:49:00 +00003980 " x = 3 * x + 1;\n"
Steve Block3ce2e202009-11-05 08:53:23 +00003981 " y_global = y_global + 5;\n"
Steve Blocka7e24c12009-10-30 11:49:00 +00003982 " return x;\n"
3983 "}\n"
3984 "\n"
3985 "function dog() {\n"
3986 " var x = 1;\n"
3987 " x = y_global;"
3988 " var z = 3;"
3989 " x += 100;\n"
3990 " return x;\n"
3991 "}\n"
3992 "\n";
3993 const char* source_2 = "cat(17);\n"
3994 "cat(19);\n";
3995
3996 v8::HandleScope scope;
3997 DebugLocalContext env;
3998 v8::Debug::SetMessageHandler2(&BreakpointsMessageHandler);
3999
4000 CompileRun(source_1);
4001 breakpoints_barriers->barrier_1.Wait();
4002 breakpoints_barriers->barrier_2.Wait();
4003 CompileRun(source_2);
4004}
4005
4006
4007void BreakpointsDebuggerThread::Run() {
4008 const int kBufSize = 1000;
4009 uint16_t buffer[kBufSize];
4010
4011 const char* command_1 = "{\"seq\":101,"
4012 "\"type\":\"request\","
4013 "\"command\":\"setbreakpoint\","
4014 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
4015 const char* command_2 = "{\"seq\":102,"
4016 "\"type\":\"request\","
4017 "\"command\":\"setbreakpoint\","
4018 "\"arguments\":{\"type\":\"function\",\"target\":\"dog\",\"line\":3}}";
Steve Block3ce2e202009-11-05 08:53:23 +00004019 const char* command_3 = "{\"seq\":103,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004020 "\"type\":\"request\","
4021 "\"command\":\"evaluate\","
4022 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false}}";
Steve Block3ce2e202009-11-05 08:53:23 +00004023 const char* command_4 = "{\"seq\":104,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004024 "\"type\":\"request\","
4025 "\"command\":\"evaluate\","
Steve Block3ce2e202009-11-05 08:53:23 +00004026 "\"arguments\":{\"expression\":\"x + 1\",\"disable_break\":true}}";
4027 const char* command_5 = "{\"seq\":105,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004028 "\"type\":\"request\","
4029 "\"command\":\"continue\"}";
Steve Block3ce2e202009-11-05 08:53:23 +00004030 const char* command_6 = "{\"seq\":106,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004031 "\"type\":\"request\","
4032 "\"command\":\"continue\"}";
Steve Block3ce2e202009-11-05 08:53:23 +00004033 const char* command_7 = "{\"seq\":107,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004034 "\"type\":\"request\","
4035 "\"command\":\"evaluate\","
4036 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true}}";
Steve Block3ce2e202009-11-05 08:53:23 +00004037 const char* command_8 = "{\"seq\":108,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004038 "\"type\":\"request\","
4039 "\"command\":\"continue\"}";
4040
4041
4042 // v8 thread initializes, runs source_1
4043 breakpoints_barriers->barrier_1.Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00004044 // 1:Set breakpoint in cat() (will get id 1).
Steve Blocka7e24c12009-10-30 11:49:00 +00004045 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004046 // 2:Set breakpoint in dog() (will get id 2).
Steve Blocka7e24c12009-10-30 11:49:00 +00004047 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
4048 breakpoints_barriers->barrier_2.Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00004049 // V8 thread starts compiling source_2.
Steve Blocka7e24c12009-10-30 11:49:00 +00004050 // Automatic break happens, to run queued commands
4051 // breakpoints_barriers->semaphore_1->Wait();
4052 // Commands 1 through 3 run, thread continues.
4053 // v8 thread runs source_2 to breakpoint in cat().
4054 // message callback receives break event.
4055 breakpoints_barriers->semaphore_1->Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00004056 // Must have hit breakpoint #1.
4057 CHECK_EQ(1, break_event_breakpoint_id);
Steve Blocka7e24c12009-10-30 11:49:00 +00004058 // 4:Evaluate dog() (which has a breakpoint).
4059 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_3, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004060 // V8 thread hits breakpoint in dog().
Steve Blocka7e24c12009-10-30 11:49:00 +00004061 breakpoints_barriers->semaphore_1->Wait(); // wait for break event
Steve Block3ce2e202009-11-05 08:53:23 +00004062 // Must have hit breakpoint #2.
4063 CHECK_EQ(2, break_event_breakpoint_id);
4064 // 5:Evaluate (x + 1).
Steve Blocka7e24c12009-10-30 11:49:00 +00004065 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_4, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004066 // Evaluate (x + 1) finishes.
4067 breakpoints_barriers->semaphore_1->Wait();
4068 // Must have result 108.
4069 CHECK_EQ(108, evaluate_int_result);
4070 // 6:Continue evaluation of dog().
Steve Blocka7e24c12009-10-30 11:49:00 +00004071 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_5, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004072 // Evaluate dog() finishes.
4073 breakpoints_barriers->semaphore_1->Wait();
4074 // Must have result 107.
4075 CHECK_EQ(107, evaluate_int_result);
Steve Blocka7e24c12009-10-30 11:49:00 +00004076 // 7:Continue evaluation of source_2, finish cat(17), hit breakpoint
4077 // in cat(19).
4078 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_6, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004079 // Message callback gets break event.
Steve Blocka7e24c12009-10-30 11:49:00 +00004080 breakpoints_barriers->semaphore_1->Wait(); // wait for break event
Steve Block3ce2e202009-11-05 08:53:23 +00004081 // Must have hit breakpoint #1.
4082 CHECK_EQ(1, break_event_breakpoint_id);
4083 // 8: Evaluate dog() with breaks disabled.
Steve Blocka7e24c12009-10-30 11:49:00 +00004084 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_7, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004085 // Evaluate dog() finishes.
4086 breakpoints_barriers->semaphore_1->Wait();
4087 // Must have result 116.
4088 CHECK_EQ(116, evaluate_int_result);
Steve Blocka7e24c12009-10-30 11:49:00 +00004089 // 9: Continue evaluation of source2, reach end.
4090 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_8, buffer));
4091}
4092
4093BreakpointsDebuggerThread breakpoints_debugger_thread;
4094BreakpointsV8Thread breakpoints_v8_thread;
4095
4096TEST(RecursiveBreakpoints) {
4097 i::FLAG_debugger_auto_break = true;
4098
4099 // Create a V8 environment
4100 Barriers stack_allocated_breakpoints_barriers;
4101 stack_allocated_breakpoints_barriers.Initialize();
4102 breakpoints_barriers = &stack_allocated_breakpoints_barriers;
4103
4104 breakpoints_v8_thread.Start();
4105 breakpoints_debugger_thread.Start();
4106
4107 breakpoints_v8_thread.Join();
4108 breakpoints_debugger_thread.Join();
4109}
4110
4111
4112static void DummyDebugEventListener(v8::DebugEvent event,
4113 v8::Handle<v8::Object> exec_state,
4114 v8::Handle<v8::Object> event_data,
4115 v8::Handle<v8::Value> data) {
4116}
4117
4118
4119TEST(SetDebugEventListenerOnUninitializedVM) {
4120 v8::Debug::SetDebugEventListener(DummyDebugEventListener);
4121}
4122
4123
4124static void DummyMessageHandler(const v8::Debug::Message& message) {
4125}
4126
4127
4128TEST(SetMessageHandlerOnUninitializedVM) {
4129 v8::Debug::SetMessageHandler2(DummyMessageHandler);
4130}
4131
4132
4133TEST(DebugBreakOnUninitializedVM) {
4134 v8::Debug::DebugBreak();
4135}
4136
4137
4138TEST(SendCommandToUninitializedVM) {
4139 const char* dummy_command = "{}";
4140 uint16_t dummy_buffer[80];
4141 int dummy_length = AsciiToUtf16(dummy_command, dummy_buffer);
4142 v8::Debug::SendCommand(dummy_buffer, dummy_length);
4143}
4144
4145
4146// Source for a JavaScript function which returns the data parameter of a
4147// function called in the context of the debugger. If no data parameter is
4148// passed it throws an exception.
4149static const char* debugger_call_with_data_source =
4150 "function debugger_call_with_data(exec_state, data) {"
4151 " if (data) return data;"
4152 " throw 'No data!'"
4153 "}";
4154v8::Handle<v8::Function> debugger_call_with_data;
4155
4156
4157// Source for a JavaScript function which returns the data parameter of a
4158// function called in the context of the debugger. If no data parameter is
4159// passed it throws an exception.
4160static const char* debugger_call_with_closure_source =
4161 "var x = 3;"
4162 "(function (exec_state) {"
4163 " if (exec_state.y) return x - 1;"
4164 " exec_state.y = x;"
4165 " return exec_state.y"
4166 "})";
4167v8::Handle<v8::Function> debugger_call_with_closure;
4168
4169// Function to retrieve the number of JavaScript frames by calling a JavaScript
4170// in the debugger.
4171static v8::Handle<v8::Value> CheckFrameCount(const v8::Arguments& args) {
4172 CHECK(v8::Debug::Call(frame_count)->IsNumber());
4173 CHECK_EQ(args[0]->Int32Value(),
4174 v8::Debug::Call(frame_count)->Int32Value());
4175 return v8::Undefined();
4176}
4177
4178
4179// Function to retrieve the source line of the top JavaScript frame by calling a
4180// JavaScript function in the debugger.
4181static v8::Handle<v8::Value> CheckSourceLine(const v8::Arguments& args) {
4182 CHECK(v8::Debug::Call(frame_source_line)->IsNumber());
4183 CHECK_EQ(args[0]->Int32Value(),
4184 v8::Debug::Call(frame_source_line)->Int32Value());
4185 return v8::Undefined();
4186}
4187
4188
4189// Function to test passing an additional parameter to a JavaScript function
4190// called in the debugger. It also tests that functions called in the debugger
4191// can throw exceptions.
4192static v8::Handle<v8::Value> CheckDataParameter(const v8::Arguments& args) {
4193 v8::Handle<v8::String> data = v8::String::New("Test");
4194 CHECK(v8::Debug::Call(debugger_call_with_data, data)->IsString());
4195
4196 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
4197 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
4198
4199 v8::TryCatch catcher;
4200 v8::Debug::Call(debugger_call_with_data);
4201 CHECK(catcher.HasCaught());
4202 CHECK(catcher.Exception()->IsString());
4203
4204 return v8::Undefined();
4205}
4206
4207
4208// Function to test using a JavaScript with closure in the debugger.
4209static v8::Handle<v8::Value> CheckClosure(const v8::Arguments& args) {
4210 CHECK(v8::Debug::Call(debugger_call_with_closure)->IsNumber());
4211 CHECK_EQ(3, v8::Debug::Call(debugger_call_with_closure)->Int32Value());
4212 return v8::Undefined();
4213}
4214
4215
4216// Test functions called through the debugger.
4217TEST(CallFunctionInDebugger) {
4218 // Create and enter a context with the functions CheckFrameCount,
4219 // CheckSourceLine and CheckDataParameter installed.
4220 v8::HandleScope scope;
4221 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
4222 global_template->Set(v8::String::New("CheckFrameCount"),
4223 v8::FunctionTemplate::New(CheckFrameCount));
4224 global_template->Set(v8::String::New("CheckSourceLine"),
4225 v8::FunctionTemplate::New(CheckSourceLine));
4226 global_template->Set(v8::String::New("CheckDataParameter"),
4227 v8::FunctionTemplate::New(CheckDataParameter));
4228 global_template->Set(v8::String::New("CheckClosure"),
4229 v8::FunctionTemplate::New(CheckClosure));
4230 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template);
4231 v8::Context::Scope context_scope(context);
4232
4233 // Compile a function for checking the number of JavaScript frames.
4234 v8::Script::Compile(v8::String::New(frame_count_source))->Run();
4235 frame_count = v8::Local<v8::Function>::Cast(
4236 context->Global()->Get(v8::String::New("frame_count")));
4237
4238 // Compile a function for returning the source line for the top frame.
4239 v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
4240 frame_source_line = v8::Local<v8::Function>::Cast(
4241 context->Global()->Get(v8::String::New("frame_source_line")));
4242
4243 // Compile a function returning the data parameter.
4244 v8::Script::Compile(v8::String::New(debugger_call_with_data_source))->Run();
4245 debugger_call_with_data = v8::Local<v8::Function>::Cast(
4246 context->Global()->Get(v8::String::New("debugger_call_with_data")));
4247
4248 // Compile a function capturing closure.
4249 debugger_call_with_closure = v8::Local<v8::Function>::Cast(
4250 v8::Script::Compile(
4251 v8::String::New(debugger_call_with_closure_source))->Run());
4252
4253 // Calling a function through the debugger returns undefined if there are no
4254 // JavaScript frames.
4255 CHECK(v8::Debug::Call(frame_count)->IsUndefined());
4256 CHECK(v8::Debug::Call(frame_source_line)->IsUndefined());
4257 CHECK(v8::Debug::Call(debugger_call_with_data)->IsUndefined());
4258
4259 // Test that the number of frames can be retrieved.
4260 v8::Script::Compile(v8::String::New("CheckFrameCount(1)"))->Run();
4261 v8::Script::Compile(v8::String::New("function f() {"
4262 " CheckFrameCount(2);"
4263 "}; f()"))->Run();
4264
4265 // Test that the source line can be retrieved.
4266 v8::Script::Compile(v8::String::New("CheckSourceLine(0)"))->Run();
4267 v8::Script::Compile(v8::String::New("function f() {\n"
4268 " CheckSourceLine(1)\n"
4269 " CheckSourceLine(2)\n"
4270 " CheckSourceLine(3)\n"
4271 "}; f()"))->Run();
4272
4273 // Test that a parameter can be passed to a function called in the debugger.
4274 v8::Script::Compile(v8::String::New("CheckDataParameter()"))->Run();
4275
4276 // Test that a function with closure can be run in the debugger.
4277 v8::Script::Compile(v8::String::New("CheckClosure()"))->Run();
4278
4279
4280 // Test that the source line is correct when there is a line offset.
4281 v8::ScriptOrigin origin(v8::String::New("test"),
4282 v8::Integer::New(7));
4283 v8::Script::Compile(v8::String::New("CheckSourceLine(7)"), &origin)->Run();
4284 v8::Script::Compile(v8::String::New("function f() {\n"
4285 " CheckSourceLine(8)\n"
4286 " CheckSourceLine(9)\n"
4287 " CheckSourceLine(10)\n"
4288 "}; f()"), &origin)->Run();
4289}
4290
4291
4292// Debugger message handler which counts the number of breaks.
4293static void SendContinueCommand();
4294static void MessageHandlerBreakPointHitCount(
4295 const v8::Debug::Message& message) {
4296 if (message.IsEvent() && message.GetEvent() == v8::Break) {
4297 // Count the number of breaks.
4298 break_point_hit_count++;
4299
4300 SendContinueCommand();
4301 }
4302}
4303
4304
4305// Test that clearing the debug event listener actually clears all break points
4306// and related information.
4307TEST(DebuggerUnload) {
4308 DebugLocalContext env;
4309
4310 // Check debugger is unloaded before it is used.
4311 CheckDebuggerUnloaded();
4312
4313 // Set a debug event listener.
4314 break_point_hit_count = 0;
4315 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
4316 v8::Undefined());
4317 {
4318 v8::HandleScope scope;
4319 // Create a couple of functions for the test.
4320 v8::Local<v8::Function> foo =
4321 CompileFunction(&env, "function foo(){x=1}", "foo");
4322 v8::Local<v8::Function> bar =
4323 CompileFunction(&env, "function bar(){y=2}", "bar");
4324
4325 // Set some break points.
4326 SetBreakPoint(foo, 0);
4327 SetBreakPoint(foo, 4);
4328 SetBreakPoint(bar, 0);
4329 SetBreakPoint(bar, 4);
4330
4331 // Make sure that the break points are there.
4332 break_point_hit_count = 0;
4333 foo->Call(env->Global(), 0, NULL);
4334 CHECK_EQ(2, break_point_hit_count);
4335 bar->Call(env->Global(), 0, NULL);
4336 CHECK_EQ(4, break_point_hit_count);
4337 }
4338
4339 // Remove the debug event listener without clearing breakpoints. Do this
4340 // outside a handle scope.
4341 v8::Debug::SetDebugEventListener(NULL);
4342 CheckDebuggerUnloaded(true);
4343
4344 // Now set a debug message handler.
4345 break_point_hit_count = 0;
4346 v8::Debug::SetMessageHandler2(MessageHandlerBreakPointHitCount);
4347 {
4348 v8::HandleScope scope;
4349
4350 // Get the test functions again.
4351 v8::Local<v8::Function> foo =
4352 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
4353 v8::Local<v8::Function> bar =
4354 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
4355
4356 foo->Call(env->Global(), 0, NULL);
4357 CHECK_EQ(0, break_point_hit_count);
4358
4359 // Set break points and run again.
4360 SetBreakPoint(foo, 0);
4361 SetBreakPoint(foo, 4);
4362 foo->Call(env->Global(), 0, NULL);
4363 CHECK_EQ(2, break_point_hit_count);
4364 }
4365
4366 // Remove the debug message handler without clearing breakpoints. Do this
4367 // outside a handle scope.
4368 v8::Debug::SetMessageHandler2(NULL);
4369 CheckDebuggerUnloaded(true);
4370}
4371
4372
4373// Sends continue command to the debugger.
4374static void SendContinueCommand() {
4375 const int kBufferSize = 1000;
4376 uint16_t buffer[kBufferSize];
4377 const char* command_continue =
4378 "{\"seq\":0,"
4379 "\"type\":\"request\","
4380 "\"command\":\"continue\"}";
4381
4382 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer));
4383}
4384
4385
4386// Debugger message handler which counts the number of times it is called.
4387static int message_handler_hit_count = 0;
4388static void MessageHandlerHitCount(const v8::Debug::Message& message) {
4389 message_handler_hit_count++;
4390
Steve Block3ce2e202009-11-05 08:53:23 +00004391 static char print_buffer[1000];
4392 v8::String::Value json(message.GetJSON());
4393 Utf16ToAscii(*json, json.length(), print_buffer);
4394 if (IsExceptionEventMessage(print_buffer)) {
4395 // Send a continue command for exception events.
4396 SendContinueCommand();
4397 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004398}
4399
4400
4401// Test clearing the debug message handler.
4402TEST(DebuggerClearMessageHandler) {
4403 v8::HandleScope scope;
4404 DebugLocalContext env;
4405
4406 // Check debugger is unloaded before it is used.
4407 CheckDebuggerUnloaded();
4408
4409 // Set a debug message handler.
4410 v8::Debug::SetMessageHandler2(MessageHandlerHitCount);
4411
4412 // Run code to throw a unhandled exception. This should end up in the message
4413 // handler.
4414 CompileRun("throw 1");
4415
4416 // The message handler should be called.
4417 CHECK_GT(message_handler_hit_count, 0);
4418
4419 // Clear debug message handler.
4420 message_handler_hit_count = 0;
4421 v8::Debug::SetMessageHandler(NULL);
4422
4423 // Run code to throw a unhandled exception. This should end up in the message
4424 // handler.
4425 CompileRun("throw 1");
4426
4427 // The message handler should not be called more.
4428 CHECK_EQ(0, message_handler_hit_count);
4429
4430 CheckDebuggerUnloaded(true);
4431}
4432
4433
4434// Debugger message handler which clears the message handler while active.
4435static void MessageHandlerClearingMessageHandler(
4436 const v8::Debug::Message& message) {
4437 message_handler_hit_count++;
4438
4439 // Clear debug message handler.
4440 v8::Debug::SetMessageHandler(NULL);
4441}
4442
4443
4444// Test clearing the debug message handler while processing a debug event.
4445TEST(DebuggerClearMessageHandlerWhileActive) {
4446 v8::HandleScope scope;
4447 DebugLocalContext env;
4448
4449 // Check debugger is unloaded before it is used.
4450 CheckDebuggerUnloaded();
4451
4452 // Set a debug message handler.
4453 v8::Debug::SetMessageHandler2(MessageHandlerClearingMessageHandler);
4454
4455 // Run code to throw a unhandled exception. This should end up in the message
4456 // handler.
4457 CompileRun("throw 1");
4458
4459 // The message handler should be called.
4460 CHECK_EQ(1, message_handler_hit_count);
4461
4462 CheckDebuggerUnloaded(true);
4463}
4464
4465
4466/* Test DebuggerHostDispatch */
4467/* In this test, the debugger waits for a command on a breakpoint
4468 * and is dispatching host commands while in the infinite loop.
4469 */
4470
4471class HostDispatchV8Thread : public v8::internal::Thread {
4472 public:
4473 void Run();
4474};
4475
4476class HostDispatchDebuggerThread : public v8::internal::Thread {
4477 public:
4478 void Run();
4479};
4480
4481Barriers* host_dispatch_barriers;
4482
4483static void HostDispatchMessageHandler(const v8::Debug::Message& message) {
4484 static char print_buffer[1000];
4485 v8::String::Value json(message.GetJSON());
4486 Utf16ToAscii(*json, json.length(), print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00004487}
4488
4489
4490static void HostDispatchDispatchHandler() {
4491 host_dispatch_barriers->semaphore_1->Signal();
4492}
4493
4494
4495void HostDispatchV8Thread::Run() {
4496 const char* source_1 = "var y_global = 3;\n"
4497 "function cat( new_value ) {\n"
4498 " var x = new_value;\n"
4499 " y_global = 4;\n"
4500 " x = 3 * x + 1;\n"
4501 " y_global = 5;\n"
4502 " return x;\n"
4503 "}\n"
4504 "\n";
4505 const char* source_2 = "cat(17);\n";
4506
4507 v8::HandleScope scope;
4508 DebugLocalContext env;
4509
4510 // Setup message and host dispatch handlers.
4511 v8::Debug::SetMessageHandler2(HostDispatchMessageHandler);
4512 v8::Debug::SetHostDispatchHandler(HostDispatchDispatchHandler, 10 /* ms */);
4513
4514 CompileRun(source_1);
4515 host_dispatch_barriers->barrier_1.Wait();
4516 host_dispatch_barriers->barrier_2.Wait();
4517 CompileRun(source_2);
4518}
4519
4520
4521void HostDispatchDebuggerThread::Run() {
4522 const int kBufSize = 1000;
4523 uint16_t buffer[kBufSize];
4524
4525 const char* command_1 = "{\"seq\":101,"
4526 "\"type\":\"request\","
4527 "\"command\":\"setbreakpoint\","
4528 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
4529 const char* command_2 = "{\"seq\":102,"
4530 "\"type\":\"request\","
4531 "\"command\":\"continue\"}";
4532
4533 // v8 thread initializes, runs source_1
4534 host_dispatch_barriers->barrier_1.Wait();
4535 // 1: Set breakpoint in cat().
4536 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
4537
4538 host_dispatch_barriers->barrier_2.Wait();
4539 // v8 thread starts compiling source_2.
4540 // Break happens, to run queued commands and host dispatches.
4541 // Wait for host dispatch to be processed.
4542 host_dispatch_barriers->semaphore_1->Wait();
4543 // 2: Continue evaluation
4544 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
4545}
4546
4547HostDispatchDebuggerThread host_dispatch_debugger_thread;
4548HostDispatchV8Thread host_dispatch_v8_thread;
4549
4550
4551TEST(DebuggerHostDispatch) {
4552 i::FLAG_debugger_auto_break = true;
4553
4554 // Create a V8 environment
4555 Barriers stack_allocated_host_dispatch_barriers;
4556 stack_allocated_host_dispatch_barriers.Initialize();
4557 host_dispatch_barriers = &stack_allocated_host_dispatch_barriers;
4558
4559 host_dispatch_v8_thread.Start();
4560 host_dispatch_debugger_thread.Start();
4561
4562 host_dispatch_v8_thread.Join();
4563 host_dispatch_debugger_thread.Join();
4564}
4565
4566
4567TEST(DebuggerAgent) {
4568 // Make sure these ports is not used by other tests to allow tests to run in
4569 // parallel.
4570 const int kPort1 = 5858;
4571 const int kPort2 = 5857;
4572 const int kPort3 = 5856;
4573
4574 // Make a string with the port2 number.
4575 const int kPortBufferLen = 6;
4576 char port2_str[kPortBufferLen];
4577 OS::SNPrintF(i::Vector<char>(port2_str, kPortBufferLen), "%d", kPort2);
4578
4579 bool ok;
4580
4581 // Initialize the socket library.
4582 i::Socket::Setup();
4583
4584 // Test starting and stopping the agent without any client connection.
4585 i::Debugger::StartAgent("test", kPort1);
4586 i::Debugger::StopAgent();
4587
4588 // Test starting the agent, connecting a client and shutting down the agent
4589 // with the client connected.
4590 ok = i::Debugger::StartAgent("test", kPort2);
4591 CHECK(ok);
4592 i::Debugger::WaitForAgent();
4593 i::Socket* client = i::OS::CreateSocket();
4594 ok = client->Connect("localhost", port2_str);
4595 CHECK(ok);
4596 i::Debugger::StopAgent();
4597 delete client;
4598
4599 // Test starting and stopping the agent with the required port already
4600 // occoupied.
4601 i::Socket* server = i::OS::CreateSocket();
4602 server->Bind(kPort3);
4603
4604 i::Debugger::StartAgent("test", kPort3);
4605 i::Debugger::StopAgent();
4606
4607 delete server;
4608}
4609
4610
4611class DebuggerAgentProtocolServerThread : public i::Thread {
4612 public:
4613 explicit DebuggerAgentProtocolServerThread(int port)
4614 : port_(port), server_(NULL), client_(NULL),
4615 listening_(OS::CreateSemaphore(0)) {
4616 }
4617 ~DebuggerAgentProtocolServerThread() {
4618 // Close both sockets.
4619 delete client_;
4620 delete server_;
4621 delete listening_;
4622 }
4623
4624 void Run();
4625 void WaitForListening() { listening_->Wait(); }
4626 char* body() { return *body_; }
4627
4628 private:
4629 int port_;
4630 i::SmartPointer<char> body_;
4631 i::Socket* server_; // Server socket used for bind/accept.
4632 i::Socket* client_; // Single client connection used by the test.
4633 i::Semaphore* listening_; // Signalled when the server is in listen mode.
4634};
4635
4636
4637void DebuggerAgentProtocolServerThread::Run() {
4638 bool ok;
4639
4640 // Create the server socket and bind it to the requested port.
4641 server_ = i::OS::CreateSocket();
4642 CHECK(server_ != NULL);
4643 ok = server_->Bind(port_);
4644 CHECK(ok);
4645
4646 // Listen for new connections.
4647 ok = server_->Listen(1);
4648 CHECK(ok);
4649 listening_->Signal();
4650
4651 // Accept a connection.
4652 client_ = server_->Accept();
4653 CHECK(client_ != NULL);
4654
4655 // Receive a debugger agent protocol message.
4656 i::DebuggerAgentUtil::ReceiveMessage(client_);
4657}
4658
4659
4660TEST(DebuggerAgentProtocolOverflowHeader) {
4661 // Make sure this port is not used by other tests to allow tests to run in
4662 // parallel.
4663 const int kPort = 5860;
4664 static const char* kLocalhost = "localhost";
4665
4666 // Make a string with the port number.
4667 const int kPortBufferLen = 6;
4668 char port_str[kPortBufferLen];
4669 OS::SNPrintF(i::Vector<char>(port_str, kPortBufferLen), "%d", kPort);
4670
4671 // Initialize the socket library.
4672 i::Socket::Setup();
4673
4674 // Create a socket server to receive a debugger agent message.
4675 DebuggerAgentProtocolServerThread* server =
4676 new DebuggerAgentProtocolServerThread(kPort);
4677 server->Start();
4678 server->WaitForListening();
4679
4680 // Connect.
4681 i::Socket* client = i::OS::CreateSocket();
4682 CHECK(client != NULL);
4683 bool ok = client->Connect(kLocalhost, port_str);
4684 CHECK(ok);
4685
4686 // Send headers which overflow the receive buffer.
4687 static const int kBufferSize = 1000;
4688 char buffer[kBufferSize];
4689
4690 // Long key and short value: XXXX....XXXX:0\r\n.
4691 for (int i = 0; i < kBufferSize - 4; i++) {
4692 buffer[i] = 'X';
4693 }
4694 buffer[kBufferSize - 4] = ':';
4695 buffer[kBufferSize - 3] = '0';
4696 buffer[kBufferSize - 2] = '\r';
4697 buffer[kBufferSize - 1] = '\n';
4698 client->Send(buffer, kBufferSize);
4699
4700 // Short key and long value: X:XXXX....XXXX\r\n.
4701 buffer[0] = 'X';
4702 buffer[1] = ':';
4703 for (int i = 2; i < kBufferSize - 2; i++) {
4704 buffer[i] = 'X';
4705 }
4706 buffer[kBufferSize - 2] = '\r';
4707 buffer[kBufferSize - 1] = '\n';
4708 client->Send(buffer, kBufferSize);
4709
4710 // Add empty body to request.
4711 const char* content_length_zero_header = "Content-Length:0\r\n";
4712 client->Send(content_length_zero_header, strlen(content_length_zero_header));
4713 client->Send("\r\n", 2);
4714
4715 // Wait until data is received.
4716 server->Join();
4717
4718 // Check for empty body.
4719 CHECK(server->body() == NULL);
4720
4721 // Close the client before the server to avoid TIME_WAIT issues.
4722 client->Shutdown();
4723 delete client;
4724 delete server;
4725}
4726
4727
4728// Test for issue http://code.google.com/p/v8/issues/detail?id=289.
4729// Make sure that DebugGetLoadedScripts doesn't return scripts
4730// with disposed external source.
4731class EmptyExternalStringResource : public v8::String::ExternalStringResource {
4732 public:
4733 EmptyExternalStringResource() { empty_[0] = 0; }
4734 virtual ~EmptyExternalStringResource() {}
4735 virtual size_t length() const { return empty_.length(); }
4736 virtual const uint16_t* data() const { return empty_.start(); }
4737 private:
4738 ::v8::internal::EmbeddedVector<uint16_t, 1> empty_;
4739};
4740
4741
4742TEST(DebugGetLoadedScripts) {
4743 v8::HandleScope scope;
4744 DebugLocalContext env;
4745 env.ExposeDebug();
4746
4747 EmptyExternalStringResource source_ext_str;
4748 v8::Local<v8::String> source = v8::String::NewExternal(&source_ext_str);
4749 v8::Handle<v8::Script> evil_script = v8::Script::Compile(source);
4750 Handle<i::ExternalTwoByteString> i_source(
4751 i::ExternalTwoByteString::cast(*v8::Utils::OpenHandle(*source)));
4752 // This situation can happen if source was an external string disposed
4753 // by its owner.
4754 i_source->set_resource(0);
4755
4756 bool allow_natives_syntax = i::FLAG_allow_natives_syntax;
4757 i::FLAG_allow_natives_syntax = true;
4758 CompileRun(
4759 "var scripts = %DebugGetLoadedScripts();"
4760 "var count = scripts.length;"
4761 "for (var i = 0; i < count; ++i) {"
4762 " scripts[i].line_ends;"
4763 "}");
4764 // Must not crash while accessing line_ends.
4765 i::FLAG_allow_natives_syntax = allow_natives_syntax;
4766
4767 // Some scripts are retrieved - at least the number of native scripts.
4768 CHECK_GT((*env)->Global()->Get(v8::String::New("count"))->Int32Value(), 8);
4769}
4770
4771
4772// Test script break points set on lines.
4773TEST(ScriptNameAndData) {
4774 v8::HandleScope scope;
4775 DebugLocalContext env;
4776 env.ExposeDebug();
4777
4778 // Create functions for retrieving script name and data for the function on
4779 // the top frame when hitting a break point.
4780 frame_script_name = CompileFunction(&env,
4781 frame_script_name_source,
4782 "frame_script_name");
4783 frame_script_data = CompileFunction(&env,
4784 frame_script_data_source,
4785 "frame_script_data");
4786
4787 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
4788 v8::Undefined());
4789
4790 // Test function source.
4791 v8::Local<v8::String> script = v8::String::New(
4792 "function f() {\n"
4793 " debugger;\n"
4794 "}\n");
4795
4796 v8::ScriptOrigin origin1 = v8::ScriptOrigin(v8::String::New("name"));
4797 v8::Handle<v8::Script> script1 = v8::Script::Compile(script, &origin1);
4798 script1->SetData(v8::String::New("data"));
4799 script1->Run();
4800 v8::Local<v8::Function> f;
4801 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
4802
4803 f->Call(env->Global(), 0, NULL);
4804 CHECK_EQ(1, break_point_hit_count);
4805 CHECK_EQ("name", last_script_name_hit);
4806 CHECK_EQ("data", last_script_data_hit);
4807
4808 // Compile the same script again without setting data. As the compilation
4809 // cache is disabled when debugging expect the data to be missing.
4810 v8::Script::Compile(script, &origin1)->Run();
4811 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
4812 f->Call(env->Global(), 0, NULL);
4813 CHECK_EQ(2, break_point_hit_count);
4814 CHECK_EQ("name", last_script_name_hit);
4815 CHECK_EQ("", last_script_data_hit); // Undefined results in empty string.
4816
4817 v8::Local<v8::String> data_obj_source = v8::String::New(
4818 "({ a: 'abc',\n"
4819 " b: 123,\n"
4820 " toString: function() { return this.a + ' ' + this.b; }\n"
4821 "})\n");
4822 v8::Local<v8::Value> data_obj = v8::Script::Compile(data_obj_source)->Run();
4823 v8::ScriptOrigin origin2 = v8::ScriptOrigin(v8::String::New("new name"));
4824 v8::Handle<v8::Script> script2 = v8::Script::Compile(script, &origin2);
4825 script2->Run();
4826 script2->SetData(data_obj);
4827 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
4828 f->Call(env->Global(), 0, NULL);
4829 CHECK_EQ(3, break_point_hit_count);
4830 CHECK_EQ("new name", last_script_name_hit);
4831 CHECK_EQ("abc 123", last_script_data_hit);
4832}
4833
4834
4835static v8::Persistent<v8::Context> expected_context;
4836static v8::Handle<v8::Value> expected_context_data;
4837
4838
4839// Check that the expected context is the one generating the debug event.
4840static void ContextCheckMessageHandler(const v8::Debug::Message& message) {
4841 CHECK(message.GetEventContext() == expected_context);
4842 CHECK(message.GetEventContext()->GetData()->StrictEquals(
4843 expected_context_data));
4844 message_handler_hit_count++;
4845
Steve Block3ce2e202009-11-05 08:53:23 +00004846 static char print_buffer[1000];
4847 v8::String::Value json(message.GetJSON());
4848 Utf16ToAscii(*json, json.length(), print_buffer);
4849
Steve Blocka7e24c12009-10-30 11:49:00 +00004850 // Send a continue command for break events.
Steve Block3ce2e202009-11-05 08:53:23 +00004851 if (IsBreakEventMessage(print_buffer)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00004852 SendContinueCommand();
4853 }
4854}
4855
4856
4857// Test which creates two contexts and sets different embedder data on each.
4858// Checks that this data is set correctly and that when the debug message
4859// handler is called the expected context is the one active.
4860TEST(ContextData) {
4861 v8::HandleScope scope;
4862
4863 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler);
4864
4865 // Create two contexts.
4866 v8::Persistent<v8::Context> context_1;
4867 v8::Persistent<v8::Context> context_2;
4868 v8::Handle<v8::ObjectTemplate> global_template =
4869 v8::Handle<v8::ObjectTemplate>();
4870 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
4871 context_1 = v8::Context::New(NULL, global_template, global_object);
4872 context_2 = v8::Context::New(NULL, global_template, global_object);
4873
4874 // Default data value is undefined.
4875 CHECK(context_1->GetData()->IsUndefined());
4876 CHECK(context_2->GetData()->IsUndefined());
4877
4878 // Set and check different data values.
4879 v8::Handle<v8::Value> data_1 = v8::Number::New(1);
4880 v8::Handle<v8::Value> data_2 = v8::String::New("2");
4881 context_1->SetData(data_1);
4882 context_2->SetData(data_2);
4883 CHECK(context_1->GetData()->StrictEquals(data_1));
4884 CHECK(context_2->GetData()->StrictEquals(data_2));
4885
4886 // Simple test function which causes a break.
4887 const char* source = "function f() { debugger; }";
4888
4889 // Enter and run function in the first context.
4890 {
4891 v8::Context::Scope context_scope(context_1);
4892 expected_context = context_1;
4893 expected_context_data = data_1;
4894 v8::Local<v8::Function> f = CompileFunction(source, "f");
4895 f->Call(context_1->Global(), 0, NULL);
4896 }
4897
4898
4899 // Enter and run function in the second context.
4900 {
4901 v8::Context::Scope context_scope(context_2);
4902 expected_context = context_2;
4903 expected_context_data = data_2;
4904 v8::Local<v8::Function> f = CompileFunction(source, "f");
4905 f->Call(context_2->Global(), 0, NULL);
4906 }
4907
4908 // Two times compile event and two times break event.
4909 CHECK_GT(message_handler_hit_count, 4);
4910
4911 v8::Debug::SetMessageHandler2(NULL);
4912 CheckDebuggerUnloaded();
4913}
4914
4915
4916// Debug message handler which issues a debug break when it hits a break event.
4917static int message_handler_break_hit_count = 0;
4918static void DebugBreakMessageHandler(const v8::Debug::Message& message) {
4919 // Schedule a debug break for break events.
4920 if (message.IsEvent() && message.GetEvent() == v8::Break) {
4921 message_handler_break_hit_count++;
4922 if (message_handler_break_hit_count == 1) {
4923 v8::Debug::DebugBreak();
4924 }
4925 }
4926
4927 // Issue a continue command if this event will not cause the VM to start
4928 // running.
4929 if (!message.WillStartRunning()) {
4930 SendContinueCommand();
4931 }
4932}
4933
4934
4935// Test that a debug break can be scheduled while in a message handler.
4936TEST(DebugBreakInMessageHandler) {
4937 v8::HandleScope scope;
4938 DebugLocalContext env;
4939
4940 v8::Debug::SetMessageHandler2(DebugBreakMessageHandler);
4941
4942 // Test functions.
4943 const char* script = "function f() { debugger; g(); } function g() { }";
4944 CompileRun(script);
4945 v8::Local<v8::Function> f =
4946 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
4947 v8::Local<v8::Function> g =
4948 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
4949
4950 // Call f then g. The debugger statement in f will casue a break which will
4951 // cause another break.
4952 f->Call(env->Global(), 0, NULL);
4953 CHECK_EQ(2, message_handler_break_hit_count);
4954 // Calling g will not cause any additional breaks.
4955 g->Call(env->Global(), 0, NULL);
4956 CHECK_EQ(2, message_handler_break_hit_count);
4957}
4958
4959
4960#ifdef V8_NATIVE_REGEXP
4961// Debug event handler which gets the function on the top frame and schedules a
4962// break a number of times.
4963static void DebugEventDebugBreak(
4964 v8::DebugEvent event,
4965 v8::Handle<v8::Object> exec_state,
4966 v8::Handle<v8::Object> event_data,
4967 v8::Handle<v8::Value> data) {
4968
4969 if (event == v8::Break) {
4970 break_point_hit_count++;
4971
4972 // Get the name of the top frame function.
4973 if (!frame_function_name.IsEmpty()) {
4974 // Get the name of the function.
4975 const int argc = 1;
4976 v8::Handle<v8::Value> argv[argc] = { exec_state };
4977 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
4978 argc, argv);
4979 if (result->IsUndefined()) {
4980 last_function_hit[0] = '\0';
4981 } else {
4982 CHECK(result->IsString());
4983 v8::Handle<v8::String> function_name(result->ToString());
4984 function_name->WriteAscii(last_function_hit);
4985 }
4986 }
4987
4988 // Keep forcing breaks.
4989 if (break_point_hit_count < 20) {
4990 v8::Debug::DebugBreak();
4991 }
4992 }
4993}
4994
4995
4996TEST(RegExpDebugBreak) {
4997 // This test only applies to native regexps.
4998 v8::HandleScope scope;
4999 DebugLocalContext env;
5000
5001 // Create a function for checking the function when hitting a break point.
5002 frame_function_name = CompileFunction(&env,
5003 frame_function_name_source,
5004 "frame_function_name");
5005
5006 // Test RegExp which matches white spaces and comments at the begining of a
5007 // source line.
5008 const char* script =
5009 "var sourceLineBeginningSkip = /^(?:[ \\v\\h]*(?:\\/\\*.*?\\*\\/)*)*/;\n"
5010 "function f(s) { return s.match(sourceLineBeginningSkip)[0].length; }";
5011
5012 v8::Local<v8::Function> f = CompileFunction(script, "f");
5013 const int argc = 1;
5014 v8::Handle<v8::Value> argv[argc] = { v8::String::New(" /* xxx */ a=0;") };
5015 v8::Local<v8::Value> result = f->Call(env->Global(), argc, argv);
5016 CHECK_EQ(12, result->Int32Value());
5017
5018 v8::Debug::SetDebugEventListener(DebugEventDebugBreak);
5019 v8::Debug::DebugBreak();
5020 result = f->Call(env->Global(), argc, argv);
5021
5022 // Check that there was only one break event. Matching RegExp should not
5023 // cause Break events.
5024 CHECK_EQ(1, break_point_hit_count);
5025 CHECK_EQ("f", last_function_hit);
5026}
5027#endif // V8_NATIVE_REGEXP
5028
5029
5030// Common part of EvalContextData and NestedBreakEventContextData tests.
5031static void ExecuteScriptForContextCheck() {
5032 // Create a context.
5033 v8::Persistent<v8::Context> context_1;
5034 v8::Handle<v8::ObjectTemplate> global_template =
5035 v8::Handle<v8::ObjectTemplate>();
5036 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
5037 context_1 = v8::Context::New(NULL, global_template, global_object);
5038
5039 // Default data value is undefined.
5040 CHECK(context_1->GetData()->IsUndefined());
5041
5042 // Set and check a data value.
5043 v8::Handle<v8::Value> data_1 = v8::Number::New(1);
5044 context_1->SetData(data_1);
5045 CHECK(context_1->GetData()->StrictEquals(data_1));
5046
5047 // Simple test function with eval that causes a break.
5048 const char* source = "function f() { eval('debugger;'); }";
5049
5050 // Enter and run function in the context.
5051 {
5052 v8::Context::Scope context_scope(context_1);
5053 expected_context = context_1;
5054 expected_context_data = data_1;
5055 v8::Local<v8::Function> f = CompileFunction(source, "f");
5056 f->Call(context_1->Global(), 0, NULL);
5057 }
5058}
5059
5060
5061// Test which creates a context and sets embedder data on it. Checks that this
5062// data is set correctly and that when the debug message handler is called for
5063// break event in an eval statement the expected context is the one returned by
5064// Message.GetEventContext.
5065TEST(EvalContextData) {
5066 v8::HandleScope scope;
5067 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler);
5068
5069 ExecuteScriptForContextCheck();
5070
5071 // One time compile event and one time break event.
5072 CHECK_GT(message_handler_hit_count, 2);
5073 v8::Debug::SetMessageHandler2(NULL);
5074 CheckDebuggerUnloaded();
5075}
5076
5077
5078static bool sent_eval = false;
5079static int break_count = 0;
5080static int continue_command_send_count = 0;
5081// Check that the expected context is the one generating the debug event
5082// including the case of nested break event.
5083static void DebugEvalContextCheckMessageHandler(
5084 const v8::Debug::Message& message) {
5085 CHECK(message.GetEventContext() == expected_context);
5086 CHECK(message.GetEventContext()->GetData()->StrictEquals(
5087 expected_context_data));
5088 message_handler_hit_count++;
5089
Steve Block3ce2e202009-11-05 08:53:23 +00005090 static char print_buffer[1000];
5091 v8::String::Value json(message.GetJSON());
5092 Utf16ToAscii(*json, json.length(), print_buffer);
5093
5094 if (IsBreakEventMessage(print_buffer)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005095 break_count++;
5096 if (!sent_eval) {
5097 sent_eval = true;
5098
5099 const int kBufferSize = 1000;
5100 uint16_t buffer[kBufferSize];
5101 const char* eval_command =
5102 "{\"seq\":0,"
5103 "\"type\":\"request\","
5104 "\"command\":\"evaluate\","
5105 "arguments:{\"expression\":\"debugger;\","
5106 "\"global\":true,\"disable_break\":false}}";
5107
5108 // Send evaluate command.
5109 v8::Debug::SendCommand(buffer, AsciiToUtf16(eval_command, buffer));
5110 return;
5111 } else {
5112 // It's a break event caused by the evaluation request above.
5113 SendContinueCommand();
5114 continue_command_send_count++;
5115 }
Steve Block3ce2e202009-11-05 08:53:23 +00005116 } else if (IsEvaluateResponseMessage(print_buffer) &&
5117 continue_command_send_count < 2) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005118 // Response to the evaluation request. We're still on the breakpoint so
5119 // send continue.
5120 SendContinueCommand();
5121 continue_command_send_count++;
5122 }
5123}
5124
5125
5126// Tests that context returned for break event is correct when the event occurs
5127// in 'evaluate' debugger request.
5128TEST(NestedBreakEventContextData) {
5129 v8::HandleScope scope;
5130 break_count = 0;
5131 message_handler_hit_count = 0;
5132 v8::Debug::SetMessageHandler2(DebugEvalContextCheckMessageHandler);
5133
5134 ExecuteScriptForContextCheck();
5135
5136 // One time compile event and two times break event.
5137 CHECK_GT(message_handler_hit_count, 3);
5138
5139 // One break from the source and another from the evaluate request.
5140 CHECK_EQ(break_count, 2);
5141 v8::Debug::SetMessageHandler2(NULL);
5142 CheckDebuggerUnloaded();
5143}
5144
5145
5146// Debug event listener which counts the script collected events.
5147int script_collected_count = 0;
5148static void DebugEventScriptCollectedEvent(v8::DebugEvent event,
5149 v8::Handle<v8::Object> exec_state,
5150 v8::Handle<v8::Object> event_data,
5151 v8::Handle<v8::Value> data) {
5152 // Count the number of breaks.
5153 if (event == v8::ScriptCollected) {
5154 script_collected_count++;
5155 }
5156}
5157
5158
5159// Test that scripts collected are reported through the debug event listener.
5160TEST(ScriptCollectedEvent) {
5161 break_point_hit_count = 0;
5162 script_collected_count = 0;
5163 v8::HandleScope scope;
5164 DebugLocalContext env;
5165
5166 // Request the loaded scripts to initialize the debugger script cache.
5167 Debug::GetLoadedScripts();
5168
5169 // Do garbage collection to ensure that only the script in this test will be
5170 // collected afterwards.
5171 Heap::CollectAllGarbage(false);
5172
5173 script_collected_count = 0;
5174 v8::Debug::SetDebugEventListener(DebugEventScriptCollectedEvent,
5175 v8::Undefined());
5176 {
5177 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run();
5178 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run();
5179 }
5180
5181 // Do garbage collection to collect the script above which is no longer
5182 // referenced.
5183 Heap::CollectAllGarbage(false);
5184
5185 CHECK_EQ(2, script_collected_count);
5186
5187 v8::Debug::SetDebugEventListener(NULL);
5188 CheckDebuggerUnloaded();
5189}
5190
5191
5192// Debug event listener which counts the script collected events.
5193int script_collected_message_count = 0;
5194static void ScriptCollectedMessageHandler(const v8::Debug::Message& message) {
5195 // Count the number of scripts collected.
5196 if (message.IsEvent() && message.GetEvent() == v8::ScriptCollected) {
5197 script_collected_message_count++;
5198 v8::Handle<v8::Context> context = message.GetEventContext();
5199 CHECK(context.IsEmpty());
5200 }
5201}
5202
5203
5204// Test that GetEventContext doesn't fail and return empty handle for
5205// ScriptCollected events.
5206TEST(ScriptCollectedEventContext) {
5207 script_collected_message_count = 0;
5208 v8::HandleScope scope;
5209
5210 { // Scope for the DebugLocalContext.
5211 DebugLocalContext env;
5212
5213 // Request the loaded scripts to initialize the debugger script cache.
5214 Debug::GetLoadedScripts();
5215
5216 // Do garbage collection to ensure that only the script in this test will be
5217 // collected afterwards.
5218 Heap::CollectAllGarbage(false);
5219
5220 v8::Debug::SetMessageHandler2(ScriptCollectedMessageHandler);
5221 {
5222 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run();
5223 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run();
5224 }
5225 }
5226
5227 // Do garbage collection to collect the script above which is no longer
5228 // referenced.
5229 Heap::CollectAllGarbage(false);
5230
5231 CHECK_EQ(2, script_collected_message_count);
5232
5233 v8::Debug::SetMessageHandler2(NULL);
5234}
5235
5236
5237// Debug event listener which counts the after compile events.
5238int after_compile_message_count = 0;
5239static void AfterCompileMessageHandler(const v8::Debug::Message& message) {
5240 // Count the number of scripts collected.
5241 if (message.IsEvent()) {
5242 if (message.GetEvent() == v8::AfterCompile) {
5243 after_compile_message_count++;
5244 } else if (message.GetEvent() == v8::Break) {
5245 SendContinueCommand();
5246 }
5247 }
5248}
5249
5250
5251// Tests that after compile event is sent as many times as there are scripts
5252// compiled.
5253TEST(AfterCompileMessageWhenMessageHandlerIsReset) {
5254 v8::HandleScope scope;
5255 DebugLocalContext env;
5256 after_compile_message_count = 0;
5257 const char* script = "var a=1";
5258
5259 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5260 v8::Script::Compile(v8::String::New(script))->Run();
5261 v8::Debug::SetMessageHandler2(NULL);
5262
5263 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5264 v8::Debug::DebugBreak();
5265 v8::Script::Compile(v8::String::New(script))->Run();
5266
5267 // Setting listener to NULL should cause debugger unload.
5268 v8::Debug::SetMessageHandler2(NULL);
5269 CheckDebuggerUnloaded();
5270
5271 // Compilation cache should be disabled when debugger is active.
5272 CHECK_EQ(2, after_compile_message_count);
5273}
5274
5275
5276// Tests that break event is sent when message handler is reset.
5277TEST(BreakMessageWhenMessageHandlerIsReset) {
5278 v8::HandleScope scope;
5279 DebugLocalContext env;
5280 after_compile_message_count = 0;
5281 const char* script = "function f() {};";
5282
5283 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5284 v8::Script::Compile(v8::String::New(script))->Run();
5285 v8::Debug::SetMessageHandler2(NULL);
5286
5287 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5288 v8::Debug::DebugBreak();
5289 v8::Local<v8::Function> f =
5290 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5291 f->Call(env->Global(), 0, NULL);
5292
5293 // Setting message handler to NULL should cause debugger unload.
5294 v8::Debug::SetMessageHandler2(NULL);
5295 CheckDebuggerUnloaded();
5296
5297 // Compilation cache should be disabled when debugger is active.
5298 CHECK_EQ(1, after_compile_message_count);
5299}
5300
5301
5302static int exception_event_count = 0;
5303static void ExceptionMessageHandler(const v8::Debug::Message& message) {
5304 if (message.IsEvent() && message.GetEvent() == v8::Exception) {
5305 exception_event_count++;
5306 SendContinueCommand();
5307 }
5308}
5309
5310
5311// Tests that exception event is sent when message handler is reset.
5312TEST(ExceptionMessageWhenMessageHandlerIsReset) {
5313 v8::HandleScope scope;
5314 DebugLocalContext env;
5315 exception_event_count = 0;
5316 const char* script = "function f() {throw new Error()};";
5317
5318 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5319 v8::Script::Compile(v8::String::New(script))->Run();
5320 v8::Debug::SetMessageHandler2(NULL);
5321
5322 v8::Debug::SetMessageHandler2(ExceptionMessageHandler);
5323 v8::Local<v8::Function> f =
5324 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5325 f->Call(env->Global(), 0, NULL);
5326
5327 // Setting message handler to NULL should cause debugger unload.
5328 v8::Debug::SetMessageHandler2(NULL);
5329 CheckDebuggerUnloaded();
5330
5331 CHECK_EQ(1, exception_event_count);
5332}
5333
5334
5335// Tests after compile event is sent when there are some provisional
5336// breakpoints out of the scripts lines range.
5337TEST(ProvisionalBreakpointOnLineOutOfRange) {
5338 v8::HandleScope scope;
5339 DebugLocalContext env;
5340 env.ExposeDebug();
5341 const char* script = "function f() {};";
5342 const char* resource_name = "test_resource";
5343
5344 // Set a couple of provisional breakpoint on lines out of the script lines
5345 // range.
5346 int sbp1 = SetScriptBreakPointByNameFromJS(resource_name, 3,
5347 -1 /* no column */);
5348 int sbp2 = SetScriptBreakPointByNameFromJS(resource_name, 5, 5);
5349
5350 after_compile_message_count = 0;
5351 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5352
5353 v8::ScriptOrigin origin(
5354 v8::String::New(resource_name),
5355 v8::Integer::New(10),
5356 v8::Integer::New(1));
5357 // Compile a script whose first line number is greater than the breakpoints'
5358 // lines.
5359 v8::Script::Compile(v8::String::New(script), &origin)->Run();
5360
5361 // If the script is compiled successfully there is exactly one after compile
5362 // event. In case of an exception in debugger code after compile event is not
5363 // sent.
5364 CHECK_EQ(1, after_compile_message_count);
5365
5366 ClearBreakPointFromJS(sbp1);
5367 ClearBreakPointFromJS(sbp2);
5368 v8::Debug::SetMessageHandler2(NULL);
5369}
5370
5371
5372static void BreakMessageHandler(const v8::Debug::Message& message) {
5373 if (message.IsEvent() && message.GetEvent() == v8::Break) {
5374 // Count the number of breaks.
5375 break_point_hit_count++;
5376
5377 v8::HandleScope scope;
5378 v8::Handle<v8::String> json = message.GetJSON();
5379
5380 SendContinueCommand();
5381 } else if (message.IsEvent() && message.GetEvent() == v8::AfterCompile) {
5382 v8::HandleScope scope;
5383
5384 bool is_debug_break = i::StackGuard::IsDebugBreak();
5385 // Force DebugBreak flag while serializer is working.
5386 i::StackGuard::DebugBreak();
5387
5388 // Force serialization to trigger some internal JS execution.
5389 v8::Handle<v8::String> json = message.GetJSON();
5390
5391 // Restore previous state.
5392 if (is_debug_break) {
5393 i::StackGuard::DebugBreak();
5394 } else {
5395 i::StackGuard::Continue(i::DEBUGBREAK);
5396 }
5397 }
5398}
5399
5400
5401// Test that if DebugBreak is forced it is ignored when code from
5402// debug-delay.js is executed.
5403TEST(NoDebugBreakInAfterCompileMessageHandler) {
5404 v8::HandleScope scope;
5405 DebugLocalContext env;
5406
5407 // Register a debug event listener which sets the break flag and counts.
5408 v8::Debug::SetMessageHandler2(BreakMessageHandler);
5409
5410 // Set the debug break flag.
5411 v8::Debug::DebugBreak();
5412
5413 // Create a function for testing stepping.
5414 const char* src = "function f() { eval('var x = 10;'); } ";
5415 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
5416
5417 // There should be only one break event.
5418 CHECK_EQ(1, break_point_hit_count);
5419
5420 // Set the debug break flag again.
5421 v8::Debug::DebugBreak();
5422 f->Call(env->Global(), 0, NULL);
5423 // There should be one more break event when the script is evaluated in 'f'.
5424 CHECK_EQ(2, break_point_hit_count);
5425
5426 // Get rid of the debug message handler.
5427 v8::Debug::SetMessageHandler2(NULL);
5428 CheckDebuggerUnloaded();
5429}
5430
5431
5432TEST(GetMirror) {
5433 v8::HandleScope scope;
5434 DebugLocalContext env;
5435 v8::Handle<v8::Value> obj = v8::Debug::GetMirror(v8::String::New("hodja"));
5436 v8::Handle<v8::Function> run_test = v8::Handle<v8::Function>::Cast(
5437 v8::Script::New(
5438 v8::String::New(
5439 "function runTest(mirror) {"
5440 " return mirror.isString() && (mirror.length() == 5);"
5441 "}"
5442 ""
5443 "runTest;"))->Run());
5444 v8::Handle<v8::Value> result = run_test->Call(env->Global(), 1, &obj);
5445 CHECK(result->IsTrue());
5446}