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