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