blob: 583a9c2c298553d506d17b1f5910fa234ab73731 [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
2050// Thest that the evaluation of expressions when a break point is hit generates
2051// the correct results.
2052TEST(DebugEvaluate) {
2053 v8::HandleScope scope;
2054 DebugLocalContext env;
2055 env.ExposeDebug();
2056
2057 // Create a function for checking the evaluation when hitting a break point.
2058 evaluate_check_function = CompileFunction(&env,
2059 evaluate_check_source,
2060 "evaluate_check");
2061 // Register the debug event listener
2062 v8::Debug::SetDebugEventListener(DebugEventEvaluate);
2063
2064 // Different expected vaules of x and a when in a break point (u = undefined,
2065 // d = Hello, world!).
2066 struct EvaluateCheck checks_uu[] = {
2067 {"x", v8::Undefined()},
2068 {"a", v8::Undefined()},
2069 {NULL, v8::Handle<v8::Value>()}
2070 };
2071 struct EvaluateCheck checks_hu[] = {
2072 {"x", v8::String::New("Hello, world!")},
2073 {"a", v8::Undefined()},
2074 {NULL, v8::Handle<v8::Value>()}
2075 };
2076 struct EvaluateCheck checks_hh[] = {
2077 {"x", v8::String::New("Hello, world!")},
2078 {"a", v8::String::New("Hello, world!")},
2079 {NULL, v8::Handle<v8::Value>()}
2080 };
2081
2082 // Simple test function. The "y=0" is in the function foo to provide a break
2083 // location. For "y=0" the "y" is at position 15 in the barbar function
2084 // therefore setting breakpoint at position 15 will break at "y=0" and
2085 // setting it higher will break after.
2086 v8::Local<v8::Function> foo = CompileFunction(&env,
2087 "function foo(x) {"
2088 " var a;"
2089 " y=0; /* To ensure break location.*/"
2090 " a=x;"
2091 "}",
2092 "foo");
2093 const int foo_break_position = 15;
2094
2095 // Arguments with one parameter "Hello, world!"
2096 v8::Handle<v8::Value> argv_foo[1] = { v8::String::New("Hello, world!") };
2097
2098 // Call foo with breakpoint set before a=x and undefined as parameter.
2099 int bp = SetBreakPoint(foo, foo_break_position);
2100 checks = checks_uu;
2101 foo->Call(env->Global(), 0, NULL);
2102
2103 // Call foo with breakpoint set before a=x and parameter "Hello, world!".
2104 checks = checks_hu;
2105 foo->Call(env->Global(), 1, argv_foo);
2106
2107 // Call foo with breakpoint set after a=x and parameter "Hello, world!".
2108 ClearBreakPoint(bp);
2109 SetBreakPoint(foo, foo_break_position + 1);
2110 checks = checks_hh;
2111 foo->Call(env->Global(), 1, argv_foo);
2112
2113 // Test function with an inner function. The "y=0" is in function barbar
2114 // to provide a break location. For "y=0" the "y" is at position 8 in the
2115 // barbar function therefore setting breakpoint at position 8 will break at
2116 // "y=0" and setting it higher will break after.
2117 v8::Local<v8::Function> bar = CompileFunction(&env,
2118 "y = 0;"
2119 "x = 'Goodbye, world!';"
2120 "function bar(x, b) {"
2121 " var a;"
2122 " function barbar() {"
2123 " y=0; /* To ensure break location.*/"
2124 " a=x;"
2125 " };"
2126 " debug.Debug.clearAllBreakPoints();"
2127 " barbar();"
2128 " y=0;a=x;"
2129 "}",
2130 "bar");
2131 const int barbar_break_position = 8;
2132
2133 // Call bar setting breakpoint before a=x in barbar and undefined as
2134 // parameter.
2135 checks = checks_uu;
2136 v8::Handle<v8::Value> argv_bar_1[2] = {
2137 v8::Undefined(),
2138 v8::Number::New(barbar_break_position)
2139 };
2140 bar->Call(env->Global(), 2, argv_bar_1);
2141
2142 // Call bar setting breakpoint before a=x in barbar and parameter
2143 // "Hello, world!".
2144 checks = checks_hu;
2145 v8::Handle<v8::Value> argv_bar_2[2] = {
2146 v8::String::New("Hello, world!"),
2147 v8::Number::New(barbar_break_position)
2148 };
2149 bar->Call(env->Global(), 2, argv_bar_2);
2150
2151 // Call bar setting breakpoint after a=x in barbar and parameter
2152 // "Hello, world!".
2153 checks = checks_hh;
2154 v8::Handle<v8::Value> argv_bar_3[2] = {
2155 v8::String::New("Hello, world!"),
2156 v8::Number::New(barbar_break_position + 1)
2157 };
2158 bar->Call(env->Global(), 2, argv_bar_3);
2159
2160 v8::Debug::SetDebugEventListener(NULL);
2161 CheckDebuggerUnloaded();
2162}
2163
Leon Clarkee46be812010-01-19 14:06:41 +00002164// Copies a C string to a 16-bit string. Does not check for buffer overflow.
2165// Does not use the V8 engine to convert strings, so it can be used
2166// in any thread. Returns the length of the string.
2167int AsciiToUtf16(const char* input_buffer, uint16_t* output_buffer) {
2168 int i;
2169 for (i = 0; input_buffer[i] != '\0'; ++i) {
2170 // ASCII does not use chars > 127, but be careful anyway.
2171 output_buffer[i] = static_cast<unsigned char>(input_buffer[i]);
2172 }
2173 output_buffer[i] = 0;
2174 return i;
2175}
2176
2177// Copies a 16-bit string to a C string by dropping the high byte of
2178// each character. Does not check for buffer overflow.
2179// Can be used in any thread. Requires string length as an input.
2180int Utf16ToAscii(const uint16_t* input_buffer, int length,
2181 char* output_buffer, int output_len = -1) {
2182 if (output_len >= 0) {
2183 if (length > output_len - 1) {
2184 length = output_len - 1;
2185 }
2186 }
2187
2188 for (int i = 0; i < length; ++i) {
2189 output_buffer[i] = static_cast<char>(input_buffer[i]);
2190 }
2191 output_buffer[length] = '\0';
2192 return length;
2193}
2194
2195
2196// We match parts of the message to get evaluate result int value.
2197bool GetEvaluateStringResult(char *message, char* buffer, int buffer_size) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002198 if (strstr(message, "\"command\":\"evaluate\"") == NULL) {
2199 return false;
2200 }
2201 const char* prefix = "\"text\":\"";
2202 char* pos1 = strstr(message, prefix);
2203 if (pos1 == NULL) {
2204 return false;
2205 }
2206 pos1 += strlen(prefix);
2207 char* pos2 = strchr(pos1, '"');
2208 if (pos2 == NULL) {
Leon Clarkee46be812010-01-19 14:06:41 +00002209 return false;
2210 }
2211 Vector<char> buf(buffer, buffer_size);
Leon Clarked91b9f72010-01-27 17:25:45 +00002212 int len = static_cast<int>(pos2 - pos1);
2213 if (len > buffer_size - 1) {
2214 len = buffer_size - 1;
2215 }
2216 OS::StrNCpy(buf, pos1, len);
Leon Clarkee46be812010-01-19 14:06:41 +00002217 buffer[buffer_size - 1] = '\0';
2218 return true;
2219}
2220
2221
2222struct EvaluateResult {
2223 static const int kBufferSize = 20;
2224 char buffer[kBufferSize];
2225};
2226
2227struct DebugProcessDebugMessagesData {
2228 static const int kArraySize = 5;
2229 int counter;
2230 EvaluateResult results[kArraySize];
2231
2232 void reset() {
2233 counter = 0;
2234 }
2235 EvaluateResult* current() {
2236 return &results[counter % kArraySize];
2237 }
2238 void next() {
2239 counter++;
2240 }
2241};
2242
2243DebugProcessDebugMessagesData process_debug_messages_data;
2244
2245static void DebugProcessDebugMessagesHandler(
2246 const uint16_t* message,
2247 int length,
2248 v8::Debug::ClientData* client_data) {
2249
2250 const int kBufferSize = 100000;
2251 char print_buffer[kBufferSize];
2252 Utf16ToAscii(message, length, print_buffer, kBufferSize);
2253
2254 EvaluateResult* array_item = process_debug_messages_data.current();
2255
2256 bool res = GetEvaluateStringResult(print_buffer,
2257 array_item->buffer,
2258 EvaluateResult::kBufferSize);
2259 if (res) {
2260 process_debug_messages_data.next();
2261 }
2262}
2263
2264// Test that the evaluation of expressions works even from ProcessDebugMessages
2265// i.e. with empty stack.
2266TEST(DebugEvaluateWithoutStack) {
2267 v8::Debug::SetMessageHandler(DebugProcessDebugMessagesHandler);
2268
2269 v8::HandleScope scope;
2270 DebugLocalContext env;
2271
2272 const char* source =
2273 "var v1 = 'Pinguin';\n function getAnimal() { return 'Capy' + 'bara'; }";
2274
2275 v8::Script::Compile(v8::String::New(source))->Run();
2276
2277 v8::Debug::ProcessDebugMessages();
2278
2279 const int kBufferSize = 1000;
2280 uint16_t buffer[kBufferSize];
2281
2282 const char* command_111 = "{\"seq\":111,"
2283 "\"type\":\"request\","
2284 "\"command\":\"evaluate\","
2285 "\"arguments\":{"
2286 " \"global\":true,"
2287 " \"expression\":\"v1\",\"disable_break\":true"
2288 "}}";
2289
2290 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_111, buffer));
2291
2292 const char* command_112 = "{\"seq\":112,"
2293 "\"type\":\"request\","
2294 "\"command\":\"evaluate\","
2295 "\"arguments\":{"
2296 " \"global\":true,"
2297 " \"expression\":\"getAnimal()\",\"disable_break\":true"
2298 "}}";
2299
2300 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_112, buffer));
2301
2302 const char* command_113 = "{\"seq\":113,"
2303 "\"type\":\"request\","
2304 "\"command\":\"evaluate\","
2305 "\"arguments\":{"
2306 " \"global\":true,"
2307 " \"expression\":\"239 + 566\",\"disable_break\":true"
2308 "}}";
2309
2310 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_113, buffer));
2311
2312 v8::Debug::ProcessDebugMessages();
2313
2314 CHECK_EQ(3, process_debug_messages_data.counter);
2315
Leon Clarked91b9f72010-01-27 17:25:45 +00002316 CHECK_EQ(strcmp("Pinguin", process_debug_messages_data.results[0].buffer), 0);
2317 CHECK_EQ(strcmp("Capybara", process_debug_messages_data.results[1].buffer),
2318 0);
2319 CHECK_EQ(strcmp("805", process_debug_messages_data.results[2].buffer), 0);
Leon Clarkee46be812010-01-19 14:06:41 +00002320
2321 v8::Debug::SetMessageHandler(NULL);
2322 v8::Debug::SetDebugEventListener(NULL);
2323 CheckDebuggerUnloaded();
2324}
2325
Steve Blocka7e24c12009-10-30 11:49:00 +00002326
2327// Simple test of the stepping mechanism using only store ICs.
2328TEST(DebugStepLinear) {
2329 v8::HandleScope scope;
2330 DebugLocalContext env;
2331
2332 // Create a function for testing stepping.
2333 v8::Local<v8::Function> foo = CompileFunction(&env,
2334 "function foo(){a=1;b=1;c=1;}",
2335 "foo");
2336 SetBreakPoint(foo, 3);
2337
2338 // Register a debug event listener which steps and counts.
2339 v8::Debug::SetDebugEventListener(DebugEventStep);
2340
2341 step_action = StepIn;
2342 break_point_hit_count = 0;
2343 foo->Call(env->Global(), 0, NULL);
2344
2345 // With stepping all break locations are hit.
2346 CHECK_EQ(4, break_point_hit_count);
2347
2348 v8::Debug::SetDebugEventListener(NULL);
2349 CheckDebuggerUnloaded();
2350
2351 // Register a debug event listener which just counts.
2352 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2353
2354 SetBreakPoint(foo, 3);
2355 break_point_hit_count = 0;
2356 foo->Call(env->Global(), 0, NULL);
2357
2358 // Without stepping only active break points are hit.
2359 CHECK_EQ(1, break_point_hit_count);
2360
2361 v8::Debug::SetDebugEventListener(NULL);
2362 CheckDebuggerUnloaded();
2363}
2364
2365
2366// Test of the stepping mechanism for keyed load in a loop.
2367TEST(DebugStepKeyedLoadLoop) {
2368 v8::HandleScope scope;
2369 DebugLocalContext env;
2370
2371 // Create a function for testing stepping of keyed load. The statement 'y=1'
2372 // is there to have more than one breakable statement in the loop, TODO(315).
2373 v8::Local<v8::Function> foo = CompileFunction(
2374 &env,
2375 "function foo(a) {\n"
2376 " var x;\n"
2377 " var len = a.length;\n"
2378 " for (var i = 0; i < len; i++) {\n"
2379 " y = 1;\n"
2380 " x = a[i];\n"
2381 " }\n"
2382 "}\n",
2383 "foo");
2384
2385 // Create array [0,1,2,3,4,5,6,7,8,9]
2386 v8::Local<v8::Array> a = v8::Array::New(10);
2387 for (int i = 0; i < 10; i++) {
2388 a->Set(v8::Number::New(i), v8::Number::New(i));
2389 }
2390
2391 // Call function without any break points to ensure inlining is in place.
2392 const int kArgc = 1;
2393 v8::Handle<v8::Value> args[kArgc] = { a };
2394 foo->Call(env->Global(), kArgc, args);
2395
2396 // Register a debug event listener which steps and counts.
2397 v8::Debug::SetDebugEventListener(DebugEventStep);
2398
2399 // Setup break point and step through the function.
2400 SetBreakPoint(foo, 3);
2401 step_action = StepNext;
2402 break_point_hit_count = 0;
2403 foo->Call(env->Global(), kArgc, args);
2404
2405 // With stepping all break locations are hit.
2406 CHECK_EQ(22, break_point_hit_count);
2407
2408 v8::Debug::SetDebugEventListener(NULL);
2409 CheckDebuggerUnloaded();
2410}
2411
2412
2413// Test of the stepping mechanism for keyed store in a loop.
2414TEST(DebugStepKeyedStoreLoop) {
2415 v8::HandleScope scope;
2416 DebugLocalContext env;
2417
2418 // Create a function for testing stepping of keyed store. The statement 'y=1'
2419 // is there to have more than one breakable statement in the loop, TODO(315).
2420 v8::Local<v8::Function> foo = CompileFunction(
2421 &env,
2422 "function foo(a) {\n"
2423 " var len = a.length;\n"
2424 " for (var i = 0; i < len; i++) {\n"
2425 " y = 1;\n"
2426 " a[i] = 42;\n"
2427 " }\n"
2428 "}\n",
2429 "foo");
2430
2431 // Create array [0,1,2,3,4,5,6,7,8,9]
2432 v8::Local<v8::Array> a = v8::Array::New(10);
2433 for (int i = 0; i < 10; i++) {
2434 a->Set(v8::Number::New(i), v8::Number::New(i));
2435 }
2436
2437 // Call function without any break points to ensure inlining is in place.
2438 const int kArgc = 1;
2439 v8::Handle<v8::Value> args[kArgc] = { a };
2440 foo->Call(env->Global(), kArgc, args);
2441
2442 // Register a debug event listener which steps and counts.
2443 v8::Debug::SetDebugEventListener(DebugEventStep);
2444
2445 // Setup break point and step through the function.
2446 SetBreakPoint(foo, 3);
2447 step_action = StepNext;
2448 break_point_hit_count = 0;
2449 foo->Call(env->Global(), kArgc, args);
2450
2451 // With stepping all break locations are hit.
2452 CHECK_EQ(22, break_point_hit_count);
2453
2454 v8::Debug::SetDebugEventListener(NULL);
2455 CheckDebuggerUnloaded();
2456}
2457
2458
2459// Test the stepping mechanism with different ICs.
2460TEST(DebugStepLinearMixedICs) {
2461 v8::HandleScope scope;
2462 DebugLocalContext env;
2463
2464 // Create a function for testing stepping.
2465 v8::Local<v8::Function> foo = CompileFunction(&env,
2466 "function bar() {};"
2467 "function foo() {"
2468 " var x;"
2469 " var index='name';"
2470 " var y = {};"
2471 " a=1;b=2;x=a;y[index]=3;x=y[index];bar();}", "foo");
2472 SetBreakPoint(foo, 0);
2473
2474 // Register a debug event listener which steps and counts.
2475 v8::Debug::SetDebugEventListener(DebugEventStep);
2476
2477 step_action = StepIn;
2478 break_point_hit_count = 0;
2479 foo->Call(env->Global(), 0, NULL);
2480
2481 // With stepping all break locations are hit.
2482 CHECK_EQ(8, break_point_hit_count);
2483
2484 v8::Debug::SetDebugEventListener(NULL);
2485 CheckDebuggerUnloaded();
2486
2487 // Register a debug event listener which just counts.
2488 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2489
2490 SetBreakPoint(foo, 0);
2491 break_point_hit_count = 0;
2492 foo->Call(env->Global(), 0, NULL);
2493
2494 // Without stepping only active break points are hit.
2495 CHECK_EQ(1, break_point_hit_count);
2496
2497 v8::Debug::SetDebugEventListener(NULL);
2498 CheckDebuggerUnloaded();
2499}
2500
2501
2502TEST(DebugStepIf) {
2503 v8::HandleScope scope;
2504 DebugLocalContext env;
2505
2506 // Register a debug event listener which steps and counts.
2507 v8::Debug::SetDebugEventListener(DebugEventStep);
2508
2509 // Create a function for testing stepping.
2510 const int argc = 1;
2511 const char* src = "function foo(x) { "
2512 " a = 1;"
2513 " if (x) {"
2514 " b = 1;"
2515 " } else {"
2516 " c = 1;"
2517 " d = 1;"
2518 " }"
2519 "}";
2520 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2521 SetBreakPoint(foo, 0);
2522
2523 // Stepping through the true part.
2524 step_action = StepIn;
2525 break_point_hit_count = 0;
2526 v8::Handle<v8::Value> argv_true[argc] = { v8::True() };
2527 foo->Call(env->Global(), argc, argv_true);
2528 CHECK_EQ(3, break_point_hit_count);
2529
2530 // Stepping through the false part.
2531 step_action = StepIn;
2532 break_point_hit_count = 0;
2533 v8::Handle<v8::Value> argv_false[argc] = { v8::False() };
2534 foo->Call(env->Global(), argc, argv_false);
2535 CHECK_EQ(4, break_point_hit_count);
2536
2537 // Get rid of the debug event listener.
2538 v8::Debug::SetDebugEventListener(NULL);
2539 CheckDebuggerUnloaded();
2540}
2541
2542
2543TEST(DebugStepSwitch) {
2544 v8::HandleScope scope;
2545 DebugLocalContext env;
2546
2547 // Register a debug event listener which steps and counts.
2548 v8::Debug::SetDebugEventListener(DebugEventStep);
2549
2550 // Create a function for testing stepping.
2551 const int argc = 1;
2552 const char* src = "function foo(x) { "
2553 " a = 1;"
2554 " switch (x) {"
2555 " case 1:"
2556 " b = 1;"
2557 " case 2:"
2558 " c = 1;"
2559 " break;"
2560 " case 3:"
2561 " d = 1;"
2562 " e = 1;"
2563 " break;"
2564 " }"
2565 "}";
2566 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2567 SetBreakPoint(foo, 0);
2568
2569 // One case with fall-through.
2570 step_action = StepIn;
2571 break_point_hit_count = 0;
2572 v8::Handle<v8::Value> argv_1[argc] = { v8::Number::New(1) };
2573 foo->Call(env->Global(), argc, argv_1);
2574 CHECK_EQ(4, break_point_hit_count);
2575
2576 // Another case.
2577 step_action = StepIn;
2578 break_point_hit_count = 0;
2579 v8::Handle<v8::Value> argv_2[argc] = { v8::Number::New(2) };
2580 foo->Call(env->Global(), argc, argv_2);
2581 CHECK_EQ(3, break_point_hit_count);
2582
2583 // Last case.
2584 step_action = StepIn;
2585 break_point_hit_count = 0;
2586 v8::Handle<v8::Value> argv_3[argc] = { v8::Number::New(3) };
2587 foo->Call(env->Global(), argc, argv_3);
2588 CHECK_EQ(4, break_point_hit_count);
2589
2590 // Get rid of the debug event listener.
2591 v8::Debug::SetDebugEventListener(NULL);
2592 CheckDebuggerUnloaded();
2593}
2594
2595
2596TEST(DebugStepFor) {
2597 v8::HandleScope scope;
2598 DebugLocalContext env;
2599
2600 // Register a debug event listener which steps and counts.
2601 v8::Debug::SetDebugEventListener(DebugEventStep);
2602
2603 // Create a function for testing stepping.
2604 const int argc = 1;
2605 const char* src = "function foo(x) { "
2606 " a = 1;"
2607 " for (i = 0; i < x; i++) {"
2608 " b = 1;"
2609 " }"
2610 "}";
2611 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
2612 SetBreakPoint(foo, 8); // "a = 1;"
2613
2614 // Looping 10 times.
2615 step_action = StepIn;
2616 break_point_hit_count = 0;
2617 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) };
2618 foo->Call(env->Global(), argc, argv_10);
2619 CHECK_EQ(23, break_point_hit_count);
2620
2621 // Looping 100 times.
2622 step_action = StepIn;
2623 break_point_hit_count = 0;
2624 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) };
2625 foo->Call(env->Global(), argc, argv_100);
2626 CHECK_EQ(203, break_point_hit_count);
2627
2628 // Get rid of the debug event listener.
2629 v8::Debug::SetDebugEventListener(NULL);
2630 CheckDebuggerUnloaded();
2631}
2632
2633
2634TEST(StepInOutSimple) {
2635 v8::HandleScope scope;
2636 DebugLocalContext env;
2637
2638 // Create a function for checking the function when hitting a break point.
2639 frame_function_name = CompileFunction(&env,
2640 frame_function_name_source,
2641 "frame_function_name");
2642
2643 // Register a debug event listener which steps and counts.
2644 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
2645
2646 // Create functions for testing stepping.
2647 const char* src = "function a() {b();c();}; "
2648 "function b() {c();}; "
2649 "function c() {}; ";
2650 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
2651 SetBreakPoint(a, 0);
2652
2653 // Step through invocation of a with step in.
2654 step_action = StepIn;
2655 break_point_hit_count = 0;
2656 expected_step_sequence = "abcbaca";
2657 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002658 CHECK_EQ(StrLength(expected_step_sequence),
2659 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002660
2661 // Step through invocation of a with step next.
2662 step_action = StepNext;
2663 break_point_hit_count = 0;
2664 expected_step_sequence = "aaa";
2665 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002666 CHECK_EQ(StrLength(expected_step_sequence),
2667 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002668
2669 // Step through invocation of a with step out.
2670 step_action = StepOut;
2671 break_point_hit_count = 0;
2672 expected_step_sequence = "a";
2673 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002674 CHECK_EQ(StrLength(expected_step_sequence),
2675 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002676
2677 // Get rid of the debug event listener.
2678 v8::Debug::SetDebugEventListener(NULL);
2679 CheckDebuggerUnloaded();
2680}
2681
2682
2683TEST(StepInOutTree) {
2684 v8::HandleScope scope;
2685 DebugLocalContext env;
2686
2687 // Create a function for checking the function when hitting a break point.
2688 frame_function_name = CompileFunction(&env,
2689 frame_function_name_source,
2690 "frame_function_name");
2691
2692 // Register a debug event listener which steps and counts.
2693 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
2694
2695 // Create functions for testing stepping.
2696 const char* src = "function a() {b(c(d()),d());c(d());d()}; "
2697 "function b(x,y) {c();}; "
2698 "function c(x) {}; "
2699 "function d() {}; ";
2700 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
2701 SetBreakPoint(a, 0);
2702
2703 // Step through invocation of a with step in.
2704 step_action = StepIn;
2705 break_point_hit_count = 0;
2706 expected_step_sequence = "adacadabcbadacada";
2707 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002708 CHECK_EQ(StrLength(expected_step_sequence),
2709 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002710
2711 // Step through invocation of a with step next.
2712 step_action = StepNext;
2713 break_point_hit_count = 0;
2714 expected_step_sequence = "aaaa";
2715 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002716 CHECK_EQ(StrLength(expected_step_sequence),
2717 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002718
2719 // Step through invocation of a with step out.
2720 step_action = StepOut;
2721 break_point_hit_count = 0;
2722 expected_step_sequence = "a";
2723 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002724 CHECK_EQ(StrLength(expected_step_sequence),
2725 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002726
2727 // Get rid of the debug event listener.
2728 v8::Debug::SetDebugEventListener(NULL);
2729 CheckDebuggerUnloaded(true);
2730}
2731
2732
2733TEST(StepInOutBranch) {
2734 v8::HandleScope scope;
2735 DebugLocalContext env;
2736
2737 // Create a function for checking the function when hitting a break point.
2738 frame_function_name = CompileFunction(&env,
2739 frame_function_name_source,
2740 "frame_function_name");
2741
2742 // Register a debug event listener which steps and counts.
2743 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
2744
2745 // Create functions for testing stepping.
2746 const char* src = "function a() {b(false);c();}; "
2747 "function b(x) {if(x){c();};}; "
2748 "function c() {}; ";
2749 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
2750 SetBreakPoint(a, 0);
2751
2752 // Step through invocation of a.
2753 step_action = StepIn;
2754 break_point_hit_count = 0;
2755 expected_step_sequence = "abaca";
2756 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00002757 CHECK_EQ(StrLength(expected_step_sequence),
2758 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002759
2760 // Get rid of the debug event listener.
2761 v8::Debug::SetDebugEventListener(NULL);
2762 CheckDebuggerUnloaded();
2763}
2764
2765
2766// Test that step in does not step into native functions.
2767TEST(DebugStepNatives) {
2768 v8::HandleScope scope;
2769 DebugLocalContext env;
2770
2771 // Create a function for testing stepping.
2772 v8::Local<v8::Function> foo = CompileFunction(
2773 &env,
2774 "function foo(){debugger;Math.sin(1);}",
2775 "foo");
2776
2777 // Register a debug event listener which steps and counts.
2778 v8::Debug::SetDebugEventListener(DebugEventStep);
2779
2780 step_action = StepIn;
2781 break_point_hit_count = 0;
2782 foo->Call(env->Global(), 0, NULL);
2783
2784 // With stepping all break locations are hit.
2785 CHECK_EQ(3, break_point_hit_count);
2786
2787 v8::Debug::SetDebugEventListener(NULL);
2788 CheckDebuggerUnloaded();
2789
2790 // Register a debug event listener which just counts.
2791 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2792
2793 break_point_hit_count = 0;
2794 foo->Call(env->Global(), 0, NULL);
2795
2796 // Without stepping only active break points are hit.
2797 CHECK_EQ(1, break_point_hit_count);
2798
2799 v8::Debug::SetDebugEventListener(NULL);
2800 CheckDebuggerUnloaded();
2801}
2802
2803
2804// Test that step in works with function.apply.
2805TEST(DebugStepFunctionApply) {
2806 v8::HandleScope scope;
2807 DebugLocalContext env;
2808
2809 // Create a function for testing stepping.
2810 v8::Local<v8::Function> foo = CompileFunction(
2811 &env,
2812 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
2813 "function foo(){ debugger; bar.apply(this, [1,2,3]); }",
2814 "foo");
2815
2816 // Register a debug event listener which steps and counts.
2817 v8::Debug::SetDebugEventListener(DebugEventStep);
2818
2819 step_action = StepIn;
2820 break_point_hit_count = 0;
2821 foo->Call(env->Global(), 0, NULL);
2822
2823 // With stepping all break locations are hit.
2824 CHECK_EQ(6, break_point_hit_count);
2825
2826 v8::Debug::SetDebugEventListener(NULL);
2827 CheckDebuggerUnloaded();
2828
2829 // Register a debug event listener which just counts.
2830 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2831
2832 break_point_hit_count = 0;
2833 foo->Call(env->Global(), 0, NULL);
2834
2835 // Without stepping only the debugger statement is hit.
2836 CHECK_EQ(1, break_point_hit_count);
2837
2838 v8::Debug::SetDebugEventListener(NULL);
2839 CheckDebuggerUnloaded();
2840}
2841
2842
2843// Test that step in works with function.call.
2844TEST(DebugStepFunctionCall) {
2845 v8::HandleScope scope;
2846 DebugLocalContext env;
2847
2848 // Create a function for testing stepping.
2849 v8::Local<v8::Function> foo = CompileFunction(
2850 &env,
2851 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
2852 "function foo(a){ debugger;"
2853 " if (a) {"
2854 " bar.call(this, 1, 2, 3);"
2855 " } else {"
2856 " bar.call(this, 0);"
2857 " }"
2858 "}",
2859 "foo");
2860
2861 // Register a debug event listener which steps and counts.
2862 v8::Debug::SetDebugEventListener(DebugEventStep);
2863 step_action = StepIn;
2864
2865 // Check stepping where the if condition in bar is false.
2866 break_point_hit_count = 0;
2867 foo->Call(env->Global(), 0, NULL);
2868 CHECK_EQ(4, break_point_hit_count);
2869
2870 // Check stepping where the if condition in bar is true.
2871 break_point_hit_count = 0;
2872 const int argc = 1;
2873 v8::Handle<v8::Value> argv[argc] = { v8::True() };
2874 foo->Call(env->Global(), argc, argv);
2875 CHECK_EQ(6, break_point_hit_count);
2876
2877 v8::Debug::SetDebugEventListener(NULL);
2878 CheckDebuggerUnloaded();
2879
2880 // Register a debug event listener which just counts.
2881 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2882
2883 break_point_hit_count = 0;
2884 foo->Call(env->Global(), 0, NULL);
2885
2886 // Without stepping only the debugger statement is hit.
2887 CHECK_EQ(1, break_point_hit_count);
2888
2889 v8::Debug::SetDebugEventListener(NULL);
2890 CheckDebuggerUnloaded();
2891}
2892
2893
Steve Blockd0582a62009-12-15 09:54:21 +00002894// Tests that breakpoint will be hit if it's set in script.
2895TEST(PauseInScript) {
2896 v8::HandleScope scope;
2897 DebugLocalContext env;
2898 env.ExposeDebug();
2899
2900 // Register a debug event listener which counts.
2901 v8::Debug::SetDebugEventListener(DebugEventCounter);
2902
2903 // Create a script that returns a function.
2904 const char* src = "(function (evt) {})";
2905 const char* script_name = "StepInHandlerTest";
2906
2907 // Set breakpoint in the script.
2908 SetScriptBreakPointByNameFromJS(script_name, 0, -1);
2909 break_point_hit_count = 0;
2910
2911 v8::ScriptOrigin origin(v8::String::New(script_name), v8::Integer::New(0));
2912 v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(src),
2913 &origin);
2914 v8::Local<v8::Value> r = script->Run();
2915
2916 CHECK(r->IsFunction());
2917 CHECK_EQ(1, break_point_hit_count);
2918
2919 // Get rid of the debug event listener.
2920 v8::Debug::SetDebugEventListener(NULL);
2921 CheckDebuggerUnloaded();
2922}
2923
2924
Steve Blocka7e24c12009-10-30 11:49:00 +00002925// Test break on exceptions. For each exception break combination the number
2926// of debug event exception callbacks and message callbacks are collected. The
2927// number of debug event exception callbacks are used to check that the
2928// debugger is called correctly and the number of message callbacks is used to
2929// check that uncaught exceptions are still returned even if there is a break
2930// for them.
2931TEST(BreakOnException) {
2932 v8::HandleScope scope;
2933 DebugLocalContext env;
2934 env.ExposeDebug();
2935
2936 v8::internal::Top::TraceException(false);
2937
2938 // Create functions for testing break on exception.
2939 v8::Local<v8::Function> throws =
2940 CompileFunction(&env, "function throws(){throw 1;}", "throws");
2941 v8::Local<v8::Function> caught =
2942 CompileFunction(&env,
2943 "function caught(){try {throws();} catch(e) {};}",
2944 "caught");
2945 v8::Local<v8::Function> notCaught =
2946 CompileFunction(&env, "function notCaught(){throws();}", "notCaught");
2947
2948 v8::V8::AddMessageListener(MessageCallbackCount);
2949 v8::Debug::SetDebugEventListener(DebugEventCounter);
2950
2951 // Initial state should be break on uncaught exception.
2952 DebugEventCounterClear();
2953 MessageCallbackCountClear();
2954 caught->Call(env->Global(), 0, NULL);
2955 CHECK_EQ(0, exception_hit_count);
2956 CHECK_EQ(0, uncaught_exception_hit_count);
2957 CHECK_EQ(0, message_callback_count);
2958 notCaught->Call(env->Global(), 0, NULL);
2959 CHECK_EQ(1, exception_hit_count);
2960 CHECK_EQ(1, uncaught_exception_hit_count);
2961 CHECK_EQ(1, message_callback_count);
2962
2963 // No break on exception
2964 DebugEventCounterClear();
2965 MessageCallbackCountClear();
2966 ChangeBreakOnException(false, false);
2967 caught->Call(env->Global(), 0, NULL);
2968 CHECK_EQ(0, exception_hit_count);
2969 CHECK_EQ(0, uncaught_exception_hit_count);
2970 CHECK_EQ(0, message_callback_count);
2971 notCaught->Call(env->Global(), 0, NULL);
2972 CHECK_EQ(0, exception_hit_count);
2973 CHECK_EQ(0, uncaught_exception_hit_count);
2974 CHECK_EQ(1, message_callback_count);
2975
2976 // Break on uncaught exception
2977 DebugEventCounterClear();
2978 MessageCallbackCountClear();
2979 ChangeBreakOnException(false, true);
2980 caught->Call(env->Global(), 0, NULL);
2981 CHECK_EQ(0, exception_hit_count);
2982 CHECK_EQ(0, uncaught_exception_hit_count);
2983 CHECK_EQ(0, message_callback_count);
2984 notCaught->Call(env->Global(), 0, NULL);
2985 CHECK_EQ(1, exception_hit_count);
2986 CHECK_EQ(1, uncaught_exception_hit_count);
2987 CHECK_EQ(1, message_callback_count);
2988
2989 // Break on exception and uncaught exception
2990 DebugEventCounterClear();
2991 MessageCallbackCountClear();
2992 ChangeBreakOnException(true, true);
2993 caught->Call(env->Global(), 0, NULL);
2994 CHECK_EQ(1, exception_hit_count);
2995 CHECK_EQ(0, uncaught_exception_hit_count);
2996 CHECK_EQ(0, message_callback_count);
2997 notCaught->Call(env->Global(), 0, NULL);
2998 CHECK_EQ(2, exception_hit_count);
2999 CHECK_EQ(1, uncaught_exception_hit_count);
3000 CHECK_EQ(1, message_callback_count);
3001
3002 // Break on exception
3003 DebugEventCounterClear();
3004 MessageCallbackCountClear();
3005 ChangeBreakOnException(true, false);
3006 caught->Call(env->Global(), 0, NULL);
3007 CHECK_EQ(1, exception_hit_count);
3008 CHECK_EQ(0, uncaught_exception_hit_count);
3009 CHECK_EQ(0, message_callback_count);
3010 notCaught->Call(env->Global(), 0, NULL);
3011 CHECK_EQ(2, exception_hit_count);
3012 CHECK_EQ(1, uncaught_exception_hit_count);
3013 CHECK_EQ(1, message_callback_count);
3014
3015 // No break on exception using JavaScript
3016 DebugEventCounterClear();
3017 MessageCallbackCountClear();
3018 ChangeBreakOnExceptionFromJS(false, false);
3019 caught->Call(env->Global(), 0, NULL);
3020 CHECK_EQ(0, exception_hit_count);
3021 CHECK_EQ(0, uncaught_exception_hit_count);
3022 CHECK_EQ(0, message_callback_count);
3023 notCaught->Call(env->Global(), 0, NULL);
3024 CHECK_EQ(0, exception_hit_count);
3025 CHECK_EQ(0, uncaught_exception_hit_count);
3026 CHECK_EQ(1, message_callback_count);
3027
3028 // Break on uncaught exception using JavaScript
3029 DebugEventCounterClear();
3030 MessageCallbackCountClear();
3031 ChangeBreakOnExceptionFromJS(false, true);
3032 caught->Call(env->Global(), 0, NULL);
3033 CHECK_EQ(0, exception_hit_count);
3034 CHECK_EQ(0, uncaught_exception_hit_count);
3035 CHECK_EQ(0, message_callback_count);
3036 notCaught->Call(env->Global(), 0, NULL);
3037 CHECK_EQ(1, exception_hit_count);
3038 CHECK_EQ(1, uncaught_exception_hit_count);
3039 CHECK_EQ(1, message_callback_count);
3040
3041 // Break on exception and uncaught exception using JavaScript
3042 DebugEventCounterClear();
3043 MessageCallbackCountClear();
3044 ChangeBreakOnExceptionFromJS(true, true);
3045 caught->Call(env->Global(), 0, NULL);
3046 CHECK_EQ(1, exception_hit_count);
3047 CHECK_EQ(0, message_callback_count);
3048 CHECK_EQ(0, uncaught_exception_hit_count);
3049 notCaught->Call(env->Global(), 0, NULL);
3050 CHECK_EQ(2, exception_hit_count);
3051 CHECK_EQ(1, uncaught_exception_hit_count);
3052 CHECK_EQ(1, message_callback_count);
3053
3054 // Break on exception using JavaScript
3055 DebugEventCounterClear();
3056 MessageCallbackCountClear();
3057 ChangeBreakOnExceptionFromJS(true, false);
3058 caught->Call(env->Global(), 0, NULL);
3059 CHECK_EQ(1, exception_hit_count);
3060 CHECK_EQ(0, uncaught_exception_hit_count);
3061 CHECK_EQ(0, message_callback_count);
3062 notCaught->Call(env->Global(), 0, NULL);
3063 CHECK_EQ(2, exception_hit_count);
3064 CHECK_EQ(1, uncaught_exception_hit_count);
3065 CHECK_EQ(1, message_callback_count);
3066
3067 v8::Debug::SetDebugEventListener(NULL);
3068 CheckDebuggerUnloaded();
3069 v8::V8::RemoveMessageListeners(MessageCallbackCount);
3070}
3071
3072
3073// Test break on exception from compiler errors. When compiling using
3074// v8::Script::Compile there is no JavaScript stack whereas when compiling using
3075// eval there are JavaScript frames.
3076TEST(BreakOnCompileException) {
3077 v8::HandleScope scope;
3078 DebugLocalContext env;
3079
3080 v8::internal::Top::TraceException(false);
3081
3082 // Create a function for checking the function when hitting a break point.
3083 frame_count = CompileFunction(&env, frame_count_source, "frame_count");
3084
3085 v8::V8::AddMessageListener(MessageCallbackCount);
3086 v8::Debug::SetDebugEventListener(DebugEventCounter);
3087
3088 DebugEventCounterClear();
3089 MessageCallbackCountClear();
3090
3091 // Check initial state.
3092 CHECK_EQ(0, exception_hit_count);
3093 CHECK_EQ(0, uncaught_exception_hit_count);
3094 CHECK_EQ(0, message_callback_count);
3095 CHECK_EQ(-1, last_js_stack_height);
3096
3097 // Throws SyntaxError: Unexpected end of input
3098 v8::Script::Compile(v8::String::New("+++"));
3099 CHECK_EQ(1, exception_hit_count);
3100 CHECK_EQ(1, uncaught_exception_hit_count);
3101 CHECK_EQ(1, message_callback_count);
3102 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack.
3103
3104 // Throws SyntaxError: Unexpected identifier
3105 v8::Script::Compile(v8::String::New("x x"));
3106 CHECK_EQ(2, exception_hit_count);
3107 CHECK_EQ(2, uncaught_exception_hit_count);
3108 CHECK_EQ(2, message_callback_count);
3109 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack.
3110
3111 // Throws SyntaxError: Unexpected end of input
3112 v8::Script::Compile(v8::String::New("eval('+++')"))->Run();
3113 CHECK_EQ(3, exception_hit_count);
3114 CHECK_EQ(3, uncaught_exception_hit_count);
3115 CHECK_EQ(3, message_callback_count);
3116 CHECK_EQ(1, last_js_stack_height);
3117
3118 // Throws SyntaxError: Unexpected identifier
3119 v8::Script::Compile(v8::String::New("eval('x x')"))->Run();
3120 CHECK_EQ(4, exception_hit_count);
3121 CHECK_EQ(4, uncaught_exception_hit_count);
3122 CHECK_EQ(4, message_callback_count);
3123 CHECK_EQ(1, last_js_stack_height);
3124}
3125
3126
3127TEST(StepWithException) {
3128 v8::HandleScope scope;
3129 DebugLocalContext env;
3130
3131 // Create a function for checking the function when hitting a break point.
3132 frame_function_name = CompileFunction(&env,
3133 frame_function_name_source,
3134 "frame_function_name");
3135
3136 // Register a debug event listener which steps and counts.
3137 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3138
3139 // Create functions for testing stepping.
3140 const char* src = "function a() { n(); }; "
3141 "function b() { c(); }; "
3142 "function c() { n(); }; "
3143 "function d() { x = 1; try { e(); } catch(x) { x = 2; } }; "
3144 "function e() { n(); }; "
3145 "function f() { x = 1; try { g(); } catch(x) { x = 2; } }; "
3146 "function g() { h(); }; "
3147 "function h() { x = 1; throw 1; }; ";
3148
3149 // Step through invocation of a.
3150 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3151 SetBreakPoint(a, 0);
3152 step_action = StepIn;
3153 break_point_hit_count = 0;
3154 expected_step_sequence = "aa";
3155 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003156 CHECK_EQ(StrLength(expected_step_sequence),
3157 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003158
3159 // Step through invocation of b + c.
3160 v8::Local<v8::Function> b = CompileFunction(&env, src, "b");
3161 SetBreakPoint(b, 0);
3162 step_action = StepIn;
3163 break_point_hit_count = 0;
3164 expected_step_sequence = "bcc";
3165 b->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003166 CHECK_EQ(StrLength(expected_step_sequence),
3167 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003168
3169 // Step through invocation of d + e.
3170 v8::Local<v8::Function> d = CompileFunction(&env, src, "d");
3171 SetBreakPoint(d, 0);
3172 ChangeBreakOnException(false, true);
3173 step_action = StepIn;
3174 break_point_hit_count = 0;
3175 expected_step_sequence = "dded";
3176 d->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003177 CHECK_EQ(StrLength(expected_step_sequence),
3178 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003179
3180 // Step through invocation of d + e now with break on caught exceptions.
3181 ChangeBreakOnException(true, true);
3182 step_action = StepIn;
3183 break_point_hit_count = 0;
3184 expected_step_sequence = "ddeed";
3185 d->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003186 CHECK_EQ(StrLength(expected_step_sequence),
3187 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003188
3189 // Step through invocation of f + g + h.
3190 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
3191 SetBreakPoint(f, 0);
3192 ChangeBreakOnException(false, true);
3193 step_action = StepIn;
3194 break_point_hit_count = 0;
3195 expected_step_sequence = "ffghf";
3196 f->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003197 CHECK_EQ(StrLength(expected_step_sequence),
3198 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003199
3200 // Step through invocation of f + g + h now with break on caught exceptions.
3201 ChangeBreakOnException(true, true);
3202 step_action = StepIn;
3203 break_point_hit_count = 0;
3204 expected_step_sequence = "ffghhf";
3205 f->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003206 CHECK_EQ(StrLength(expected_step_sequence),
3207 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003208
3209 // Get rid of the debug event listener.
3210 v8::Debug::SetDebugEventListener(NULL);
3211 CheckDebuggerUnloaded();
3212}
3213
3214
3215TEST(DebugBreak) {
3216 v8::HandleScope scope;
3217 DebugLocalContext env;
3218
3219 // This test should be run with option --verify-heap. As --verify-heap is
3220 // only available in debug mode only check for it in that case.
3221#ifdef DEBUG
3222 CHECK(v8::internal::FLAG_verify_heap);
3223#endif
3224
3225 // Register a debug event listener which sets the break flag and counts.
3226 v8::Debug::SetDebugEventListener(DebugEventBreak);
3227
3228 // Create a function for testing stepping.
3229 const char* src = "function f0() {}"
3230 "function f1(x1) {}"
3231 "function f2(x1,x2) {}"
3232 "function f3(x1,x2,x3) {}";
3233 v8::Local<v8::Function> f0 = CompileFunction(&env, src, "f0");
3234 v8::Local<v8::Function> f1 = CompileFunction(&env, src, "f1");
3235 v8::Local<v8::Function> f2 = CompileFunction(&env, src, "f2");
3236 v8::Local<v8::Function> f3 = CompileFunction(&env, src, "f3");
3237
3238 // Call the function to make sure it is compiled.
3239 v8::Handle<v8::Value> argv[] = { v8::Number::New(1),
3240 v8::Number::New(1),
3241 v8::Number::New(1),
3242 v8::Number::New(1) };
3243
3244 // Call all functions to make sure that they are compiled.
3245 f0->Call(env->Global(), 0, NULL);
3246 f1->Call(env->Global(), 0, NULL);
3247 f2->Call(env->Global(), 0, NULL);
3248 f3->Call(env->Global(), 0, NULL);
3249
3250 // Set the debug break flag.
3251 v8::Debug::DebugBreak();
3252
3253 // Call all functions with different argument count.
3254 break_point_hit_count = 0;
3255 for (unsigned int i = 0; i < ARRAY_SIZE(argv); i++) {
3256 f0->Call(env->Global(), i, argv);
3257 f1->Call(env->Global(), i, argv);
3258 f2->Call(env->Global(), i, argv);
3259 f3->Call(env->Global(), i, argv);
3260 }
3261
3262 // One break for each function called.
3263 CHECK_EQ(4 * ARRAY_SIZE(argv), break_point_hit_count);
3264
3265 // Get rid of the debug event listener.
3266 v8::Debug::SetDebugEventListener(NULL);
3267 CheckDebuggerUnloaded();
3268}
3269
3270
3271// Test to ensure that JavaScript code keeps running while the debug break
3272// through the stack limit flag is set but breaks are disabled.
3273TEST(DisableBreak) {
3274 v8::HandleScope scope;
3275 DebugLocalContext env;
3276
3277 // Register a debug event listener which sets the break flag and counts.
3278 v8::Debug::SetDebugEventListener(DebugEventCounter);
3279
3280 // Create a function for testing stepping.
3281 const char* src = "function f() {g()};function g(){i=0; while(i<10){i++}}";
3282 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
3283
3284 // Set the debug break flag.
3285 v8::Debug::DebugBreak();
3286
3287 // Call all functions with different argument count.
3288 break_point_hit_count = 0;
3289 f->Call(env->Global(), 0, NULL);
3290 CHECK_EQ(1, break_point_hit_count);
3291
3292 {
3293 v8::Debug::DebugBreak();
3294 v8::internal::DisableBreak disable_break(true);
3295 f->Call(env->Global(), 0, NULL);
3296 CHECK_EQ(1, break_point_hit_count);
3297 }
3298
3299 f->Call(env->Global(), 0, NULL);
3300 CHECK_EQ(2, break_point_hit_count);
3301
3302 // Get rid of the debug event listener.
3303 v8::Debug::SetDebugEventListener(NULL);
3304 CheckDebuggerUnloaded();
3305}
3306
Leon Clarkee46be812010-01-19 14:06:41 +00003307static const char* kSimpleExtensionSource =
3308 "(function Foo() {"
3309 " return 4;"
3310 "})() ";
3311
3312// http://crbug.com/28933
3313// Test that debug break is disabled when bootstrapper is active.
3314TEST(NoBreakWhenBootstrapping) {
3315 v8::HandleScope scope;
3316
3317 // Register a debug event listener which sets the break flag and counts.
3318 v8::Debug::SetDebugEventListener(DebugEventCounter);
3319
3320 // Set the debug break flag.
3321 v8::Debug::DebugBreak();
3322 break_point_hit_count = 0;
3323 {
3324 // Create a context with an extension to make sure that some JavaScript
3325 // code is executed during bootstrapping.
3326 v8::RegisterExtension(new v8::Extension("simpletest",
3327 kSimpleExtensionSource));
3328 const char* extension_names[] = { "simpletest" };
3329 v8::ExtensionConfiguration extensions(1, extension_names);
3330 v8::Persistent<v8::Context> context = v8::Context::New(&extensions);
3331 context.Dispose();
3332 }
3333 // Check that no DebugBreak events occured during the context creation.
3334 CHECK_EQ(0, break_point_hit_count);
3335
3336 // Get rid of the debug event listener.
3337 v8::Debug::SetDebugEventListener(NULL);
3338 CheckDebuggerUnloaded();
3339}
Steve Blocka7e24c12009-10-30 11:49:00 +00003340
3341static v8::Handle<v8::Array> NamedEnum(const v8::AccessorInfo&) {
3342 v8::Handle<v8::Array> result = v8::Array::New(3);
3343 result->Set(v8::Integer::New(0), v8::String::New("a"));
3344 result->Set(v8::Integer::New(1), v8::String::New("b"));
3345 result->Set(v8::Integer::New(2), v8::String::New("c"));
3346 return result;
3347}
3348
3349
3350static v8::Handle<v8::Array> IndexedEnum(const v8::AccessorInfo&) {
3351 v8::Handle<v8::Array> result = v8::Array::New(2);
3352 result->Set(v8::Integer::New(0), v8::Number::New(1));
3353 result->Set(v8::Integer::New(1), v8::Number::New(10));
3354 return result;
3355}
3356
3357
3358static v8::Handle<v8::Value> NamedGetter(v8::Local<v8::String> name,
3359 const v8::AccessorInfo& info) {
3360 v8::String::AsciiValue n(name);
3361 if (strcmp(*n, "a") == 0) {
3362 return v8::String::New("AA");
3363 } else if (strcmp(*n, "b") == 0) {
3364 return v8::String::New("BB");
3365 } else if (strcmp(*n, "c") == 0) {
3366 return v8::String::New("CC");
3367 } else {
3368 return v8::Undefined();
3369 }
3370
3371 return name;
3372}
3373
3374
3375static v8::Handle<v8::Value> IndexedGetter(uint32_t index,
3376 const v8::AccessorInfo& info) {
3377 return v8::Number::New(index + 1);
3378}
3379
3380
3381TEST(InterceptorPropertyMirror) {
3382 // Create a V8 environment with debug access.
3383 v8::HandleScope scope;
3384 DebugLocalContext env;
3385 env.ExposeDebug();
3386
3387 // Create object with named interceptor.
3388 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
3389 named->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum);
3390 env->Global()->Set(v8::String::New("intercepted_named"),
3391 named->NewInstance());
3392
3393 // Create object with indexed interceptor.
3394 v8::Handle<v8::ObjectTemplate> indexed = v8::ObjectTemplate::New();
3395 indexed->SetIndexedPropertyHandler(IndexedGetter,
3396 NULL,
3397 NULL,
3398 NULL,
3399 IndexedEnum);
3400 env->Global()->Set(v8::String::New("intercepted_indexed"),
3401 indexed->NewInstance());
3402
3403 // Create object with both named and indexed interceptor.
3404 v8::Handle<v8::ObjectTemplate> both = v8::ObjectTemplate::New();
3405 both->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum);
3406 both->SetIndexedPropertyHandler(IndexedGetter, NULL, NULL, NULL, IndexedEnum);
3407 env->Global()->Set(v8::String::New("intercepted_both"), both->NewInstance());
3408
3409 // Get mirrors for the three objects with interceptor.
3410 CompileRun(
3411 "named_mirror = debug.MakeMirror(intercepted_named);"
3412 "indexed_mirror = debug.MakeMirror(intercepted_indexed);"
3413 "both_mirror = debug.MakeMirror(intercepted_both)");
3414 CHECK(CompileRun(
3415 "named_mirror instanceof debug.ObjectMirror")->BooleanValue());
3416 CHECK(CompileRun(
3417 "indexed_mirror instanceof debug.ObjectMirror")->BooleanValue());
3418 CHECK(CompileRun(
3419 "both_mirror instanceof debug.ObjectMirror")->BooleanValue());
3420
3421 // Get the property names from the interceptors
3422 CompileRun(
3423 "named_names = named_mirror.propertyNames();"
3424 "indexed_names = indexed_mirror.propertyNames();"
3425 "both_names = both_mirror.propertyNames()");
3426 CHECK_EQ(3, CompileRun("named_names.length")->Int32Value());
3427 CHECK_EQ(2, CompileRun("indexed_names.length")->Int32Value());
3428 CHECK_EQ(5, CompileRun("both_names.length")->Int32Value());
3429
3430 // Check the expected number of properties.
3431 const char* source;
3432 source = "named_mirror.properties().length";
3433 CHECK_EQ(3, CompileRun(source)->Int32Value());
3434
3435 source = "indexed_mirror.properties().length";
3436 CHECK_EQ(2, CompileRun(source)->Int32Value());
3437
3438 source = "both_mirror.properties().length";
3439 CHECK_EQ(5, CompileRun(source)->Int32Value());
3440
3441 // 1 is PropertyKind.Named;
3442 source = "both_mirror.properties(1).length";
3443 CHECK_EQ(3, CompileRun(source)->Int32Value());
3444
3445 // 2 is PropertyKind.Indexed;
3446 source = "both_mirror.properties(2).length";
3447 CHECK_EQ(2, CompileRun(source)->Int32Value());
3448
3449 // 3 is PropertyKind.Named | PropertyKind.Indexed;
3450 source = "both_mirror.properties(3).length";
3451 CHECK_EQ(5, CompileRun(source)->Int32Value());
3452
3453 // Get the interceptor properties for the object with only named interceptor.
3454 CompileRun("named_values = named_mirror.properties()");
3455
3456 // Check that the properties are interceptor properties.
3457 for (int i = 0; i < 3; i++) {
3458 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
3459 OS::SNPrintF(buffer,
3460 "named_values[%d] instanceof debug.PropertyMirror", i);
3461 CHECK(CompileRun(buffer.start())->BooleanValue());
3462
3463 // 4 is PropertyType.Interceptor
3464 OS::SNPrintF(buffer, "named_values[%d].propertyType()", i);
3465 CHECK_EQ(4, CompileRun(buffer.start())->Int32Value());
3466
3467 OS::SNPrintF(buffer, "named_values[%d].isNative()", i);
3468 CHECK(CompileRun(buffer.start())->BooleanValue());
3469 }
3470
3471 // Get the interceptor properties for the object with only indexed
3472 // interceptor.
3473 CompileRun("indexed_values = indexed_mirror.properties()");
3474
3475 // Check that the properties are interceptor properties.
3476 for (int i = 0; i < 2; i++) {
3477 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
3478 OS::SNPrintF(buffer,
3479 "indexed_values[%d] instanceof debug.PropertyMirror", i);
3480 CHECK(CompileRun(buffer.start())->BooleanValue());
3481 }
3482
3483 // Get the interceptor properties for the object with both types of
3484 // interceptors.
3485 CompileRun("both_values = both_mirror.properties()");
3486
3487 // Check that the properties are interceptor properties.
3488 for (int i = 0; i < 5; i++) {
3489 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
3490 OS::SNPrintF(buffer, "both_values[%d] instanceof debug.PropertyMirror", i);
3491 CHECK(CompileRun(buffer.start())->BooleanValue());
3492 }
3493
3494 // Check the property names.
3495 source = "both_values[0].name() == 'a'";
3496 CHECK(CompileRun(source)->BooleanValue());
3497
3498 source = "both_values[1].name() == 'b'";
3499 CHECK(CompileRun(source)->BooleanValue());
3500
3501 source = "both_values[2].name() == 'c'";
3502 CHECK(CompileRun(source)->BooleanValue());
3503
3504 source = "both_values[3].name() == 1";
3505 CHECK(CompileRun(source)->BooleanValue());
3506
3507 source = "both_values[4].name() == 10";
3508 CHECK(CompileRun(source)->BooleanValue());
3509}
3510
3511
3512TEST(HiddenPrototypePropertyMirror) {
3513 // Create a V8 environment with debug access.
3514 v8::HandleScope scope;
3515 DebugLocalContext env;
3516 env.ExposeDebug();
3517
3518 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New();
3519 t0->InstanceTemplate()->Set(v8::String::New("x"), v8::Number::New(0));
3520 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
3521 t1->SetHiddenPrototype(true);
3522 t1->InstanceTemplate()->Set(v8::String::New("y"), v8::Number::New(1));
3523 v8::Handle<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New();
3524 t2->SetHiddenPrototype(true);
3525 t2->InstanceTemplate()->Set(v8::String::New("z"), v8::Number::New(2));
3526 v8::Handle<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New();
3527 t3->InstanceTemplate()->Set(v8::String::New("u"), v8::Number::New(3));
3528
3529 // Create object and set them on the global object.
3530 v8::Handle<v8::Object> o0 = t0->GetFunction()->NewInstance();
3531 env->Global()->Set(v8::String::New("o0"), o0);
3532 v8::Handle<v8::Object> o1 = t1->GetFunction()->NewInstance();
3533 env->Global()->Set(v8::String::New("o1"), o1);
3534 v8::Handle<v8::Object> o2 = t2->GetFunction()->NewInstance();
3535 env->Global()->Set(v8::String::New("o2"), o2);
3536 v8::Handle<v8::Object> o3 = t3->GetFunction()->NewInstance();
3537 env->Global()->Set(v8::String::New("o3"), o3);
3538
3539 // Get mirrors for the four objects.
3540 CompileRun(
3541 "o0_mirror = debug.MakeMirror(o0);"
3542 "o1_mirror = debug.MakeMirror(o1);"
3543 "o2_mirror = debug.MakeMirror(o2);"
3544 "o3_mirror = debug.MakeMirror(o3)");
3545 CHECK(CompileRun("o0_mirror instanceof debug.ObjectMirror")->BooleanValue());
3546 CHECK(CompileRun("o1_mirror instanceof debug.ObjectMirror")->BooleanValue());
3547 CHECK(CompileRun("o2_mirror instanceof debug.ObjectMirror")->BooleanValue());
3548 CHECK(CompileRun("o3_mirror instanceof debug.ObjectMirror")->BooleanValue());
3549
3550 // Check that each object has one property.
3551 CHECK_EQ(1, CompileRun(
3552 "o0_mirror.propertyNames().length")->Int32Value());
3553 CHECK_EQ(1, CompileRun(
3554 "o1_mirror.propertyNames().length")->Int32Value());
3555 CHECK_EQ(1, CompileRun(
3556 "o2_mirror.propertyNames().length")->Int32Value());
3557 CHECK_EQ(1, CompileRun(
3558 "o3_mirror.propertyNames().length")->Int32Value());
3559
3560 // Set o1 as prototype for o0. o1 has the hidden prototype flag so all
3561 // properties on o1 should be seen on o0.
3562 o0->Set(v8::String::New("__proto__"), o1);
3563 CHECK_EQ(2, CompileRun(
3564 "o0_mirror.propertyNames().length")->Int32Value());
3565 CHECK_EQ(0, CompileRun(
3566 "o0_mirror.property('x').value().value()")->Int32Value());
3567 CHECK_EQ(1, CompileRun(
3568 "o0_mirror.property('y').value().value()")->Int32Value());
3569
3570 // Set o2 as prototype for o0 (it will end up after o1 as o1 has the hidden
3571 // prototype flag. o2 also has the hidden prototype flag so all properties
3572 // on o2 should be seen on o0 as well as properties on o1.
3573 o0->Set(v8::String::New("__proto__"), o2);
3574 CHECK_EQ(3, CompileRun(
3575 "o0_mirror.propertyNames().length")->Int32Value());
3576 CHECK_EQ(0, CompileRun(
3577 "o0_mirror.property('x').value().value()")->Int32Value());
3578 CHECK_EQ(1, CompileRun(
3579 "o0_mirror.property('y').value().value()")->Int32Value());
3580 CHECK_EQ(2, CompileRun(
3581 "o0_mirror.property('z').value().value()")->Int32Value());
3582
3583 // Set o3 as prototype for o0 (it will end up after o1 and o2 as both o1 and
3584 // o2 has the hidden prototype flag. o3 does not have the hidden prototype
3585 // flag so properties on o3 should not be seen on o0 whereas the properties
3586 // from o1 and o2 should still be seen on o0.
3587 // Final prototype chain: o0 -> o1 -> o2 -> o3
3588 // Hidden prototypes: ^^ ^^
3589 o0->Set(v8::String::New("__proto__"), o3);
3590 CHECK_EQ(3, CompileRun(
3591 "o0_mirror.propertyNames().length")->Int32Value());
3592 CHECK_EQ(1, CompileRun(
3593 "o3_mirror.propertyNames().length")->Int32Value());
3594 CHECK_EQ(0, CompileRun(
3595 "o0_mirror.property('x').value().value()")->Int32Value());
3596 CHECK_EQ(1, CompileRun(
3597 "o0_mirror.property('y').value().value()")->Int32Value());
3598 CHECK_EQ(2, CompileRun(
3599 "o0_mirror.property('z').value().value()")->Int32Value());
3600 CHECK(CompileRun("o0_mirror.property('u').isUndefined()")->BooleanValue());
3601
3602 // The prototype (__proto__) for o0 should be o3 as o1 and o2 are hidden.
3603 CHECK(CompileRun("o0_mirror.protoObject() == o3_mirror")->BooleanValue());
3604}
3605
3606
3607static v8::Handle<v8::Value> ProtperyXNativeGetter(
3608 v8::Local<v8::String> property, const v8::AccessorInfo& info) {
3609 return v8::Integer::New(10);
3610}
3611
3612
3613TEST(NativeGetterPropertyMirror) {
3614 // Create a V8 environment with debug access.
3615 v8::HandleScope scope;
3616 DebugLocalContext env;
3617 env.ExposeDebug();
3618
3619 v8::Handle<v8::String> name = v8::String::New("x");
3620 // Create object with named accessor.
3621 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
3622 named->SetAccessor(name, &ProtperyXNativeGetter, NULL,
3623 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None);
3624
3625 // Create object with named property getter.
3626 env->Global()->Set(v8::String::New("instance"), named->NewInstance());
3627 CHECK_EQ(10, CompileRun("instance.x")->Int32Value());
3628
3629 // Get mirror for the object with property getter.
3630 CompileRun("instance_mirror = debug.MakeMirror(instance);");
3631 CHECK(CompileRun(
3632 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue());
3633
3634 CompileRun("named_names = instance_mirror.propertyNames();");
3635 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
3636 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue());
3637 CHECK(CompileRun(
3638 "instance_mirror.property('x').value().isNumber()")->BooleanValue());
3639 CHECK(CompileRun(
3640 "instance_mirror.property('x').value().value() == 10")->BooleanValue());
3641}
3642
3643
3644static v8::Handle<v8::Value> ProtperyXNativeGetterThrowingError(
3645 v8::Local<v8::String> property, const v8::AccessorInfo& info) {
3646 return CompileRun("throw new Error('Error message');");
3647}
3648
3649
3650TEST(NativeGetterThrowingErrorPropertyMirror) {
3651 // Create a V8 environment with debug access.
3652 v8::HandleScope scope;
3653 DebugLocalContext env;
3654 env.ExposeDebug();
3655
3656 v8::Handle<v8::String> name = v8::String::New("x");
3657 // Create object with named accessor.
3658 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
3659 named->SetAccessor(name, &ProtperyXNativeGetterThrowingError, NULL,
3660 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None);
3661
3662 // Create object with named property getter.
3663 env->Global()->Set(v8::String::New("instance"), named->NewInstance());
3664
3665 // Get mirror for the object with property getter.
3666 CompileRun("instance_mirror = debug.MakeMirror(instance);");
3667 CHECK(CompileRun(
3668 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue());
3669 CompileRun("named_names = instance_mirror.propertyNames();");
3670 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
3671 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue());
3672 CHECK(CompileRun(
3673 "instance_mirror.property('x').value().isError()")->BooleanValue());
3674
3675 // Check that the message is that passed to the Error constructor.
3676 CHECK(CompileRun(
3677 "instance_mirror.property('x').value().message() == 'Error message'")->
3678 BooleanValue());
3679}
3680
3681
Steve Blockd0582a62009-12-15 09:54:21 +00003682// Test that hidden properties object is not returned as an unnamed property
3683// among regular properties.
3684// See http://crbug.com/26491
3685TEST(NoHiddenProperties) {
3686 // Create a V8 environment with debug access.
3687 v8::HandleScope scope;
3688 DebugLocalContext env;
3689 env.ExposeDebug();
3690
3691 // Create an object in the global scope.
3692 const char* source = "var obj = {a: 1};";
3693 v8::Script::Compile(v8::String::New(source))->Run();
3694 v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(
3695 env->Global()->Get(v8::String::New("obj")));
3696 // Set a hidden property on the object.
3697 obj->SetHiddenValue(v8::String::New("v8::test-debug::a"),
3698 v8::Int32::New(11));
3699
3700 // Get mirror for the object with property getter.
3701 CompileRun("var obj_mirror = debug.MakeMirror(obj);");
3702 CHECK(CompileRun(
3703 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue());
3704 CompileRun("var named_names = obj_mirror.propertyNames();");
3705 // There should be exactly one property. But there is also an unnamed
3706 // property whose value is hidden properties dictionary. The latter
3707 // property should not be in the list of reguar properties.
3708 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
3709 CHECK(CompileRun("named_names[0] == 'a'")->BooleanValue());
3710 CHECK(CompileRun(
3711 "obj_mirror.property('a').value().value() == 1")->BooleanValue());
3712
3713 // Object created by t0 will become hidden prototype of object 'obj'.
3714 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New();
3715 t0->InstanceTemplate()->Set(v8::String::New("b"), v8::Number::New(2));
3716 t0->SetHiddenPrototype(true);
3717 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
3718 t1->InstanceTemplate()->Set(v8::String::New("c"), v8::Number::New(3));
3719
3720 // Create proto objects, add hidden properties to them and set them on
3721 // the global object.
3722 v8::Handle<v8::Object> protoObj = t0->GetFunction()->NewInstance();
3723 protoObj->SetHiddenValue(v8::String::New("v8::test-debug::b"),
3724 v8::Int32::New(12));
3725 env->Global()->Set(v8::String::New("protoObj"), protoObj);
3726 v8::Handle<v8::Object> grandProtoObj = t1->GetFunction()->NewInstance();
3727 grandProtoObj->SetHiddenValue(v8::String::New("v8::test-debug::c"),
3728 v8::Int32::New(13));
3729 env->Global()->Set(v8::String::New("grandProtoObj"), grandProtoObj);
3730
3731 // Setting prototypes: obj->protoObj->grandProtoObj
3732 protoObj->Set(v8::String::New("__proto__"), grandProtoObj);
3733 obj->Set(v8::String::New("__proto__"), protoObj);
3734
3735 // Get mirror for the object with property getter.
3736 CompileRun("var obj_mirror = debug.MakeMirror(obj);");
3737 CHECK(CompileRun(
3738 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue());
3739 CompileRun("var named_names = obj_mirror.propertyNames();");
3740 // There should be exactly two properties - one from the object itself and
3741 // another from its hidden prototype.
3742 CHECK_EQ(2, CompileRun("named_names.length")->Int32Value());
3743 CHECK(CompileRun("named_names.sort(); named_names[0] == 'a' &&"
3744 "named_names[1] == 'b'")->BooleanValue());
3745 CHECK(CompileRun(
3746 "obj_mirror.property('a').value().value() == 1")->BooleanValue());
3747 CHECK(CompileRun(
3748 "obj_mirror.property('b').value().value() == 2")->BooleanValue());
3749}
3750
Steve Blocka7e24c12009-10-30 11:49:00 +00003751
3752// Multithreaded tests of JSON debugger protocol
3753
3754// Support classes
3755
Steve Blocka7e24c12009-10-30 11:49:00 +00003756// Provides synchronization between k threads, where k is an input to the
3757// constructor. The Wait() call blocks a thread until it is called for the
3758// k'th time, then all calls return. Each ThreadBarrier object can only
3759// be used once.
3760class ThreadBarrier {
3761 public:
3762 explicit ThreadBarrier(int num_threads);
3763 ~ThreadBarrier();
3764 void Wait();
3765 private:
3766 int num_threads_;
3767 int num_blocked_;
3768 v8::internal::Mutex* lock_;
3769 v8::internal::Semaphore* sem_;
3770 bool invalid_;
3771};
3772
3773ThreadBarrier::ThreadBarrier(int num_threads)
3774 : num_threads_(num_threads), num_blocked_(0) {
3775 lock_ = OS::CreateMutex();
3776 sem_ = OS::CreateSemaphore(0);
3777 invalid_ = false; // A barrier may only be used once. Then it is invalid.
3778}
3779
3780// Do not call, due to race condition with Wait().
3781// Could be resolved with Pthread condition variables.
3782ThreadBarrier::~ThreadBarrier() {
3783 lock_->Lock();
3784 delete lock_;
3785 delete sem_;
3786}
3787
3788void ThreadBarrier::Wait() {
3789 lock_->Lock();
3790 CHECK(!invalid_);
3791 if (num_blocked_ == num_threads_ - 1) {
3792 // Signal and unblock all waiting threads.
3793 for (int i = 0; i < num_threads_ - 1; ++i) {
3794 sem_->Signal();
3795 }
3796 invalid_ = true;
3797 printf("BARRIER\n\n");
3798 fflush(stdout);
3799 lock_->Unlock();
3800 } else { // Wait for the semaphore.
3801 ++num_blocked_;
3802 lock_->Unlock(); // Potential race condition with destructor because
3803 sem_->Wait(); // these two lines are not atomic.
3804 }
3805}
3806
3807// A set containing enough barriers and semaphores for any of the tests.
3808class Barriers {
3809 public:
3810 Barriers();
3811 void Initialize();
3812 ThreadBarrier barrier_1;
3813 ThreadBarrier barrier_2;
3814 ThreadBarrier barrier_3;
3815 ThreadBarrier barrier_4;
3816 ThreadBarrier barrier_5;
3817 v8::internal::Semaphore* semaphore_1;
3818 v8::internal::Semaphore* semaphore_2;
3819};
3820
3821Barriers::Barriers() : barrier_1(2), barrier_2(2),
3822 barrier_3(2), barrier_4(2), barrier_5(2) {}
3823
3824void Barriers::Initialize() {
3825 semaphore_1 = OS::CreateSemaphore(0);
3826 semaphore_2 = OS::CreateSemaphore(0);
3827}
3828
3829
3830// We match parts of the message to decide if it is a break message.
3831bool IsBreakEventMessage(char *message) {
3832 const char* type_event = "\"type\":\"event\"";
3833 const char* event_break = "\"event\":\"break\"";
3834 // Does the message contain both type:event and event:break?
3835 return strstr(message, type_event) != NULL &&
3836 strstr(message, event_break) != NULL;
3837}
3838
3839
Steve Block3ce2e202009-11-05 08:53:23 +00003840// We match parts of the message to decide if it is a exception message.
3841bool IsExceptionEventMessage(char *message) {
3842 const char* type_event = "\"type\":\"event\"";
3843 const char* event_exception = "\"event\":\"exception\"";
3844 // Does the message contain both type:event and event:exception?
3845 return strstr(message, type_event) != NULL &&
3846 strstr(message, event_exception) != NULL;
3847}
3848
3849
3850// We match the message wether it is an evaluate response message.
3851bool IsEvaluateResponseMessage(char* message) {
3852 const char* type_response = "\"type\":\"response\"";
3853 const char* command_evaluate = "\"command\":\"evaluate\"";
3854 // Does the message contain both type:response and command:evaluate?
3855 return strstr(message, type_response) != NULL &&
3856 strstr(message, command_evaluate) != NULL;
3857}
3858
3859
3860// We match parts of the message to get evaluate result int value.
3861int GetEvaluateIntResult(char *message) {
3862 const char* value = "\"value\":";
3863 char* pos = strstr(message, value);
3864 if (pos == NULL) {
3865 return -1;
3866 }
3867 int res = -1;
3868 res = atoi(pos + strlen(value));
3869 return res;
3870}
3871
3872
3873// We match parts of the message to get hit breakpoint id.
3874int GetBreakpointIdFromBreakEventMessage(char *message) {
3875 const char* breakpoints = "\"breakpoints\":[";
3876 char* pos = strstr(message, breakpoints);
3877 if (pos == NULL) {
3878 return -1;
3879 }
3880 int res = -1;
3881 res = atoi(pos + strlen(breakpoints));
3882 return res;
3883}
3884
3885
Leon Clarked91b9f72010-01-27 17:25:45 +00003886// We match parts of the message to get total frames number.
3887int GetTotalFramesInt(char *message) {
3888 const char* prefix = "\"totalFrames\":";
3889 char* pos = strstr(message, prefix);
3890 if (pos == NULL) {
3891 return -1;
3892 }
3893 pos += strlen(prefix);
3894 char* pos_end = pos;
3895 int res = static_cast<int>(strtol(pos, &pos_end, 10));
3896 if (pos_end == pos) {
3897 return -1;
3898 }
3899 return res;
3900}
3901
3902
Steve Blocka7e24c12009-10-30 11:49:00 +00003903/* Test MessageQueues */
3904/* Tests the message queues that hold debugger commands and
3905 * response messages to the debugger. Fills queues and makes
3906 * them grow.
3907 */
3908Barriers message_queue_barriers;
3909
3910// This is the debugger thread, that executes no v8 calls except
3911// placing JSON debugger commands in the queue.
3912class MessageQueueDebuggerThread : public v8::internal::Thread {
3913 public:
3914 void Run();
3915};
3916
3917static void MessageHandler(const uint16_t* message, int length,
3918 v8::Debug::ClientData* client_data) {
3919 static char print_buffer[1000];
3920 Utf16ToAscii(message, length, print_buffer);
3921 if (IsBreakEventMessage(print_buffer)) {
3922 // Lets test script wait until break occurs to send commands.
3923 // Signals when a break is reported.
3924 message_queue_barriers.semaphore_2->Signal();
3925 }
3926
3927 // Allow message handler to block on a semaphore, to test queueing of
3928 // messages while blocked.
3929 message_queue_barriers.semaphore_1->Wait();
Steve Blocka7e24c12009-10-30 11:49:00 +00003930}
3931
3932void MessageQueueDebuggerThread::Run() {
3933 const int kBufferSize = 1000;
3934 uint16_t buffer_1[kBufferSize];
3935 uint16_t buffer_2[kBufferSize];
3936 const char* command_1 =
3937 "{\"seq\":117,"
3938 "\"type\":\"request\","
3939 "\"command\":\"evaluate\","
3940 "\"arguments\":{\"expression\":\"1+2\"}}";
3941 const char* command_2 =
3942 "{\"seq\":118,"
3943 "\"type\":\"request\","
3944 "\"command\":\"evaluate\","
3945 "\"arguments\":{\"expression\":\"1+a\"}}";
3946 const char* command_3 =
3947 "{\"seq\":119,"
3948 "\"type\":\"request\","
3949 "\"command\":\"evaluate\","
3950 "\"arguments\":{\"expression\":\"c.d * b\"}}";
3951 const char* command_continue =
3952 "{\"seq\":106,"
3953 "\"type\":\"request\","
3954 "\"command\":\"continue\"}";
3955 const char* command_single_step =
3956 "{\"seq\":107,"
3957 "\"type\":\"request\","
3958 "\"command\":\"continue\","
3959 "\"arguments\":{\"stepaction\":\"next\"}}";
3960
3961 /* Interleaved sequence of actions by the two threads:*/
3962 // Main thread compiles and runs source_1
3963 message_queue_barriers.semaphore_1->Signal();
3964 message_queue_barriers.barrier_1.Wait();
3965 // Post 6 commands, filling the command queue and making it expand.
3966 // These calls return immediately, but the commands stay on the queue
3967 // until the execution of source_2.
3968 // Note: AsciiToUtf16 executes before SendCommand, so command is copied
3969 // to buffer before buffer is sent to SendCommand.
3970 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1));
3971 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2));
3972 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3973 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3974 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3975 message_queue_barriers.barrier_2.Wait();
3976 // Main thread compiles and runs source_2.
3977 // Queued commands are executed at the start of compilation of source_2(
3978 // beforeCompile event).
3979 // Free the message handler to process all the messages from the queue. 7
3980 // messages are expected: 2 afterCompile events and 5 responses.
3981 // All the commands added so far will fail to execute as long as call stack
3982 // is empty on beforeCompile event.
3983 for (int i = 0; i < 6 ; ++i) {
3984 message_queue_barriers.semaphore_1->Signal();
3985 }
3986 message_queue_barriers.barrier_3.Wait();
3987 // Main thread compiles and runs source_3.
3988 // Don't stop in the afterCompile handler.
3989 message_queue_barriers.semaphore_1->Signal();
3990 // source_3 includes a debugger statement, which causes a break event.
3991 // Wait on break event from hitting "debugger" statement
3992 message_queue_barriers.semaphore_2->Wait();
3993 // These should execute after the "debugger" statement in source_2
3994 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1));
3995 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2));
3996 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
3997 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_single_step, buffer_2));
3998 // Run after 2 break events, 4 responses.
3999 for (int i = 0; i < 6 ; ++i) {
4000 message_queue_barriers.semaphore_1->Signal();
4001 }
4002 // Wait on break event after a single step executes.
4003 message_queue_barriers.semaphore_2->Wait();
4004 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_2, buffer_1));
4005 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_continue, buffer_2));
4006 // Run after 2 responses.
4007 for (int i = 0; i < 2 ; ++i) {
4008 message_queue_barriers.semaphore_1->Signal();
4009 }
4010 // Main thread continues running source_3 to end, waits for this thread.
4011}
4012
4013MessageQueueDebuggerThread message_queue_debugger_thread;
4014
4015// This thread runs the v8 engine.
4016TEST(MessageQueues) {
4017 // Create a V8 environment
4018 v8::HandleScope scope;
4019 DebugLocalContext env;
4020 message_queue_barriers.Initialize();
4021 v8::Debug::SetMessageHandler(MessageHandler);
4022 message_queue_debugger_thread.Start();
4023
4024 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
4025 const char* source_2 = "e = 17;";
4026 const char* source_3 = "a = 4; debugger; a = 5; a = 6; a = 7;";
4027
4028 // See MessageQueueDebuggerThread::Run for interleaved sequence of
4029 // API calls and events in the two threads.
4030 CompileRun(source_1);
4031 message_queue_barriers.barrier_1.Wait();
4032 message_queue_barriers.barrier_2.Wait();
4033 CompileRun(source_2);
4034 message_queue_barriers.barrier_3.Wait();
4035 CompileRun(source_3);
4036 message_queue_debugger_thread.Join();
4037 fflush(stdout);
4038}
4039
4040
4041class TestClientData : public v8::Debug::ClientData {
4042 public:
4043 TestClientData() {
4044 constructor_call_counter++;
4045 }
4046 virtual ~TestClientData() {
4047 destructor_call_counter++;
4048 }
4049
4050 static void ResetCounters() {
4051 constructor_call_counter = 0;
4052 destructor_call_counter = 0;
4053 }
4054
4055 static int constructor_call_counter;
4056 static int destructor_call_counter;
4057};
4058
4059int TestClientData::constructor_call_counter = 0;
4060int TestClientData::destructor_call_counter = 0;
4061
4062
4063// Tests that MessageQueue doesn't destroy client data when expands and
4064// does destroy when it dies.
4065TEST(MessageQueueExpandAndDestroy) {
4066 TestClientData::ResetCounters();
4067 { // Create a scope for the queue.
4068 CommandMessageQueue queue(1);
4069 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4070 new TestClientData()));
4071 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4072 new TestClientData()));
4073 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4074 new TestClientData()));
4075 CHECK_EQ(0, TestClientData::destructor_call_counter);
4076 queue.Get().Dispose();
4077 CHECK_EQ(1, TestClientData::destructor_call_counter);
4078 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4079 new TestClientData()));
4080 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4081 new TestClientData()));
4082 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4083 new TestClientData()));
4084 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4085 new TestClientData()));
4086 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4087 new TestClientData()));
4088 CHECK_EQ(1, TestClientData::destructor_call_counter);
4089 queue.Get().Dispose();
4090 CHECK_EQ(2, TestClientData::destructor_call_counter);
4091 }
4092 // All the client data should be destroyed when the queue is destroyed.
4093 CHECK_EQ(TestClientData::destructor_call_counter,
4094 TestClientData::destructor_call_counter);
4095}
4096
4097
4098static int handled_client_data_instances_count = 0;
4099static void MessageHandlerCountingClientData(
4100 const v8::Debug::Message& message) {
4101 if (message.GetClientData() != NULL) {
4102 handled_client_data_instances_count++;
4103 }
4104}
4105
4106
4107// Tests that all client data passed to the debugger are sent to the handler.
4108TEST(SendClientDataToHandler) {
4109 // Create a V8 environment
4110 v8::HandleScope scope;
4111 DebugLocalContext env;
4112 TestClientData::ResetCounters();
4113 handled_client_data_instances_count = 0;
4114 v8::Debug::SetMessageHandler2(MessageHandlerCountingClientData);
4115 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
4116 const int kBufferSize = 1000;
4117 uint16_t buffer[kBufferSize];
4118 const char* command_1 =
4119 "{\"seq\":117,"
4120 "\"type\":\"request\","
4121 "\"command\":\"evaluate\","
4122 "\"arguments\":{\"expression\":\"1+2\"}}";
4123 const char* command_2 =
4124 "{\"seq\":118,"
4125 "\"type\":\"request\","
4126 "\"command\":\"evaluate\","
4127 "\"arguments\":{\"expression\":\"1+a\"}}";
4128 const char* command_continue =
4129 "{\"seq\":106,"
4130 "\"type\":\"request\","
4131 "\"command\":\"continue\"}";
4132
4133 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer),
4134 new TestClientData());
4135 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer), NULL);
4136 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer),
4137 new TestClientData());
4138 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer),
4139 new TestClientData());
4140 // All the messages will be processed on beforeCompile event.
4141 CompileRun(source_1);
4142 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer));
4143 CHECK_EQ(3, TestClientData::constructor_call_counter);
4144 CHECK_EQ(TestClientData::constructor_call_counter,
4145 handled_client_data_instances_count);
4146 CHECK_EQ(TestClientData::constructor_call_counter,
4147 TestClientData::destructor_call_counter);
4148}
4149
4150
4151/* Test ThreadedDebugging */
4152/* This test interrupts a running infinite loop that is
4153 * occupying the v8 thread by a break command from the
4154 * debugger thread. It then changes the value of a
4155 * global object, to make the loop terminate.
4156 */
4157
4158Barriers threaded_debugging_barriers;
4159
4160class V8Thread : public v8::internal::Thread {
4161 public:
4162 void Run();
4163};
4164
4165class DebuggerThread : public v8::internal::Thread {
4166 public:
4167 void Run();
4168};
4169
4170
4171static v8::Handle<v8::Value> ThreadedAtBarrier1(const v8::Arguments& args) {
4172 threaded_debugging_barriers.barrier_1.Wait();
4173 return v8::Undefined();
4174}
4175
4176
4177static void ThreadedMessageHandler(const v8::Debug::Message& message) {
4178 static char print_buffer[1000];
4179 v8::String::Value json(message.GetJSON());
4180 Utf16ToAscii(*json, json.length(), print_buffer);
4181 if (IsBreakEventMessage(print_buffer)) {
4182 threaded_debugging_barriers.barrier_2.Wait();
4183 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004184}
4185
4186
4187void V8Thread::Run() {
4188 const char* source =
4189 "flag = true;\n"
4190 "function bar( new_value ) {\n"
4191 " flag = new_value;\n"
4192 " return \"Return from bar(\" + new_value + \")\";\n"
4193 "}\n"
4194 "\n"
4195 "function foo() {\n"
4196 " var x = 1;\n"
4197 " while ( flag == true ) {\n"
4198 " if ( x == 1 ) {\n"
4199 " ThreadedAtBarrier1();\n"
4200 " }\n"
4201 " x = x + 1;\n"
4202 " }\n"
4203 "}\n"
4204 "\n"
4205 "foo();\n";
4206
4207 v8::HandleScope scope;
4208 DebugLocalContext env;
4209 v8::Debug::SetMessageHandler2(&ThreadedMessageHandler);
4210 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
4211 global_template->Set(v8::String::New("ThreadedAtBarrier1"),
4212 v8::FunctionTemplate::New(ThreadedAtBarrier1));
4213 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template);
4214 v8::Context::Scope context_scope(context);
4215
4216 CompileRun(source);
4217}
4218
4219void DebuggerThread::Run() {
4220 const int kBufSize = 1000;
4221 uint16_t buffer[kBufSize];
4222
4223 const char* command_1 = "{\"seq\":102,"
4224 "\"type\":\"request\","
4225 "\"command\":\"evaluate\","
4226 "\"arguments\":{\"expression\":\"bar(false)\"}}";
4227 const char* command_2 = "{\"seq\":103,"
4228 "\"type\":\"request\","
4229 "\"command\":\"continue\"}";
4230
4231 threaded_debugging_barriers.barrier_1.Wait();
4232 v8::Debug::DebugBreak();
4233 threaded_debugging_barriers.barrier_2.Wait();
4234 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
4235 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
4236}
4237
4238DebuggerThread debugger_thread;
4239V8Thread v8_thread;
4240
4241TEST(ThreadedDebugging) {
4242 // Create a V8 environment
4243 threaded_debugging_barriers.Initialize();
4244
4245 v8_thread.Start();
4246 debugger_thread.Start();
4247
4248 v8_thread.Join();
4249 debugger_thread.Join();
4250}
4251
4252/* Test RecursiveBreakpoints */
4253/* In this test, the debugger evaluates a function with a breakpoint, after
4254 * hitting a breakpoint in another function. We do this with both values
4255 * of the flag enabling recursive breakpoints, and verify that the second
4256 * breakpoint is hit when enabled, and missed when disabled.
4257 */
4258
4259class BreakpointsV8Thread : public v8::internal::Thread {
4260 public:
4261 void Run();
4262};
4263
4264class BreakpointsDebuggerThread : public v8::internal::Thread {
4265 public:
Leon Clarked91b9f72010-01-27 17:25:45 +00004266 explicit BreakpointsDebuggerThread(bool global_evaluate)
4267 : global_evaluate_(global_evaluate) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00004268 void Run();
Leon Clarked91b9f72010-01-27 17:25:45 +00004269
4270 private:
4271 bool global_evaluate_;
Steve Blocka7e24c12009-10-30 11:49:00 +00004272};
4273
4274
4275Barriers* breakpoints_barriers;
Steve Block3ce2e202009-11-05 08:53:23 +00004276int break_event_breakpoint_id;
4277int evaluate_int_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00004278
4279static void BreakpointsMessageHandler(const v8::Debug::Message& message) {
4280 static char print_buffer[1000];
4281 v8::String::Value json(message.GetJSON());
4282 Utf16ToAscii(*json, json.length(), print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00004283
Steve Blocka7e24c12009-10-30 11:49:00 +00004284 if (IsBreakEventMessage(print_buffer)) {
Steve Block3ce2e202009-11-05 08:53:23 +00004285 break_event_breakpoint_id =
4286 GetBreakpointIdFromBreakEventMessage(print_buffer);
4287 breakpoints_barriers->semaphore_1->Signal();
4288 } else if (IsEvaluateResponseMessage(print_buffer)) {
4289 evaluate_int_result = GetEvaluateIntResult(print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00004290 breakpoints_barriers->semaphore_1->Signal();
4291 }
4292}
4293
4294
4295void BreakpointsV8Thread::Run() {
4296 const char* source_1 = "var y_global = 3;\n"
4297 "function cat( new_value ) {\n"
4298 " var x = new_value;\n"
Steve Block3ce2e202009-11-05 08:53:23 +00004299 " y_global = y_global + 4;\n"
Steve Blocka7e24c12009-10-30 11:49:00 +00004300 " x = 3 * x + 1;\n"
Steve Block3ce2e202009-11-05 08:53:23 +00004301 " y_global = y_global + 5;\n"
Steve Blocka7e24c12009-10-30 11:49:00 +00004302 " return x;\n"
4303 "}\n"
4304 "\n"
4305 "function dog() {\n"
4306 " var x = 1;\n"
4307 " x = y_global;"
4308 " var z = 3;"
4309 " x += 100;\n"
4310 " return x;\n"
4311 "}\n"
4312 "\n";
4313 const char* source_2 = "cat(17);\n"
4314 "cat(19);\n";
4315
4316 v8::HandleScope scope;
4317 DebugLocalContext env;
4318 v8::Debug::SetMessageHandler2(&BreakpointsMessageHandler);
4319
4320 CompileRun(source_1);
4321 breakpoints_barriers->barrier_1.Wait();
4322 breakpoints_barriers->barrier_2.Wait();
4323 CompileRun(source_2);
4324}
4325
4326
4327void BreakpointsDebuggerThread::Run() {
4328 const int kBufSize = 1000;
4329 uint16_t buffer[kBufSize];
4330
4331 const char* command_1 = "{\"seq\":101,"
4332 "\"type\":\"request\","
4333 "\"command\":\"setbreakpoint\","
4334 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
4335 const char* command_2 = "{\"seq\":102,"
4336 "\"type\":\"request\","
4337 "\"command\":\"setbreakpoint\","
4338 "\"arguments\":{\"type\":\"function\",\"target\":\"dog\",\"line\":3}}";
Leon Clarked91b9f72010-01-27 17:25:45 +00004339 const char* command_3;
4340 if (this->global_evaluate_) {
4341 command_3 = "{\"seq\":103,"
4342 "\"type\":\"request\","
4343 "\"command\":\"evaluate\","
4344 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false,"
4345 "\"global\":true}}";
4346 } else {
4347 command_3 = "{\"seq\":103,"
4348 "\"type\":\"request\","
4349 "\"command\":\"evaluate\","
4350 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false}}";
4351 }
4352 const char* command_4;
4353 if (this->global_evaluate_) {
4354 command_4 = "{\"seq\":104,"
4355 "\"type\":\"request\","
4356 "\"command\":\"evaluate\","
4357 "\"arguments\":{\"expression\":\"100 + 8\",\"disable_break\":true,"
4358 "\"global\":true}}";
4359 } else {
4360 command_4 = "{\"seq\":104,"
4361 "\"type\":\"request\","
4362 "\"command\":\"evaluate\","
4363 "\"arguments\":{\"expression\":\"x + 1\",\"disable_break\":true}}";
4364 }
Steve Block3ce2e202009-11-05 08:53:23 +00004365 const char* command_5 = "{\"seq\":105,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004366 "\"type\":\"request\","
4367 "\"command\":\"continue\"}";
Steve Block3ce2e202009-11-05 08:53:23 +00004368 const char* command_6 = "{\"seq\":106,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004369 "\"type\":\"request\","
4370 "\"command\":\"continue\"}";
Leon Clarked91b9f72010-01-27 17:25:45 +00004371 const char* command_7;
4372 if (this->global_evaluate_) {
4373 command_7 = "{\"seq\":107,"
4374 "\"type\":\"request\","
4375 "\"command\":\"evaluate\","
4376 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true,"
4377 "\"global\":true}}";
4378 } else {
4379 command_7 = "{\"seq\":107,"
4380 "\"type\":\"request\","
4381 "\"command\":\"evaluate\","
4382 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true}}";
4383 }
Steve Block3ce2e202009-11-05 08:53:23 +00004384 const char* command_8 = "{\"seq\":108,"
Steve Blocka7e24c12009-10-30 11:49:00 +00004385 "\"type\":\"request\","
4386 "\"command\":\"continue\"}";
4387
4388
4389 // v8 thread initializes, runs source_1
4390 breakpoints_barriers->barrier_1.Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00004391 // 1:Set breakpoint in cat() (will get id 1).
Steve Blocka7e24c12009-10-30 11:49:00 +00004392 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004393 // 2:Set breakpoint in dog() (will get id 2).
Steve Blocka7e24c12009-10-30 11:49:00 +00004394 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
4395 breakpoints_barriers->barrier_2.Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00004396 // V8 thread starts compiling source_2.
Steve Blocka7e24c12009-10-30 11:49:00 +00004397 // Automatic break happens, to run queued commands
4398 // breakpoints_barriers->semaphore_1->Wait();
4399 // Commands 1 through 3 run, thread continues.
4400 // v8 thread runs source_2 to breakpoint in cat().
4401 // message callback receives break event.
4402 breakpoints_barriers->semaphore_1->Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00004403 // Must have hit breakpoint #1.
4404 CHECK_EQ(1, break_event_breakpoint_id);
Steve Blocka7e24c12009-10-30 11:49:00 +00004405 // 4:Evaluate dog() (which has a breakpoint).
4406 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_3, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004407 // V8 thread hits breakpoint in dog().
Steve Blocka7e24c12009-10-30 11:49:00 +00004408 breakpoints_barriers->semaphore_1->Wait(); // wait for break event
Steve Block3ce2e202009-11-05 08:53:23 +00004409 // Must have hit breakpoint #2.
4410 CHECK_EQ(2, break_event_breakpoint_id);
4411 // 5:Evaluate (x + 1).
Steve Blocka7e24c12009-10-30 11:49:00 +00004412 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_4, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004413 // Evaluate (x + 1) finishes.
4414 breakpoints_barriers->semaphore_1->Wait();
4415 // Must have result 108.
4416 CHECK_EQ(108, evaluate_int_result);
4417 // 6:Continue evaluation of dog().
Steve Blocka7e24c12009-10-30 11:49:00 +00004418 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_5, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004419 // Evaluate dog() finishes.
4420 breakpoints_barriers->semaphore_1->Wait();
4421 // Must have result 107.
4422 CHECK_EQ(107, evaluate_int_result);
Steve Blocka7e24c12009-10-30 11:49:00 +00004423 // 7:Continue evaluation of source_2, finish cat(17), hit breakpoint
4424 // in cat(19).
4425 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_6, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004426 // Message callback gets break event.
Steve Blocka7e24c12009-10-30 11:49:00 +00004427 breakpoints_barriers->semaphore_1->Wait(); // wait for break event
Steve Block3ce2e202009-11-05 08:53:23 +00004428 // Must have hit breakpoint #1.
4429 CHECK_EQ(1, break_event_breakpoint_id);
4430 // 8: Evaluate dog() with breaks disabled.
Steve Blocka7e24c12009-10-30 11:49:00 +00004431 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_7, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00004432 // Evaluate dog() finishes.
4433 breakpoints_barriers->semaphore_1->Wait();
4434 // Must have result 116.
4435 CHECK_EQ(116, evaluate_int_result);
Steve Blocka7e24c12009-10-30 11:49:00 +00004436 // 9: Continue evaluation of source2, reach end.
4437 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_8, buffer));
4438}
4439
Leon Clarked91b9f72010-01-27 17:25:45 +00004440void TestRecursiveBreakpointsGeneric(bool global_evaluate) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00004441 i::FLAG_debugger_auto_break = true;
Leon Clarke888f6722010-01-27 15:57:47 +00004442
Leon Clarked91b9f72010-01-27 17:25:45 +00004443 BreakpointsDebuggerThread breakpoints_debugger_thread(global_evaluate);
4444 BreakpointsV8Thread breakpoints_v8_thread;
4445
Steve Blocka7e24c12009-10-30 11:49:00 +00004446 // Create a V8 environment
4447 Barriers stack_allocated_breakpoints_barriers;
4448 stack_allocated_breakpoints_barriers.Initialize();
4449 breakpoints_barriers = &stack_allocated_breakpoints_barriers;
4450
4451 breakpoints_v8_thread.Start();
4452 breakpoints_debugger_thread.Start();
4453
4454 breakpoints_v8_thread.Join();
4455 breakpoints_debugger_thread.Join();
4456}
4457
Leon Clarked91b9f72010-01-27 17:25:45 +00004458TEST(RecursiveBreakpoints) {
4459 TestRecursiveBreakpointsGeneric(false);
4460}
4461
4462TEST(RecursiveBreakpointsGlobal) {
4463 TestRecursiveBreakpointsGeneric(true);
4464}
4465
Steve Blocka7e24c12009-10-30 11:49:00 +00004466
4467static void DummyDebugEventListener(v8::DebugEvent event,
4468 v8::Handle<v8::Object> exec_state,
4469 v8::Handle<v8::Object> event_data,
4470 v8::Handle<v8::Value> data) {
4471}
4472
4473
4474TEST(SetDebugEventListenerOnUninitializedVM) {
4475 v8::Debug::SetDebugEventListener(DummyDebugEventListener);
4476}
4477
4478
4479static void DummyMessageHandler(const v8::Debug::Message& message) {
4480}
4481
4482
4483TEST(SetMessageHandlerOnUninitializedVM) {
4484 v8::Debug::SetMessageHandler2(DummyMessageHandler);
4485}
4486
4487
4488TEST(DebugBreakOnUninitializedVM) {
4489 v8::Debug::DebugBreak();
4490}
4491
4492
4493TEST(SendCommandToUninitializedVM) {
4494 const char* dummy_command = "{}";
4495 uint16_t dummy_buffer[80];
4496 int dummy_length = AsciiToUtf16(dummy_command, dummy_buffer);
4497 v8::Debug::SendCommand(dummy_buffer, dummy_length);
4498}
4499
4500
4501// Source for a JavaScript function which returns the data parameter of a
4502// function called in the context of the debugger. If no data parameter is
4503// passed it throws an exception.
4504static const char* debugger_call_with_data_source =
4505 "function debugger_call_with_data(exec_state, data) {"
4506 " if (data) return data;"
4507 " throw 'No data!'"
4508 "}";
4509v8::Handle<v8::Function> debugger_call_with_data;
4510
4511
4512// Source for a JavaScript function which returns the data parameter of a
4513// function called in the context of the debugger. If no data parameter is
4514// passed it throws an exception.
4515static const char* debugger_call_with_closure_source =
4516 "var x = 3;"
4517 "(function (exec_state) {"
4518 " if (exec_state.y) return x - 1;"
4519 " exec_state.y = x;"
4520 " return exec_state.y"
4521 "})";
4522v8::Handle<v8::Function> debugger_call_with_closure;
4523
4524// Function to retrieve the number of JavaScript frames by calling a JavaScript
4525// in the debugger.
4526static v8::Handle<v8::Value> CheckFrameCount(const v8::Arguments& args) {
4527 CHECK(v8::Debug::Call(frame_count)->IsNumber());
4528 CHECK_EQ(args[0]->Int32Value(),
4529 v8::Debug::Call(frame_count)->Int32Value());
4530 return v8::Undefined();
4531}
4532
4533
4534// Function to retrieve the source line of the top JavaScript frame by calling a
4535// JavaScript function in the debugger.
4536static v8::Handle<v8::Value> CheckSourceLine(const v8::Arguments& args) {
4537 CHECK(v8::Debug::Call(frame_source_line)->IsNumber());
4538 CHECK_EQ(args[0]->Int32Value(),
4539 v8::Debug::Call(frame_source_line)->Int32Value());
4540 return v8::Undefined();
4541}
4542
4543
4544// Function to test passing an additional parameter to a JavaScript function
4545// called in the debugger. It also tests that functions called in the debugger
4546// can throw exceptions.
4547static v8::Handle<v8::Value> CheckDataParameter(const v8::Arguments& args) {
4548 v8::Handle<v8::String> data = v8::String::New("Test");
4549 CHECK(v8::Debug::Call(debugger_call_with_data, data)->IsString());
4550
4551 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
4552 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
4553
4554 v8::TryCatch catcher;
4555 v8::Debug::Call(debugger_call_with_data);
4556 CHECK(catcher.HasCaught());
4557 CHECK(catcher.Exception()->IsString());
4558
4559 return v8::Undefined();
4560}
4561
4562
4563// Function to test using a JavaScript with closure in the debugger.
4564static v8::Handle<v8::Value> CheckClosure(const v8::Arguments& args) {
4565 CHECK(v8::Debug::Call(debugger_call_with_closure)->IsNumber());
4566 CHECK_EQ(3, v8::Debug::Call(debugger_call_with_closure)->Int32Value());
4567 return v8::Undefined();
4568}
4569
4570
4571// Test functions called through the debugger.
4572TEST(CallFunctionInDebugger) {
4573 // Create and enter a context with the functions CheckFrameCount,
4574 // CheckSourceLine and CheckDataParameter installed.
4575 v8::HandleScope scope;
4576 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
4577 global_template->Set(v8::String::New("CheckFrameCount"),
4578 v8::FunctionTemplate::New(CheckFrameCount));
4579 global_template->Set(v8::String::New("CheckSourceLine"),
4580 v8::FunctionTemplate::New(CheckSourceLine));
4581 global_template->Set(v8::String::New("CheckDataParameter"),
4582 v8::FunctionTemplate::New(CheckDataParameter));
4583 global_template->Set(v8::String::New("CheckClosure"),
4584 v8::FunctionTemplate::New(CheckClosure));
4585 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template);
4586 v8::Context::Scope context_scope(context);
4587
4588 // Compile a function for checking the number of JavaScript frames.
4589 v8::Script::Compile(v8::String::New(frame_count_source))->Run();
4590 frame_count = v8::Local<v8::Function>::Cast(
4591 context->Global()->Get(v8::String::New("frame_count")));
4592
4593 // Compile a function for returning the source line for the top frame.
4594 v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
4595 frame_source_line = v8::Local<v8::Function>::Cast(
4596 context->Global()->Get(v8::String::New("frame_source_line")));
4597
4598 // Compile a function returning the data parameter.
4599 v8::Script::Compile(v8::String::New(debugger_call_with_data_source))->Run();
4600 debugger_call_with_data = v8::Local<v8::Function>::Cast(
4601 context->Global()->Get(v8::String::New("debugger_call_with_data")));
4602
4603 // Compile a function capturing closure.
4604 debugger_call_with_closure = v8::Local<v8::Function>::Cast(
4605 v8::Script::Compile(
4606 v8::String::New(debugger_call_with_closure_source))->Run());
4607
4608 // Calling a function through the debugger returns undefined if there are no
4609 // JavaScript frames.
4610 CHECK(v8::Debug::Call(frame_count)->IsUndefined());
4611 CHECK(v8::Debug::Call(frame_source_line)->IsUndefined());
4612 CHECK(v8::Debug::Call(debugger_call_with_data)->IsUndefined());
4613
4614 // Test that the number of frames can be retrieved.
4615 v8::Script::Compile(v8::String::New("CheckFrameCount(1)"))->Run();
4616 v8::Script::Compile(v8::String::New("function f() {"
4617 " CheckFrameCount(2);"
4618 "}; f()"))->Run();
4619
4620 // Test that the source line can be retrieved.
4621 v8::Script::Compile(v8::String::New("CheckSourceLine(0)"))->Run();
4622 v8::Script::Compile(v8::String::New("function f() {\n"
4623 " CheckSourceLine(1)\n"
4624 " CheckSourceLine(2)\n"
4625 " CheckSourceLine(3)\n"
4626 "}; f()"))->Run();
4627
4628 // Test that a parameter can be passed to a function called in the debugger.
4629 v8::Script::Compile(v8::String::New("CheckDataParameter()"))->Run();
4630
4631 // Test that a function with closure can be run in the debugger.
4632 v8::Script::Compile(v8::String::New("CheckClosure()"))->Run();
4633
4634
4635 // Test that the source line is correct when there is a line offset.
4636 v8::ScriptOrigin origin(v8::String::New("test"),
4637 v8::Integer::New(7));
4638 v8::Script::Compile(v8::String::New("CheckSourceLine(7)"), &origin)->Run();
4639 v8::Script::Compile(v8::String::New("function f() {\n"
4640 " CheckSourceLine(8)\n"
4641 " CheckSourceLine(9)\n"
4642 " CheckSourceLine(10)\n"
4643 "}; f()"), &origin)->Run();
4644}
4645
4646
4647// Debugger message handler which counts the number of breaks.
4648static void SendContinueCommand();
4649static void MessageHandlerBreakPointHitCount(
4650 const v8::Debug::Message& message) {
4651 if (message.IsEvent() && message.GetEvent() == v8::Break) {
4652 // Count the number of breaks.
4653 break_point_hit_count++;
4654
4655 SendContinueCommand();
4656 }
4657}
4658
4659
4660// Test that clearing the debug event listener actually clears all break points
4661// and related information.
4662TEST(DebuggerUnload) {
4663 DebugLocalContext env;
4664
4665 // Check debugger is unloaded before it is used.
4666 CheckDebuggerUnloaded();
4667
4668 // Set a debug event listener.
4669 break_point_hit_count = 0;
4670 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
4671 v8::Undefined());
4672 {
4673 v8::HandleScope scope;
4674 // Create a couple of functions for the test.
4675 v8::Local<v8::Function> foo =
4676 CompileFunction(&env, "function foo(){x=1}", "foo");
4677 v8::Local<v8::Function> bar =
4678 CompileFunction(&env, "function bar(){y=2}", "bar");
4679
4680 // Set some break points.
4681 SetBreakPoint(foo, 0);
4682 SetBreakPoint(foo, 4);
4683 SetBreakPoint(bar, 0);
4684 SetBreakPoint(bar, 4);
4685
4686 // Make sure that the break points are there.
4687 break_point_hit_count = 0;
4688 foo->Call(env->Global(), 0, NULL);
4689 CHECK_EQ(2, break_point_hit_count);
4690 bar->Call(env->Global(), 0, NULL);
4691 CHECK_EQ(4, break_point_hit_count);
4692 }
4693
4694 // Remove the debug event listener without clearing breakpoints. Do this
4695 // outside a handle scope.
4696 v8::Debug::SetDebugEventListener(NULL);
4697 CheckDebuggerUnloaded(true);
4698
4699 // Now set a debug message handler.
4700 break_point_hit_count = 0;
4701 v8::Debug::SetMessageHandler2(MessageHandlerBreakPointHitCount);
4702 {
4703 v8::HandleScope scope;
4704
4705 // Get the test functions again.
4706 v8::Local<v8::Function> foo =
4707 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
4708 v8::Local<v8::Function> bar =
4709 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
4710
4711 foo->Call(env->Global(), 0, NULL);
4712 CHECK_EQ(0, break_point_hit_count);
4713
4714 // Set break points and run again.
4715 SetBreakPoint(foo, 0);
4716 SetBreakPoint(foo, 4);
4717 foo->Call(env->Global(), 0, NULL);
4718 CHECK_EQ(2, break_point_hit_count);
4719 }
4720
4721 // Remove the debug message handler without clearing breakpoints. Do this
4722 // outside a handle scope.
4723 v8::Debug::SetMessageHandler2(NULL);
4724 CheckDebuggerUnloaded(true);
4725}
4726
4727
4728// Sends continue command to the debugger.
4729static void SendContinueCommand() {
4730 const int kBufferSize = 1000;
4731 uint16_t buffer[kBufferSize];
4732 const char* command_continue =
4733 "{\"seq\":0,"
4734 "\"type\":\"request\","
4735 "\"command\":\"continue\"}";
4736
4737 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer));
4738}
4739
4740
4741// Debugger message handler which counts the number of times it is called.
4742static int message_handler_hit_count = 0;
4743static void MessageHandlerHitCount(const v8::Debug::Message& message) {
4744 message_handler_hit_count++;
4745
Steve Block3ce2e202009-11-05 08:53:23 +00004746 static char print_buffer[1000];
4747 v8::String::Value json(message.GetJSON());
4748 Utf16ToAscii(*json, json.length(), print_buffer);
4749 if (IsExceptionEventMessage(print_buffer)) {
4750 // Send a continue command for exception events.
4751 SendContinueCommand();
4752 }
Steve Blocka7e24c12009-10-30 11:49:00 +00004753}
4754
4755
4756// Test clearing the debug message handler.
4757TEST(DebuggerClearMessageHandler) {
4758 v8::HandleScope scope;
4759 DebugLocalContext env;
4760
4761 // Check debugger is unloaded before it is used.
4762 CheckDebuggerUnloaded();
4763
4764 // Set a debug message handler.
4765 v8::Debug::SetMessageHandler2(MessageHandlerHitCount);
4766
4767 // Run code to throw a unhandled exception. This should end up in the message
4768 // handler.
4769 CompileRun("throw 1");
4770
4771 // The message handler should be called.
4772 CHECK_GT(message_handler_hit_count, 0);
4773
4774 // Clear debug message handler.
4775 message_handler_hit_count = 0;
4776 v8::Debug::SetMessageHandler(NULL);
4777
4778 // Run code to throw a unhandled exception. This should end up in the message
4779 // handler.
4780 CompileRun("throw 1");
4781
4782 // The message handler should not be called more.
4783 CHECK_EQ(0, message_handler_hit_count);
4784
4785 CheckDebuggerUnloaded(true);
4786}
4787
4788
4789// Debugger message handler which clears the message handler while active.
4790static void MessageHandlerClearingMessageHandler(
4791 const v8::Debug::Message& message) {
4792 message_handler_hit_count++;
4793
4794 // Clear debug message handler.
4795 v8::Debug::SetMessageHandler(NULL);
4796}
4797
4798
4799// Test clearing the debug message handler while processing a debug event.
4800TEST(DebuggerClearMessageHandlerWhileActive) {
4801 v8::HandleScope scope;
4802 DebugLocalContext env;
4803
4804 // Check debugger is unloaded before it is used.
4805 CheckDebuggerUnloaded();
4806
4807 // Set a debug message handler.
4808 v8::Debug::SetMessageHandler2(MessageHandlerClearingMessageHandler);
4809
4810 // Run code to throw a unhandled exception. This should end up in the message
4811 // handler.
4812 CompileRun("throw 1");
4813
4814 // The message handler should be called.
4815 CHECK_EQ(1, message_handler_hit_count);
4816
4817 CheckDebuggerUnloaded(true);
4818}
4819
4820
4821/* Test DebuggerHostDispatch */
4822/* In this test, the debugger waits for a command on a breakpoint
4823 * and is dispatching host commands while in the infinite loop.
4824 */
4825
4826class HostDispatchV8Thread : public v8::internal::Thread {
4827 public:
4828 void Run();
4829};
4830
4831class HostDispatchDebuggerThread : public v8::internal::Thread {
4832 public:
4833 void Run();
4834};
4835
4836Barriers* host_dispatch_barriers;
4837
4838static void HostDispatchMessageHandler(const v8::Debug::Message& message) {
4839 static char print_buffer[1000];
4840 v8::String::Value json(message.GetJSON());
4841 Utf16ToAscii(*json, json.length(), print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00004842}
4843
4844
4845static void HostDispatchDispatchHandler() {
4846 host_dispatch_barriers->semaphore_1->Signal();
4847}
4848
4849
4850void HostDispatchV8Thread::Run() {
4851 const char* source_1 = "var y_global = 3;\n"
4852 "function cat( new_value ) {\n"
4853 " var x = new_value;\n"
4854 " y_global = 4;\n"
4855 " x = 3 * x + 1;\n"
4856 " y_global = 5;\n"
4857 " return x;\n"
4858 "}\n"
4859 "\n";
4860 const char* source_2 = "cat(17);\n";
4861
4862 v8::HandleScope scope;
4863 DebugLocalContext env;
4864
4865 // Setup message and host dispatch handlers.
4866 v8::Debug::SetMessageHandler2(HostDispatchMessageHandler);
4867 v8::Debug::SetHostDispatchHandler(HostDispatchDispatchHandler, 10 /* ms */);
4868
4869 CompileRun(source_1);
4870 host_dispatch_barriers->barrier_1.Wait();
4871 host_dispatch_barriers->barrier_2.Wait();
4872 CompileRun(source_2);
4873}
4874
4875
4876void HostDispatchDebuggerThread::Run() {
4877 const int kBufSize = 1000;
4878 uint16_t buffer[kBufSize];
4879
4880 const char* command_1 = "{\"seq\":101,"
4881 "\"type\":\"request\","
4882 "\"command\":\"setbreakpoint\","
4883 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
4884 const char* command_2 = "{\"seq\":102,"
4885 "\"type\":\"request\","
4886 "\"command\":\"continue\"}";
4887
4888 // v8 thread initializes, runs source_1
4889 host_dispatch_barriers->barrier_1.Wait();
4890 // 1: Set breakpoint in cat().
4891 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
4892
4893 host_dispatch_barriers->barrier_2.Wait();
4894 // v8 thread starts compiling source_2.
4895 // Break happens, to run queued commands and host dispatches.
4896 // Wait for host dispatch to be processed.
4897 host_dispatch_barriers->semaphore_1->Wait();
4898 // 2: Continue evaluation
4899 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
4900}
4901
4902HostDispatchDebuggerThread host_dispatch_debugger_thread;
4903HostDispatchV8Thread host_dispatch_v8_thread;
4904
4905
4906TEST(DebuggerHostDispatch) {
4907 i::FLAG_debugger_auto_break = true;
4908
4909 // Create a V8 environment
4910 Barriers stack_allocated_host_dispatch_barriers;
4911 stack_allocated_host_dispatch_barriers.Initialize();
4912 host_dispatch_barriers = &stack_allocated_host_dispatch_barriers;
4913
4914 host_dispatch_v8_thread.Start();
4915 host_dispatch_debugger_thread.Start();
4916
4917 host_dispatch_v8_thread.Join();
4918 host_dispatch_debugger_thread.Join();
4919}
4920
4921
Steve Blockd0582a62009-12-15 09:54:21 +00004922/* Test DebugMessageDispatch */
4923/* In this test, the V8 thread waits for a message from the debug thread.
4924 * The DebugMessageDispatchHandler is executed from the debugger thread
4925 * which signals the V8 thread to wake up.
4926 */
4927
4928class DebugMessageDispatchV8Thread : public v8::internal::Thread {
4929 public:
4930 void Run();
4931};
4932
4933class DebugMessageDispatchDebuggerThread : public v8::internal::Thread {
4934 public:
4935 void Run();
4936};
4937
4938Barriers* debug_message_dispatch_barriers;
4939
4940
4941static void DebugMessageHandler() {
4942 debug_message_dispatch_barriers->semaphore_1->Signal();
4943}
4944
4945
4946void DebugMessageDispatchV8Thread::Run() {
4947 v8::HandleScope scope;
4948 DebugLocalContext env;
4949
4950 // Setup debug message dispatch handler.
4951 v8::Debug::SetDebugMessageDispatchHandler(DebugMessageHandler);
4952
4953 CompileRun("var y = 1 + 2;\n");
4954 debug_message_dispatch_barriers->barrier_1.Wait();
4955 debug_message_dispatch_barriers->semaphore_1->Wait();
4956 debug_message_dispatch_barriers->barrier_2.Wait();
4957}
4958
4959
4960void DebugMessageDispatchDebuggerThread::Run() {
4961 debug_message_dispatch_barriers->barrier_1.Wait();
4962 SendContinueCommand();
4963 debug_message_dispatch_barriers->barrier_2.Wait();
4964}
4965
4966DebugMessageDispatchDebuggerThread debug_message_dispatch_debugger_thread;
4967DebugMessageDispatchV8Thread debug_message_dispatch_v8_thread;
4968
4969
4970TEST(DebuggerDebugMessageDispatch) {
4971 i::FLAG_debugger_auto_break = true;
4972
4973 // Create a V8 environment
4974 Barriers stack_allocated_debug_message_dispatch_barriers;
4975 stack_allocated_debug_message_dispatch_barriers.Initialize();
4976 debug_message_dispatch_barriers =
4977 &stack_allocated_debug_message_dispatch_barriers;
4978
4979 debug_message_dispatch_v8_thread.Start();
4980 debug_message_dispatch_debugger_thread.Start();
4981
4982 debug_message_dispatch_v8_thread.Join();
4983 debug_message_dispatch_debugger_thread.Join();
4984}
4985
4986
Steve Blocka7e24c12009-10-30 11:49:00 +00004987TEST(DebuggerAgent) {
4988 // Make sure these ports is not used by other tests to allow tests to run in
4989 // parallel.
4990 const int kPort1 = 5858;
4991 const int kPort2 = 5857;
4992 const int kPort3 = 5856;
4993
4994 // Make a string with the port2 number.
4995 const int kPortBufferLen = 6;
4996 char port2_str[kPortBufferLen];
4997 OS::SNPrintF(i::Vector<char>(port2_str, kPortBufferLen), "%d", kPort2);
4998
4999 bool ok;
5000
5001 // Initialize the socket library.
5002 i::Socket::Setup();
5003
5004 // Test starting and stopping the agent without any client connection.
5005 i::Debugger::StartAgent("test", kPort1);
5006 i::Debugger::StopAgent();
5007
5008 // Test starting the agent, connecting a client and shutting down the agent
5009 // with the client connected.
5010 ok = i::Debugger::StartAgent("test", kPort2);
5011 CHECK(ok);
5012 i::Debugger::WaitForAgent();
5013 i::Socket* client = i::OS::CreateSocket();
5014 ok = client->Connect("localhost", port2_str);
5015 CHECK(ok);
5016 i::Debugger::StopAgent();
5017 delete client;
5018
5019 // Test starting and stopping the agent with the required port already
5020 // occoupied.
5021 i::Socket* server = i::OS::CreateSocket();
5022 server->Bind(kPort3);
5023
5024 i::Debugger::StartAgent("test", kPort3);
5025 i::Debugger::StopAgent();
5026
5027 delete server;
5028}
5029
5030
5031class DebuggerAgentProtocolServerThread : public i::Thread {
5032 public:
5033 explicit DebuggerAgentProtocolServerThread(int port)
5034 : port_(port), server_(NULL), client_(NULL),
5035 listening_(OS::CreateSemaphore(0)) {
5036 }
5037 ~DebuggerAgentProtocolServerThread() {
5038 // Close both sockets.
5039 delete client_;
5040 delete server_;
5041 delete listening_;
5042 }
5043
5044 void Run();
5045 void WaitForListening() { listening_->Wait(); }
5046 char* body() { return *body_; }
5047
5048 private:
5049 int port_;
5050 i::SmartPointer<char> body_;
5051 i::Socket* server_; // Server socket used for bind/accept.
5052 i::Socket* client_; // Single client connection used by the test.
5053 i::Semaphore* listening_; // Signalled when the server is in listen mode.
5054};
5055
5056
5057void DebuggerAgentProtocolServerThread::Run() {
5058 bool ok;
5059
5060 // Create the server socket and bind it to the requested port.
5061 server_ = i::OS::CreateSocket();
5062 CHECK(server_ != NULL);
5063 ok = server_->Bind(port_);
5064 CHECK(ok);
5065
5066 // Listen for new connections.
5067 ok = server_->Listen(1);
5068 CHECK(ok);
5069 listening_->Signal();
5070
5071 // Accept a connection.
5072 client_ = server_->Accept();
5073 CHECK(client_ != NULL);
5074
5075 // Receive a debugger agent protocol message.
5076 i::DebuggerAgentUtil::ReceiveMessage(client_);
5077}
5078
5079
5080TEST(DebuggerAgentProtocolOverflowHeader) {
5081 // Make sure this port is not used by other tests to allow tests to run in
5082 // parallel.
5083 const int kPort = 5860;
5084 static const char* kLocalhost = "localhost";
5085
5086 // Make a string with the port number.
5087 const int kPortBufferLen = 6;
5088 char port_str[kPortBufferLen];
5089 OS::SNPrintF(i::Vector<char>(port_str, kPortBufferLen), "%d", kPort);
5090
5091 // Initialize the socket library.
5092 i::Socket::Setup();
5093
5094 // Create a socket server to receive a debugger agent message.
5095 DebuggerAgentProtocolServerThread* server =
5096 new DebuggerAgentProtocolServerThread(kPort);
5097 server->Start();
5098 server->WaitForListening();
5099
5100 // Connect.
5101 i::Socket* client = i::OS::CreateSocket();
5102 CHECK(client != NULL);
5103 bool ok = client->Connect(kLocalhost, port_str);
5104 CHECK(ok);
5105
5106 // Send headers which overflow the receive buffer.
5107 static const int kBufferSize = 1000;
5108 char buffer[kBufferSize];
5109
5110 // Long key and short value: XXXX....XXXX:0\r\n.
5111 for (int i = 0; i < kBufferSize - 4; i++) {
5112 buffer[i] = 'X';
5113 }
5114 buffer[kBufferSize - 4] = ':';
5115 buffer[kBufferSize - 3] = '0';
5116 buffer[kBufferSize - 2] = '\r';
5117 buffer[kBufferSize - 1] = '\n';
5118 client->Send(buffer, kBufferSize);
5119
5120 // Short key and long value: X:XXXX....XXXX\r\n.
5121 buffer[0] = 'X';
5122 buffer[1] = ':';
5123 for (int i = 2; i < kBufferSize - 2; i++) {
5124 buffer[i] = 'X';
5125 }
5126 buffer[kBufferSize - 2] = '\r';
5127 buffer[kBufferSize - 1] = '\n';
5128 client->Send(buffer, kBufferSize);
5129
5130 // Add empty body to request.
5131 const char* content_length_zero_header = "Content-Length:0\r\n";
Steve Blockd0582a62009-12-15 09:54:21 +00005132 client->Send(content_length_zero_header,
5133 StrLength(content_length_zero_header));
Steve Blocka7e24c12009-10-30 11:49:00 +00005134 client->Send("\r\n", 2);
5135
5136 // Wait until data is received.
5137 server->Join();
5138
5139 // Check for empty body.
5140 CHECK(server->body() == NULL);
5141
5142 // Close the client before the server to avoid TIME_WAIT issues.
5143 client->Shutdown();
5144 delete client;
5145 delete server;
5146}
5147
5148
5149// Test for issue http://code.google.com/p/v8/issues/detail?id=289.
5150// Make sure that DebugGetLoadedScripts doesn't return scripts
5151// with disposed external source.
5152class EmptyExternalStringResource : public v8::String::ExternalStringResource {
5153 public:
5154 EmptyExternalStringResource() { empty_[0] = 0; }
5155 virtual ~EmptyExternalStringResource() {}
5156 virtual size_t length() const { return empty_.length(); }
5157 virtual const uint16_t* data() const { return empty_.start(); }
5158 private:
5159 ::v8::internal::EmbeddedVector<uint16_t, 1> empty_;
5160};
5161
5162
5163TEST(DebugGetLoadedScripts) {
5164 v8::HandleScope scope;
5165 DebugLocalContext env;
5166 env.ExposeDebug();
5167
5168 EmptyExternalStringResource source_ext_str;
5169 v8::Local<v8::String> source = v8::String::NewExternal(&source_ext_str);
5170 v8::Handle<v8::Script> evil_script = v8::Script::Compile(source);
5171 Handle<i::ExternalTwoByteString> i_source(
5172 i::ExternalTwoByteString::cast(*v8::Utils::OpenHandle(*source)));
5173 // This situation can happen if source was an external string disposed
5174 // by its owner.
5175 i_source->set_resource(0);
5176
5177 bool allow_natives_syntax = i::FLAG_allow_natives_syntax;
5178 i::FLAG_allow_natives_syntax = true;
5179 CompileRun(
5180 "var scripts = %DebugGetLoadedScripts();"
5181 "var count = scripts.length;"
5182 "for (var i = 0; i < count; ++i) {"
5183 " scripts[i].line_ends;"
5184 "}");
5185 // Must not crash while accessing line_ends.
5186 i::FLAG_allow_natives_syntax = allow_natives_syntax;
5187
5188 // Some scripts are retrieved - at least the number of native scripts.
5189 CHECK_GT((*env)->Global()->Get(v8::String::New("count"))->Int32Value(), 8);
5190}
5191
5192
5193// Test script break points set on lines.
5194TEST(ScriptNameAndData) {
5195 v8::HandleScope scope;
5196 DebugLocalContext env;
5197 env.ExposeDebug();
5198
5199 // Create functions for retrieving script name and data for the function on
5200 // the top frame when hitting a break point.
5201 frame_script_name = CompileFunction(&env,
5202 frame_script_name_source,
5203 "frame_script_name");
5204 frame_script_data = CompileFunction(&env,
5205 frame_script_data_source,
5206 "frame_script_data");
5207
5208 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
5209 v8::Undefined());
5210
5211 // Test function source.
5212 v8::Local<v8::String> script = v8::String::New(
5213 "function f() {\n"
5214 " debugger;\n"
5215 "}\n");
5216
5217 v8::ScriptOrigin origin1 = v8::ScriptOrigin(v8::String::New("name"));
5218 v8::Handle<v8::Script> script1 = v8::Script::Compile(script, &origin1);
5219 script1->SetData(v8::String::New("data"));
5220 script1->Run();
5221 v8::Local<v8::Function> f;
5222 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5223
5224 f->Call(env->Global(), 0, NULL);
5225 CHECK_EQ(1, break_point_hit_count);
5226 CHECK_EQ("name", last_script_name_hit);
5227 CHECK_EQ("data", last_script_data_hit);
5228
5229 // Compile the same script again without setting data. As the compilation
5230 // cache is disabled when debugging expect the data to be missing.
5231 v8::Script::Compile(script, &origin1)->Run();
5232 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5233 f->Call(env->Global(), 0, NULL);
5234 CHECK_EQ(2, break_point_hit_count);
5235 CHECK_EQ("name", last_script_name_hit);
5236 CHECK_EQ("", last_script_data_hit); // Undefined results in empty string.
5237
5238 v8::Local<v8::String> data_obj_source = v8::String::New(
5239 "({ a: 'abc',\n"
5240 " b: 123,\n"
5241 " toString: function() { return this.a + ' ' + this.b; }\n"
5242 "})\n");
5243 v8::Local<v8::Value> data_obj = v8::Script::Compile(data_obj_source)->Run();
5244 v8::ScriptOrigin origin2 = v8::ScriptOrigin(v8::String::New("new name"));
5245 v8::Handle<v8::Script> script2 = v8::Script::Compile(script, &origin2);
5246 script2->Run();
Steve Blockd0582a62009-12-15 09:54:21 +00005247 script2->SetData(data_obj->ToString());
Steve Blocka7e24c12009-10-30 11:49:00 +00005248 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5249 f->Call(env->Global(), 0, NULL);
5250 CHECK_EQ(3, break_point_hit_count);
5251 CHECK_EQ("new name", last_script_name_hit);
5252 CHECK_EQ("abc 123", last_script_data_hit);
5253}
5254
5255
5256static v8::Persistent<v8::Context> expected_context;
5257static v8::Handle<v8::Value> expected_context_data;
5258
5259
5260// Check that the expected context is the one generating the debug event.
5261static void ContextCheckMessageHandler(const v8::Debug::Message& message) {
5262 CHECK(message.GetEventContext() == expected_context);
5263 CHECK(message.GetEventContext()->GetData()->StrictEquals(
5264 expected_context_data));
5265 message_handler_hit_count++;
5266
Steve Block3ce2e202009-11-05 08:53:23 +00005267 static char print_buffer[1000];
5268 v8::String::Value json(message.GetJSON());
5269 Utf16ToAscii(*json, json.length(), print_buffer);
5270
Steve Blocka7e24c12009-10-30 11:49:00 +00005271 // Send a continue command for break events.
Steve Block3ce2e202009-11-05 08:53:23 +00005272 if (IsBreakEventMessage(print_buffer)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005273 SendContinueCommand();
5274 }
5275}
5276
5277
5278// Test which creates two contexts and sets different embedder data on each.
5279// Checks that this data is set correctly and that when the debug message
5280// handler is called the expected context is the one active.
5281TEST(ContextData) {
5282 v8::HandleScope scope;
5283
5284 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler);
5285
5286 // Create two contexts.
5287 v8::Persistent<v8::Context> context_1;
5288 v8::Persistent<v8::Context> context_2;
5289 v8::Handle<v8::ObjectTemplate> global_template =
5290 v8::Handle<v8::ObjectTemplate>();
5291 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
5292 context_1 = v8::Context::New(NULL, global_template, global_object);
5293 context_2 = v8::Context::New(NULL, global_template, global_object);
5294
5295 // Default data value is undefined.
5296 CHECK(context_1->GetData()->IsUndefined());
5297 CHECK(context_2->GetData()->IsUndefined());
5298
5299 // Set and check different data values.
Steve Blockd0582a62009-12-15 09:54:21 +00005300 v8::Handle<v8::String> data_1 = v8::String::New("1");
5301 v8::Handle<v8::String> data_2 = v8::String::New("2");
Steve Blocka7e24c12009-10-30 11:49:00 +00005302 context_1->SetData(data_1);
5303 context_2->SetData(data_2);
5304 CHECK(context_1->GetData()->StrictEquals(data_1));
5305 CHECK(context_2->GetData()->StrictEquals(data_2));
5306
5307 // Simple test function which causes a break.
5308 const char* source = "function f() { debugger; }";
5309
5310 // Enter and run function in the first context.
5311 {
5312 v8::Context::Scope context_scope(context_1);
5313 expected_context = context_1;
5314 expected_context_data = data_1;
5315 v8::Local<v8::Function> f = CompileFunction(source, "f");
5316 f->Call(context_1->Global(), 0, NULL);
5317 }
5318
5319
5320 // Enter and run function in the second context.
5321 {
5322 v8::Context::Scope context_scope(context_2);
5323 expected_context = context_2;
5324 expected_context_data = data_2;
5325 v8::Local<v8::Function> f = CompileFunction(source, "f");
5326 f->Call(context_2->Global(), 0, NULL);
5327 }
5328
5329 // Two times compile event and two times break event.
5330 CHECK_GT(message_handler_hit_count, 4);
5331
5332 v8::Debug::SetMessageHandler2(NULL);
5333 CheckDebuggerUnloaded();
5334}
5335
5336
5337// Debug message handler which issues a debug break when it hits a break event.
5338static int message_handler_break_hit_count = 0;
5339static void DebugBreakMessageHandler(const v8::Debug::Message& message) {
5340 // Schedule a debug break for break events.
5341 if (message.IsEvent() && message.GetEvent() == v8::Break) {
5342 message_handler_break_hit_count++;
5343 if (message_handler_break_hit_count == 1) {
5344 v8::Debug::DebugBreak();
5345 }
5346 }
5347
5348 // Issue a continue command if this event will not cause the VM to start
5349 // running.
5350 if (!message.WillStartRunning()) {
5351 SendContinueCommand();
5352 }
5353}
5354
5355
5356// Test that a debug break can be scheduled while in a message handler.
5357TEST(DebugBreakInMessageHandler) {
5358 v8::HandleScope scope;
5359 DebugLocalContext env;
5360
5361 v8::Debug::SetMessageHandler2(DebugBreakMessageHandler);
5362
5363 // Test functions.
5364 const char* script = "function f() { debugger; g(); } function g() { }";
5365 CompileRun(script);
5366 v8::Local<v8::Function> f =
5367 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5368 v8::Local<v8::Function> g =
5369 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
5370
5371 // Call f then g. The debugger statement in f will casue a break which will
5372 // cause another break.
5373 f->Call(env->Global(), 0, NULL);
5374 CHECK_EQ(2, message_handler_break_hit_count);
5375 // Calling g will not cause any additional breaks.
5376 g->Call(env->Global(), 0, NULL);
5377 CHECK_EQ(2, message_handler_break_hit_count);
5378}
5379
5380
5381#ifdef V8_NATIVE_REGEXP
5382// Debug event handler which gets the function on the top frame and schedules a
5383// break a number of times.
5384static void DebugEventDebugBreak(
5385 v8::DebugEvent event,
5386 v8::Handle<v8::Object> exec_state,
5387 v8::Handle<v8::Object> event_data,
5388 v8::Handle<v8::Value> data) {
5389
5390 if (event == v8::Break) {
5391 break_point_hit_count++;
5392
5393 // Get the name of the top frame function.
5394 if (!frame_function_name.IsEmpty()) {
5395 // Get the name of the function.
5396 const int argc = 1;
5397 v8::Handle<v8::Value> argv[argc] = { exec_state };
5398 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
5399 argc, argv);
5400 if (result->IsUndefined()) {
5401 last_function_hit[0] = '\0';
5402 } else {
5403 CHECK(result->IsString());
5404 v8::Handle<v8::String> function_name(result->ToString());
5405 function_name->WriteAscii(last_function_hit);
5406 }
5407 }
5408
5409 // Keep forcing breaks.
5410 if (break_point_hit_count < 20) {
5411 v8::Debug::DebugBreak();
5412 }
5413 }
5414}
5415
5416
5417TEST(RegExpDebugBreak) {
5418 // This test only applies to native regexps.
5419 v8::HandleScope scope;
5420 DebugLocalContext env;
5421
5422 // Create a function for checking the function when hitting a break point.
5423 frame_function_name = CompileFunction(&env,
5424 frame_function_name_source,
5425 "frame_function_name");
5426
5427 // Test RegExp which matches white spaces and comments at the begining of a
5428 // source line.
5429 const char* script =
5430 "var sourceLineBeginningSkip = /^(?:[ \\v\\h]*(?:\\/\\*.*?\\*\\/)*)*/;\n"
5431 "function f(s) { return s.match(sourceLineBeginningSkip)[0].length; }";
5432
5433 v8::Local<v8::Function> f = CompileFunction(script, "f");
5434 const int argc = 1;
5435 v8::Handle<v8::Value> argv[argc] = { v8::String::New(" /* xxx */ a=0;") };
5436 v8::Local<v8::Value> result = f->Call(env->Global(), argc, argv);
5437 CHECK_EQ(12, result->Int32Value());
5438
5439 v8::Debug::SetDebugEventListener(DebugEventDebugBreak);
5440 v8::Debug::DebugBreak();
5441 result = f->Call(env->Global(), argc, argv);
5442
5443 // Check that there was only one break event. Matching RegExp should not
5444 // cause Break events.
5445 CHECK_EQ(1, break_point_hit_count);
5446 CHECK_EQ("f", last_function_hit);
5447}
5448#endif // V8_NATIVE_REGEXP
5449
5450
5451// Common part of EvalContextData and NestedBreakEventContextData tests.
5452static void ExecuteScriptForContextCheck() {
5453 // Create a context.
5454 v8::Persistent<v8::Context> context_1;
5455 v8::Handle<v8::ObjectTemplate> global_template =
5456 v8::Handle<v8::ObjectTemplate>();
5457 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
5458 context_1 = v8::Context::New(NULL, global_template, global_object);
5459
5460 // Default data value is undefined.
5461 CHECK(context_1->GetData()->IsUndefined());
5462
5463 // Set and check a data value.
Steve Blockd0582a62009-12-15 09:54:21 +00005464 v8::Handle<v8::String> data_1 = v8::String::New("1");
Steve Blocka7e24c12009-10-30 11:49:00 +00005465 context_1->SetData(data_1);
5466 CHECK(context_1->GetData()->StrictEquals(data_1));
5467
5468 // Simple test function with eval that causes a break.
5469 const char* source = "function f() { eval('debugger;'); }";
5470
5471 // Enter and run function in the context.
5472 {
5473 v8::Context::Scope context_scope(context_1);
5474 expected_context = context_1;
5475 expected_context_data = data_1;
5476 v8::Local<v8::Function> f = CompileFunction(source, "f");
5477 f->Call(context_1->Global(), 0, NULL);
5478 }
5479}
5480
5481
5482// Test which creates a context and sets embedder data on it. Checks that this
5483// data is set correctly and that when the debug message handler is called for
5484// break event in an eval statement the expected context is the one returned by
5485// Message.GetEventContext.
5486TEST(EvalContextData) {
5487 v8::HandleScope scope;
5488 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler);
5489
5490 ExecuteScriptForContextCheck();
5491
5492 // One time compile event and one time break event.
5493 CHECK_GT(message_handler_hit_count, 2);
5494 v8::Debug::SetMessageHandler2(NULL);
5495 CheckDebuggerUnloaded();
5496}
5497
5498
5499static bool sent_eval = false;
5500static int break_count = 0;
5501static int continue_command_send_count = 0;
5502// Check that the expected context is the one generating the debug event
5503// including the case of nested break event.
5504static void DebugEvalContextCheckMessageHandler(
5505 const v8::Debug::Message& message) {
5506 CHECK(message.GetEventContext() == expected_context);
5507 CHECK(message.GetEventContext()->GetData()->StrictEquals(
5508 expected_context_data));
5509 message_handler_hit_count++;
5510
Steve Block3ce2e202009-11-05 08:53:23 +00005511 static char print_buffer[1000];
5512 v8::String::Value json(message.GetJSON());
5513 Utf16ToAscii(*json, json.length(), print_buffer);
5514
5515 if (IsBreakEventMessage(print_buffer)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005516 break_count++;
5517 if (!sent_eval) {
5518 sent_eval = true;
5519
5520 const int kBufferSize = 1000;
5521 uint16_t buffer[kBufferSize];
5522 const char* eval_command =
5523 "{\"seq\":0,"
5524 "\"type\":\"request\","
5525 "\"command\":\"evaluate\","
5526 "arguments:{\"expression\":\"debugger;\","
5527 "\"global\":true,\"disable_break\":false}}";
5528
5529 // Send evaluate command.
5530 v8::Debug::SendCommand(buffer, AsciiToUtf16(eval_command, buffer));
5531 return;
5532 } else {
5533 // It's a break event caused by the evaluation request above.
5534 SendContinueCommand();
5535 continue_command_send_count++;
5536 }
Steve Block3ce2e202009-11-05 08:53:23 +00005537 } else if (IsEvaluateResponseMessage(print_buffer) &&
5538 continue_command_send_count < 2) {
Steve Blocka7e24c12009-10-30 11:49:00 +00005539 // Response to the evaluation request. We're still on the breakpoint so
5540 // send continue.
5541 SendContinueCommand();
5542 continue_command_send_count++;
5543 }
5544}
5545
5546
5547// Tests that context returned for break event is correct when the event occurs
5548// in 'evaluate' debugger request.
5549TEST(NestedBreakEventContextData) {
5550 v8::HandleScope scope;
5551 break_count = 0;
5552 message_handler_hit_count = 0;
5553 v8::Debug::SetMessageHandler2(DebugEvalContextCheckMessageHandler);
5554
5555 ExecuteScriptForContextCheck();
5556
5557 // One time compile event and two times break event.
5558 CHECK_GT(message_handler_hit_count, 3);
5559
5560 // One break from the source and another from the evaluate request.
5561 CHECK_EQ(break_count, 2);
5562 v8::Debug::SetMessageHandler2(NULL);
5563 CheckDebuggerUnloaded();
5564}
5565
5566
5567// Debug event listener which counts the script collected events.
5568int script_collected_count = 0;
5569static void DebugEventScriptCollectedEvent(v8::DebugEvent event,
5570 v8::Handle<v8::Object> exec_state,
5571 v8::Handle<v8::Object> event_data,
5572 v8::Handle<v8::Value> data) {
5573 // Count the number of breaks.
5574 if (event == v8::ScriptCollected) {
5575 script_collected_count++;
5576 }
5577}
5578
5579
5580// Test that scripts collected are reported through the debug event listener.
5581TEST(ScriptCollectedEvent) {
5582 break_point_hit_count = 0;
5583 script_collected_count = 0;
5584 v8::HandleScope scope;
5585 DebugLocalContext env;
5586
5587 // Request the loaded scripts to initialize the debugger script cache.
5588 Debug::GetLoadedScripts();
5589
5590 // Do garbage collection to ensure that only the script in this test will be
5591 // collected afterwards.
5592 Heap::CollectAllGarbage(false);
5593
5594 script_collected_count = 0;
5595 v8::Debug::SetDebugEventListener(DebugEventScriptCollectedEvent,
5596 v8::Undefined());
5597 {
5598 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run();
5599 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run();
5600 }
5601
5602 // Do garbage collection to collect the script above which is no longer
5603 // referenced.
5604 Heap::CollectAllGarbage(false);
5605
5606 CHECK_EQ(2, script_collected_count);
5607
5608 v8::Debug::SetDebugEventListener(NULL);
5609 CheckDebuggerUnloaded();
5610}
5611
5612
5613// Debug event listener which counts the script collected events.
5614int script_collected_message_count = 0;
5615static void ScriptCollectedMessageHandler(const v8::Debug::Message& message) {
5616 // Count the number of scripts collected.
5617 if (message.IsEvent() && message.GetEvent() == v8::ScriptCollected) {
5618 script_collected_message_count++;
5619 v8::Handle<v8::Context> context = message.GetEventContext();
5620 CHECK(context.IsEmpty());
5621 }
5622}
5623
5624
5625// Test that GetEventContext doesn't fail and return empty handle for
5626// ScriptCollected events.
5627TEST(ScriptCollectedEventContext) {
5628 script_collected_message_count = 0;
5629 v8::HandleScope scope;
5630
5631 { // Scope for the DebugLocalContext.
5632 DebugLocalContext env;
5633
5634 // Request the loaded scripts to initialize the debugger script cache.
5635 Debug::GetLoadedScripts();
5636
5637 // Do garbage collection to ensure that only the script in this test will be
5638 // collected afterwards.
5639 Heap::CollectAllGarbage(false);
5640
5641 v8::Debug::SetMessageHandler2(ScriptCollectedMessageHandler);
5642 {
5643 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run();
5644 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run();
5645 }
5646 }
5647
5648 // Do garbage collection to collect the script above which is no longer
5649 // referenced.
5650 Heap::CollectAllGarbage(false);
5651
5652 CHECK_EQ(2, script_collected_message_count);
5653
5654 v8::Debug::SetMessageHandler2(NULL);
5655}
5656
5657
5658// Debug event listener which counts the after compile events.
5659int after_compile_message_count = 0;
5660static void AfterCompileMessageHandler(const v8::Debug::Message& message) {
5661 // Count the number of scripts collected.
5662 if (message.IsEvent()) {
5663 if (message.GetEvent() == v8::AfterCompile) {
5664 after_compile_message_count++;
5665 } else if (message.GetEvent() == v8::Break) {
5666 SendContinueCommand();
5667 }
5668 }
5669}
5670
5671
5672// Tests that after compile event is sent as many times as there are scripts
5673// compiled.
5674TEST(AfterCompileMessageWhenMessageHandlerIsReset) {
5675 v8::HandleScope scope;
5676 DebugLocalContext env;
5677 after_compile_message_count = 0;
5678 const char* script = "var a=1";
5679
5680 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5681 v8::Script::Compile(v8::String::New(script))->Run();
5682 v8::Debug::SetMessageHandler2(NULL);
5683
5684 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5685 v8::Debug::DebugBreak();
5686 v8::Script::Compile(v8::String::New(script))->Run();
5687
5688 // Setting listener to NULL should cause debugger unload.
5689 v8::Debug::SetMessageHandler2(NULL);
5690 CheckDebuggerUnloaded();
5691
5692 // Compilation cache should be disabled when debugger is active.
5693 CHECK_EQ(2, after_compile_message_count);
5694}
5695
5696
5697// Tests that break event is sent when message handler is reset.
5698TEST(BreakMessageWhenMessageHandlerIsReset) {
5699 v8::HandleScope scope;
5700 DebugLocalContext env;
5701 after_compile_message_count = 0;
5702 const char* script = "function f() {};";
5703
5704 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5705 v8::Script::Compile(v8::String::New(script))->Run();
5706 v8::Debug::SetMessageHandler2(NULL);
5707
5708 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5709 v8::Debug::DebugBreak();
5710 v8::Local<v8::Function> f =
5711 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5712 f->Call(env->Global(), 0, NULL);
5713
5714 // Setting message handler to NULL should cause debugger unload.
5715 v8::Debug::SetMessageHandler2(NULL);
5716 CheckDebuggerUnloaded();
5717
5718 // Compilation cache should be disabled when debugger is active.
5719 CHECK_EQ(1, after_compile_message_count);
5720}
5721
5722
5723static int exception_event_count = 0;
5724static void ExceptionMessageHandler(const v8::Debug::Message& message) {
5725 if (message.IsEvent() && message.GetEvent() == v8::Exception) {
5726 exception_event_count++;
5727 SendContinueCommand();
5728 }
5729}
5730
5731
5732// Tests that exception event is sent when message handler is reset.
5733TEST(ExceptionMessageWhenMessageHandlerIsReset) {
5734 v8::HandleScope scope;
5735 DebugLocalContext env;
5736 exception_event_count = 0;
5737 const char* script = "function f() {throw new Error()};";
5738
5739 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5740 v8::Script::Compile(v8::String::New(script))->Run();
5741 v8::Debug::SetMessageHandler2(NULL);
5742
5743 v8::Debug::SetMessageHandler2(ExceptionMessageHandler);
5744 v8::Local<v8::Function> f =
5745 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
5746 f->Call(env->Global(), 0, NULL);
5747
5748 // Setting message handler to NULL should cause debugger unload.
5749 v8::Debug::SetMessageHandler2(NULL);
5750 CheckDebuggerUnloaded();
5751
5752 CHECK_EQ(1, exception_event_count);
5753}
5754
5755
5756// Tests after compile event is sent when there are some provisional
5757// breakpoints out of the scripts lines range.
5758TEST(ProvisionalBreakpointOnLineOutOfRange) {
5759 v8::HandleScope scope;
5760 DebugLocalContext env;
5761 env.ExposeDebug();
5762 const char* script = "function f() {};";
5763 const char* resource_name = "test_resource";
5764
5765 // Set a couple of provisional breakpoint on lines out of the script lines
5766 // range.
5767 int sbp1 = SetScriptBreakPointByNameFromJS(resource_name, 3,
5768 -1 /* no column */);
5769 int sbp2 = SetScriptBreakPointByNameFromJS(resource_name, 5, 5);
5770
5771 after_compile_message_count = 0;
5772 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
5773
5774 v8::ScriptOrigin origin(
5775 v8::String::New(resource_name),
5776 v8::Integer::New(10),
5777 v8::Integer::New(1));
5778 // Compile a script whose first line number is greater than the breakpoints'
5779 // lines.
5780 v8::Script::Compile(v8::String::New(script), &origin)->Run();
5781
5782 // If the script is compiled successfully there is exactly one after compile
5783 // event. In case of an exception in debugger code after compile event is not
5784 // sent.
5785 CHECK_EQ(1, after_compile_message_count);
5786
5787 ClearBreakPointFromJS(sbp1);
5788 ClearBreakPointFromJS(sbp2);
5789 v8::Debug::SetMessageHandler2(NULL);
5790}
5791
5792
5793static void BreakMessageHandler(const v8::Debug::Message& message) {
5794 if (message.IsEvent() && message.GetEvent() == v8::Break) {
5795 // Count the number of breaks.
5796 break_point_hit_count++;
5797
5798 v8::HandleScope scope;
5799 v8::Handle<v8::String> json = message.GetJSON();
5800
5801 SendContinueCommand();
5802 } else if (message.IsEvent() && message.GetEvent() == v8::AfterCompile) {
5803 v8::HandleScope scope;
5804
5805 bool is_debug_break = i::StackGuard::IsDebugBreak();
5806 // Force DebugBreak flag while serializer is working.
5807 i::StackGuard::DebugBreak();
5808
5809 // Force serialization to trigger some internal JS execution.
5810 v8::Handle<v8::String> json = message.GetJSON();
5811
5812 // Restore previous state.
5813 if (is_debug_break) {
5814 i::StackGuard::DebugBreak();
5815 } else {
5816 i::StackGuard::Continue(i::DEBUGBREAK);
5817 }
5818 }
5819}
5820
5821
5822// Test that if DebugBreak is forced it is ignored when code from
5823// debug-delay.js is executed.
5824TEST(NoDebugBreakInAfterCompileMessageHandler) {
5825 v8::HandleScope scope;
5826 DebugLocalContext env;
5827
5828 // Register a debug event listener which sets the break flag and counts.
5829 v8::Debug::SetMessageHandler2(BreakMessageHandler);
5830
5831 // Set the debug break flag.
5832 v8::Debug::DebugBreak();
5833
5834 // Create a function for testing stepping.
5835 const char* src = "function f() { eval('var x = 10;'); } ";
5836 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
5837
5838 // There should be only one break event.
5839 CHECK_EQ(1, break_point_hit_count);
5840
5841 // Set the debug break flag again.
5842 v8::Debug::DebugBreak();
5843 f->Call(env->Global(), 0, NULL);
5844 // There should be one more break event when the script is evaluated in 'f'.
5845 CHECK_EQ(2, break_point_hit_count);
5846
5847 // Get rid of the debug message handler.
5848 v8::Debug::SetMessageHandler2(NULL);
5849 CheckDebuggerUnloaded();
5850}
5851
5852
Leon Clarkee46be812010-01-19 14:06:41 +00005853static int counting_message_handler_counter;
5854
5855static void CountingMessageHandler(const v8::Debug::Message& message) {
5856 counting_message_handler_counter++;
5857}
5858
5859// Test that debug messages get processed when ProcessDebugMessages is called.
5860TEST(ProcessDebugMessages) {
5861 v8::HandleScope scope;
5862 DebugLocalContext env;
5863
5864 counting_message_handler_counter = 0;
5865
5866 v8::Debug::SetMessageHandler2(CountingMessageHandler);
5867
5868 const int kBufferSize = 1000;
5869 uint16_t buffer[kBufferSize];
5870 const char* scripts_command =
5871 "{\"seq\":0,"
5872 "\"type\":\"request\","
5873 "\"command\":\"scripts\"}";
5874
5875 // Send scripts command.
5876 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
5877
5878 CHECK_EQ(0, counting_message_handler_counter);
5879 v8::Debug::ProcessDebugMessages();
5880 // At least one message should come
5881 CHECK_GE(counting_message_handler_counter, 1);
5882
5883 counting_message_handler_counter = 0;
5884
5885 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
5886 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
5887 CHECK_EQ(0, counting_message_handler_counter);
5888 v8::Debug::ProcessDebugMessages();
5889 // At least two messages should come
5890 CHECK_GE(counting_message_handler_counter, 2);
5891
5892 // Get rid of the debug message handler.
5893 v8::Debug::SetMessageHandler2(NULL);
5894 CheckDebuggerUnloaded();
5895}
5896
5897
Leon Clarked91b9f72010-01-27 17:25:45 +00005898struct BracktraceData {
5899 static int frame_counter;
5900 static void MessageHandler(const v8::Debug::Message& message) {
5901 char print_buffer[1000];
5902 v8::String::Value json(message.GetJSON());
5903 Utf16ToAscii(*json, json.length(), print_buffer, 1000);
5904
5905 if (strstr(print_buffer, "backtrace") == NULL) {
5906 return;
5907 }
5908 frame_counter = GetTotalFramesInt(print_buffer);
5909 }
5910};
5911
5912int BracktraceData::frame_counter;
5913
5914
5915// Test that debug messages get processed when ProcessDebugMessages is called.
5916TEST(Backtrace) {
5917 v8::HandleScope scope;
5918 DebugLocalContext env;
5919
5920 v8::Debug::SetMessageHandler2(BracktraceData::MessageHandler);
5921
5922 const int kBufferSize = 1000;
5923 uint16_t buffer[kBufferSize];
5924 const char* scripts_command =
5925 "{\"seq\":0,"
5926 "\"type\":\"request\","
5927 "\"command\":\"backtrace\"}";
5928
5929 // Check backtrace from ProcessDebugMessages.
5930 BracktraceData::frame_counter = -10;
5931 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
5932 v8::Debug::ProcessDebugMessages();
5933 CHECK_EQ(BracktraceData::frame_counter, 0);
5934
5935 v8::Handle<v8::String> void0 = v8::String::New("void(0)");
5936 v8::Handle<v8::Script> script = v8::Script::Compile(void0, void0);
5937
5938 // Check backtrace from "void(0)" script.
5939 BracktraceData::frame_counter = -10;
5940 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
5941 script->Run();
5942 CHECK_EQ(BracktraceData::frame_counter, 1);
5943
5944 // Get rid of the debug message handler.
5945 v8::Debug::SetMessageHandler2(NULL);
5946 CheckDebuggerUnloaded();
5947}
5948
5949
Steve Blocka7e24c12009-10-30 11:49:00 +00005950TEST(GetMirror) {
5951 v8::HandleScope scope;
5952 DebugLocalContext env;
5953 v8::Handle<v8::Value> obj = v8::Debug::GetMirror(v8::String::New("hodja"));
5954 v8::Handle<v8::Function> run_test = v8::Handle<v8::Function>::Cast(
5955 v8::Script::New(
5956 v8::String::New(
5957 "function runTest(mirror) {"
5958 " return mirror.isString() && (mirror.length() == 5);"
5959 "}"
5960 ""
5961 "runTest;"))->Run());
5962 v8::Handle<v8::Value> result = run_test->Call(env->Global(), 1, &obj);
5963 CHECK(result->IsTrue());
5964}
Steve Blockd0582a62009-12-15 09:54:21 +00005965
5966
5967// Test that the debug break flag works with function.apply.
5968TEST(DebugBreakFunctionApply) {
5969 v8::HandleScope scope;
5970 DebugLocalContext env;
5971
5972 // Create a function for testing breaking in apply.
5973 v8::Local<v8::Function> foo = CompileFunction(
5974 &env,
5975 "function baz(x) { }"
5976 "function bar(x) { baz(); }"
5977 "function foo(){ bar.apply(this, [1]); }",
5978 "foo");
5979
5980 // Register a debug event listener which steps and counts.
5981 v8::Debug::SetDebugEventListener(DebugEventBreakMax);
5982
5983 // Set the debug break flag before calling the code using function.apply.
5984 v8::Debug::DebugBreak();
5985
5986 // Limit the number of debug breaks. This is a regression test for issue 493
5987 // where this test would enter an infinite loop.
5988 break_point_hit_count = 0;
5989 max_break_point_hit_count = 10000; // 10000 => infinite loop.
5990 foo->Call(env->Global(), 0, NULL);
5991
5992 // When keeping the debug break several break will happen.
5993 CHECK_EQ(3, break_point_hit_count);
5994
5995 v8::Debug::SetDebugEventListener(NULL);
5996 CheckDebuggerUnloaded();
5997}
5998
5999
6000v8::Handle<v8::Context> debugee_context;
6001v8::Handle<v8::Context> debugger_context;
6002
6003
6004// Property getter that checks that current and calling contexts
6005// are both the debugee contexts.
6006static v8::Handle<v8::Value> NamedGetterWithCallingContextCheck(
6007 v8::Local<v8::String> name,
6008 const v8::AccessorInfo& info) {
6009 CHECK_EQ(0, strcmp(*v8::String::AsciiValue(name), "a"));
6010 v8::Handle<v8::Context> current = v8::Context::GetCurrent();
6011 CHECK(current == debugee_context);
6012 CHECK(current != debugger_context);
6013 v8::Handle<v8::Context> calling = v8::Context::GetCalling();
6014 CHECK(calling == debugee_context);
6015 CHECK(calling != debugger_context);
6016 return v8::Int32::New(1);
6017}
6018
6019
6020// Debug event listener that checks if the first argument of a function is
6021// an object with property 'a' == 1. If the property has custom accessor
6022// this handler will eventually invoke it.
6023static void DebugEventGetAtgumentPropertyValue(
6024 v8::DebugEvent event,
6025 v8::Handle<v8::Object> exec_state,
6026 v8::Handle<v8::Object> event_data,
6027 v8::Handle<v8::Value> data) {
6028 if (event == v8::Break) {
6029 break_point_hit_count++;
6030 CHECK(debugger_context == v8::Context::GetCurrent());
6031 v8::Handle<v8::Function> func(v8::Function::Cast(*CompileRun(
6032 "(function(exec_state) {\n"
6033 " return (exec_state.frame(0).argumentValue(0).property('a').\n"
6034 " value().value() == 1);\n"
6035 "})")));
6036 const int argc = 1;
6037 v8::Handle<v8::Value> argv[argc] = { exec_state };
6038 v8::Handle<v8::Value> result = func->Call(exec_state, argc, argv);
6039 CHECK(result->IsTrue());
6040 }
6041}
6042
6043
6044TEST(CallingContextIsNotDebugContext) {
6045 // Create and enter a debugee context.
6046 v8::HandleScope scope;
6047 DebugLocalContext env;
6048 env.ExposeDebug();
6049
6050 // Save handles to the debugger and debugee contexts to be used in
6051 // NamedGetterWithCallingContextCheck.
6052 debugee_context = v8::Local<v8::Context>(*env);
6053 debugger_context = v8::Utils::ToLocal(Debug::debug_context());
6054
6055 // Create object with 'a' property accessor.
6056 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
6057 named->SetAccessor(v8::String::New("a"),
6058 NamedGetterWithCallingContextCheck);
6059 env->Global()->Set(v8::String::New("obj"),
6060 named->NewInstance());
6061
6062 // Register the debug event listener
6063 v8::Debug::SetDebugEventListener(DebugEventGetAtgumentPropertyValue);
6064
6065 // Create a function that invokes debugger.
6066 v8::Local<v8::Function> foo = CompileFunction(
6067 &env,
6068 "function bar(x) { debugger; }"
6069 "function foo(){ bar(obj); }",
6070 "foo");
6071
6072 break_point_hit_count = 0;
6073 foo->Call(env->Global(), 0, NULL);
6074 CHECK_EQ(1, break_point_hit_count);
6075
6076 v8::Debug::SetDebugEventListener(NULL);
6077 debugee_context = v8::Handle<v8::Context>();
6078 debugger_context = v8::Handle<v8::Context>();
6079 CheckDebuggerUnloaded();
6080}