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