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