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