blob: d8c1876a9fd4cb5765e69d2a10d0730a29e14b69 [file] [log] [blame]
Ben Murdoch257744e2011-11-30 15:57:28 +00001// Copyright 2011 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() {
Steve Block44f0eee2011-05-26 01:26:41 +0100146 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000147 // Expose the debug context global object in the global object for testing.
Steve Block44f0eee2011-05-26 01:26:41 +0100148 debug->Load();
149 debug->debug_context()->set_security_token(
Steve Blocka7e24c12009-10-30 11:49:00 +0000150 v8::Utils::OpenHandle(*context_)->security_token());
151
152 Handle<JSGlobalProxy> global(Handle<JSGlobalProxy>::cast(
153 v8::Utils::OpenHandle(*context_->Global())));
154 Handle<v8::internal::String> debug_string =
Steve Block44f0eee2011-05-26 01:26:41 +0100155 FACTORY->LookupAsciiSymbol("debug");
Steve Blocka7e24c12009-10-30 11:49:00 +0000156 SetProperty(global, debug_string,
Steve Block44f0eee2011-05-26 01:26:41 +0100157 Handle<Object>(debug->debug_context()->global_proxy()), DONT_ENUM,
Ben Murdoche0cee9b2011-05-25 10:26:03 +0100158 ::v8::internal::kNonStrictMode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000159 }
160 private:
161 v8::Persistent<v8::Context> context_;
162};
163
164
165// --- H e l p e r F u n c t i o n s
166
167
168// Compile and run the supplied source and return the fequested function.
169static v8::Local<v8::Function> CompileFunction(DebugLocalContext* env,
170 const char* source,
171 const char* function_name) {
172 v8::Script::Compile(v8::String::New(source))->Run();
173 return v8::Local<v8::Function>::Cast(
174 (*env)->Global()->Get(v8::String::New(function_name)));
175}
176
177
178// Compile and run the supplied source and return the requested function.
179static v8::Local<v8::Function> CompileFunction(const char* source,
180 const char* function_name) {
181 v8::Script::Compile(v8::String::New(source))->Run();
182 return v8::Local<v8::Function>::Cast(
183 v8::Context::GetCurrent()->Global()->Get(v8::String::New(function_name)));
184}
185
186
Steve Blocka7e24c12009-10-30 11:49:00 +0000187// Is there any debug info for the function?
188static bool HasDebugInfo(v8::Handle<v8::Function> fun) {
189 Handle<v8::internal::JSFunction> f = v8::Utils::OpenHandle(*fun);
190 Handle<v8::internal::SharedFunctionInfo> shared(f->shared());
191 return Debug::HasDebugInfo(shared);
192}
193
194
195// Set a break point in a function and return the associated break point
196// number.
197static int SetBreakPoint(Handle<v8::internal::JSFunction> fun, int position) {
198 static int break_point = 0;
199 Handle<v8::internal::SharedFunctionInfo> shared(fun->shared());
Steve Block44f0eee2011-05-26 01:26:41 +0100200 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
201 debug->SetBreakPoint(
Kristian Monsen9dcf7e22010-06-28 14:14:28 +0100202 shared,
203 Handle<Object>(v8::internal::Smi::FromInt(++break_point)),
204 &position);
Steve Blocka7e24c12009-10-30 11:49:00 +0000205 return break_point;
206}
207
208
209// Set a break point in a function and return the associated break point
210// number.
211static int SetBreakPoint(v8::Handle<v8::Function> fun, int position) {
212 return SetBreakPoint(v8::Utils::OpenHandle(*fun), position);
213}
214
215
216// Set a break point in a function using the Debug object and return the
217// associated break point number.
218static int SetBreakPointFromJS(const char* function_name,
219 int line, int position) {
220 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
221 OS::SNPrintF(buffer,
222 "debug.Debug.setBreakPoint(%s,%d,%d)",
223 function_name, line, position);
224 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
225 v8::Handle<v8::String> str = v8::String::New(buffer.start());
226 return v8::Script::Compile(str)->Run()->Int32Value();
227}
228
229
230// Set a break point in a script identified by id using the global Debug object.
231static int SetScriptBreakPointByIdFromJS(int script_id, int line, int column) {
232 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
233 if (column >= 0) {
234 // Column specified set script break point on precise location.
235 OS::SNPrintF(buffer,
236 "debug.Debug.setScriptBreakPointById(%d,%d,%d)",
237 script_id, line, column);
238 } else {
239 // Column not specified set script break point on line.
240 OS::SNPrintF(buffer,
241 "debug.Debug.setScriptBreakPointById(%d,%d)",
242 script_id, line);
243 }
244 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
245 {
246 v8::TryCatch try_catch;
247 v8::Handle<v8::String> str = v8::String::New(buffer.start());
248 v8::Handle<v8::Value> value = v8::Script::Compile(str)->Run();
249 CHECK(!try_catch.HasCaught());
250 return value->Int32Value();
251 }
252}
253
254
255// Set a break point in a script identified by name using the global Debug
256// object.
257static int SetScriptBreakPointByNameFromJS(const char* script_name,
258 int line, int column) {
259 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
260 if (column >= 0) {
261 // Column specified set script break point on precise location.
262 OS::SNPrintF(buffer,
263 "debug.Debug.setScriptBreakPointByName(\"%s\",%d,%d)",
264 script_name, line, column);
265 } else {
266 // Column not specified set script break point on line.
267 OS::SNPrintF(buffer,
268 "debug.Debug.setScriptBreakPointByName(\"%s\",%d)",
269 script_name, line);
270 }
271 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
272 {
273 v8::TryCatch try_catch;
274 v8::Handle<v8::String> str = v8::String::New(buffer.start());
275 v8::Handle<v8::Value> value = v8::Script::Compile(str)->Run();
276 CHECK(!try_catch.HasCaught());
277 return value->Int32Value();
278 }
279}
280
281
282// Clear a break point.
283static void ClearBreakPoint(int break_point) {
Steve Block44f0eee2011-05-26 01:26:41 +0100284 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
285 debug->ClearBreakPoint(
Steve Blocka7e24c12009-10-30 11:49:00 +0000286 Handle<Object>(v8::internal::Smi::FromInt(break_point)));
287}
288
289
290// Clear a break point using the global Debug object.
291static void ClearBreakPointFromJS(int break_point_number) {
292 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
293 OS::SNPrintF(buffer,
294 "debug.Debug.clearBreakPoint(%d)",
295 break_point_number);
296 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
297 v8::Script::Compile(v8::String::New(buffer.start()))->Run();
298}
299
300
301static void EnableScriptBreakPointFromJS(int break_point_number) {
302 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
303 OS::SNPrintF(buffer,
304 "debug.Debug.enableScriptBreakPoint(%d)",
305 break_point_number);
306 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
307 v8::Script::Compile(v8::String::New(buffer.start()))->Run();
308}
309
310
311static void DisableScriptBreakPointFromJS(int break_point_number) {
312 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
313 OS::SNPrintF(buffer,
314 "debug.Debug.disableScriptBreakPoint(%d)",
315 break_point_number);
316 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
317 v8::Script::Compile(v8::String::New(buffer.start()))->Run();
318}
319
320
321static void ChangeScriptBreakPointConditionFromJS(int break_point_number,
322 const char* condition) {
323 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
324 OS::SNPrintF(buffer,
325 "debug.Debug.changeScriptBreakPointCondition(%d, \"%s\")",
326 break_point_number, condition);
327 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
328 v8::Script::Compile(v8::String::New(buffer.start()))->Run();
329}
330
331
332static void ChangeScriptBreakPointIgnoreCountFromJS(int break_point_number,
333 int ignoreCount) {
334 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
335 OS::SNPrintF(buffer,
336 "debug.Debug.changeScriptBreakPointIgnoreCount(%d, %d)",
337 break_point_number, ignoreCount);
338 buffer[SMALL_STRING_BUFFER_SIZE - 1] = '\0';
339 v8::Script::Compile(v8::String::New(buffer.start()))->Run();
340}
341
342
343// Change break on exception.
344static void ChangeBreakOnException(bool caught, bool uncaught) {
Steve Block44f0eee2011-05-26 01:26:41 +0100345 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
346 debug->ChangeBreakOnException(v8::internal::BreakException, caught);
347 debug->ChangeBreakOnException(v8::internal::BreakUncaughtException, uncaught);
Steve Blocka7e24c12009-10-30 11:49:00 +0000348}
349
350
351// Change break on exception using the global Debug object.
352static void ChangeBreakOnExceptionFromJS(bool caught, bool uncaught) {
353 if (caught) {
354 v8::Script::Compile(
355 v8::String::New("debug.Debug.setBreakOnException()"))->Run();
356 } else {
357 v8::Script::Compile(
358 v8::String::New("debug.Debug.clearBreakOnException()"))->Run();
359 }
360 if (uncaught) {
361 v8::Script::Compile(
362 v8::String::New("debug.Debug.setBreakOnUncaughtException()"))->Run();
363 } else {
364 v8::Script::Compile(
365 v8::String::New("debug.Debug.clearBreakOnUncaughtException()"))->Run();
366 }
367}
368
369
370// Prepare to step to next break location.
371static void PrepareStep(StepAction step_action) {
Steve Block44f0eee2011-05-26 01:26:41 +0100372 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
373 debug->PrepareStep(step_action, 1);
Steve Blocka7e24c12009-10-30 11:49:00 +0000374}
375
376
377// This function is in namespace v8::internal to be friend with class
378// v8::internal::Debug.
379namespace v8 {
380namespace internal {
381
382// Collect the currently debugged functions.
383Handle<FixedArray> GetDebuggedFunctions() {
Steve Block44f0eee2011-05-26 01:26:41 +0100384 Debug* debug = Isolate::Current()->debug();
385
386 v8::internal::DebugInfoListNode* node = debug->debug_info_list_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000387
388 // Find the number of debugged functions.
389 int count = 0;
390 while (node) {
391 count++;
392 node = node->next();
393 }
394
395 // Allocate array for the debugged functions
396 Handle<FixedArray> debugged_functions =
Steve Block44f0eee2011-05-26 01:26:41 +0100397 FACTORY->NewFixedArray(count);
Steve Blocka7e24c12009-10-30 11:49:00 +0000398
399 // Run through the debug info objects and collect all functions.
400 count = 0;
401 while (node) {
402 debugged_functions->set(count++, *node->debug_info());
403 node = node->next();
404 }
405
406 return debugged_functions;
407}
408
409
410static Handle<Code> ComputeCallDebugBreak(int argc) {
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100411 CALL_HEAP_FUNCTION(
Steve Block44f0eee2011-05-26 01:26:41 +0100412 v8::internal::Isolate::Current(),
413 v8::internal::Isolate::Current()->stub_cache()->ComputeCallDebugBreak(
414 argc, Code::CALL_IC),
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100415 Code);
Steve Blocka7e24c12009-10-30 11:49:00 +0000416}
417
418
419// Check that the debugger has been fully unloaded.
420void CheckDebuggerUnloaded(bool check_functions) {
421 // Check that the debugger context is cleared and that there is no debug
422 // information stored for the debugger.
Steve Block44f0eee2011-05-26 01:26:41 +0100423 CHECK(Isolate::Current()->debug()->debug_context().is_null());
424 CHECK_EQ(NULL, Isolate::Current()->debug()->debug_info_list_);
Steve Blocka7e24c12009-10-30 11:49:00 +0000425
426 // Collect garbage to ensure weak handles are cleared.
Steve Block44f0eee2011-05-26 01:26:41 +0100427 HEAP->CollectAllGarbage(false);
428 HEAP->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +0000429
430 // Iterate the head and check that there are no debugger related objects left.
431 HeapIterator iterator;
Leon Clarked91b9f72010-01-27 17:25:45 +0000432 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000433 CHECK(!obj->IsDebugInfo());
434 CHECK(!obj->IsBreakPointInfo());
435
436 // If deep check of functions is requested check that no debug break code
437 // is left in all functions.
438 if (check_functions) {
439 if (obj->IsJSFunction()) {
440 JSFunction* fun = JSFunction::cast(obj);
441 for (RelocIterator it(fun->shared()->code()); !it.done(); it.next()) {
442 RelocInfo::Mode rmode = it.rinfo()->rmode();
443 if (RelocInfo::IsCodeTarget(rmode)) {
444 CHECK(!Debug::IsDebugBreak(it.rinfo()->target_address()));
445 } else if (RelocInfo::IsJSReturn(rmode)) {
446 CHECK(!Debug::IsDebugBreakAtReturn(it.rinfo()));
447 }
448 }
449 }
450 }
451 }
452}
453
454
Steve Block6ded16b2010-05-10 14:33:55 +0100455void ForceUnloadDebugger() {
Steve Block44f0eee2011-05-26 01:26:41 +0100456 Isolate::Current()->debugger()->never_unload_debugger_ = false;
457 Isolate::Current()->debugger()->UnloadDebugger();
Steve Block6ded16b2010-05-10 14:33:55 +0100458}
459
460
Steve Blocka7e24c12009-10-30 11:49:00 +0000461} } // namespace v8::internal
462
463
464// Check that the debugger has been fully unloaded.
465static void CheckDebuggerUnloaded(bool check_functions = false) {
Leon Clarkee46be812010-01-19 14:06:41 +0000466 // Let debugger to unload itself synchronously
467 v8::Debug::ProcessDebugMessages();
468
Steve Blocka7e24c12009-10-30 11:49:00 +0000469 v8::internal::CheckDebuggerUnloaded(check_functions);
470}
471
472
473// Inherit from BreakLocationIterator to get access to protected parts for
474// testing.
475class TestBreakLocationIterator: public v8::internal::BreakLocationIterator {
476 public:
477 explicit TestBreakLocationIterator(Handle<v8::internal::DebugInfo> debug_info)
478 : BreakLocationIterator(debug_info, v8::internal::SOURCE_BREAK_LOCATIONS) {}
479 v8::internal::RelocIterator* it() { return reloc_iterator_; }
480 v8::internal::RelocIterator* it_original() {
481 return reloc_iterator_original_;
482 }
483};
484
485
486// Compile a function, set a break point and check that the call at the break
487// location in the code is the expected debug_break function.
488void CheckDebugBreakFunction(DebugLocalContext* env,
489 const char* source, const char* name,
490 int position, v8::internal::RelocInfo::Mode mode,
491 Code* debug_break) {
Steve Block44f0eee2011-05-26 01:26:41 +0100492 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
493
Steve Blocka7e24c12009-10-30 11:49:00 +0000494 // Create function and set the break point.
495 Handle<v8::internal::JSFunction> fun = v8::Utils::OpenHandle(
496 *CompileFunction(env, source, name));
497 int bp = SetBreakPoint(fun, position);
498
499 // Check that the debug break function is as expected.
500 Handle<v8::internal::SharedFunctionInfo> shared(fun->shared());
501 CHECK(Debug::HasDebugInfo(shared));
502 TestBreakLocationIterator it1(Debug::GetDebugInfo(shared));
503 it1.FindBreakLocationFromPosition(position);
Ben Murdoch257744e2011-11-30 15:57:28 +0000504 v8::internal::RelocInfo::Mode actual_mode = it1.it()->rinfo()->rmode();
505 if (actual_mode == v8::internal::RelocInfo::CODE_TARGET_WITH_ID) {
506 actual_mode = v8::internal::RelocInfo::CODE_TARGET;
507 }
508 CHECK_EQ(mode, actual_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000509 if (mode != v8::internal::RelocInfo::JS_RETURN) {
510 CHECK_EQ(debug_break,
511 Code::GetCodeFromTargetAddress(it1.it()->rinfo()->target_address()));
512 } else {
513 CHECK(Debug::IsDebugBreakAtReturn(it1.it()->rinfo()));
514 }
515
516 // Clear the break point and check that the debug break function is no longer
517 // there
518 ClearBreakPoint(bp);
Steve Block44f0eee2011-05-26 01:26:41 +0100519 CHECK(!debug->HasDebugInfo(shared));
520 CHECK(debug->EnsureDebugInfo(shared));
Steve Blocka7e24c12009-10-30 11:49:00 +0000521 TestBreakLocationIterator it2(Debug::GetDebugInfo(shared));
522 it2.FindBreakLocationFromPosition(position);
Ben Murdoch257744e2011-11-30 15:57:28 +0000523 actual_mode = it2.it()->rinfo()->rmode();
524 if (actual_mode == v8::internal::RelocInfo::CODE_TARGET_WITH_ID) {
525 actual_mode = v8::internal::RelocInfo::CODE_TARGET;
526 }
527 CHECK_EQ(mode, actual_mode);
Steve Blocka7e24c12009-10-30 11:49:00 +0000528 if (mode == v8::internal::RelocInfo::JS_RETURN) {
529 CHECK(!Debug::IsDebugBreakAtReturn(it2.it()->rinfo()));
530 }
531}
532
533
534// --- D e b u g E v e n t H a n d l e r s
535// ---
536// --- The different tests uses a number of debug event handlers.
537// ---
538
539
Ben Murdochb0fe1622011-05-05 13:52:32 +0100540// Source for the JavaScript function which picks out the function
541// name of a frame.
Steve Blocka7e24c12009-10-30 11:49:00 +0000542const char* frame_function_name_source =
Ben Murdochb0fe1622011-05-05 13:52:32 +0100543 "function frame_function_name(exec_state, frame_number) {"
544 " return exec_state.frame(frame_number).func().name();"
Steve Blocka7e24c12009-10-30 11:49:00 +0000545 "}";
546v8::Local<v8::Function> frame_function_name;
547
548
Ben Murdochb0fe1622011-05-05 13:52:32 +0100549// Source for the JavaScript function which pick out the name of the
550// first argument of a frame.
551const char* frame_argument_name_source =
552 "function frame_argument_name(exec_state, frame_number) {"
553 " return exec_state.frame(frame_number).argumentName(0);"
554 "}";
555v8::Local<v8::Function> frame_argument_name;
556
557
558// Source for the JavaScript function which pick out the value of the
559// first argument of a frame.
560const char* frame_argument_value_source =
561 "function frame_argument_value(exec_state, frame_number) {"
562 " return exec_state.frame(frame_number).argumentValue(0).value_;"
563 "}";
564v8::Local<v8::Function> frame_argument_value;
565
566
567// Source for the JavaScript function which pick out the name of the
568// first argument of a frame.
569const char* frame_local_name_source =
570 "function frame_local_name(exec_state, frame_number) {"
571 " return exec_state.frame(frame_number).localName(0);"
572 "}";
573v8::Local<v8::Function> frame_local_name;
574
575
576// Source for the JavaScript function which pick out the value of the
577// first argument of a frame.
578const char* frame_local_value_source =
579 "function frame_local_value(exec_state, frame_number) {"
580 " return exec_state.frame(frame_number).localValue(0).value_;"
581 "}";
582v8::Local<v8::Function> frame_local_value;
583
584
585// Source for the JavaScript function which picks out the source line for the
Steve Blocka7e24c12009-10-30 11:49:00 +0000586// top frame.
587const char* frame_source_line_source =
588 "function frame_source_line(exec_state) {"
589 " return exec_state.frame(0).sourceLine();"
590 "}";
591v8::Local<v8::Function> frame_source_line;
592
593
Ben Murdochb0fe1622011-05-05 13:52:32 +0100594// Source for the JavaScript function which picks out the source column for the
Steve Blocka7e24c12009-10-30 11:49:00 +0000595// top frame.
596const char* frame_source_column_source =
597 "function frame_source_column(exec_state) {"
598 " return exec_state.frame(0).sourceColumn();"
599 "}";
600v8::Local<v8::Function> frame_source_column;
601
602
Ben Murdochb0fe1622011-05-05 13:52:32 +0100603// Source for the JavaScript function which picks out the script name for the
Steve Blocka7e24c12009-10-30 11:49:00 +0000604// top frame.
605const char* frame_script_name_source =
606 "function frame_script_name(exec_state) {"
607 " return exec_state.frame(0).func().script().name();"
608 "}";
609v8::Local<v8::Function> frame_script_name;
610
611
Ben Murdochb0fe1622011-05-05 13:52:32 +0100612// Source for the JavaScript function which picks out the script data for the
Steve Blocka7e24c12009-10-30 11:49:00 +0000613// top frame.
614const char* frame_script_data_source =
615 "function frame_script_data(exec_state) {"
616 " return exec_state.frame(0).func().script().data();"
617 "}";
618v8::Local<v8::Function> frame_script_data;
619
620
Ben Murdochb0fe1622011-05-05 13:52:32 +0100621// Source for the JavaScript function which picks out the script data from
Andrei Popescu402d9372010-02-26 13:31:12 +0000622// AfterCompile event
623const char* compiled_script_data_source =
624 "function compiled_script_data(event_data) {"
625 " return event_data.script().data();"
626 "}";
627v8::Local<v8::Function> compiled_script_data;
628
629
Ben Murdochb0fe1622011-05-05 13:52:32 +0100630// Source for the JavaScript function which returns the number of frames.
Steve Blocka7e24c12009-10-30 11:49:00 +0000631static const char* frame_count_source =
632 "function frame_count(exec_state) {"
633 " return exec_state.frameCount();"
634 "}";
635v8::Handle<v8::Function> frame_count;
636
637
638// Global variable to store the last function hit - used by some tests.
639char last_function_hit[80];
640
641// Global variable to store the name and data for last script hit - used by some
642// tests.
643char last_script_name_hit[80];
644char last_script_data_hit[80];
645
646// Global variables to store the last source position - used by some tests.
647int last_source_line = -1;
648int last_source_column = -1;
649
650// Debug event handler which counts the break points which have been hit.
651int break_point_hit_count = 0;
652static void DebugEventBreakPointHitCount(v8::DebugEvent event,
653 v8::Handle<v8::Object> exec_state,
654 v8::Handle<v8::Object> event_data,
655 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100656 Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000657 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100658 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000659
660 // Count the number of breaks.
661 if (event == v8::Break) {
662 break_point_hit_count++;
663 if (!frame_function_name.IsEmpty()) {
664 // Get the name of the function.
Ben Murdochb0fe1622011-05-05 13:52:32 +0100665 const int argc = 2;
666 v8::Handle<v8::Value> argv[argc] = { exec_state, v8::Integer::New(0) };
Steve Blocka7e24c12009-10-30 11:49:00 +0000667 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
668 argc, argv);
669 if (result->IsUndefined()) {
670 last_function_hit[0] = '\0';
671 } else {
672 CHECK(result->IsString());
673 v8::Handle<v8::String> function_name(result->ToString());
674 function_name->WriteAscii(last_function_hit);
675 }
676 }
677
678 if (!frame_source_line.IsEmpty()) {
679 // Get the source line.
680 const int argc = 1;
681 v8::Handle<v8::Value> argv[argc] = { exec_state };
682 v8::Handle<v8::Value> result = frame_source_line->Call(exec_state,
683 argc, argv);
684 CHECK(result->IsNumber());
685 last_source_line = result->Int32Value();
686 }
687
688 if (!frame_source_column.IsEmpty()) {
689 // Get the source column.
690 const int argc = 1;
691 v8::Handle<v8::Value> argv[argc] = { exec_state };
692 v8::Handle<v8::Value> result = frame_source_column->Call(exec_state,
693 argc, argv);
694 CHECK(result->IsNumber());
695 last_source_column = result->Int32Value();
696 }
697
698 if (!frame_script_name.IsEmpty()) {
699 // Get the script name of the function script.
700 const int argc = 1;
701 v8::Handle<v8::Value> argv[argc] = { exec_state };
702 v8::Handle<v8::Value> result = frame_script_name->Call(exec_state,
703 argc, argv);
704 if (result->IsUndefined()) {
705 last_script_name_hit[0] = '\0';
706 } else {
707 CHECK(result->IsString());
708 v8::Handle<v8::String> script_name(result->ToString());
709 script_name->WriteAscii(last_script_name_hit);
710 }
711 }
712
713 if (!frame_script_data.IsEmpty()) {
714 // Get the script data of the function script.
715 const int argc = 1;
716 v8::Handle<v8::Value> argv[argc] = { exec_state };
717 v8::Handle<v8::Value> result = frame_script_data->Call(exec_state,
718 argc, argv);
719 if (result->IsUndefined()) {
720 last_script_data_hit[0] = '\0';
721 } else {
722 result = result->ToString();
723 CHECK(result->IsString());
724 v8::Handle<v8::String> script_data(result->ToString());
725 script_data->WriteAscii(last_script_data_hit);
726 }
727 }
Andrei Popescu402d9372010-02-26 13:31:12 +0000728 } else if (event == v8::AfterCompile && !compiled_script_data.IsEmpty()) {
729 const int argc = 1;
730 v8::Handle<v8::Value> argv[argc] = { event_data };
731 v8::Handle<v8::Value> result = compiled_script_data->Call(exec_state,
732 argc, argv);
733 if (result->IsUndefined()) {
734 last_script_data_hit[0] = '\0';
735 } else {
736 result = result->ToString();
737 CHECK(result->IsString());
738 v8::Handle<v8::String> script_data(result->ToString());
739 script_data->WriteAscii(last_script_data_hit);
740 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000741 }
742}
743
744
745// Debug event handler which counts a number of events and collects the stack
746// height if there is a function compiled for that.
747int exception_hit_count = 0;
748int uncaught_exception_hit_count = 0;
749int last_js_stack_height = -1;
750
751static void DebugEventCounterClear() {
752 break_point_hit_count = 0;
753 exception_hit_count = 0;
754 uncaught_exception_hit_count = 0;
755}
756
757static void DebugEventCounter(v8::DebugEvent event,
758 v8::Handle<v8::Object> exec_state,
759 v8::Handle<v8::Object> event_data,
760 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100761 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
762
Steve Blocka7e24c12009-10-30 11:49:00 +0000763 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100764 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000765
766 // Count the number of breaks.
767 if (event == v8::Break) {
768 break_point_hit_count++;
769 } else if (event == v8::Exception) {
770 exception_hit_count++;
771
772 // Check whether the exception was uncaught.
773 v8::Local<v8::String> fun_name = v8::String::New("uncaught");
774 v8::Local<v8::Function> fun =
775 v8::Function::Cast(*event_data->Get(fun_name));
776 v8::Local<v8::Value> result = *fun->Call(event_data, 0, NULL);
777 if (result->IsTrue()) {
778 uncaught_exception_hit_count++;
779 }
780 }
781
782 // Collect the JavsScript stack height if the function frame_count is
783 // compiled.
784 if (!frame_count.IsEmpty()) {
785 static const int kArgc = 1;
786 v8::Handle<v8::Value> argv[kArgc] = { exec_state };
787 // Using exec_state as receiver is just to have a receiver.
788 v8::Handle<v8::Value> result = frame_count->Call(exec_state, kArgc, argv);
789 last_js_stack_height = result->Int32Value();
790 }
791}
792
793
794// Debug event handler which evaluates a number of expressions when a break
795// point is hit. Each evaluated expression is compared with an expected value.
796// For this debug event handler to work the following two global varaibles
797// must be initialized.
798// checks: An array of expressions and expected results
799// evaluate_check_function: A JavaScript function (see below)
800
801// Structure for holding checks to do.
802struct EvaluateCheck {
803 const char* expr; // An expression to evaluate when a break point is hit.
804 v8::Handle<v8::Value> expected; // The expected result.
805};
806// Array of checks to do.
807struct EvaluateCheck* checks = NULL;
808// Source for The JavaScript function which can do the evaluation when a break
809// point is hit.
810const char* evaluate_check_source =
811 "function evaluate_check(exec_state, expr, expected) {"
812 " return exec_state.frame(0).evaluate(expr).value() === expected;"
813 "}";
814v8::Local<v8::Function> evaluate_check_function;
815
816// The actual debug event described by the longer comment above.
817static void DebugEventEvaluate(v8::DebugEvent event,
818 v8::Handle<v8::Object> exec_state,
819 v8::Handle<v8::Object> event_data,
820 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100821 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000822 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100823 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000824
825 if (event == v8::Break) {
826 for (int i = 0; checks[i].expr != NULL; i++) {
827 const int argc = 3;
828 v8::Handle<v8::Value> argv[argc] = { exec_state,
829 v8::String::New(checks[i].expr),
830 checks[i].expected };
831 v8::Handle<v8::Value> result =
832 evaluate_check_function->Call(exec_state, argc, argv);
833 if (!result->IsTrue()) {
834 v8::String::AsciiValue ascii(checks[i].expected->ToString());
835 V8_Fatal(__FILE__, __LINE__, "%s != %s", checks[i].expr, *ascii);
836 }
837 }
838 }
839}
840
841
842// This debug event listener removes a breakpoint in a function
843int debug_event_remove_break_point = 0;
844static void DebugEventRemoveBreakPoint(v8::DebugEvent event,
845 v8::Handle<v8::Object> exec_state,
846 v8::Handle<v8::Object> event_data,
847 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100848 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000849 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100850 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000851
852 if (event == v8::Break) {
853 break_point_hit_count++;
854 v8::Handle<v8::Function> fun = v8::Handle<v8::Function>::Cast(data);
855 ClearBreakPoint(debug_event_remove_break_point);
856 }
857}
858
859
860// Debug event handler which counts break points hit and performs a step
861// afterwards.
862StepAction step_action = StepIn; // Step action to perform when stepping.
863static void DebugEventStep(v8::DebugEvent event,
864 v8::Handle<v8::Object> exec_state,
865 v8::Handle<v8::Object> event_data,
866 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100867 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000868 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100869 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000870
871 if (event == v8::Break) {
872 break_point_hit_count++;
873 PrepareStep(step_action);
874 }
875}
876
877
878// Debug event handler which counts break points hit and performs a step
879// afterwards. For each call the expected function is checked.
880// For this debug event handler to work the following two global varaibles
881// must be initialized.
882// expected_step_sequence: An array of the expected function call sequence.
883// frame_function_name: A JavaScript function (see below).
884
885// String containing the expected function call sequence. Note: this only works
886// if functions have name length of one.
887const char* expected_step_sequence = NULL;
888
889// The actual debug event described by the longer comment above.
890static void DebugEventStepSequence(v8::DebugEvent event,
891 v8::Handle<v8::Object> exec_state,
892 v8::Handle<v8::Object> event_data,
893 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100894 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000895 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100896 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000897
898 if (event == v8::Break || event == v8::Exception) {
899 // Check that the current function is the expected.
900 CHECK(break_point_hit_count <
Steve Blockd0582a62009-12-15 09:54:21 +0000901 StrLength(expected_step_sequence));
Ben Murdochb0fe1622011-05-05 13:52:32 +0100902 const int argc = 2;
903 v8::Handle<v8::Value> argv[argc] = { exec_state, v8::Integer::New(0) };
Steve Blocka7e24c12009-10-30 11:49:00 +0000904 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
905 argc, argv);
906 CHECK(result->IsString());
907 v8::String::AsciiValue function_name(result->ToString());
Steve Blockd0582a62009-12-15 09:54:21 +0000908 CHECK_EQ(1, StrLength(*function_name));
Steve Blocka7e24c12009-10-30 11:49:00 +0000909 CHECK_EQ((*function_name)[0],
910 expected_step_sequence[break_point_hit_count]);
911
912 // Perform step.
913 break_point_hit_count++;
914 PrepareStep(step_action);
915 }
916}
917
918
919// Debug event handler which performs a garbage collection.
920static void DebugEventBreakPointCollectGarbage(
921 v8::DebugEvent event,
922 v8::Handle<v8::Object> exec_state,
923 v8::Handle<v8::Object> event_data,
924 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100925 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000926 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100927 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000928
929 // Perform a garbage collection when break point is hit and continue. Based
930 // on the number of break points hit either scavenge or mark compact
931 // collector is used.
932 if (event == v8::Break) {
933 break_point_hit_count++;
934 if (break_point_hit_count % 2 == 0) {
935 // Scavenge.
Steve Block44f0eee2011-05-26 01:26:41 +0100936 HEAP->CollectGarbage(v8::internal::NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000937 } else {
Kristian Monsen80d68ea2010-09-08 11:05:35 +0100938 // Mark sweep compact.
Steve Block44f0eee2011-05-26 01:26:41 +0100939 HEAP->CollectAllGarbage(true);
Steve Blocka7e24c12009-10-30 11:49:00 +0000940 }
941 }
942}
943
944
945// Debug event handler which re-issues a debug break and calls the garbage
946// collector to have the heap verified.
947static void DebugEventBreak(v8::DebugEvent event,
948 v8::Handle<v8::Object> exec_state,
949 v8::Handle<v8::Object> event_data,
950 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100951 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +0000952 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100953 CHECK_NE(debug->break_id(), 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000954
955 if (event == v8::Break) {
956 // Count the number of breaks.
957 break_point_hit_count++;
958
959 // Run the garbage collector to enforce heap verification if option
960 // --verify-heap is set.
Steve Block44f0eee2011-05-26 01:26:41 +0100961 HEAP->CollectGarbage(v8::internal::NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +0000962
963 // Set the break flag again to come back here as soon as possible.
964 v8::Debug::DebugBreak();
965 }
966}
967
968
Steve Blockd0582a62009-12-15 09:54:21 +0000969// Debug event handler which re-issues a debug break until a limit has been
970// reached.
971int max_break_point_hit_count = 0;
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800972bool terminate_after_max_break_point_hit = false;
Steve Blockd0582a62009-12-15 09:54:21 +0000973static void DebugEventBreakMax(v8::DebugEvent event,
974 v8::Handle<v8::Object> exec_state,
975 v8::Handle<v8::Object> event_data,
976 v8::Handle<v8::Value> data) {
Steve Block44f0eee2011-05-26 01:26:41 +0100977 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blockd0582a62009-12-15 09:54:21 +0000978 // When hitting a debug event listener there must be a break set.
Steve Block44f0eee2011-05-26 01:26:41 +0100979 CHECK_NE(debug->break_id(), 0);
Steve Blockd0582a62009-12-15 09:54:21 +0000980
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800981 if (event == v8::Break) {
982 if (break_point_hit_count < max_break_point_hit_count) {
983 // Count the number of breaks.
984 break_point_hit_count++;
Steve Blockd0582a62009-12-15 09:54:21 +0000985
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -0800986 // Set the break flag again to come back here as soon as possible.
987 v8::Debug::DebugBreak();
988 } else if (terminate_after_max_break_point_hit) {
989 // Terminate execution after the last break if requested.
990 v8::V8::TerminateExecution();
991 }
Steve Blockd0582a62009-12-15 09:54:21 +0000992 }
993}
994
995
Steve Blocka7e24c12009-10-30 11:49:00 +0000996// --- M e s s a g e C a l l b a c k
997
998
999// Message callback which counts the number of messages.
1000int message_callback_count = 0;
1001
1002static void MessageCallbackCountClear() {
1003 message_callback_count = 0;
1004}
1005
1006static void MessageCallbackCount(v8::Handle<v8::Message> message,
1007 v8::Handle<v8::Value> data) {
1008 message_callback_count++;
1009}
1010
1011
1012// --- T h e A c t u a l T e s t s
1013
1014
1015// Test that the debug break function is the expected one for different kinds
1016// of break locations.
1017TEST(DebugStub) {
1018 using ::v8::internal::Builtins;
Steve Block44f0eee2011-05-26 01:26:41 +01001019 using ::v8::internal::Isolate;
Steve Blocka7e24c12009-10-30 11:49:00 +00001020 v8::HandleScope scope;
1021 DebugLocalContext env;
1022
1023 CheckDebugBreakFunction(&env,
1024 "function f1(){}", "f1",
1025 0,
1026 v8::internal::RelocInfo::JS_RETURN,
1027 NULL);
1028 CheckDebugBreakFunction(&env,
1029 "function f2(){x=1;}", "f2",
1030 0,
Steve Block1e0659c2011-05-24 12:43:12 +01001031 v8::internal::RelocInfo::CODE_TARGET_CONTEXT,
Steve Block44f0eee2011-05-26 01:26:41 +01001032 Isolate::Current()->builtins()->builtin(
1033 Builtins::kStoreIC_DebugBreak));
Steve Blocka7e24c12009-10-30 11:49:00 +00001034 CheckDebugBreakFunction(&env,
1035 "function f3(){var a=x;}", "f3",
1036 0,
1037 v8::internal::RelocInfo::CODE_TARGET_CONTEXT,
Steve Block44f0eee2011-05-26 01:26:41 +01001038 Isolate::Current()->builtins()->builtin(
1039 Builtins::kLoadIC_DebugBreak));
Steve Blocka7e24c12009-10-30 11:49:00 +00001040
1041// TODO(1240753): Make the test architecture independent or split
1042// parts of the debugger into architecture dependent files. This
1043// part currently disabled as it is not portable between IA32/ARM.
1044// Currently on ICs for keyed store/load on ARM.
1045#if !defined (__arm__) && !defined(__thumb__)
1046 CheckDebugBreakFunction(
1047 &env,
1048 "function f4(){var index='propertyName'; var a={}; a[index] = 'x';}",
1049 "f4",
1050 0,
1051 v8::internal::RelocInfo::CODE_TARGET,
Steve Block44f0eee2011-05-26 01:26:41 +01001052 Isolate::Current()->builtins()->builtin(
1053 Builtins::kKeyedStoreIC_DebugBreak));
Steve Blocka7e24c12009-10-30 11:49:00 +00001054 CheckDebugBreakFunction(
1055 &env,
1056 "function f5(){var index='propertyName'; var a={}; return a[index];}",
1057 "f5",
1058 0,
1059 v8::internal::RelocInfo::CODE_TARGET,
Steve Block44f0eee2011-05-26 01:26:41 +01001060 Isolate::Current()->builtins()->builtin(
1061 Builtins::kKeyedLoadIC_DebugBreak));
Steve Blocka7e24c12009-10-30 11:49:00 +00001062#endif
1063
1064 // Check the debug break code stubs for call ICs with different number of
1065 // parameters.
1066 Handle<Code> debug_break_0 = v8::internal::ComputeCallDebugBreak(0);
1067 Handle<Code> debug_break_1 = v8::internal::ComputeCallDebugBreak(1);
1068 Handle<Code> debug_break_4 = v8::internal::ComputeCallDebugBreak(4);
1069
1070 CheckDebugBreakFunction(&env,
1071 "function f4_0(){x();}", "f4_0",
1072 0,
1073 v8::internal::RelocInfo::CODE_TARGET_CONTEXT,
1074 *debug_break_0);
1075
1076 CheckDebugBreakFunction(&env,
1077 "function f4_1(){x(1);}", "f4_1",
1078 0,
1079 v8::internal::RelocInfo::CODE_TARGET_CONTEXT,
1080 *debug_break_1);
1081
1082 CheckDebugBreakFunction(&env,
1083 "function f4_4(){x(1,2,3,4);}", "f4_4",
1084 0,
1085 v8::internal::RelocInfo::CODE_TARGET_CONTEXT,
1086 *debug_break_4);
1087}
1088
1089
1090// Test that the debug info in the VM is in sync with the functions being
1091// debugged.
1092TEST(DebugInfo) {
1093 v8::HandleScope scope;
1094 DebugLocalContext env;
1095 // Create a couple of functions for the test.
1096 v8::Local<v8::Function> foo =
1097 CompileFunction(&env, "function foo(){}", "foo");
1098 v8::Local<v8::Function> bar =
1099 CompileFunction(&env, "function bar(){}", "bar");
1100 // Initially no functions are debugged.
1101 CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length());
1102 CHECK(!HasDebugInfo(foo));
1103 CHECK(!HasDebugInfo(bar));
1104 // One function (foo) is debugged.
1105 int bp1 = SetBreakPoint(foo, 0);
1106 CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length());
1107 CHECK(HasDebugInfo(foo));
1108 CHECK(!HasDebugInfo(bar));
1109 // Two functions are debugged.
1110 int bp2 = SetBreakPoint(bar, 0);
1111 CHECK_EQ(2, v8::internal::GetDebuggedFunctions()->length());
1112 CHECK(HasDebugInfo(foo));
1113 CHECK(HasDebugInfo(bar));
1114 // One function (bar) is debugged.
1115 ClearBreakPoint(bp1);
1116 CHECK_EQ(1, v8::internal::GetDebuggedFunctions()->length());
1117 CHECK(!HasDebugInfo(foo));
1118 CHECK(HasDebugInfo(bar));
1119 // No functions are debugged.
1120 ClearBreakPoint(bp2);
1121 CHECK_EQ(0, v8::internal::GetDebuggedFunctions()->length());
1122 CHECK(!HasDebugInfo(foo));
1123 CHECK(!HasDebugInfo(bar));
1124}
1125
1126
1127// Test that a break point can be set at an IC store location.
1128TEST(BreakPointICStore) {
1129 break_point_hit_count = 0;
1130 v8::HandleScope scope;
1131 DebugLocalContext env;
1132
1133 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1134 v8::Undefined());
1135 v8::Script::Compile(v8::String::New("function foo(){bar=0;}"))->Run();
1136 v8::Local<v8::Function> foo =
1137 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
1138
1139 // Run without breakpoints.
1140 foo->Call(env->Global(), 0, NULL);
1141 CHECK_EQ(0, break_point_hit_count);
1142
1143 // Run with breakpoint
1144 int bp = SetBreakPoint(foo, 0);
1145 foo->Call(env->Global(), 0, NULL);
1146 CHECK_EQ(1, break_point_hit_count);
1147 foo->Call(env->Global(), 0, NULL);
1148 CHECK_EQ(2, break_point_hit_count);
1149
1150 // Run without breakpoints.
1151 ClearBreakPoint(bp);
1152 foo->Call(env->Global(), 0, NULL);
1153 CHECK_EQ(2, break_point_hit_count);
1154
1155 v8::Debug::SetDebugEventListener(NULL);
1156 CheckDebuggerUnloaded();
1157}
1158
1159
1160// Test that a break point can be set at an IC load location.
1161TEST(BreakPointICLoad) {
1162 break_point_hit_count = 0;
1163 v8::HandleScope scope;
1164 DebugLocalContext env;
1165 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1166 v8::Undefined());
1167 v8::Script::Compile(v8::String::New("bar=1"))->Run();
1168 v8::Script::Compile(v8::String::New("function foo(){var x=bar;}"))->Run();
1169 v8::Local<v8::Function> foo =
1170 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
1171
1172 // Run without breakpoints.
1173 foo->Call(env->Global(), 0, NULL);
1174 CHECK_EQ(0, break_point_hit_count);
1175
Steve Block44f0eee2011-05-26 01:26:41 +01001176 // Run with breakpoint.
Steve Blocka7e24c12009-10-30 11:49:00 +00001177 int bp = SetBreakPoint(foo, 0);
1178 foo->Call(env->Global(), 0, NULL);
1179 CHECK_EQ(1, break_point_hit_count);
1180 foo->Call(env->Global(), 0, NULL);
1181 CHECK_EQ(2, break_point_hit_count);
1182
1183 // Run without breakpoints.
1184 ClearBreakPoint(bp);
1185 foo->Call(env->Global(), 0, NULL);
1186 CHECK_EQ(2, break_point_hit_count);
1187
1188 v8::Debug::SetDebugEventListener(NULL);
1189 CheckDebuggerUnloaded();
1190}
1191
1192
1193// Test that a break point can be set at an IC call location.
1194TEST(BreakPointICCall) {
1195 break_point_hit_count = 0;
1196 v8::HandleScope scope;
1197 DebugLocalContext env;
1198 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1199 v8::Undefined());
1200 v8::Script::Compile(v8::String::New("function bar(){}"))->Run();
1201 v8::Script::Compile(v8::String::New("function foo(){bar();}"))->Run();
1202 v8::Local<v8::Function> foo =
1203 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
1204
1205 // Run without breakpoints.
1206 foo->Call(env->Global(), 0, NULL);
1207 CHECK_EQ(0, break_point_hit_count);
1208
Steve Block44f0eee2011-05-26 01:26:41 +01001209 // Run with breakpoint
Steve Blocka7e24c12009-10-30 11:49:00 +00001210 int bp = SetBreakPoint(foo, 0);
1211 foo->Call(env->Global(), 0, NULL);
1212 CHECK_EQ(1, break_point_hit_count);
1213 foo->Call(env->Global(), 0, NULL);
1214 CHECK_EQ(2, break_point_hit_count);
1215
1216 // Run without breakpoints.
1217 ClearBreakPoint(bp);
1218 foo->Call(env->Global(), 0, NULL);
1219 CHECK_EQ(2, break_point_hit_count);
1220
1221 v8::Debug::SetDebugEventListener(NULL);
1222 CheckDebuggerUnloaded();
1223}
1224
1225
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001226// Test that a break point can be set at an IC call location and survive a GC.
1227TEST(BreakPointICCallWithGC) {
1228 break_point_hit_count = 0;
1229 v8::HandleScope scope;
1230 DebugLocalContext env;
1231 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage,
1232 v8::Undefined());
1233 v8::Script::Compile(v8::String::New("function bar(){return 1;}"))->Run();
1234 v8::Script::Compile(v8::String::New("function foo(){return bar();}"))->Run();
1235 v8::Local<v8::Function> foo =
1236 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
1237
1238 // Run without breakpoints.
1239 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1240 CHECK_EQ(0, break_point_hit_count);
1241
1242 // Run with breakpoint.
1243 int bp = SetBreakPoint(foo, 0);
1244 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1245 CHECK_EQ(1, break_point_hit_count);
1246 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1247 CHECK_EQ(2, break_point_hit_count);
1248
1249 // Run without breakpoints.
1250 ClearBreakPoint(bp);
1251 foo->Call(env->Global(), 0, NULL);
1252 CHECK_EQ(2, break_point_hit_count);
1253
1254 v8::Debug::SetDebugEventListener(NULL);
1255 CheckDebuggerUnloaded();
1256}
1257
1258
1259// Test that a break point can be set at an IC call location and survive a GC.
1260TEST(BreakPointConstructCallWithGC) {
1261 break_point_hit_count = 0;
1262 v8::HandleScope scope;
1263 DebugLocalContext env;
1264 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage,
1265 v8::Undefined());
1266 v8::Script::Compile(v8::String::New("function bar(){ this.x = 1;}"))->Run();
1267 v8::Script::Compile(v8::String::New(
1268 "function foo(){return new bar(1).x;}"))->Run();
1269 v8::Local<v8::Function> foo =
1270 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
1271
1272 // Run without breakpoints.
1273 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1274 CHECK_EQ(0, break_point_hit_count);
1275
1276 // Run with breakpoint.
1277 int bp = SetBreakPoint(foo, 0);
1278 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1279 CHECK_EQ(1, break_point_hit_count);
1280 CHECK_EQ(1, foo->Call(env->Global(), 0, NULL)->Int32Value());
1281 CHECK_EQ(2, break_point_hit_count);
1282
1283 // Run without breakpoints.
1284 ClearBreakPoint(bp);
1285 foo->Call(env->Global(), 0, NULL);
1286 CHECK_EQ(2, break_point_hit_count);
1287
1288 v8::Debug::SetDebugEventListener(NULL);
1289 CheckDebuggerUnloaded();
1290}
1291
1292
Steve Blocka7e24c12009-10-30 11:49:00 +00001293// Test that a break point can be set at a return store location.
1294TEST(BreakPointReturn) {
1295 break_point_hit_count = 0;
1296 v8::HandleScope scope;
1297 DebugLocalContext env;
1298
1299 // Create a functions for checking the source line and column when hitting
1300 // a break point.
1301 frame_source_line = CompileFunction(&env,
1302 frame_source_line_source,
1303 "frame_source_line");
1304 frame_source_column = CompileFunction(&env,
1305 frame_source_column_source,
1306 "frame_source_column");
1307
1308
1309 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1310 v8::Undefined());
1311 v8::Script::Compile(v8::String::New("function foo(){}"))->Run();
1312 v8::Local<v8::Function> foo =
1313 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
1314
1315 // Run without breakpoints.
1316 foo->Call(env->Global(), 0, NULL);
1317 CHECK_EQ(0, break_point_hit_count);
1318
1319 // Run with breakpoint
1320 int bp = SetBreakPoint(foo, 0);
1321 foo->Call(env->Global(), 0, NULL);
1322 CHECK_EQ(1, break_point_hit_count);
1323 CHECK_EQ(0, last_source_line);
Ben Murdochbb769b22010-08-11 14:56:33 +01001324 CHECK_EQ(15, last_source_column);
Steve Blocka7e24c12009-10-30 11:49:00 +00001325 foo->Call(env->Global(), 0, NULL);
1326 CHECK_EQ(2, break_point_hit_count);
1327 CHECK_EQ(0, last_source_line);
Ben Murdochbb769b22010-08-11 14:56:33 +01001328 CHECK_EQ(15, last_source_column);
Steve Blocka7e24c12009-10-30 11:49:00 +00001329
1330 // Run without breakpoints.
1331 ClearBreakPoint(bp);
1332 foo->Call(env->Global(), 0, NULL);
1333 CHECK_EQ(2, break_point_hit_count);
1334
1335 v8::Debug::SetDebugEventListener(NULL);
1336 CheckDebuggerUnloaded();
1337}
1338
1339
1340static void CallWithBreakPoints(v8::Local<v8::Object> recv,
1341 v8::Local<v8::Function> f,
1342 int break_point_count,
1343 int call_count) {
1344 break_point_hit_count = 0;
1345 for (int i = 0; i < call_count; i++) {
1346 f->Call(recv, 0, NULL);
1347 CHECK_EQ((i + 1) * break_point_count, break_point_hit_count);
1348 }
1349}
1350
1351// Test GC during break point processing.
1352TEST(GCDuringBreakPointProcessing) {
1353 break_point_hit_count = 0;
1354 v8::HandleScope scope;
1355 DebugLocalContext env;
1356
1357 v8::Debug::SetDebugEventListener(DebugEventBreakPointCollectGarbage,
1358 v8::Undefined());
1359 v8::Local<v8::Function> foo;
1360
1361 // Test IC store break point with garbage collection.
1362 foo = CompileFunction(&env, "function foo(){bar=0;}", "foo");
1363 SetBreakPoint(foo, 0);
1364 CallWithBreakPoints(env->Global(), foo, 1, 10);
1365
1366 // Test IC load break point with garbage collection.
1367 foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo");
1368 SetBreakPoint(foo, 0);
1369 CallWithBreakPoints(env->Global(), foo, 1, 10);
1370
1371 // Test IC call break point with garbage collection.
1372 foo = CompileFunction(&env, "function bar(){};function foo(){bar();}", "foo");
1373 SetBreakPoint(foo, 0);
1374 CallWithBreakPoints(env->Global(), foo, 1, 10);
1375
1376 // Test return break point with garbage collection.
1377 foo = CompileFunction(&env, "function foo(){}", "foo");
1378 SetBreakPoint(foo, 0);
1379 CallWithBreakPoints(env->Global(), foo, 1, 25);
1380
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001381 // Test debug break slot break point with garbage collection.
1382 foo = CompileFunction(&env, "function foo(){var a;}", "foo");
1383 SetBreakPoint(foo, 0);
1384 CallWithBreakPoints(env->Global(), foo, 1, 25);
1385
Steve Blocka7e24c12009-10-30 11:49:00 +00001386 v8::Debug::SetDebugEventListener(NULL);
1387 CheckDebuggerUnloaded();
1388}
1389
1390
1391// Call the function three times with different garbage collections in between
1392// and make sure that the break point survives.
Ben Murdochbb769b22010-08-11 14:56:33 +01001393static void CallAndGC(v8::Local<v8::Object> recv,
1394 v8::Local<v8::Function> f,
1395 bool force_compaction) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001396 break_point_hit_count = 0;
1397
1398 for (int i = 0; i < 3; i++) {
1399 // Call function.
1400 f->Call(recv, 0, NULL);
1401 CHECK_EQ(1 + i * 3, break_point_hit_count);
1402
1403 // Scavenge and call function.
Steve Block44f0eee2011-05-26 01:26:41 +01001404 HEAP->CollectGarbage(v8::internal::NEW_SPACE);
Steve Blocka7e24c12009-10-30 11:49:00 +00001405 f->Call(recv, 0, NULL);
1406 CHECK_EQ(2 + i * 3, break_point_hit_count);
1407
1408 // Mark sweep (and perhaps compact) and call function.
Steve Block44f0eee2011-05-26 01:26:41 +01001409 HEAP->CollectAllGarbage(force_compaction);
Steve Blocka7e24c12009-10-30 11:49:00 +00001410 f->Call(recv, 0, NULL);
1411 CHECK_EQ(3 + i * 3, break_point_hit_count);
1412 }
1413}
1414
1415
Ben Murdochbb769b22010-08-11 14:56:33 +01001416static void TestBreakPointSurviveGC(bool force_compaction) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001417 break_point_hit_count = 0;
1418 v8::HandleScope scope;
1419 DebugLocalContext env;
1420
1421 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1422 v8::Undefined());
1423 v8::Local<v8::Function> foo;
1424
1425 // Test IC store break point with garbage collection.
Ben Murdochbb769b22010-08-11 14:56:33 +01001426 {
1427 v8::Local<v8::Function> bar =
1428 CompileFunction(&env, "function foo(){}", "foo");
1429 foo = CompileFunction(&env, "function foo(){bar=0;}", "foo");
1430 SetBreakPoint(foo, 0);
1431 }
1432 CallAndGC(env->Global(), foo, force_compaction);
Steve Blocka7e24c12009-10-30 11:49:00 +00001433
1434 // Test IC load break point with garbage collection.
Ben Murdochbb769b22010-08-11 14:56:33 +01001435 {
1436 v8::Local<v8::Function> bar =
1437 CompileFunction(&env, "function foo(){}", "foo");
1438 foo = CompileFunction(&env, "bar=1;function foo(){var x=bar;}", "foo");
1439 SetBreakPoint(foo, 0);
1440 }
1441 CallAndGC(env->Global(), foo, force_compaction);
Steve Blocka7e24c12009-10-30 11:49:00 +00001442
1443 // Test IC call break point with garbage collection.
Ben Murdochbb769b22010-08-11 14:56:33 +01001444 {
1445 v8::Local<v8::Function> bar =
1446 CompileFunction(&env, "function foo(){}", "foo");
1447 foo = CompileFunction(&env,
1448 "function bar(){};function foo(){bar();}",
1449 "foo");
1450 SetBreakPoint(foo, 0);
1451 }
1452 CallAndGC(env->Global(), foo, force_compaction);
Steve Blocka7e24c12009-10-30 11:49:00 +00001453
1454 // Test return break point with garbage collection.
Ben Murdochbb769b22010-08-11 14:56:33 +01001455 {
1456 v8::Local<v8::Function> bar =
1457 CompileFunction(&env, "function foo(){}", "foo");
1458 foo = CompileFunction(&env, "function foo(){}", "foo");
1459 SetBreakPoint(foo, 0);
1460 }
1461 CallAndGC(env->Global(), foo, force_compaction);
1462
1463 // Test non IC break point with garbage collection.
1464 {
1465 v8::Local<v8::Function> bar =
1466 CompileFunction(&env, "function foo(){}", "foo");
1467 foo = CompileFunction(&env, "function foo(){var bar=0;}", "foo");
1468 SetBreakPoint(foo, 0);
1469 }
1470 CallAndGC(env->Global(), foo, force_compaction);
1471
Steve Blocka7e24c12009-10-30 11:49:00 +00001472
1473 v8::Debug::SetDebugEventListener(NULL);
1474 CheckDebuggerUnloaded();
1475}
1476
1477
Ben Murdochbb769b22010-08-11 14:56:33 +01001478// Test that a break point can be set at a return store location.
1479TEST(BreakPointSurviveGC) {
1480 TestBreakPointSurviveGC(false);
1481 TestBreakPointSurviveGC(true);
1482}
1483
1484
Steve Blocka7e24c12009-10-30 11:49:00 +00001485// Test that break points can be set using the global Debug object.
1486TEST(BreakPointThroughJavaScript) {
1487 break_point_hit_count = 0;
1488 v8::HandleScope scope;
1489 DebugLocalContext env;
1490 env.ExposeDebug();
1491
1492 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1493 v8::Undefined());
1494 v8::Script::Compile(v8::String::New("function bar(){}"))->Run();
1495 v8::Script::Compile(v8::String::New("function foo(){bar();bar();}"))->Run();
1496 // 012345678901234567890
1497 // 1 2
1498 // Break points are set at position 3 and 9
1499 v8::Local<v8::Script> foo = v8::Script::Compile(v8::String::New("foo()"));
1500
1501 // Run without breakpoints.
1502 foo->Run();
1503 CHECK_EQ(0, break_point_hit_count);
1504
1505 // Run with one breakpoint
1506 int bp1 = SetBreakPointFromJS("foo", 0, 3);
1507 foo->Run();
1508 CHECK_EQ(1, break_point_hit_count);
1509 foo->Run();
1510 CHECK_EQ(2, break_point_hit_count);
1511
1512 // Run with two breakpoints
1513 int bp2 = SetBreakPointFromJS("foo", 0, 9);
1514 foo->Run();
1515 CHECK_EQ(4, break_point_hit_count);
1516 foo->Run();
1517 CHECK_EQ(6, break_point_hit_count);
1518
1519 // Run with one breakpoint
1520 ClearBreakPointFromJS(bp2);
1521 foo->Run();
1522 CHECK_EQ(7, break_point_hit_count);
1523 foo->Run();
1524 CHECK_EQ(8, break_point_hit_count);
1525
1526 // Run without breakpoints.
1527 ClearBreakPointFromJS(bp1);
1528 foo->Run();
1529 CHECK_EQ(8, break_point_hit_count);
1530
1531 v8::Debug::SetDebugEventListener(NULL);
1532 CheckDebuggerUnloaded();
1533
1534 // Make sure that the break point numbers are consecutive.
1535 CHECK_EQ(1, bp1);
1536 CHECK_EQ(2, bp2);
1537}
1538
1539
1540// Test that break points on scripts identified by name can be set using the
1541// global Debug object.
1542TEST(ScriptBreakPointByNameThroughJavaScript) {
1543 break_point_hit_count = 0;
1544 v8::HandleScope scope;
1545 DebugLocalContext env;
1546 env.ExposeDebug();
1547
1548 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1549 v8::Undefined());
1550
1551 v8::Local<v8::String> script = v8::String::New(
1552 "function f() {\n"
1553 " function h() {\n"
1554 " a = 0; // line 2\n"
1555 " }\n"
1556 " b = 1; // line 4\n"
1557 " return h();\n"
1558 "}\n"
1559 "\n"
1560 "function g() {\n"
1561 " function h() {\n"
1562 " a = 0;\n"
1563 " }\n"
1564 " b = 2; // line 12\n"
1565 " h();\n"
1566 " b = 3; // line 14\n"
1567 " f(); // line 15\n"
1568 "}");
1569
1570 // Compile the script and get the two functions.
1571 v8::ScriptOrigin origin =
1572 v8::ScriptOrigin(v8::String::New("test"));
1573 v8::Script::Compile(script, &origin)->Run();
1574 v8::Local<v8::Function> f =
1575 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1576 v8::Local<v8::Function> g =
1577 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
1578
1579 // Call f and g without break points.
1580 break_point_hit_count = 0;
1581 f->Call(env->Global(), 0, NULL);
1582 CHECK_EQ(0, break_point_hit_count);
1583 g->Call(env->Global(), 0, NULL);
1584 CHECK_EQ(0, break_point_hit_count);
1585
1586 // Call f and g with break point on line 12.
1587 int sbp1 = SetScriptBreakPointByNameFromJS("test", 12, 0);
1588 break_point_hit_count = 0;
1589 f->Call(env->Global(), 0, NULL);
1590 CHECK_EQ(0, break_point_hit_count);
1591 g->Call(env->Global(), 0, NULL);
1592 CHECK_EQ(1, break_point_hit_count);
1593
1594 // Remove the break point again.
1595 break_point_hit_count = 0;
1596 ClearBreakPointFromJS(sbp1);
1597 f->Call(env->Global(), 0, NULL);
1598 CHECK_EQ(0, break_point_hit_count);
1599 g->Call(env->Global(), 0, NULL);
1600 CHECK_EQ(0, break_point_hit_count);
1601
1602 // Call f and g with break point on line 2.
1603 int sbp2 = SetScriptBreakPointByNameFromJS("test", 2, 0);
1604 break_point_hit_count = 0;
1605 f->Call(env->Global(), 0, NULL);
1606 CHECK_EQ(1, break_point_hit_count);
1607 g->Call(env->Global(), 0, NULL);
1608 CHECK_EQ(2, break_point_hit_count);
1609
1610 // Call f and g with break point on line 2, 4, 12, 14 and 15.
1611 int sbp3 = SetScriptBreakPointByNameFromJS("test", 4, 0);
1612 int sbp4 = SetScriptBreakPointByNameFromJS("test", 12, 0);
1613 int sbp5 = SetScriptBreakPointByNameFromJS("test", 14, 0);
1614 int sbp6 = SetScriptBreakPointByNameFromJS("test", 15, 0);
1615 break_point_hit_count = 0;
1616 f->Call(env->Global(), 0, NULL);
1617 CHECK_EQ(2, break_point_hit_count);
1618 g->Call(env->Global(), 0, NULL);
1619 CHECK_EQ(7, break_point_hit_count);
1620
1621 // Remove all the break points again.
1622 break_point_hit_count = 0;
1623 ClearBreakPointFromJS(sbp2);
1624 ClearBreakPointFromJS(sbp3);
1625 ClearBreakPointFromJS(sbp4);
1626 ClearBreakPointFromJS(sbp5);
1627 ClearBreakPointFromJS(sbp6);
1628 f->Call(env->Global(), 0, NULL);
1629 CHECK_EQ(0, break_point_hit_count);
1630 g->Call(env->Global(), 0, NULL);
1631 CHECK_EQ(0, break_point_hit_count);
1632
1633 v8::Debug::SetDebugEventListener(NULL);
1634 CheckDebuggerUnloaded();
1635
1636 // Make sure that the break point numbers are consecutive.
1637 CHECK_EQ(1, sbp1);
1638 CHECK_EQ(2, sbp2);
1639 CHECK_EQ(3, sbp3);
1640 CHECK_EQ(4, sbp4);
1641 CHECK_EQ(5, sbp5);
1642 CHECK_EQ(6, sbp6);
1643}
1644
1645
1646TEST(ScriptBreakPointByIdThroughJavaScript) {
1647 break_point_hit_count = 0;
1648 v8::HandleScope scope;
1649 DebugLocalContext env;
1650 env.ExposeDebug();
1651
1652 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1653 v8::Undefined());
1654
1655 v8::Local<v8::String> source = v8::String::New(
1656 "function f() {\n"
1657 " function h() {\n"
1658 " a = 0; // line 2\n"
1659 " }\n"
1660 " b = 1; // line 4\n"
1661 " return h();\n"
1662 "}\n"
1663 "\n"
1664 "function g() {\n"
1665 " function h() {\n"
1666 " a = 0;\n"
1667 " }\n"
1668 " b = 2; // line 12\n"
1669 " h();\n"
1670 " b = 3; // line 14\n"
1671 " f(); // line 15\n"
1672 "}");
1673
1674 // Compile the script and get the two functions.
1675 v8::ScriptOrigin origin =
1676 v8::ScriptOrigin(v8::String::New("test"));
1677 v8::Local<v8::Script> script = v8::Script::Compile(source, &origin);
1678 script->Run();
1679 v8::Local<v8::Function> f =
1680 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1681 v8::Local<v8::Function> g =
1682 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
1683
1684 // Get the script id knowing that internally it is a 32 integer.
1685 uint32_t script_id = script->Id()->Uint32Value();
1686
1687 // Call f and g without break points.
1688 break_point_hit_count = 0;
1689 f->Call(env->Global(), 0, NULL);
1690 CHECK_EQ(0, break_point_hit_count);
1691 g->Call(env->Global(), 0, NULL);
1692 CHECK_EQ(0, break_point_hit_count);
1693
1694 // Call f and g with break point on line 12.
1695 int sbp1 = SetScriptBreakPointByIdFromJS(script_id, 12, 0);
1696 break_point_hit_count = 0;
1697 f->Call(env->Global(), 0, NULL);
1698 CHECK_EQ(0, break_point_hit_count);
1699 g->Call(env->Global(), 0, NULL);
1700 CHECK_EQ(1, break_point_hit_count);
1701
1702 // Remove the break point again.
1703 break_point_hit_count = 0;
1704 ClearBreakPointFromJS(sbp1);
1705 f->Call(env->Global(), 0, NULL);
1706 CHECK_EQ(0, break_point_hit_count);
1707 g->Call(env->Global(), 0, NULL);
1708 CHECK_EQ(0, break_point_hit_count);
1709
1710 // Call f and g with break point on line 2.
1711 int sbp2 = SetScriptBreakPointByIdFromJS(script_id, 2, 0);
1712 break_point_hit_count = 0;
1713 f->Call(env->Global(), 0, NULL);
1714 CHECK_EQ(1, break_point_hit_count);
1715 g->Call(env->Global(), 0, NULL);
1716 CHECK_EQ(2, break_point_hit_count);
1717
1718 // Call f and g with break point on line 2, 4, 12, 14 and 15.
1719 int sbp3 = SetScriptBreakPointByIdFromJS(script_id, 4, 0);
1720 int sbp4 = SetScriptBreakPointByIdFromJS(script_id, 12, 0);
1721 int sbp5 = SetScriptBreakPointByIdFromJS(script_id, 14, 0);
1722 int sbp6 = SetScriptBreakPointByIdFromJS(script_id, 15, 0);
1723 break_point_hit_count = 0;
1724 f->Call(env->Global(), 0, NULL);
1725 CHECK_EQ(2, break_point_hit_count);
1726 g->Call(env->Global(), 0, NULL);
1727 CHECK_EQ(7, break_point_hit_count);
1728
1729 // Remove all the break points again.
1730 break_point_hit_count = 0;
1731 ClearBreakPointFromJS(sbp2);
1732 ClearBreakPointFromJS(sbp3);
1733 ClearBreakPointFromJS(sbp4);
1734 ClearBreakPointFromJS(sbp5);
1735 ClearBreakPointFromJS(sbp6);
1736 f->Call(env->Global(), 0, NULL);
1737 CHECK_EQ(0, break_point_hit_count);
1738 g->Call(env->Global(), 0, NULL);
1739 CHECK_EQ(0, break_point_hit_count);
1740
1741 v8::Debug::SetDebugEventListener(NULL);
1742 CheckDebuggerUnloaded();
1743
1744 // Make sure that the break point numbers are consecutive.
1745 CHECK_EQ(1, sbp1);
1746 CHECK_EQ(2, sbp2);
1747 CHECK_EQ(3, sbp3);
1748 CHECK_EQ(4, sbp4);
1749 CHECK_EQ(5, sbp5);
1750 CHECK_EQ(6, sbp6);
1751}
1752
1753
1754// Test conditional script break points.
1755TEST(EnableDisableScriptBreakPoint) {
1756 break_point_hit_count = 0;
1757 v8::HandleScope scope;
1758 DebugLocalContext env;
1759 env.ExposeDebug();
1760
1761 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1762 v8::Undefined());
1763
1764 v8::Local<v8::String> script = v8::String::New(
1765 "function f() {\n"
1766 " a = 0; // line 1\n"
1767 "};");
1768
1769 // Compile the script and get function f.
1770 v8::ScriptOrigin origin =
1771 v8::ScriptOrigin(v8::String::New("test"));
1772 v8::Script::Compile(script, &origin)->Run();
1773 v8::Local<v8::Function> f =
1774 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1775
1776 // Set script break point on line 1 (in function f).
1777 int sbp = SetScriptBreakPointByNameFromJS("test", 1, 0);
1778
1779 // Call f while enabeling and disabling the script break point.
1780 break_point_hit_count = 0;
1781 f->Call(env->Global(), 0, NULL);
1782 CHECK_EQ(1, break_point_hit_count);
1783
1784 DisableScriptBreakPointFromJS(sbp);
1785 f->Call(env->Global(), 0, NULL);
1786 CHECK_EQ(1, break_point_hit_count);
1787
1788 EnableScriptBreakPointFromJS(sbp);
1789 f->Call(env->Global(), 0, NULL);
1790 CHECK_EQ(2, break_point_hit_count);
1791
1792 DisableScriptBreakPointFromJS(sbp);
1793 f->Call(env->Global(), 0, NULL);
1794 CHECK_EQ(2, break_point_hit_count);
1795
1796 // Reload the script and get f again checking that the disabeling survives.
1797 v8::Script::Compile(script, &origin)->Run();
1798 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1799 f->Call(env->Global(), 0, NULL);
1800 CHECK_EQ(2, break_point_hit_count);
1801
1802 EnableScriptBreakPointFromJS(sbp);
1803 f->Call(env->Global(), 0, NULL);
1804 CHECK_EQ(3, break_point_hit_count);
1805
1806 v8::Debug::SetDebugEventListener(NULL);
1807 CheckDebuggerUnloaded();
1808}
1809
1810
1811// Test conditional script break points.
1812TEST(ConditionalScriptBreakPoint) {
1813 break_point_hit_count = 0;
1814 v8::HandleScope scope;
1815 DebugLocalContext env;
1816 env.ExposeDebug();
1817
1818 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1819 v8::Undefined());
1820
1821 v8::Local<v8::String> script = v8::String::New(
1822 "count = 0;\n"
1823 "function f() {\n"
1824 " g(count++); // line 2\n"
1825 "};\n"
1826 "function g(x) {\n"
1827 " var a=x; // line 5\n"
1828 "};");
1829
1830 // Compile the script and get function f.
1831 v8::ScriptOrigin origin =
1832 v8::ScriptOrigin(v8::String::New("test"));
1833 v8::Script::Compile(script, &origin)->Run();
1834 v8::Local<v8::Function> f =
1835 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1836
1837 // Set script break point on line 5 (in function g).
1838 int sbp1 = SetScriptBreakPointByNameFromJS("test", 5, 0);
1839
1840 // Call f with different conditions on the script break point.
1841 break_point_hit_count = 0;
1842 ChangeScriptBreakPointConditionFromJS(sbp1, "false");
1843 f->Call(env->Global(), 0, NULL);
1844 CHECK_EQ(0, break_point_hit_count);
1845
1846 ChangeScriptBreakPointConditionFromJS(sbp1, "true");
1847 break_point_hit_count = 0;
1848 f->Call(env->Global(), 0, NULL);
1849 CHECK_EQ(1, break_point_hit_count);
1850
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01001851 ChangeScriptBreakPointConditionFromJS(sbp1, "x % 2 == 0");
Steve Blocka7e24c12009-10-30 11:49:00 +00001852 break_point_hit_count = 0;
1853 for (int i = 0; i < 10; i++) {
1854 f->Call(env->Global(), 0, NULL);
1855 }
1856 CHECK_EQ(5, break_point_hit_count);
1857
1858 // Reload the script and get f again checking that the condition survives.
1859 v8::Script::Compile(script, &origin)->Run();
1860 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1861
1862 break_point_hit_count = 0;
1863 for (int i = 0; i < 10; i++) {
1864 f->Call(env->Global(), 0, NULL);
1865 }
1866 CHECK_EQ(5, break_point_hit_count);
1867
1868 v8::Debug::SetDebugEventListener(NULL);
1869 CheckDebuggerUnloaded();
1870}
1871
1872
1873// Test ignore count on script break points.
1874TEST(ScriptBreakPointIgnoreCount) {
1875 break_point_hit_count = 0;
1876 v8::HandleScope scope;
1877 DebugLocalContext env;
1878 env.ExposeDebug();
1879
1880 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1881 v8::Undefined());
1882
1883 v8::Local<v8::String> script = v8::String::New(
1884 "function f() {\n"
1885 " a = 0; // line 1\n"
1886 "};");
1887
1888 // Compile the script and get function f.
1889 v8::ScriptOrigin origin =
1890 v8::ScriptOrigin(v8::String::New("test"));
1891 v8::Script::Compile(script, &origin)->Run();
1892 v8::Local<v8::Function> f =
1893 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1894
1895 // Set script break point on line 1 (in function f).
1896 int sbp = SetScriptBreakPointByNameFromJS("test", 1, 0);
1897
1898 // Call f with different ignores on the script break point.
1899 break_point_hit_count = 0;
1900 ChangeScriptBreakPointIgnoreCountFromJS(sbp, 1);
1901 f->Call(env->Global(), 0, NULL);
1902 CHECK_EQ(0, break_point_hit_count);
1903 f->Call(env->Global(), 0, NULL);
1904 CHECK_EQ(1, break_point_hit_count);
1905
1906 ChangeScriptBreakPointIgnoreCountFromJS(sbp, 5);
1907 break_point_hit_count = 0;
1908 for (int i = 0; i < 10; i++) {
1909 f->Call(env->Global(), 0, NULL);
1910 }
1911 CHECK_EQ(5, break_point_hit_count);
1912
1913 // Reload the script and get f again checking that the ignore survives.
1914 v8::Script::Compile(script, &origin)->Run();
1915 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1916
1917 break_point_hit_count = 0;
1918 for (int i = 0; i < 10; i++) {
1919 f->Call(env->Global(), 0, NULL);
1920 }
1921 CHECK_EQ(5, break_point_hit_count);
1922
1923 v8::Debug::SetDebugEventListener(NULL);
1924 CheckDebuggerUnloaded();
1925}
1926
1927
1928// Test that script break points survive when a script is reloaded.
1929TEST(ScriptBreakPointReload) {
1930 break_point_hit_count = 0;
1931 v8::HandleScope scope;
1932 DebugLocalContext env;
1933 env.ExposeDebug();
1934
1935 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1936 v8::Undefined());
1937
1938 v8::Local<v8::Function> f;
1939 v8::Local<v8::String> script = v8::String::New(
1940 "function f() {\n"
1941 " function h() {\n"
1942 " a = 0; // line 2\n"
1943 " }\n"
1944 " b = 1; // line 4\n"
1945 " return h();\n"
1946 "}");
1947
1948 v8::ScriptOrigin origin_1 = v8::ScriptOrigin(v8::String::New("1"));
1949 v8::ScriptOrigin origin_2 = v8::ScriptOrigin(v8::String::New("2"));
1950
1951 // Set a script break point before the script is loaded.
1952 SetScriptBreakPointByNameFromJS("1", 2, 0);
1953
1954 // Compile the script and get the function.
1955 v8::Script::Compile(script, &origin_1)->Run();
1956 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1957
1958 // Call f and check that the script break point is active.
1959 break_point_hit_count = 0;
1960 f->Call(env->Global(), 0, NULL);
1961 CHECK_EQ(1, break_point_hit_count);
1962
1963 // Compile the script again with a different script data and get the
1964 // function.
1965 v8::Script::Compile(script, &origin_2)->Run();
1966 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1967
1968 // Call f and check that no break points are set.
1969 break_point_hit_count = 0;
1970 f->Call(env->Global(), 0, NULL);
1971 CHECK_EQ(0, break_point_hit_count);
1972
1973 // Compile the script again and get the function.
1974 v8::Script::Compile(script, &origin_1)->Run();
1975 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
1976
1977 // Call f and check that the script break point is active.
1978 break_point_hit_count = 0;
1979 f->Call(env->Global(), 0, NULL);
1980 CHECK_EQ(1, break_point_hit_count);
1981
1982 v8::Debug::SetDebugEventListener(NULL);
1983 CheckDebuggerUnloaded();
1984}
1985
1986
1987// Test when several scripts has the same script data
1988TEST(ScriptBreakPointMultiple) {
1989 break_point_hit_count = 0;
1990 v8::HandleScope scope;
1991 DebugLocalContext env;
1992 env.ExposeDebug();
1993
1994 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
1995 v8::Undefined());
1996
1997 v8::Local<v8::Function> f;
1998 v8::Local<v8::String> script_f = v8::String::New(
1999 "function f() {\n"
2000 " a = 0; // line 1\n"
2001 "}");
2002
2003 v8::Local<v8::Function> g;
2004 v8::Local<v8::String> script_g = v8::String::New(
2005 "function g() {\n"
2006 " b = 0; // line 1\n"
2007 "}");
2008
2009 v8::ScriptOrigin origin =
2010 v8::ScriptOrigin(v8::String::New("test"));
2011
2012 // Set a script break point before the scripts are loaded.
2013 int sbp = SetScriptBreakPointByNameFromJS("test", 1, 0);
2014
2015 // Compile the scripts with same script data and get the functions.
2016 v8::Script::Compile(script_f, &origin)->Run();
2017 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
2018 v8::Script::Compile(script_g, &origin)->Run();
2019 g = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
2020
2021 // Call f and g and check that the script break point is active.
2022 break_point_hit_count = 0;
2023 f->Call(env->Global(), 0, NULL);
2024 CHECK_EQ(1, break_point_hit_count);
2025 g->Call(env->Global(), 0, NULL);
2026 CHECK_EQ(2, break_point_hit_count);
2027
2028 // Clear the script break point.
2029 ClearBreakPointFromJS(sbp);
2030
2031 // Call f and g and check that the script break point is no longer active.
2032 break_point_hit_count = 0;
2033 f->Call(env->Global(), 0, NULL);
2034 CHECK_EQ(0, break_point_hit_count);
2035 g->Call(env->Global(), 0, NULL);
2036 CHECK_EQ(0, break_point_hit_count);
2037
2038 // Set script break point with the scripts loaded.
2039 sbp = SetScriptBreakPointByNameFromJS("test", 1, 0);
2040
2041 // Call f and g and check that the script break point is active.
2042 break_point_hit_count = 0;
2043 f->Call(env->Global(), 0, NULL);
2044 CHECK_EQ(1, break_point_hit_count);
2045 g->Call(env->Global(), 0, NULL);
2046 CHECK_EQ(2, break_point_hit_count);
2047
2048 v8::Debug::SetDebugEventListener(NULL);
2049 CheckDebuggerUnloaded();
2050}
2051
2052
2053// Test the script origin which has both name and line offset.
2054TEST(ScriptBreakPointLineOffset) {
2055 break_point_hit_count = 0;
2056 v8::HandleScope scope;
2057 DebugLocalContext env;
2058 env.ExposeDebug();
2059
2060 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
2061 v8::Undefined());
2062
2063 v8::Local<v8::Function> f;
2064 v8::Local<v8::String> script = v8::String::New(
2065 "function f() {\n"
2066 " a = 0; // line 8 as this script has line offset 7\n"
2067 " b = 0; // line 9 as this script has line offset 7\n"
2068 "}");
2069
2070 // Create script origin both name and line offset.
2071 v8::ScriptOrigin origin(v8::String::New("test.html"),
2072 v8::Integer::New(7));
2073
2074 // Set two script break points before the script is loaded.
2075 int sbp1 = SetScriptBreakPointByNameFromJS("test.html", 8, 0);
2076 int sbp2 = SetScriptBreakPointByNameFromJS("test.html", 9, 0);
2077
2078 // Compile the script and get the function.
2079 v8::Script::Compile(script, &origin)->Run();
2080 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
2081
2082 // Call f and check that the script break point is active.
2083 break_point_hit_count = 0;
2084 f->Call(env->Global(), 0, NULL);
2085 CHECK_EQ(2, break_point_hit_count);
2086
2087 // Clear the script break points.
2088 ClearBreakPointFromJS(sbp1);
2089 ClearBreakPointFromJS(sbp2);
2090
2091 // Call f and check that no script break points are active.
2092 break_point_hit_count = 0;
2093 f->Call(env->Global(), 0, NULL);
2094 CHECK_EQ(0, break_point_hit_count);
2095
2096 // Set a script break point with the script loaded.
2097 sbp1 = SetScriptBreakPointByNameFromJS("test.html", 9, 0);
2098
2099 // Call f and check that the script break point is active.
2100 break_point_hit_count = 0;
2101 f->Call(env->Global(), 0, NULL);
2102 CHECK_EQ(1, break_point_hit_count);
2103
2104 v8::Debug::SetDebugEventListener(NULL);
2105 CheckDebuggerUnloaded();
2106}
2107
2108
2109// Test script break points set on lines.
2110TEST(ScriptBreakPointLine) {
2111 v8::HandleScope scope;
2112 DebugLocalContext env;
2113 env.ExposeDebug();
2114
2115 // Create a function for checking the function when hitting a break point.
2116 frame_function_name = CompileFunction(&env,
2117 frame_function_name_source,
2118 "frame_function_name");
2119
2120 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
2121 v8::Undefined());
2122
2123 v8::Local<v8::Function> f;
2124 v8::Local<v8::Function> g;
2125 v8::Local<v8::String> script = v8::String::New(
2126 "a = 0 // line 0\n"
2127 "function f() {\n"
2128 " a = 1; // line 2\n"
2129 "}\n"
2130 " a = 2; // line 4\n"
2131 " /* xx */ function g() { // line 5\n"
2132 " function h() { // line 6\n"
2133 " a = 3; // line 7\n"
2134 " }\n"
2135 " h(); // line 9\n"
2136 " a = 4; // line 10\n"
2137 " }\n"
2138 " a=5; // line 12");
2139
2140 // Set a couple script break point before the script is loaded.
2141 int sbp1 = SetScriptBreakPointByNameFromJS("test.html", 0, -1);
2142 int sbp2 = SetScriptBreakPointByNameFromJS("test.html", 1, -1);
2143 int sbp3 = SetScriptBreakPointByNameFromJS("test.html", 5, -1);
2144
2145 // Compile the script and get the function.
2146 break_point_hit_count = 0;
2147 v8::ScriptOrigin origin(v8::String::New("test.html"), v8::Integer::New(0));
2148 v8::Script::Compile(script, &origin)->Run();
2149 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
2150 g = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
2151
2152 // Chesk that a break point was hit when the script was run.
2153 CHECK_EQ(1, break_point_hit_count);
Steve Blockd0582a62009-12-15 09:54:21 +00002154 CHECK_EQ(0, StrLength(last_function_hit));
Steve Blocka7e24c12009-10-30 11:49:00 +00002155
2156 // Call f and check that the script break point.
2157 f->Call(env->Global(), 0, NULL);
2158 CHECK_EQ(2, break_point_hit_count);
2159 CHECK_EQ("f", last_function_hit);
2160
2161 // Call g and check that the script break point.
2162 g->Call(env->Global(), 0, NULL);
2163 CHECK_EQ(3, break_point_hit_count);
2164 CHECK_EQ("g", last_function_hit);
2165
2166 // Clear the script break point on g and set one on h.
2167 ClearBreakPointFromJS(sbp3);
2168 int sbp4 = SetScriptBreakPointByNameFromJS("test.html", 6, -1);
2169
2170 // Call g and check that the script break point in h is hit.
2171 g->Call(env->Global(), 0, NULL);
2172 CHECK_EQ(4, break_point_hit_count);
2173 CHECK_EQ("h", last_function_hit);
2174
2175 // Clear break points in f and h. Set a new one in the script between
2176 // functions f and g and test that there is no break points in f and g any
2177 // more.
2178 ClearBreakPointFromJS(sbp2);
2179 ClearBreakPointFromJS(sbp4);
2180 int sbp5 = SetScriptBreakPointByNameFromJS("test.html", 4, -1);
2181 break_point_hit_count = 0;
2182 f->Call(env->Global(), 0, NULL);
2183 g->Call(env->Global(), 0, NULL);
2184 CHECK_EQ(0, break_point_hit_count);
2185
2186 // Reload the script which should hit two break points.
2187 break_point_hit_count = 0;
2188 v8::Script::Compile(script, &origin)->Run();
2189 CHECK_EQ(2, break_point_hit_count);
Steve Blockd0582a62009-12-15 09:54:21 +00002190 CHECK_EQ(0, StrLength(last_function_hit));
Steve Blocka7e24c12009-10-30 11:49:00 +00002191
2192 // Set a break point in the code after the last function decleration.
2193 int sbp6 = SetScriptBreakPointByNameFromJS("test.html", 12, -1);
2194
2195 // Reload the script which should hit three break points.
2196 break_point_hit_count = 0;
2197 v8::Script::Compile(script, &origin)->Run();
2198 CHECK_EQ(3, break_point_hit_count);
Steve Blockd0582a62009-12-15 09:54:21 +00002199 CHECK_EQ(0, StrLength(last_function_hit));
Steve Blocka7e24c12009-10-30 11:49:00 +00002200
2201 // Clear the last break points, and reload the script which should not hit any
2202 // break points.
2203 ClearBreakPointFromJS(sbp1);
2204 ClearBreakPointFromJS(sbp5);
2205 ClearBreakPointFromJS(sbp6);
2206 break_point_hit_count = 0;
2207 v8::Script::Compile(script, &origin)->Run();
2208 CHECK_EQ(0, break_point_hit_count);
2209
2210 v8::Debug::SetDebugEventListener(NULL);
2211 CheckDebuggerUnloaded();
2212}
2213
2214
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002215// Test top level script break points set on lines.
2216TEST(ScriptBreakPointLineTopLevel) {
2217 v8::HandleScope scope;
2218 DebugLocalContext env;
2219 env.ExposeDebug();
2220
2221 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
2222 v8::Undefined());
2223
2224 v8::Local<v8::String> script = v8::String::New(
2225 "function f() {\n"
2226 " a = 1; // line 1\n"
2227 "}\n"
2228 "a = 2; // line 3\n");
2229 v8::Local<v8::Function> f;
2230 {
2231 v8::HandleScope scope;
2232 v8::Script::Compile(script, v8::String::New("test.html"))->Run();
2233 }
2234 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
2235
Steve Block44f0eee2011-05-26 01:26:41 +01002236 HEAP->CollectAllGarbage(false);
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01002237
2238 SetScriptBreakPointByNameFromJS("test.html", 3, -1);
2239
2240 // Call f and check that there was no break points.
2241 break_point_hit_count = 0;
2242 f->Call(env->Global(), 0, NULL);
2243 CHECK_EQ(0, break_point_hit_count);
2244
2245 // Recompile and run script and check that break point was hit.
2246 break_point_hit_count = 0;
2247 v8::Script::Compile(script, v8::String::New("test.html"))->Run();
2248 CHECK_EQ(1, break_point_hit_count);
2249
2250 // Call f and check that there are still no break points.
2251 break_point_hit_count = 0;
2252 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
2253 CHECK_EQ(0, break_point_hit_count);
2254
2255 v8::Debug::SetDebugEventListener(NULL);
2256 CheckDebuggerUnloaded();
2257}
2258
2259
Steve Block8defd9f2010-07-08 12:39:36 +01002260// Test that it is possible to add and remove break points in a top level
2261// function which has no references but has not been collected yet.
2262TEST(ScriptBreakPointTopLevelCrash) {
2263 v8::HandleScope scope;
2264 DebugLocalContext env;
2265 env.ExposeDebug();
2266
2267 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
2268 v8::Undefined());
2269
2270 v8::Local<v8::String> script_source = v8::String::New(
2271 "function f() {\n"
2272 " return 0;\n"
2273 "}\n"
2274 "f()");
2275
2276 int sbp1 = SetScriptBreakPointByNameFromJS("test.html", 3, -1);
2277 {
2278 v8::HandleScope scope;
2279 break_point_hit_count = 0;
2280 v8::Script::Compile(script_source, v8::String::New("test.html"))->Run();
2281 CHECK_EQ(1, break_point_hit_count);
2282 }
2283
2284 int sbp2 = SetScriptBreakPointByNameFromJS("test.html", 3, -1);
2285 ClearBreakPointFromJS(sbp1);
2286 ClearBreakPointFromJS(sbp2);
2287
2288 v8::Debug::SetDebugEventListener(NULL);
2289 CheckDebuggerUnloaded();
2290}
2291
2292
Steve Blocka7e24c12009-10-30 11:49:00 +00002293// Test that it is possible to remove the last break point for a function
2294// inside the break handling of that break point.
2295TEST(RemoveBreakPointInBreak) {
2296 v8::HandleScope scope;
2297 DebugLocalContext env;
2298
2299 v8::Local<v8::Function> foo =
2300 CompileFunction(&env, "function foo(){a=1;}", "foo");
2301 debug_event_remove_break_point = SetBreakPoint(foo, 0);
2302
2303 // Register the debug event listener pasing the function
2304 v8::Debug::SetDebugEventListener(DebugEventRemoveBreakPoint, foo);
2305
2306 break_point_hit_count = 0;
2307 foo->Call(env->Global(), 0, NULL);
2308 CHECK_EQ(1, break_point_hit_count);
2309
2310 break_point_hit_count = 0;
2311 foo->Call(env->Global(), 0, NULL);
2312 CHECK_EQ(0, break_point_hit_count);
2313
2314 v8::Debug::SetDebugEventListener(NULL);
2315 CheckDebuggerUnloaded();
2316}
2317
2318
2319// Test that the debugger statement causes a break.
2320TEST(DebuggerStatement) {
2321 break_point_hit_count = 0;
2322 v8::HandleScope scope;
2323 DebugLocalContext env;
2324 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
2325 v8::Undefined());
2326 v8::Script::Compile(v8::String::New("function bar(){debugger}"))->Run();
2327 v8::Script::Compile(v8::String::New(
2328 "function foo(){debugger;debugger;}"))->Run();
2329 v8::Local<v8::Function> foo =
2330 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
2331 v8::Local<v8::Function> bar =
2332 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("bar")));
2333
2334 // Run function with debugger statement
2335 bar->Call(env->Global(), 0, NULL);
2336 CHECK_EQ(1, break_point_hit_count);
2337
2338 // Run function with two debugger statement
2339 foo->Call(env->Global(), 0, NULL);
2340 CHECK_EQ(3, break_point_hit_count);
2341
2342 v8::Debug::SetDebugEventListener(NULL);
2343 CheckDebuggerUnloaded();
2344}
2345
2346
Steve Block8defd9f2010-07-08 12:39:36 +01002347// Test setting a breakpoint on the debugger statement.
Leon Clarke4515c472010-02-03 11:58:03 +00002348TEST(DebuggerStatementBreakpoint) {
2349 break_point_hit_count = 0;
2350 v8::HandleScope scope;
2351 DebugLocalContext env;
2352 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
2353 v8::Undefined());
2354 v8::Script::Compile(v8::String::New("function foo(){debugger;}"))->Run();
2355 v8::Local<v8::Function> foo =
2356 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
2357
2358 // The debugger statement triggers breakpint hit
2359 foo->Call(env->Global(), 0, NULL);
2360 CHECK_EQ(1, break_point_hit_count);
2361
2362 int bp = SetBreakPoint(foo, 0);
2363
2364 // Set breakpoint does not duplicate hits
2365 foo->Call(env->Global(), 0, NULL);
2366 CHECK_EQ(2, break_point_hit_count);
2367
2368 ClearBreakPoint(bp);
2369 v8::Debug::SetDebugEventListener(NULL);
2370 CheckDebuggerUnloaded();
2371}
2372
2373
Steve Blocka7e24c12009-10-30 11:49:00 +00002374// Thest that the evaluation of expressions when a break point is hit generates
2375// the correct results.
2376TEST(DebugEvaluate) {
2377 v8::HandleScope scope;
2378 DebugLocalContext env;
2379 env.ExposeDebug();
2380
2381 // Create a function for checking the evaluation when hitting a break point.
2382 evaluate_check_function = CompileFunction(&env,
2383 evaluate_check_source,
2384 "evaluate_check");
2385 // Register the debug event listener
2386 v8::Debug::SetDebugEventListener(DebugEventEvaluate);
2387
2388 // Different expected vaules of x and a when in a break point (u = undefined,
2389 // d = Hello, world!).
2390 struct EvaluateCheck checks_uu[] = {
2391 {"x", v8::Undefined()},
2392 {"a", v8::Undefined()},
2393 {NULL, v8::Handle<v8::Value>()}
2394 };
2395 struct EvaluateCheck checks_hu[] = {
2396 {"x", v8::String::New("Hello, world!")},
2397 {"a", v8::Undefined()},
2398 {NULL, v8::Handle<v8::Value>()}
2399 };
2400 struct EvaluateCheck checks_hh[] = {
2401 {"x", v8::String::New("Hello, world!")},
2402 {"a", v8::String::New("Hello, world!")},
2403 {NULL, v8::Handle<v8::Value>()}
2404 };
2405
2406 // Simple test function. The "y=0" is in the function foo to provide a break
2407 // location. For "y=0" the "y" is at position 15 in the barbar function
2408 // therefore setting breakpoint at position 15 will break at "y=0" and
2409 // setting it higher will break after.
2410 v8::Local<v8::Function> foo = CompileFunction(&env,
2411 "function foo(x) {"
2412 " var a;"
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002413 " y=0;" // To ensure break location 1.
Steve Blocka7e24c12009-10-30 11:49:00 +00002414 " a=x;"
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002415 " y=0;" // To ensure break location 2.
Steve Blocka7e24c12009-10-30 11:49:00 +00002416 "}",
2417 "foo");
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002418 const int foo_break_position_1 = 15;
2419 const int foo_break_position_2 = 29;
Steve Blocka7e24c12009-10-30 11:49:00 +00002420
2421 // Arguments with one parameter "Hello, world!"
2422 v8::Handle<v8::Value> argv_foo[1] = { v8::String::New("Hello, world!") };
2423
2424 // Call foo with breakpoint set before a=x and undefined as parameter.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002425 int bp = SetBreakPoint(foo, foo_break_position_1);
Steve Blocka7e24c12009-10-30 11:49:00 +00002426 checks = checks_uu;
2427 foo->Call(env->Global(), 0, NULL);
2428
2429 // Call foo with breakpoint set before a=x and parameter "Hello, world!".
2430 checks = checks_hu;
2431 foo->Call(env->Global(), 1, argv_foo);
2432
2433 // Call foo with breakpoint set after a=x and parameter "Hello, world!".
2434 ClearBreakPoint(bp);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002435 SetBreakPoint(foo, foo_break_position_2);
Steve Blocka7e24c12009-10-30 11:49:00 +00002436 checks = checks_hh;
2437 foo->Call(env->Global(), 1, argv_foo);
2438
2439 // Test function with an inner function. The "y=0" is in function barbar
2440 // to provide a break location. For "y=0" the "y" is at position 8 in the
2441 // barbar function therefore setting breakpoint at position 8 will break at
2442 // "y=0" and setting it higher will break after.
2443 v8::Local<v8::Function> bar = CompileFunction(&env,
2444 "y = 0;"
2445 "x = 'Goodbye, world!';"
2446 "function bar(x, b) {"
2447 " var a;"
2448 " function barbar() {"
2449 " y=0; /* To ensure break location.*/"
2450 " a=x;"
2451 " };"
2452 " debug.Debug.clearAllBreakPoints();"
2453 " barbar();"
2454 " y=0;a=x;"
2455 "}",
2456 "bar");
2457 const int barbar_break_position = 8;
2458
2459 // Call bar setting breakpoint before a=x in barbar and undefined as
2460 // parameter.
2461 checks = checks_uu;
2462 v8::Handle<v8::Value> argv_bar_1[2] = {
2463 v8::Undefined(),
2464 v8::Number::New(barbar_break_position)
2465 };
2466 bar->Call(env->Global(), 2, argv_bar_1);
2467
2468 // Call bar setting breakpoint before a=x in barbar and parameter
2469 // "Hello, world!".
2470 checks = checks_hu;
2471 v8::Handle<v8::Value> argv_bar_2[2] = {
2472 v8::String::New("Hello, world!"),
2473 v8::Number::New(barbar_break_position)
2474 };
2475 bar->Call(env->Global(), 2, argv_bar_2);
2476
2477 // Call bar setting breakpoint after a=x in barbar and parameter
2478 // "Hello, world!".
2479 checks = checks_hh;
2480 v8::Handle<v8::Value> argv_bar_3[2] = {
2481 v8::String::New("Hello, world!"),
2482 v8::Number::New(barbar_break_position + 1)
2483 };
2484 bar->Call(env->Global(), 2, argv_bar_3);
2485
2486 v8::Debug::SetDebugEventListener(NULL);
2487 CheckDebuggerUnloaded();
2488}
2489
Leon Clarkee46be812010-01-19 14:06:41 +00002490// Copies a C string to a 16-bit string. Does not check for buffer overflow.
2491// Does not use the V8 engine to convert strings, so it can be used
2492// in any thread. Returns the length of the string.
2493int AsciiToUtf16(const char* input_buffer, uint16_t* output_buffer) {
2494 int i;
2495 for (i = 0; input_buffer[i] != '\0'; ++i) {
2496 // ASCII does not use chars > 127, but be careful anyway.
2497 output_buffer[i] = static_cast<unsigned char>(input_buffer[i]);
2498 }
2499 output_buffer[i] = 0;
2500 return i;
2501}
2502
2503// Copies a 16-bit string to a C string by dropping the high byte of
2504// each character. Does not check for buffer overflow.
2505// Can be used in any thread. Requires string length as an input.
2506int Utf16ToAscii(const uint16_t* input_buffer, int length,
2507 char* output_buffer, int output_len = -1) {
2508 if (output_len >= 0) {
2509 if (length > output_len - 1) {
2510 length = output_len - 1;
2511 }
2512 }
2513
2514 for (int i = 0; i < length; ++i) {
2515 output_buffer[i] = static_cast<char>(input_buffer[i]);
2516 }
2517 output_buffer[length] = '\0';
2518 return length;
2519}
2520
2521
2522// We match parts of the message to get evaluate result int value.
2523bool GetEvaluateStringResult(char *message, char* buffer, int buffer_size) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002524 if (strstr(message, "\"command\":\"evaluate\"") == NULL) {
2525 return false;
2526 }
2527 const char* prefix = "\"text\":\"";
2528 char* pos1 = strstr(message, prefix);
2529 if (pos1 == NULL) {
2530 return false;
2531 }
2532 pos1 += strlen(prefix);
2533 char* pos2 = strchr(pos1, '"');
2534 if (pos2 == NULL) {
Leon Clarkee46be812010-01-19 14:06:41 +00002535 return false;
2536 }
2537 Vector<char> buf(buffer, buffer_size);
Leon Clarked91b9f72010-01-27 17:25:45 +00002538 int len = static_cast<int>(pos2 - pos1);
2539 if (len > buffer_size - 1) {
2540 len = buffer_size - 1;
2541 }
2542 OS::StrNCpy(buf, pos1, len);
Leon Clarkee46be812010-01-19 14:06:41 +00002543 buffer[buffer_size - 1] = '\0';
2544 return true;
2545}
2546
2547
2548struct EvaluateResult {
2549 static const int kBufferSize = 20;
2550 char buffer[kBufferSize];
2551};
2552
2553struct DebugProcessDebugMessagesData {
2554 static const int kArraySize = 5;
2555 int counter;
2556 EvaluateResult results[kArraySize];
2557
2558 void reset() {
2559 counter = 0;
2560 }
2561 EvaluateResult* current() {
2562 return &results[counter % kArraySize];
2563 }
2564 void next() {
2565 counter++;
2566 }
2567};
2568
2569DebugProcessDebugMessagesData process_debug_messages_data;
2570
2571static void DebugProcessDebugMessagesHandler(
2572 const uint16_t* message,
2573 int length,
2574 v8::Debug::ClientData* client_data) {
2575
2576 const int kBufferSize = 100000;
2577 char print_buffer[kBufferSize];
2578 Utf16ToAscii(message, length, print_buffer, kBufferSize);
2579
2580 EvaluateResult* array_item = process_debug_messages_data.current();
2581
2582 bool res = GetEvaluateStringResult(print_buffer,
2583 array_item->buffer,
2584 EvaluateResult::kBufferSize);
2585 if (res) {
2586 process_debug_messages_data.next();
2587 }
2588}
2589
2590// Test that the evaluation of expressions works even from ProcessDebugMessages
2591// i.e. with empty stack.
2592TEST(DebugEvaluateWithoutStack) {
2593 v8::Debug::SetMessageHandler(DebugProcessDebugMessagesHandler);
2594
2595 v8::HandleScope scope;
2596 DebugLocalContext env;
2597
2598 const char* source =
2599 "var v1 = 'Pinguin';\n function getAnimal() { return 'Capy' + 'bara'; }";
2600
2601 v8::Script::Compile(v8::String::New(source))->Run();
2602
2603 v8::Debug::ProcessDebugMessages();
2604
2605 const int kBufferSize = 1000;
2606 uint16_t buffer[kBufferSize];
2607
2608 const char* command_111 = "{\"seq\":111,"
2609 "\"type\":\"request\","
2610 "\"command\":\"evaluate\","
2611 "\"arguments\":{"
2612 " \"global\":true,"
2613 " \"expression\":\"v1\",\"disable_break\":true"
2614 "}}";
2615
2616 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_111, buffer));
2617
2618 const char* command_112 = "{\"seq\":112,"
2619 "\"type\":\"request\","
2620 "\"command\":\"evaluate\","
2621 "\"arguments\":{"
2622 " \"global\":true,"
2623 " \"expression\":\"getAnimal()\",\"disable_break\":true"
2624 "}}";
2625
2626 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_112, buffer));
2627
2628 const char* command_113 = "{\"seq\":113,"
2629 "\"type\":\"request\","
2630 "\"command\":\"evaluate\","
2631 "\"arguments\":{"
2632 " \"global\":true,"
2633 " \"expression\":\"239 + 566\",\"disable_break\":true"
2634 "}}";
2635
2636 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_113, buffer));
2637
2638 v8::Debug::ProcessDebugMessages();
2639
2640 CHECK_EQ(3, process_debug_messages_data.counter);
2641
Leon Clarked91b9f72010-01-27 17:25:45 +00002642 CHECK_EQ(strcmp("Pinguin", process_debug_messages_data.results[0].buffer), 0);
2643 CHECK_EQ(strcmp("Capybara", process_debug_messages_data.results[1].buffer),
2644 0);
2645 CHECK_EQ(strcmp("805", process_debug_messages_data.results[2].buffer), 0);
Leon Clarkee46be812010-01-19 14:06:41 +00002646
2647 v8::Debug::SetMessageHandler(NULL);
2648 v8::Debug::SetDebugEventListener(NULL);
2649 CheckDebuggerUnloaded();
2650}
2651
Steve Blocka7e24c12009-10-30 11:49:00 +00002652
2653// Simple test of the stepping mechanism using only store ICs.
2654TEST(DebugStepLinear) {
2655 v8::HandleScope scope;
2656 DebugLocalContext env;
2657
2658 // Create a function for testing stepping.
2659 v8::Local<v8::Function> foo = CompileFunction(&env,
2660 "function foo(){a=1;b=1;c=1;}",
2661 "foo");
Ben Murdochb0fe1622011-05-05 13:52:32 +01002662
2663 // Run foo to allow it to get optimized.
2664 CompileRun("a=0; b=0; c=0; foo();");
2665
Steve Blocka7e24c12009-10-30 11:49:00 +00002666 SetBreakPoint(foo, 3);
2667
2668 // Register a debug event listener which steps and counts.
2669 v8::Debug::SetDebugEventListener(DebugEventStep);
2670
2671 step_action = StepIn;
2672 break_point_hit_count = 0;
2673 foo->Call(env->Global(), 0, NULL);
2674
2675 // With stepping all break locations are hit.
2676 CHECK_EQ(4, break_point_hit_count);
2677
2678 v8::Debug::SetDebugEventListener(NULL);
2679 CheckDebuggerUnloaded();
2680
2681 // Register a debug event listener which just counts.
2682 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2683
2684 SetBreakPoint(foo, 3);
2685 break_point_hit_count = 0;
2686 foo->Call(env->Global(), 0, NULL);
2687
2688 // Without stepping only active break points are hit.
2689 CHECK_EQ(1, break_point_hit_count);
2690
2691 v8::Debug::SetDebugEventListener(NULL);
2692 CheckDebuggerUnloaded();
2693}
2694
2695
2696// Test of the stepping mechanism for keyed load in a loop.
2697TEST(DebugStepKeyedLoadLoop) {
2698 v8::HandleScope scope;
2699 DebugLocalContext env;
2700
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002701 // Register a debug event listener which steps and counts.
2702 v8::Debug::SetDebugEventListener(DebugEventStep);
2703
Steve Blocka7e24c12009-10-30 11:49:00 +00002704 // Create a function for testing stepping of keyed load. The statement 'y=1'
2705 // is there to have more than one breakable statement in the loop, TODO(315).
2706 v8::Local<v8::Function> foo = CompileFunction(
2707 &env,
2708 "function foo(a) {\n"
2709 " var x;\n"
2710 " var len = a.length;\n"
2711 " for (var i = 0; i < len; i++) {\n"
2712 " y = 1;\n"
2713 " x = a[i];\n"
2714 " }\n"
Ben Murdochb0fe1622011-05-05 13:52:32 +01002715 "}\n"
2716 "y=0\n",
Steve Blocka7e24c12009-10-30 11:49:00 +00002717 "foo");
2718
2719 // Create array [0,1,2,3,4,5,6,7,8,9]
2720 v8::Local<v8::Array> a = v8::Array::New(10);
2721 for (int i = 0; i < 10; i++) {
2722 a->Set(v8::Number::New(i), v8::Number::New(i));
2723 }
2724
2725 // Call function without any break points to ensure inlining is in place.
2726 const int kArgc = 1;
2727 v8::Handle<v8::Value> args[kArgc] = { a };
2728 foo->Call(env->Global(), kArgc, args);
2729
Steve Blocka7e24c12009-10-30 11:49:00 +00002730 // Setup break point and step through the function.
2731 SetBreakPoint(foo, 3);
2732 step_action = StepNext;
2733 break_point_hit_count = 0;
2734 foo->Call(env->Global(), kArgc, args);
2735
2736 // With stepping all break locations are hit.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002737 CHECK_EQ(33, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002738
2739 v8::Debug::SetDebugEventListener(NULL);
2740 CheckDebuggerUnloaded();
2741}
2742
2743
2744// Test of the stepping mechanism for keyed store in a loop.
2745TEST(DebugStepKeyedStoreLoop) {
2746 v8::HandleScope scope;
2747 DebugLocalContext env;
2748
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002749 // Register a debug event listener which steps and counts.
2750 v8::Debug::SetDebugEventListener(DebugEventStep);
2751
Steve Blocka7e24c12009-10-30 11:49:00 +00002752 // Create a function for testing stepping of keyed store. The statement 'y=1'
2753 // is there to have more than one breakable statement in the loop, TODO(315).
2754 v8::Local<v8::Function> foo = CompileFunction(
2755 &env,
2756 "function foo(a) {\n"
2757 " var len = a.length;\n"
2758 " for (var i = 0; i < len; i++) {\n"
2759 " y = 1;\n"
2760 " a[i] = 42;\n"
2761 " }\n"
Ben Murdochb0fe1622011-05-05 13:52:32 +01002762 "}\n"
2763 "y=0\n",
Steve Blocka7e24c12009-10-30 11:49:00 +00002764 "foo");
2765
2766 // Create array [0,1,2,3,4,5,6,7,8,9]
2767 v8::Local<v8::Array> a = v8::Array::New(10);
2768 for (int i = 0; i < 10; i++) {
2769 a->Set(v8::Number::New(i), v8::Number::New(i));
2770 }
2771
2772 // Call function without any break points to ensure inlining is in place.
2773 const int kArgc = 1;
2774 v8::Handle<v8::Value> args[kArgc] = { a };
2775 foo->Call(env->Global(), kArgc, args);
2776
Steve Blocka7e24c12009-10-30 11:49:00 +00002777 // Setup break point and step through the function.
2778 SetBreakPoint(foo, 3);
2779 step_action = StepNext;
2780 break_point_hit_count = 0;
2781 foo->Call(env->Global(), kArgc, args);
2782
2783 // With stepping all break locations are hit.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002784 CHECK_EQ(32, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002785
2786 v8::Debug::SetDebugEventListener(NULL);
2787 CheckDebuggerUnloaded();
2788}
2789
2790
Kristian Monsen25f61362010-05-21 11:50:48 +01002791// Test of the stepping mechanism for named load in a loop.
2792TEST(DebugStepNamedLoadLoop) {
2793 v8::HandleScope scope;
2794 DebugLocalContext env;
2795
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002796 // Register a debug event listener which steps and counts.
2797 v8::Debug::SetDebugEventListener(DebugEventStep);
2798
Kristian Monsen25f61362010-05-21 11:50:48 +01002799 // Create a function for testing stepping of named load.
2800 v8::Local<v8::Function> foo = CompileFunction(
2801 &env,
2802 "function foo() {\n"
2803 " var a = [];\n"
2804 " var s = \"\";\n"
2805 " for (var i = 0; i < 10; i++) {\n"
2806 " var v = new V(i, i + 1);\n"
2807 " v.y;\n"
2808 " a.length;\n" // Special case: array length.
2809 " s.length;\n" // Special case: string length.
2810 " }\n"
2811 "}\n"
2812 "function V(x, y) {\n"
2813 " this.x = x;\n"
2814 " this.y = y;\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
Kristian Monsen25f61362010-05-21 11:50:48 +01002821 // Setup break point and step through the function.
2822 SetBreakPoint(foo, 4);
2823 step_action = StepNext;
2824 break_point_hit_count = 0;
2825 foo->Call(env->Global(), 0, NULL);
2826
2827 // With stepping all break locations are hit.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002828 CHECK_EQ(53, break_point_hit_count);
Kristian Monsen25f61362010-05-21 11:50:48 +01002829
2830 v8::Debug::SetDebugEventListener(NULL);
2831 CheckDebuggerUnloaded();
2832}
2833
2834
Ben Murdochb0fe1622011-05-05 13:52:32 +01002835static void DoDebugStepNamedStoreLoop(int expected) {
Iain Merrick75681382010-08-19 15:07:18 +01002836 v8::HandleScope scope;
2837 DebugLocalContext env;
2838
Ben Murdochb0fe1622011-05-05 13:52:32 +01002839 // Register a debug event listener which steps and counts.
2840 v8::Debug::SetDebugEventListener(DebugEventStep);
Iain Merrick75681382010-08-19 15:07:18 +01002841
2842 // Create a function for testing stepping of named store.
2843 v8::Local<v8::Function> foo = CompileFunction(
2844 &env,
2845 "function foo() {\n"
2846 " var a = {a:1};\n"
2847 " for (var i = 0; i < 10; i++) {\n"
2848 " a.a = 2\n"
2849 " }\n"
2850 "}\n",
2851 "foo");
2852
2853 // Call function without any break points to ensure inlining is in place.
2854 foo->Call(env->Global(), 0, NULL);
2855
Iain Merrick75681382010-08-19 15:07:18 +01002856 // Setup break point and step through the function.
2857 SetBreakPoint(foo, 3);
2858 step_action = StepNext;
2859 break_point_hit_count = 0;
2860 foo->Call(env->Global(), 0, NULL);
2861
2862 // With stepping all expected break locations are hit.
2863 CHECK_EQ(expected, break_point_hit_count);
2864
2865 v8::Debug::SetDebugEventListener(NULL);
2866 CheckDebuggerUnloaded();
2867}
2868
2869
2870// Test of the stepping mechanism for named load in a loop.
Ben Murdochb0fe1622011-05-05 13:52:32 +01002871TEST(DebugStepNamedStoreLoop) {
Iain Merrick75681382010-08-19 15:07:18 +01002872 DoDebugStepNamedStoreLoop(22);
2873}
2874
2875
Steve Blocka7e24c12009-10-30 11:49:00 +00002876// Test the stepping mechanism with different ICs.
2877TEST(DebugStepLinearMixedICs) {
2878 v8::HandleScope scope;
2879 DebugLocalContext env;
2880
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002881 // Register a debug event listener which steps and counts.
2882 v8::Debug::SetDebugEventListener(DebugEventStep);
2883
Steve Blocka7e24c12009-10-30 11:49:00 +00002884 // Create a function for testing stepping.
2885 v8::Local<v8::Function> foo = CompileFunction(&env,
2886 "function bar() {};"
2887 "function foo() {"
2888 " var x;"
2889 " var index='name';"
2890 " var y = {};"
2891 " a=1;b=2;x=a;y[index]=3;x=y[index];bar();}", "foo");
Ben Murdochb0fe1622011-05-05 13:52:32 +01002892
2893 // Run functions to allow them to get optimized.
2894 CompileRun("a=0; b=0; bar(); foo();");
2895
Steve Blocka7e24c12009-10-30 11:49:00 +00002896 SetBreakPoint(foo, 0);
2897
Steve Blocka7e24c12009-10-30 11:49:00 +00002898 step_action = StepIn;
2899 break_point_hit_count = 0;
2900 foo->Call(env->Global(), 0, NULL);
2901
2902 // With stepping all break locations are hit.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002903 CHECK_EQ(11, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00002904
2905 v8::Debug::SetDebugEventListener(NULL);
2906 CheckDebuggerUnloaded();
2907
2908 // Register a debug event listener which just counts.
2909 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
2910
2911 SetBreakPoint(foo, 0);
2912 break_point_hit_count = 0;
2913 foo->Call(env->Global(), 0, NULL);
2914
2915 // Without stepping only active break points are hit.
2916 CHECK_EQ(1, break_point_hit_count);
2917
2918 v8::Debug::SetDebugEventListener(NULL);
2919 CheckDebuggerUnloaded();
2920}
2921
2922
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002923TEST(DebugStepDeclarations) {
2924 v8::HandleScope scope;
2925 DebugLocalContext env;
2926
2927 // Register a debug event listener which steps and counts.
2928 v8::Debug::SetDebugEventListener(DebugEventStep);
2929
Ben Murdochb0fe1622011-05-05 13:52:32 +01002930 // Create a function for testing stepping. Run it to allow it to get
2931 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002932 const char* src = "function foo() { "
2933 " var a;"
2934 " var b = 1;"
2935 " var c = foo;"
2936 " var d = Math.floor;"
2937 " var e = b + d(1.2);"
Ben Murdochb0fe1622011-05-05 13:52:32 +01002938 "}"
2939 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002940 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
Ben Murdochb0fe1622011-05-05 13:52:32 +01002941
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002942 SetBreakPoint(foo, 0);
2943
2944 // Stepping through the declarations.
2945 step_action = StepIn;
2946 break_point_hit_count = 0;
2947 foo->Call(env->Global(), 0, NULL);
2948 CHECK_EQ(6, break_point_hit_count);
2949
2950 // Get rid of the debug event listener.
2951 v8::Debug::SetDebugEventListener(NULL);
2952 CheckDebuggerUnloaded();
2953}
2954
2955
2956TEST(DebugStepLocals) {
2957 v8::HandleScope scope;
2958 DebugLocalContext env;
2959
2960 // Register a debug event listener which steps and counts.
2961 v8::Debug::SetDebugEventListener(DebugEventStep);
2962
Ben Murdochb0fe1622011-05-05 13:52:32 +01002963 // Create a function for testing stepping. Run it to allow it to get
2964 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002965 const char* src = "function foo() { "
2966 " var a,b;"
2967 " a = 1;"
2968 " b = a + 2;"
2969 " b = 1 + 2 + 3;"
2970 " a = Math.floor(b);"
Ben Murdochb0fe1622011-05-05 13:52:32 +01002971 "}"
2972 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002973 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
Ben Murdochb0fe1622011-05-05 13:52:32 +01002974
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002975 SetBreakPoint(foo, 0);
2976
2977 // Stepping through the declarations.
2978 step_action = StepIn;
2979 break_point_hit_count = 0;
2980 foo->Call(env->Global(), 0, NULL);
2981 CHECK_EQ(6, break_point_hit_count);
2982
2983 // Get rid of the debug event listener.
2984 v8::Debug::SetDebugEventListener(NULL);
2985 CheckDebuggerUnloaded();
2986}
2987
2988
Steve Blocka7e24c12009-10-30 11:49:00 +00002989TEST(DebugStepIf) {
2990 v8::HandleScope scope;
2991 DebugLocalContext env;
2992
2993 // Register a debug event listener which steps and counts.
2994 v8::Debug::SetDebugEventListener(DebugEventStep);
2995
Ben Murdochb0fe1622011-05-05 13:52:32 +01002996 // Create a function for testing stepping. Run it to allow it to get
2997 // optimized.
Steve Blocka7e24c12009-10-30 11:49:00 +00002998 const int argc = 1;
2999 const char* src = "function foo(x) { "
3000 " a = 1;"
3001 " if (x) {"
3002 " b = 1;"
3003 " } else {"
3004 " c = 1;"
3005 " d = 1;"
3006 " }"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003007 "}"
3008 "a=0; b=0; c=0; d=0; foo()";
Steve Blocka7e24c12009-10-30 11:49:00 +00003009 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3010 SetBreakPoint(foo, 0);
3011
3012 // Stepping through the true part.
3013 step_action = StepIn;
3014 break_point_hit_count = 0;
3015 v8::Handle<v8::Value> argv_true[argc] = { v8::True() };
3016 foo->Call(env->Global(), argc, argv_true);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003017 CHECK_EQ(4, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003018
3019 // Stepping through the false part.
3020 step_action = StepIn;
3021 break_point_hit_count = 0;
3022 v8::Handle<v8::Value> argv_false[argc] = { v8::False() };
3023 foo->Call(env->Global(), argc, argv_false);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003024 CHECK_EQ(5, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003025
3026 // Get rid of the debug event listener.
3027 v8::Debug::SetDebugEventListener(NULL);
3028 CheckDebuggerUnloaded();
3029}
3030
3031
3032TEST(DebugStepSwitch) {
3033 v8::HandleScope scope;
3034 DebugLocalContext env;
3035
3036 // Register a debug event listener which steps and counts.
3037 v8::Debug::SetDebugEventListener(DebugEventStep);
3038
Ben Murdochb0fe1622011-05-05 13:52:32 +01003039 // Create a function for testing stepping. Run it to allow it to get
3040 // optimized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003041 const int argc = 1;
3042 const char* src = "function foo(x) { "
3043 " a = 1;"
3044 " switch (x) {"
3045 " case 1:"
3046 " b = 1;"
3047 " case 2:"
3048 " c = 1;"
3049 " break;"
3050 " case 3:"
3051 " d = 1;"
3052 " e = 1;"
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003053 " f = 1;"
Steve Blocka7e24c12009-10-30 11:49:00 +00003054 " break;"
3055 " }"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003056 "}"
3057 "a=0; b=0; c=0; d=0; e=0; f=0; foo()";
Steve Blocka7e24c12009-10-30 11:49:00 +00003058 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3059 SetBreakPoint(foo, 0);
3060
3061 // One case with fall-through.
3062 step_action = StepIn;
3063 break_point_hit_count = 0;
3064 v8::Handle<v8::Value> argv_1[argc] = { v8::Number::New(1) };
3065 foo->Call(env->Global(), argc, argv_1);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003066 CHECK_EQ(6, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003067
3068 // Another case.
3069 step_action = StepIn;
3070 break_point_hit_count = 0;
3071 v8::Handle<v8::Value> argv_2[argc] = { v8::Number::New(2) };
3072 foo->Call(env->Global(), argc, argv_2);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003073 CHECK_EQ(5, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003074
3075 // Last case.
3076 step_action = StepIn;
3077 break_point_hit_count = 0;
3078 v8::Handle<v8::Value> argv_3[argc] = { v8::Number::New(3) };
3079 foo->Call(env->Global(), argc, argv_3);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003080 CHECK_EQ(7, break_point_hit_count);
3081
3082 // Get rid of the debug event listener.
3083 v8::Debug::SetDebugEventListener(NULL);
3084 CheckDebuggerUnloaded();
3085}
3086
3087
3088TEST(DebugStepWhile) {
3089 v8::HandleScope scope;
3090 DebugLocalContext env;
3091
3092 // Register a debug event listener which steps and counts.
3093 v8::Debug::SetDebugEventListener(DebugEventStep);
3094
Ben Murdochb0fe1622011-05-05 13:52:32 +01003095 // Create a function for testing stepping. Run it to allow it to get
3096 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003097 const int argc = 1;
3098 const char* src = "function foo(x) { "
3099 " var a = 0;"
3100 " while (a < x) {"
3101 " a++;"
3102 " }"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003103 "}"
3104 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003105 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3106 SetBreakPoint(foo, 8); // "var a = 0;"
3107
3108 // Looping 10 times.
3109 step_action = StepIn;
3110 break_point_hit_count = 0;
3111 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) };
3112 foo->Call(env->Global(), argc, argv_10);
Ben Murdochb0fe1622011-05-05 13:52:32 +01003113 CHECK_EQ(22, break_point_hit_count);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003114
3115 // Looping 100 times.
3116 step_action = StepIn;
3117 break_point_hit_count = 0;
3118 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) };
3119 foo->Call(env->Global(), argc, argv_100);
Ben Murdochb0fe1622011-05-05 13:52:32 +01003120 CHECK_EQ(202, break_point_hit_count);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003121
3122 // Get rid of the debug event listener.
3123 v8::Debug::SetDebugEventListener(NULL);
3124 CheckDebuggerUnloaded();
3125}
3126
3127
3128TEST(DebugStepDoWhile) {
3129 v8::HandleScope scope;
3130 DebugLocalContext env;
3131
3132 // Register a debug event listener which steps and counts.
3133 v8::Debug::SetDebugEventListener(DebugEventStep);
3134
Ben Murdochb0fe1622011-05-05 13:52:32 +01003135 // Create a function for testing stepping. Run it to allow it to get
3136 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003137 const int argc = 1;
3138 const char* src = "function foo(x) { "
3139 " var a = 0;"
3140 " do {"
3141 " a++;"
3142 " } while (a < x)"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003143 "}"
3144 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003145 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3146 SetBreakPoint(foo, 8); // "var a = 0;"
3147
3148 // Looping 10 times.
3149 step_action = StepIn;
3150 break_point_hit_count = 0;
3151 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) };
3152 foo->Call(env->Global(), argc, argv_10);
3153 CHECK_EQ(22, break_point_hit_count);
3154
3155 // Looping 100 times.
3156 step_action = StepIn;
3157 break_point_hit_count = 0;
3158 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) };
3159 foo->Call(env->Global(), argc, argv_100);
3160 CHECK_EQ(202, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003161
3162 // Get rid of the debug event listener.
3163 v8::Debug::SetDebugEventListener(NULL);
3164 CheckDebuggerUnloaded();
3165}
3166
3167
3168TEST(DebugStepFor) {
3169 v8::HandleScope scope;
3170 DebugLocalContext env;
3171
3172 // Register a debug event listener which steps and counts.
3173 v8::Debug::SetDebugEventListener(DebugEventStep);
3174
Ben Murdochb0fe1622011-05-05 13:52:32 +01003175 // Create a function for testing stepping. Run it to allow it to get
3176 // optimized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003177 const int argc = 1;
3178 const char* src = "function foo(x) { "
3179 " a = 1;"
3180 " for (i = 0; i < x; i++) {"
3181 " b = 1;"
3182 " }"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003183 "}"
3184 "a=0; b=0; i=0; foo()";
Steve Blocka7e24c12009-10-30 11:49:00 +00003185 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
Ben Murdochb0fe1622011-05-05 13:52:32 +01003186
Steve Blocka7e24c12009-10-30 11:49:00 +00003187 SetBreakPoint(foo, 8); // "a = 1;"
3188
3189 // Looping 10 times.
3190 step_action = StepIn;
3191 break_point_hit_count = 0;
3192 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) };
3193 foo->Call(env->Global(), argc, argv_10);
3194 CHECK_EQ(23, break_point_hit_count);
3195
3196 // Looping 100 times.
3197 step_action = StepIn;
3198 break_point_hit_count = 0;
3199 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) };
3200 foo->Call(env->Global(), argc, argv_100);
3201 CHECK_EQ(203, break_point_hit_count);
3202
3203 // Get rid of the debug event listener.
3204 v8::Debug::SetDebugEventListener(NULL);
3205 CheckDebuggerUnloaded();
3206}
3207
3208
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003209TEST(DebugStepForContinue) {
3210 v8::HandleScope scope;
3211 DebugLocalContext env;
3212
3213 // Register a debug event listener which steps and counts.
3214 v8::Debug::SetDebugEventListener(DebugEventStep);
3215
Ben Murdochb0fe1622011-05-05 13:52:32 +01003216 // Create a function for testing stepping. Run it to allow it to get
3217 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003218 const int argc = 1;
3219 const char* src = "function foo(x) { "
3220 " var a = 0;"
3221 " var b = 0;"
3222 " var c = 0;"
3223 " for (var i = 0; i < x; i++) {"
3224 " a++;"
3225 " if (a % 2 == 0) continue;"
3226 " b++;"
3227 " c++;"
3228 " }"
3229 " return b;"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003230 "}"
3231 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003232 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3233 v8::Handle<v8::Value> result;
3234 SetBreakPoint(foo, 8); // "var a = 0;"
3235
3236 // Each loop generates 4 or 5 steps depending on whether a is equal.
3237
3238 // Looping 10 times.
3239 step_action = StepIn;
3240 break_point_hit_count = 0;
3241 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) };
3242 result = foo->Call(env->Global(), argc, argv_10);
3243 CHECK_EQ(5, result->Int32Value());
3244 CHECK_EQ(50, break_point_hit_count);
3245
3246 // Looping 100 times.
3247 step_action = StepIn;
3248 break_point_hit_count = 0;
3249 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) };
3250 result = foo->Call(env->Global(), argc, argv_100);
3251 CHECK_EQ(50, result->Int32Value());
3252 CHECK_EQ(455, break_point_hit_count);
3253
3254 // Get rid of the debug event listener.
3255 v8::Debug::SetDebugEventListener(NULL);
3256 CheckDebuggerUnloaded();
3257}
3258
3259
3260TEST(DebugStepForBreak) {
3261 v8::HandleScope scope;
3262 DebugLocalContext env;
3263
3264 // Register a debug event listener which steps and counts.
3265 v8::Debug::SetDebugEventListener(DebugEventStep);
3266
Ben Murdochb0fe1622011-05-05 13:52:32 +01003267 // Create a function for testing stepping. Run it to allow it to get
3268 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003269 const int argc = 1;
3270 const char* src = "function foo(x) { "
3271 " var a = 0;"
3272 " var b = 0;"
3273 " var c = 0;"
3274 " for (var i = 0; i < 1000; i++) {"
3275 " a++;"
3276 " if (a == x) break;"
3277 " b++;"
3278 " c++;"
3279 " }"
3280 " return b;"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003281 "}"
3282 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003283 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3284 v8::Handle<v8::Value> result;
3285 SetBreakPoint(foo, 8); // "var a = 0;"
3286
3287 // Each loop generates 5 steps except for the last (when break is executed)
3288 // which only generates 4.
3289
3290 // Looping 10 times.
3291 step_action = StepIn;
3292 break_point_hit_count = 0;
3293 v8::Handle<v8::Value> argv_10[argc] = { v8::Number::New(10) };
3294 result = foo->Call(env->Global(), argc, argv_10);
3295 CHECK_EQ(9, result->Int32Value());
3296 CHECK_EQ(53, break_point_hit_count);
3297
3298 // Looping 100 times.
3299 step_action = StepIn;
3300 break_point_hit_count = 0;
3301 v8::Handle<v8::Value> argv_100[argc] = { v8::Number::New(100) };
3302 result = foo->Call(env->Global(), argc, argv_100);
3303 CHECK_EQ(99, result->Int32Value());
3304 CHECK_EQ(503, break_point_hit_count);
3305
3306 // Get rid of the debug event listener.
3307 v8::Debug::SetDebugEventListener(NULL);
3308 CheckDebuggerUnloaded();
3309}
3310
3311
3312TEST(DebugStepForIn) {
3313 v8::HandleScope scope;
3314 DebugLocalContext env;
3315
3316 // Register a debug event listener which steps and counts.
3317 v8::Debug::SetDebugEventListener(DebugEventStep);
3318
Ben Murdochb0fe1622011-05-05 13:52:32 +01003319 // Create a function for testing stepping. Run it to allow it to get
3320 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003321 v8::Local<v8::Function> foo;
3322 const char* src_1 = "function foo() { "
3323 " var a = [1, 2];"
3324 " for (x in a) {"
3325 " b = 0;"
3326 " }"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003327 "}"
3328 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003329 foo = CompileFunction(&env, src_1, "foo");
3330 SetBreakPoint(foo, 0); // "var a = ..."
3331
3332 step_action = StepIn;
3333 break_point_hit_count = 0;
3334 foo->Call(env->Global(), 0, NULL);
3335 CHECK_EQ(6, break_point_hit_count);
3336
Ben Murdochb0fe1622011-05-05 13:52:32 +01003337 // Create a function for testing stepping. Run it to allow it to get
3338 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003339 const char* src_2 = "function foo() { "
3340 " var a = {a:[1, 2, 3]};"
3341 " for (x in a.a) {"
3342 " b = 0;"
3343 " }"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003344 "}"
3345 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003346 foo = CompileFunction(&env, src_2, "foo");
3347 SetBreakPoint(foo, 0); // "var a = ..."
3348
3349 step_action = StepIn;
3350 break_point_hit_count = 0;
3351 foo->Call(env->Global(), 0, NULL);
3352 CHECK_EQ(8, break_point_hit_count);
3353
3354 // Get rid of the debug event listener.
3355 v8::Debug::SetDebugEventListener(NULL);
3356 CheckDebuggerUnloaded();
3357}
3358
3359
3360TEST(DebugStepWith) {
3361 v8::HandleScope scope;
3362 DebugLocalContext env;
3363
3364 // Register a debug event listener which steps and counts.
3365 v8::Debug::SetDebugEventListener(DebugEventStep);
3366
Ben Murdochb0fe1622011-05-05 13:52:32 +01003367 // Create a function for testing stepping. Run it to allow it to get
3368 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003369 const char* src = "function foo(x) { "
3370 " var a = {};"
3371 " with (a) {}"
3372 " with (b) {}"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003373 "}"
3374 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003375 env->Global()->Set(v8::String::New("b"), v8::Object::New());
3376 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3377 v8::Handle<v8::Value> result;
3378 SetBreakPoint(foo, 8); // "var a = {};"
3379
3380 step_action = StepIn;
3381 break_point_hit_count = 0;
3382 foo->Call(env->Global(), 0, NULL);
3383 CHECK_EQ(4, break_point_hit_count);
3384
3385 // Get rid of the debug event listener.
3386 v8::Debug::SetDebugEventListener(NULL);
3387 CheckDebuggerUnloaded();
3388}
3389
3390
3391TEST(DebugConditional) {
3392 v8::HandleScope scope;
3393 DebugLocalContext env;
3394
3395 // Register a debug event listener which steps and counts.
3396 v8::Debug::SetDebugEventListener(DebugEventStep);
3397
Ben Murdochb0fe1622011-05-05 13:52:32 +01003398 // Create a function for testing stepping. Run it to allow it to get
3399 // optimized.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003400 const char* src = "function foo(x) { "
3401 " var a;"
3402 " a = x ? 1 : 2;"
3403 " return a;"
Ben Murdochb0fe1622011-05-05 13:52:32 +01003404 "}"
3405 "foo()";
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003406 v8::Local<v8::Function> foo = CompileFunction(&env, src, "foo");
3407 SetBreakPoint(foo, 0); // "var a;"
3408
3409 step_action = StepIn;
3410 break_point_hit_count = 0;
3411 foo->Call(env->Global(), 0, NULL);
3412 CHECK_EQ(5, break_point_hit_count);
3413
3414 step_action = StepIn;
3415 break_point_hit_count = 0;
3416 const int argc = 1;
3417 v8::Handle<v8::Value> argv_true[argc] = { v8::True() };
3418 foo->Call(env->Global(), argc, argv_true);
3419 CHECK_EQ(5, break_point_hit_count);
3420
3421 // Get rid of the debug event listener.
3422 v8::Debug::SetDebugEventListener(NULL);
3423 CheckDebuggerUnloaded();
3424}
3425
3426
Steve Blocka7e24c12009-10-30 11:49:00 +00003427TEST(StepInOutSimple) {
3428 v8::HandleScope scope;
3429 DebugLocalContext env;
3430
3431 // Create a function for checking the function when hitting a break point.
3432 frame_function_name = CompileFunction(&env,
3433 frame_function_name_source,
3434 "frame_function_name");
3435
3436 // Register a debug event listener which steps and counts.
3437 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3438
Ben Murdochb0fe1622011-05-05 13:52:32 +01003439 // Create a function for testing stepping. Run it to allow it to get
3440 // optimized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003441 const char* src = "function a() {b();c();}; "
3442 "function b() {c();}; "
Ben Murdochb0fe1622011-05-05 13:52:32 +01003443 "function c() {}; "
3444 "a(); b(); c()";
Steve Blocka7e24c12009-10-30 11:49:00 +00003445 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3446 SetBreakPoint(a, 0);
3447
3448 // Step through invocation of a with step in.
3449 step_action = StepIn;
3450 break_point_hit_count = 0;
3451 expected_step_sequence = "abcbaca";
3452 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003453 CHECK_EQ(StrLength(expected_step_sequence),
3454 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003455
3456 // Step through invocation of a with step next.
3457 step_action = StepNext;
3458 break_point_hit_count = 0;
3459 expected_step_sequence = "aaa";
3460 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003461 CHECK_EQ(StrLength(expected_step_sequence),
3462 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003463
3464 // Step through invocation of a with step out.
3465 step_action = StepOut;
3466 break_point_hit_count = 0;
3467 expected_step_sequence = "a";
3468 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003469 CHECK_EQ(StrLength(expected_step_sequence),
3470 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003471
3472 // Get rid of the debug event listener.
3473 v8::Debug::SetDebugEventListener(NULL);
3474 CheckDebuggerUnloaded();
3475}
3476
3477
3478TEST(StepInOutTree) {
3479 v8::HandleScope scope;
3480 DebugLocalContext env;
3481
3482 // Create a function for checking the function when hitting a break point.
3483 frame_function_name = CompileFunction(&env,
3484 frame_function_name_source,
3485 "frame_function_name");
3486
3487 // Register a debug event listener which steps and counts.
3488 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3489
Ben Murdochb0fe1622011-05-05 13:52:32 +01003490 // Create a function for testing stepping. Run it to allow it to get
3491 // optimized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003492 const char* src = "function a() {b(c(d()),d());c(d());d()}; "
3493 "function b(x,y) {c();}; "
3494 "function c(x) {}; "
Ben Murdochb0fe1622011-05-05 13:52:32 +01003495 "function d() {}; "
3496 "a(); b(); c(); d()";
Steve Blocka7e24c12009-10-30 11:49:00 +00003497 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3498 SetBreakPoint(a, 0);
3499
3500 // Step through invocation of a with step in.
3501 step_action = StepIn;
3502 break_point_hit_count = 0;
3503 expected_step_sequence = "adacadabcbadacada";
3504 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003505 CHECK_EQ(StrLength(expected_step_sequence),
3506 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003507
3508 // Step through invocation of a with step next.
3509 step_action = StepNext;
3510 break_point_hit_count = 0;
3511 expected_step_sequence = "aaaa";
3512 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003513 CHECK_EQ(StrLength(expected_step_sequence),
3514 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003515
3516 // Step through invocation of a with step out.
3517 step_action = StepOut;
3518 break_point_hit_count = 0;
3519 expected_step_sequence = "a";
3520 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(true);
3527}
3528
3529
3530TEST(StepInOutBranch) {
3531 v8::HandleScope scope;
3532 DebugLocalContext env;
3533
3534 // Create a function for checking the function when hitting a break point.
3535 frame_function_name = CompileFunction(&env,
3536 frame_function_name_source,
3537 "frame_function_name");
3538
3539 // Register a debug event listener which steps and counts.
3540 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3541
Ben Murdochb0fe1622011-05-05 13:52:32 +01003542 // Create a function for testing stepping. Run it to allow it to get
3543 // optimized.
Steve Blocka7e24c12009-10-30 11:49:00 +00003544 const char* src = "function a() {b(false);c();}; "
3545 "function b(x) {if(x){c();};}; "
Ben Murdochb0fe1622011-05-05 13:52:32 +01003546 "function c() {}; "
3547 "a(); b(); c()";
Steve Blocka7e24c12009-10-30 11:49:00 +00003548 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3549 SetBreakPoint(a, 0);
3550
3551 // Step through invocation of a.
3552 step_action = StepIn;
3553 break_point_hit_count = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003554 expected_step_sequence = "abbaca";
Steve Blocka7e24c12009-10-30 11:49:00 +00003555 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003556 CHECK_EQ(StrLength(expected_step_sequence),
3557 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003558
3559 // Get rid of the debug event listener.
3560 v8::Debug::SetDebugEventListener(NULL);
3561 CheckDebuggerUnloaded();
3562}
3563
3564
3565// Test that step in does not step into native functions.
3566TEST(DebugStepNatives) {
3567 v8::HandleScope scope;
3568 DebugLocalContext env;
3569
3570 // Create a function for testing stepping.
3571 v8::Local<v8::Function> foo = CompileFunction(
3572 &env,
3573 "function foo(){debugger;Math.sin(1);}",
3574 "foo");
3575
3576 // Register a debug event listener which steps and counts.
3577 v8::Debug::SetDebugEventListener(DebugEventStep);
3578
3579 step_action = StepIn;
3580 break_point_hit_count = 0;
3581 foo->Call(env->Global(), 0, NULL);
3582
3583 // With stepping all break locations are hit.
3584 CHECK_EQ(3, break_point_hit_count);
3585
3586 v8::Debug::SetDebugEventListener(NULL);
3587 CheckDebuggerUnloaded();
3588
3589 // Register a debug event listener which just counts.
3590 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
3591
3592 break_point_hit_count = 0;
3593 foo->Call(env->Global(), 0, NULL);
3594
3595 // Without stepping only active break points are hit.
3596 CHECK_EQ(1, break_point_hit_count);
3597
3598 v8::Debug::SetDebugEventListener(NULL);
3599 CheckDebuggerUnloaded();
3600}
3601
3602
3603// Test that step in works with function.apply.
3604TEST(DebugStepFunctionApply) {
3605 v8::HandleScope scope;
3606 DebugLocalContext env;
3607
3608 // Create a function for testing stepping.
3609 v8::Local<v8::Function> foo = CompileFunction(
3610 &env,
3611 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
3612 "function foo(){ debugger; bar.apply(this, [1,2,3]); }",
3613 "foo");
3614
3615 // Register a debug event listener which steps and counts.
3616 v8::Debug::SetDebugEventListener(DebugEventStep);
3617
3618 step_action = StepIn;
3619 break_point_hit_count = 0;
3620 foo->Call(env->Global(), 0, NULL);
3621
3622 // With stepping all break locations are hit.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003623 CHECK_EQ(7, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003624
3625 v8::Debug::SetDebugEventListener(NULL);
3626 CheckDebuggerUnloaded();
3627
3628 // Register a debug event listener which just counts.
3629 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
3630
3631 break_point_hit_count = 0;
3632 foo->Call(env->Global(), 0, NULL);
3633
3634 // Without stepping only the debugger statement is hit.
3635 CHECK_EQ(1, break_point_hit_count);
3636
3637 v8::Debug::SetDebugEventListener(NULL);
3638 CheckDebuggerUnloaded();
3639}
3640
3641
3642// Test that step in works with function.call.
3643TEST(DebugStepFunctionCall) {
3644 v8::HandleScope scope;
3645 DebugLocalContext env;
3646
3647 // Create a function for testing stepping.
3648 v8::Local<v8::Function> foo = CompileFunction(
3649 &env,
3650 "function bar(x, y, z) { if (x == 1) { a = y; b = z; } }"
3651 "function foo(a){ debugger;"
3652 " if (a) {"
3653 " bar.call(this, 1, 2, 3);"
3654 " } else {"
3655 " bar.call(this, 0);"
3656 " }"
3657 "}",
3658 "foo");
3659
3660 // Register a debug event listener which steps and counts.
3661 v8::Debug::SetDebugEventListener(DebugEventStep);
3662 step_action = StepIn;
3663
3664 // Check stepping where the if condition in bar is false.
3665 break_point_hit_count = 0;
3666 foo->Call(env->Global(), 0, NULL);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003667 CHECK_EQ(6, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003668
3669 // Check stepping where the if condition in bar is true.
3670 break_point_hit_count = 0;
3671 const int argc = 1;
3672 v8::Handle<v8::Value> argv[argc] = { v8::True() };
3673 foo->Call(env->Global(), argc, argv);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003674 CHECK_EQ(8, break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003675
3676 v8::Debug::SetDebugEventListener(NULL);
3677 CheckDebuggerUnloaded();
3678
3679 // Register a debug event listener which just counts.
3680 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount);
3681
3682 break_point_hit_count = 0;
3683 foo->Call(env->Global(), 0, NULL);
3684
3685 // Without stepping only the debugger statement is hit.
3686 CHECK_EQ(1, break_point_hit_count);
3687
3688 v8::Debug::SetDebugEventListener(NULL);
3689 CheckDebuggerUnloaded();
3690}
3691
3692
Steve Blockd0582a62009-12-15 09:54:21 +00003693// Tests that breakpoint will be hit if it's set in script.
3694TEST(PauseInScript) {
3695 v8::HandleScope scope;
3696 DebugLocalContext env;
3697 env.ExposeDebug();
3698
3699 // Register a debug event listener which counts.
3700 v8::Debug::SetDebugEventListener(DebugEventCounter);
3701
3702 // Create a script that returns a function.
3703 const char* src = "(function (evt) {})";
3704 const char* script_name = "StepInHandlerTest";
3705
3706 // Set breakpoint in the script.
3707 SetScriptBreakPointByNameFromJS(script_name, 0, -1);
3708 break_point_hit_count = 0;
3709
3710 v8::ScriptOrigin origin(v8::String::New(script_name), v8::Integer::New(0));
3711 v8::Handle<v8::Script> script = v8::Script::Compile(v8::String::New(src),
3712 &origin);
3713 v8::Local<v8::Value> r = script->Run();
3714
3715 CHECK(r->IsFunction());
3716 CHECK_EQ(1, break_point_hit_count);
3717
3718 // Get rid of the debug event listener.
3719 v8::Debug::SetDebugEventListener(NULL);
3720 CheckDebuggerUnloaded();
3721}
3722
3723
Steve Blocka7e24c12009-10-30 11:49:00 +00003724// Test break on exceptions. For each exception break combination the number
3725// of debug event exception callbacks and message callbacks are collected. The
3726// number of debug event exception callbacks are used to check that the
3727// debugger is called correctly and the number of message callbacks is used to
3728// check that uncaught exceptions are still returned even if there is a break
3729// for them.
3730TEST(BreakOnException) {
3731 v8::HandleScope scope;
3732 DebugLocalContext env;
3733 env.ExposeDebug();
3734
Steve Block44f0eee2011-05-26 01:26:41 +01003735 v8::internal::Isolate::Current()->TraceException(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003736
3737 // Create functions for testing break on exception.
3738 v8::Local<v8::Function> throws =
3739 CompileFunction(&env, "function throws(){throw 1;}", "throws");
3740 v8::Local<v8::Function> caught =
3741 CompileFunction(&env,
3742 "function caught(){try {throws();} catch(e) {};}",
3743 "caught");
3744 v8::Local<v8::Function> notCaught =
3745 CompileFunction(&env, "function notCaught(){throws();}", "notCaught");
3746
3747 v8::V8::AddMessageListener(MessageCallbackCount);
3748 v8::Debug::SetDebugEventListener(DebugEventCounter);
3749
Ben Murdoch086aeea2011-05-13 15:57:08 +01003750 // Initial state should be no break on exceptions.
Steve Blocka7e24c12009-10-30 11:49:00 +00003751 DebugEventCounterClear();
3752 MessageCallbackCountClear();
3753 caught->Call(env->Global(), 0, NULL);
3754 CHECK_EQ(0, exception_hit_count);
3755 CHECK_EQ(0, uncaught_exception_hit_count);
3756 CHECK_EQ(0, message_callback_count);
3757 notCaught->Call(env->Global(), 0, NULL);
Ben Murdoch086aeea2011-05-13 15:57:08 +01003758 CHECK_EQ(0, exception_hit_count);
3759 CHECK_EQ(0, uncaught_exception_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003760 CHECK_EQ(1, message_callback_count);
3761
3762 // No break on exception
3763 DebugEventCounterClear();
3764 MessageCallbackCountClear();
3765 ChangeBreakOnException(false, false);
3766 caught->Call(env->Global(), 0, NULL);
3767 CHECK_EQ(0, exception_hit_count);
3768 CHECK_EQ(0, uncaught_exception_hit_count);
3769 CHECK_EQ(0, message_callback_count);
3770 notCaught->Call(env->Global(), 0, NULL);
3771 CHECK_EQ(0, exception_hit_count);
3772 CHECK_EQ(0, uncaught_exception_hit_count);
3773 CHECK_EQ(1, message_callback_count);
3774
3775 // Break on uncaught exception
3776 DebugEventCounterClear();
3777 MessageCallbackCountClear();
3778 ChangeBreakOnException(false, true);
3779 caught->Call(env->Global(), 0, NULL);
3780 CHECK_EQ(0, exception_hit_count);
3781 CHECK_EQ(0, uncaught_exception_hit_count);
3782 CHECK_EQ(0, message_callback_count);
3783 notCaught->Call(env->Global(), 0, NULL);
3784 CHECK_EQ(1, exception_hit_count);
3785 CHECK_EQ(1, uncaught_exception_hit_count);
3786 CHECK_EQ(1, message_callback_count);
3787
3788 // Break on exception and uncaught exception
3789 DebugEventCounterClear();
3790 MessageCallbackCountClear();
3791 ChangeBreakOnException(true, true);
3792 caught->Call(env->Global(), 0, NULL);
3793 CHECK_EQ(1, exception_hit_count);
3794 CHECK_EQ(0, uncaught_exception_hit_count);
3795 CHECK_EQ(0, message_callback_count);
3796 notCaught->Call(env->Global(), 0, NULL);
3797 CHECK_EQ(2, exception_hit_count);
3798 CHECK_EQ(1, uncaught_exception_hit_count);
3799 CHECK_EQ(1, message_callback_count);
3800
3801 // Break on exception
3802 DebugEventCounterClear();
3803 MessageCallbackCountClear();
3804 ChangeBreakOnException(true, false);
3805 caught->Call(env->Global(), 0, NULL);
3806 CHECK_EQ(1, exception_hit_count);
3807 CHECK_EQ(0, uncaught_exception_hit_count);
3808 CHECK_EQ(0, message_callback_count);
3809 notCaught->Call(env->Global(), 0, NULL);
3810 CHECK_EQ(2, exception_hit_count);
3811 CHECK_EQ(1, uncaught_exception_hit_count);
3812 CHECK_EQ(1, message_callback_count);
3813
3814 // No break on exception using JavaScript
3815 DebugEventCounterClear();
3816 MessageCallbackCountClear();
3817 ChangeBreakOnExceptionFromJS(false, false);
3818 caught->Call(env->Global(), 0, NULL);
3819 CHECK_EQ(0, exception_hit_count);
3820 CHECK_EQ(0, uncaught_exception_hit_count);
3821 CHECK_EQ(0, message_callback_count);
3822 notCaught->Call(env->Global(), 0, NULL);
3823 CHECK_EQ(0, exception_hit_count);
3824 CHECK_EQ(0, uncaught_exception_hit_count);
3825 CHECK_EQ(1, message_callback_count);
3826
3827 // Break on uncaught exception using JavaScript
3828 DebugEventCounterClear();
3829 MessageCallbackCountClear();
3830 ChangeBreakOnExceptionFromJS(false, true);
3831 caught->Call(env->Global(), 0, NULL);
3832 CHECK_EQ(0, exception_hit_count);
3833 CHECK_EQ(0, uncaught_exception_hit_count);
3834 CHECK_EQ(0, message_callback_count);
3835 notCaught->Call(env->Global(), 0, NULL);
3836 CHECK_EQ(1, exception_hit_count);
3837 CHECK_EQ(1, uncaught_exception_hit_count);
3838 CHECK_EQ(1, message_callback_count);
3839
3840 // Break on exception and uncaught exception using JavaScript
3841 DebugEventCounterClear();
3842 MessageCallbackCountClear();
3843 ChangeBreakOnExceptionFromJS(true, true);
3844 caught->Call(env->Global(), 0, NULL);
3845 CHECK_EQ(1, exception_hit_count);
3846 CHECK_EQ(0, message_callback_count);
3847 CHECK_EQ(0, uncaught_exception_hit_count);
3848 notCaught->Call(env->Global(), 0, NULL);
3849 CHECK_EQ(2, exception_hit_count);
3850 CHECK_EQ(1, uncaught_exception_hit_count);
3851 CHECK_EQ(1, message_callback_count);
3852
3853 // Break on exception using JavaScript
3854 DebugEventCounterClear();
3855 MessageCallbackCountClear();
3856 ChangeBreakOnExceptionFromJS(true, false);
3857 caught->Call(env->Global(), 0, NULL);
3858 CHECK_EQ(1, exception_hit_count);
3859 CHECK_EQ(0, uncaught_exception_hit_count);
3860 CHECK_EQ(0, message_callback_count);
3861 notCaught->Call(env->Global(), 0, NULL);
3862 CHECK_EQ(2, exception_hit_count);
3863 CHECK_EQ(1, uncaught_exception_hit_count);
3864 CHECK_EQ(1, message_callback_count);
3865
3866 v8::Debug::SetDebugEventListener(NULL);
3867 CheckDebuggerUnloaded();
3868 v8::V8::RemoveMessageListeners(MessageCallbackCount);
3869}
3870
3871
3872// Test break on exception from compiler errors. When compiling using
3873// v8::Script::Compile there is no JavaScript stack whereas when compiling using
3874// eval there are JavaScript frames.
3875TEST(BreakOnCompileException) {
3876 v8::HandleScope scope;
3877 DebugLocalContext env;
3878
Ben Murdoch086aeea2011-05-13 15:57:08 +01003879 // For this test, we want to break on uncaught exceptions:
3880 ChangeBreakOnException(false, true);
3881
Steve Block44f0eee2011-05-26 01:26:41 +01003882 v8::internal::Isolate::Current()->TraceException(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00003883
3884 // Create a function for checking the function when hitting a break point.
3885 frame_count = CompileFunction(&env, frame_count_source, "frame_count");
3886
3887 v8::V8::AddMessageListener(MessageCallbackCount);
3888 v8::Debug::SetDebugEventListener(DebugEventCounter);
3889
3890 DebugEventCounterClear();
3891 MessageCallbackCountClear();
3892
3893 // Check initial state.
3894 CHECK_EQ(0, exception_hit_count);
3895 CHECK_EQ(0, uncaught_exception_hit_count);
3896 CHECK_EQ(0, message_callback_count);
3897 CHECK_EQ(-1, last_js_stack_height);
3898
3899 // Throws SyntaxError: Unexpected end of input
3900 v8::Script::Compile(v8::String::New("+++"));
3901 CHECK_EQ(1, exception_hit_count);
3902 CHECK_EQ(1, uncaught_exception_hit_count);
3903 CHECK_EQ(1, message_callback_count);
3904 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack.
3905
3906 // Throws SyntaxError: Unexpected identifier
3907 v8::Script::Compile(v8::String::New("x x"));
3908 CHECK_EQ(2, exception_hit_count);
3909 CHECK_EQ(2, uncaught_exception_hit_count);
3910 CHECK_EQ(2, message_callback_count);
3911 CHECK_EQ(0, last_js_stack_height); // No JavaScript stack.
3912
3913 // Throws SyntaxError: Unexpected end of input
3914 v8::Script::Compile(v8::String::New("eval('+++')"))->Run();
3915 CHECK_EQ(3, exception_hit_count);
3916 CHECK_EQ(3, uncaught_exception_hit_count);
3917 CHECK_EQ(3, message_callback_count);
3918 CHECK_EQ(1, last_js_stack_height);
3919
3920 // Throws SyntaxError: Unexpected identifier
3921 v8::Script::Compile(v8::String::New("eval('x x')"))->Run();
3922 CHECK_EQ(4, exception_hit_count);
3923 CHECK_EQ(4, uncaught_exception_hit_count);
3924 CHECK_EQ(4, message_callback_count);
3925 CHECK_EQ(1, last_js_stack_height);
3926}
3927
3928
3929TEST(StepWithException) {
3930 v8::HandleScope scope;
3931 DebugLocalContext env;
3932
Ben Murdoch086aeea2011-05-13 15:57:08 +01003933 // For this test, we want to break on uncaught exceptions:
3934 ChangeBreakOnException(false, true);
3935
Steve Blocka7e24c12009-10-30 11:49:00 +00003936 // Create a function for checking the function when hitting a break point.
3937 frame_function_name = CompileFunction(&env,
3938 frame_function_name_source,
3939 "frame_function_name");
3940
3941 // Register a debug event listener which steps and counts.
3942 v8::Debug::SetDebugEventListener(DebugEventStepSequence);
3943
3944 // Create functions for testing stepping.
3945 const char* src = "function a() { n(); }; "
3946 "function b() { c(); }; "
3947 "function c() { n(); }; "
3948 "function d() { x = 1; try { e(); } catch(x) { x = 2; } }; "
3949 "function e() { n(); }; "
3950 "function f() { x = 1; try { g(); } catch(x) { x = 2; } }; "
3951 "function g() { h(); }; "
3952 "function h() { x = 1; throw 1; }; ";
3953
3954 // Step through invocation of a.
3955 v8::Local<v8::Function> a = CompileFunction(&env, src, "a");
3956 SetBreakPoint(a, 0);
3957 step_action = StepIn;
3958 break_point_hit_count = 0;
3959 expected_step_sequence = "aa";
3960 a->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003961 CHECK_EQ(StrLength(expected_step_sequence),
3962 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003963
3964 // Step through invocation of b + c.
3965 v8::Local<v8::Function> b = CompileFunction(&env, src, "b");
3966 SetBreakPoint(b, 0);
3967 step_action = StepIn;
3968 break_point_hit_count = 0;
3969 expected_step_sequence = "bcc";
3970 b->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003971 CHECK_EQ(StrLength(expected_step_sequence),
3972 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003973 // Step through invocation of d + e.
3974 v8::Local<v8::Function> d = CompileFunction(&env, src, "d");
3975 SetBreakPoint(d, 0);
3976 ChangeBreakOnException(false, true);
3977 step_action = StepIn;
3978 break_point_hit_count = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003979 expected_step_sequence = "ddedd";
Steve Blocka7e24c12009-10-30 11:49:00 +00003980 d->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003981 CHECK_EQ(StrLength(expected_step_sequence),
3982 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003983
3984 // Step through invocation of d + e now with break on caught exceptions.
3985 ChangeBreakOnException(true, true);
3986 step_action = StepIn;
3987 break_point_hit_count = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003988 expected_step_sequence = "ddeedd";
Steve Blocka7e24c12009-10-30 11:49:00 +00003989 d->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00003990 CHECK_EQ(StrLength(expected_step_sequence),
3991 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00003992
3993 // Step through invocation of f + g + h.
3994 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
3995 SetBreakPoint(f, 0);
3996 ChangeBreakOnException(false, true);
3997 step_action = StepIn;
3998 break_point_hit_count = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01003999 expected_step_sequence = "ffghhff";
Steve Blocka7e24c12009-10-30 11:49:00 +00004000 f->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00004001 CHECK_EQ(StrLength(expected_step_sequence),
4002 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00004003
4004 // Step through invocation of f + g + h now with break on caught exceptions.
4005 ChangeBreakOnException(true, true);
4006 step_action = StepIn;
4007 break_point_hit_count = 0;
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01004008 expected_step_sequence = "ffghhhff";
Steve Blocka7e24c12009-10-30 11:49:00 +00004009 f->Call(env->Global(), 0, NULL);
Steve Blockd0582a62009-12-15 09:54:21 +00004010 CHECK_EQ(StrLength(expected_step_sequence),
4011 break_point_hit_count);
Steve Blocka7e24c12009-10-30 11:49:00 +00004012
4013 // Get rid of the debug event listener.
4014 v8::Debug::SetDebugEventListener(NULL);
4015 CheckDebuggerUnloaded();
4016}
4017
4018
4019TEST(DebugBreak) {
4020 v8::HandleScope scope;
4021 DebugLocalContext env;
4022
4023 // This test should be run with option --verify-heap. As --verify-heap is
4024 // only available in debug mode only check for it in that case.
4025#ifdef DEBUG
4026 CHECK(v8::internal::FLAG_verify_heap);
4027#endif
4028
4029 // Register a debug event listener which sets the break flag and counts.
4030 v8::Debug::SetDebugEventListener(DebugEventBreak);
4031
4032 // Create a function for testing stepping.
4033 const char* src = "function f0() {}"
4034 "function f1(x1) {}"
4035 "function f2(x1,x2) {}"
4036 "function f3(x1,x2,x3) {}";
4037 v8::Local<v8::Function> f0 = CompileFunction(&env, src, "f0");
4038 v8::Local<v8::Function> f1 = CompileFunction(&env, src, "f1");
4039 v8::Local<v8::Function> f2 = CompileFunction(&env, src, "f2");
4040 v8::Local<v8::Function> f3 = CompileFunction(&env, src, "f3");
4041
4042 // Call the function to make sure it is compiled.
4043 v8::Handle<v8::Value> argv[] = { v8::Number::New(1),
4044 v8::Number::New(1),
4045 v8::Number::New(1),
4046 v8::Number::New(1) };
4047
4048 // Call all functions to make sure that they are compiled.
4049 f0->Call(env->Global(), 0, NULL);
4050 f1->Call(env->Global(), 0, NULL);
4051 f2->Call(env->Global(), 0, NULL);
4052 f3->Call(env->Global(), 0, NULL);
4053
4054 // Set the debug break flag.
4055 v8::Debug::DebugBreak();
4056
4057 // Call all functions with different argument count.
4058 break_point_hit_count = 0;
4059 for (unsigned int i = 0; i < ARRAY_SIZE(argv); i++) {
4060 f0->Call(env->Global(), i, argv);
4061 f1->Call(env->Global(), i, argv);
4062 f2->Call(env->Global(), i, argv);
4063 f3->Call(env->Global(), i, argv);
4064 }
4065
4066 // One break for each function called.
4067 CHECK_EQ(4 * ARRAY_SIZE(argv), break_point_hit_count);
4068
4069 // Get rid of the debug event listener.
4070 v8::Debug::SetDebugEventListener(NULL);
4071 CheckDebuggerUnloaded();
4072}
4073
4074
4075// Test to ensure that JavaScript code keeps running while the debug break
4076// through the stack limit flag is set but breaks are disabled.
4077TEST(DisableBreak) {
4078 v8::HandleScope scope;
4079 DebugLocalContext env;
4080
4081 // Register a debug event listener which sets the break flag and counts.
4082 v8::Debug::SetDebugEventListener(DebugEventCounter);
4083
4084 // Create a function for testing stepping.
4085 const char* src = "function f() {g()};function g(){i=0; while(i<10){i++}}";
4086 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
4087
4088 // Set the debug break flag.
4089 v8::Debug::DebugBreak();
4090
4091 // Call all functions with different argument count.
4092 break_point_hit_count = 0;
4093 f->Call(env->Global(), 0, NULL);
4094 CHECK_EQ(1, break_point_hit_count);
4095
4096 {
4097 v8::Debug::DebugBreak();
4098 v8::internal::DisableBreak disable_break(true);
4099 f->Call(env->Global(), 0, NULL);
4100 CHECK_EQ(1, break_point_hit_count);
4101 }
4102
4103 f->Call(env->Global(), 0, NULL);
4104 CHECK_EQ(2, break_point_hit_count);
4105
4106 // Get rid of the debug event listener.
4107 v8::Debug::SetDebugEventListener(NULL);
4108 CheckDebuggerUnloaded();
4109}
4110
Leon Clarkee46be812010-01-19 14:06:41 +00004111static const char* kSimpleExtensionSource =
4112 "(function Foo() {"
4113 " return 4;"
4114 "})() ";
4115
4116// http://crbug.com/28933
4117// Test that debug break is disabled when bootstrapper is active.
4118TEST(NoBreakWhenBootstrapping) {
4119 v8::HandleScope scope;
4120
4121 // Register a debug event listener which sets the break flag and counts.
4122 v8::Debug::SetDebugEventListener(DebugEventCounter);
4123
4124 // Set the debug break flag.
4125 v8::Debug::DebugBreak();
4126 break_point_hit_count = 0;
4127 {
4128 // Create a context with an extension to make sure that some JavaScript
4129 // code is executed during bootstrapping.
4130 v8::RegisterExtension(new v8::Extension("simpletest",
4131 kSimpleExtensionSource));
4132 const char* extension_names[] = { "simpletest" };
4133 v8::ExtensionConfiguration extensions(1, extension_names);
4134 v8::Persistent<v8::Context> context = v8::Context::New(&extensions);
4135 context.Dispose();
4136 }
4137 // Check that no DebugBreak events occured during the context creation.
4138 CHECK_EQ(0, break_point_hit_count);
4139
4140 // Get rid of the debug event listener.
4141 v8::Debug::SetDebugEventListener(NULL);
4142 CheckDebuggerUnloaded();
4143}
Steve Blocka7e24c12009-10-30 11:49:00 +00004144
4145static v8::Handle<v8::Array> NamedEnum(const v8::AccessorInfo&) {
4146 v8::Handle<v8::Array> result = v8::Array::New(3);
4147 result->Set(v8::Integer::New(0), v8::String::New("a"));
4148 result->Set(v8::Integer::New(1), v8::String::New("b"));
4149 result->Set(v8::Integer::New(2), v8::String::New("c"));
4150 return result;
4151}
4152
4153
4154static v8::Handle<v8::Array> IndexedEnum(const v8::AccessorInfo&) {
4155 v8::Handle<v8::Array> result = v8::Array::New(2);
4156 result->Set(v8::Integer::New(0), v8::Number::New(1));
4157 result->Set(v8::Integer::New(1), v8::Number::New(10));
4158 return result;
4159}
4160
4161
4162static v8::Handle<v8::Value> NamedGetter(v8::Local<v8::String> name,
4163 const v8::AccessorInfo& info) {
4164 v8::String::AsciiValue n(name);
4165 if (strcmp(*n, "a") == 0) {
4166 return v8::String::New("AA");
4167 } else if (strcmp(*n, "b") == 0) {
4168 return v8::String::New("BB");
4169 } else if (strcmp(*n, "c") == 0) {
4170 return v8::String::New("CC");
4171 } else {
4172 return v8::Undefined();
4173 }
4174
4175 return name;
4176}
4177
4178
4179static v8::Handle<v8::Value> IndexedGetter(uint32_t index,
4180 const v8::AccessorInfo& info) {
4181 return v8::Number::New(index + 1);
4182}
4183
4184
4185TEST(InterceptorPropertyMirror) {
4186 // Create a V8 environment with debug access.
4187 v8::HandleScope scope;
4188 DebugLocalContext env;
4189 env.ExposeDebug();
4190
4191 // Create object with named interceptor.
4192 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
4193 named->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum);
4194 env->Global()->Set(v8::String::New("intercepted_named"),
4195 named->NewInstance());
4196
4197 // Create object with indexed interceptor.
4198 v8::Handle<v8::ObjectTemplate> indexed = v8::ObjectTemplate::New();
4199 indexed->SetIndexedPropertyHandler(IndexedGetter,
4200 NULL,
4201 NULL,
4202 NULL,
4203 IndexedEnum);
4204 env->Global()->Set(v8::String::New("intercepted_indexed"),
4205 indexed->NewInstance());
4206
4207 // Create object with both named and indexed interceptor.
4208 v8::Handle<v8::ObjectTemplate> both = v8::ObjectTemplate::New();
4209 both->SetNamedPropertyHandler(NamedGetter, NULL, NULL, NULL, NamedEnum);
4210 both->SetIndexedPropertyHandler(IndexedGetter, NULL, NULL, NULL, IndexedEnum);
4211 env->Global()->Set(v8::String::New("intercepted_both"), both->NewInstance());
4212
4213 // Get mirrors for the three objects with interceptor.
4214 CompileRun(
4215 "named_mirror = debug.MakeMirror(intercepted_named);"
4216 "indexed_mirror = debug.MakeMirror(intercepted_indexed);"
4217 "both_mirror = debug.MakeMirror(intercepted_both)");
4218 CHECK(CompileRun(
4219 "named_mirror instanceof debug.ObjectMirror")->BooleanValue());
4220 CHECK(CompileRun(
4221 "indexed_mirror instanceof debug.ObjectMirror")->BooleanValue());
4222 CHECK(CompileRun(
4223 "both_mirror instanceof debug.ObjectMirror")->BooleanValue());
4224
4225 // Get the property names from the interceptors
4226 CompileRun(
4227 "named_names = named_mirror.propertyNames();"
4228 "indexed_names = indexed_mirror.propertyNames();"
4229 "both_names = both_mirror.propertyNames()");
4230 CHECK_EQ(3, CompileRun("named_names.length")->Int32Value());
4231 CHECK_EQ(2, CompileRun("indexed_names.length")->Int32Value());
4232 CHECK_EQ(5, CompileRun("both_names.length")->Int32Value());
4233
4234 // Check the expected number of properties.
4235 const char* source;
4236 source = "named_mirror.properties().length";
4237 CHECK_EQ(3, CompileRun(source)->Int32Value());
4238
4239 source = "indexed_mirror.properties().length";
4240 CHECK_EQ(2, CompileRun(source)->Int32Value());
4241
4242 source = "both_mirror.properties().length";
4243 CHECK_EQ(5, CompileRun(source)->Int32Value());
4244
4245 // 1 is PropertyKind.Named;
4246 source = "both_mirror.properties(1).length";
4247 CHECK_EQ(3, CompileRun(source)->Int32Value());
4248
4249 // 2 is PropertyKind.Indexed;
4250 source = "both_mirror.properties(2).length";
4251 CHECK_EQ(2, CompileRun(source)->Int32Value());
4252
4253 // 3 is PropertyKind.Named | PropertyKind.Indexed;
4254 source = "both_mirror.properties(3).length";
4255 CHECK_EQ(5, CompileRun(source)->Int32Value());
4256
4257 // Get the interceptor properties for the object with only named interceptor.
4258 CompileRun("named_values = named_mirror.properties()");
4259
4260 // Check that the properties are interceptor properties.
4261 for (int i = 0; i < 3; i++) {
4262 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
4263 OS::SNPrintF(buffer,
4264 "named_values[%d] instanceof debug.PropertyMirror", i);
4265 CHECK(CompileRun(buffer.start())->BooleanValue());
4266
Ben Murdoch257744e2011-11-30 15:57:28 +00004267 // 5 is PropertyType.Interceptor
Steve Blocka7e24c12009-10-30 11:49:00 +00004268 OS::SNPrintF(buffer, "named_values[%d].propertyType()", i);
Ben Murdoch257744e2011-11-30 15:57:28 +00004269 CHECK_EQ(5, CompileRun(buffer.start())->Int32Value());
Steve Blocka7e24c12009-10-30 11:49:00 +00004270
4271 OS::SNPrintF(buffer, "named_values[%d].isNative()", i);
4272 CHECK(CompileRun(buffer.start())->BooleanValue());
4273 }
4274
4275 // Get the interceptor properties for the object with only indexed
4276 // interceptor.
4277 CompileRun("indexed_values = indexed_mirror.properties()");
4278
4279 // Check that the properties are interceptor properties.
4280 for (int i = 0; i < 2; i++) {
4281 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
4282 OS::SNPrintF(buffer,
4283 "indexed_values[%d] instanceof debug.PropertyMirror", i);
4284 CHECK(CompileRun(buffer.start())->BooleanValue());
4285 }
4286
4287 // Get the interceptor properties for the object with both types of
4288 // interceptors.
4289 CompileRun("both_values = both_mirror.properties()");
4290
4291 // Check that the properties are interceptor properties.
4292 for (int i = 0; i < 5; i++) {
4293 EmbeddedVector<char, SMALL_STRING_BUFFER_SIZE> buffer;
4294 OS::SNPrintF(buffer, "both_values[%d] instanceof debug.PropertyMirror", i);
4295 CHECK(CompileRun(buffer.start())->BooleanValue());
4296 }
4297
4298 // Check the property names.
4299 source = "both_values[0].name() == 'a'";
4300 CHECK(CompileRun(source)->BooleanValue());
4301
4302 source = "both_values[1].name() == 'b'";
4303 CHECK(CompileRun(source)->BooleanValue());
4304
4305 source = "both_values[2].name() == 'c'";
4306 CHECK(CompileRun(source)->BooleanValue());
4307
4308 source = "both_values[3].name() == 1";
4309 CHECK(CompileRun(source)->BooleanValue());
4310
4311 source = "both_values[4].name() == 10";
4312 CHECK(CompileRun(source)->BooleanValue());
4313}
4314
4315
4316TEST(HiddenPrototypePropertyMirror) {
4317 // Create a V8 environment with debug access.
4318 v8::HandleScope scope;
4319 DebugLocalContext env;
4320 env.ExposeDebug();
4321
4322 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New();
4323 t0->InstanceTemplate()->Set(v8::String::New("x"), v8::Number::New(0));
4324 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
4325 t1->SetHiddenPrototype(true);
4326 t1->InstanceTemplate()->Set(v8::String::New("y"), v8::Number::New(1));
4327 v8::Handle<v8::FunctionTemplate> t2 = v8::FunctionTemplate::New();
4328 t2->SetHiddenPrototype(true);
4329 t2->InstanceTemplate()->Set(v8::String::New("z"), v8::Number::New(2));
4330 v8::Handle<v8::FunctionTemplate> t3 = v8::FunctionTemplate::New();
4331 t3->InstanceTemplate()->Set(v8::String::New("u"), v8::Number::New(3));
4332
4333 // Create object and set them on the global object.
4334 v8::Handle<v8::Object> o0 = t0->GetFunction()->NewInstance();
4335 env->Global()->Set(v8::String::New("o0"), o0);
4336 v8::Handle<v8::Object> o1 = t1->GetFunction()->NewInstance();
4337 env->Global()->Set(v8::String::New("o1"), o1);
4338 v8::Handle<v8::Object> o2 = t2->GetFunction()->NewInstance();
4339 env->Global()->Set(v8::String::New("o2"), o2);
4340 v8::Handle<v8::Object> o3 = t3->GetFunction()->NewInstance();
4341 env->Global()->Set(v8::String::New("o3"), o3);
4342
4343 // Get mirrors for the four objects.
4344 CompileRun(
4345 "o0_mirror = debug.MakeMirror(o0);"
4346 "o1_mirror = debug.MakeMirror(o1);"
4347 "o2_mirror = debug.MakeMirror(o2);"
4348 "o3_mirror = debug.MakeMirror(o3)");
4349 CHECK(CompileRun("o0_mirror instanceof debug.ObjectMirror")->BooleanValue());
4350 CHECK(CompileRun("o1_mirror instanceof debug.ObjectMirror")->BooleanValue());
4351 CHECK(CompileRun("o2_mirror instanceof debug.ObjectMirror")->BooleanValue());
4352 CHECK(CompileRun("o3_mirror instanceof debug.ObjectMirror")->BooleanValue());
4353
4354 // Check that each object has one property.
4355 CHECK_EQ(1, CompileRun(
4356 "o0_mirror.propertyNames().length")->Int32Value());
4357 CHECK_EQ(1, CompileRun(
4358 "o1_mirror.propertyNames().length")->Int32Value());
4359 CHECK_EQ(1, CompileRun(
4360 "o2_mirror.propertyNames().length")->Int32Value());
4361 CHECK_EQ(1, CompileRun(
4362 "o3_mirror.propertyNames().length")->Int32Value());
4363
4364 // Set o1 as prototype for o0. o1 has the hidden prototype flag so all
4365 // properties on o1 should be seen on o0.
4366 o0->Set(v8::String::New("__proto__"), o1);
4367 CHECK_EQ(2, CompileRun(
4368 "o0_mirror.propertyNames().length")->Int32Value());
4369 CHECK_EQ(0, CompileRun(
4370 "o0_mirror.property('x').value().value()")->Int32Value());
4371 CHECK_EQ(1, CompileRun(
4372 "o0_mirror.property('y').value().value()")->Int32Value());
4373
4374 // Set o2 as prototype for o0 (it will end up after o1 as o1 has the hidden
4375 // prototype flag. o2 also has the hidden prototype flag so all properties
4376 // on o2 should be seen on o0 as well as properties on o1.
4377 o0->Set(v8::String::New("__proto__"), o2);
4378 CHECK_EQ(3, CompileRun(
4379 "o0_mirror.propertyNames().length")->Int32Value());
4380 CHECK_EQ(0, CompileRun(
4381 "o0_mirror.property('x').value().value()")->Int32Value());
4382 CHECK_EQ(1, CompileRun(
4383 "o0_mirror.property('y').value().value()")->Int32Value());
4384 CHECK_EQ(2, CompileRun(
4385 "o0_mirror.property('z').value().value()")->Int32Value());
4386
4387 // Set o3 as prototype for o0 (it will end up after o1 and o2 as both o1 and
4388 // o2 has the hidden prototype flag. o3 does not have the hidden prototype
4389 // flag so properties on o3 should not be seen on o0 whereas the properties
4390 // from o1 and o2 should still be seen on o0.
4391 // Final prototype chain: o0 -> o1 -> o2 -> o3
4392 // Hidden prototypes: ^^ ^^
4393 o0->Set(v8::String::New("__proto__"), o3);
4394 CHECK_EQ(3, CompileRun(
4395 "o0_mirror.propertyNames().length")->Int32Value());
4396 CHECK_EQ(1, CompileRun(
4397 "o3_mirror.propertyNames().length")->Int32Value());
4398 CHECK_EQ(0, CompileRun(
4399 "o0_mirror.property('x').value().value()")->Int32Value());
4400 CHECK_EQ(1, CompileRun(
4401 "o0_mirror.property('y').value().value()")->Int32Value());
4402 CHECK_EQ(2, CompileRun(
4403 "o0_mirror.property('z').value().value()")->Int32Value());
4404 CHECK(CompileRun("o0_mirror.property('u').isUndefined()")->BooleanValue());
4405
4406 // The prototype (__proto__) for o0 should be o3 as o1 and o2 are hidden.
4407 CHECK(CompileRun("o0_mirror.protoObject() == o3_mirror")->BooleanValue());
4408}
4409
4410
4411static v8::Handle<v8::Value> ProtperyXNativeGetter(
4412 v8::Local<v8::String> property, const v8::AccessorInfo& info) {
4413 return v8::Integer::New(10);
4414}
4415
4416
4417TEST(NativeGetterPropertyMirror) {
4418 // Create a V8 environment with debug access.
4419 v8::HandleScope scope;
4420 DebugLocalContext env;
4421 env.ExposeDebug();
4422
4423 v8::Handle<v8::String> name = v8::String::New("x");
4424 // Create object with named accessor.
4425 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
4426 named->SetAccessor(name, &ProtperyXNativeGetter, NULL,
4427 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None);
4428
4429 // Create object with named property getter.
4430 env->Global()->Set(v8::String::New("instance"), named->NewInstance());
4431 CHECK_EQ(10, CompileRun("instance.x")->Int32Value());
4432
4433 // Get mirror for the object with property getter.
4434 CompileRun("instance_mirror = debug.MakeMirror(instance);");
4435 CHECK(CompileRun(
4436 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue());
4437
4438 CompileRun("named_names = instance_mirror.propertyNames();");
4439 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
4440 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue());
4441 CHECK(CompileRun(
4442 "instance_mirror.property('x').value().isNumber()")->BooleanValue());
4443 CHECK(CompileRun(
4444 "instance_mirror.property('x').value().value() == 10")->BooleanValue());
4445}
4446
4447
4448static v8::Handle<v8::Value> ProtperyXNativeGetterThrowingError(
4449 v8::Local<v8::String> property, const v8::AccessorInfo& info) {
4450 return CompileRun("throw new Error('Error message');");
4451}
4452
4453
4454TEST(NativeGetterThrowingErrorPropertyMirror) {
4455 // Create a V8 environment with debug access.
4456 v8::HandleScope scope;
4457 DebugLocalContext env;
4458 env.ExposeDebug();
4459
4460 v8::Handle<v8::String> name = v8::String::New("x");
4461 // Create object with named accessor.
4462 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
4463 named->SetAccessor(name, &ProtperyXNativeGetterThrowingError, NULL,
4464 v8::Handle<v8::Value>(), v8::DEFAULT, v8::None);
4465
4466 // Create object with named property getter.
4467 env->Global()->Set(v8::String::New("instance"), named->NewInstance());
4468
4469 // Get mirror for the object with property getter.
4470 CompileRun("instance_mirror = debug.MakeMirror(instance);");
4471 CHECK(CompileRun(
4472 "instance_mirror instanceof debug.ObjectMirror")->BooleanValue());
4473 CompileRun("named_names = instance_mirror.propertyNames();");
4474 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
4475 CHECK(CompileRun("named_names[0] == 'x'")->BooleanValue());
4476 CHECK(CompileRun(
4477 "instance_mirror.property('x').value().isError()")->BooleanValue());
4478
4479 // Check that the message is that passed to the Error constructor.
4480 CHECK(CompileRun(
4481 "instance_mirror.property('x').value().message() == 'Error message'")->
4482 BooleanValue());
4483}
4484
4485
Steve Blockd0582a62009-12-15 09:54:21 +00004486// Test that hidden properties object is not returned as an unnamed property
4487// among regular properties.
4488// See http://crbug.com/26491
4489TEST(NoHiddenProperties) {
4490 // Create a V8 environment with debug access.
4491 v8::HandleScope scope;
4492 DebugLocalContext env;
4493 env.ExposeDebug();
4494
4495 // Create an object in the global scope.
4496 const char* source = "var obj = {a: 1};";
4497 v8::Script::Compile(v8::String::New(source))->Run();
4498 v8::Local<v8::Object> obj = v8::Local<v8::Object>::Cast(
4499 env->Global()->Get(v8::String::New("obj")));
4500 // Set a hidden property on the object.
4501 obj->SetHiddenValue(v8::String::New("v8::test-debug::a"),
4502 v8::Int32::New(11));
4503
4504 // Get mirror for the object with property getter.
4505 CompileRun("var obj_mirror = debug.MakeMirror(obj);");
4506 CHECK(CompileRun(
4507 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue());
4508 CompileRun("var named_names = obj_mirror.propertyNames();");
4509 // There should be exactly one property. But there is also an unnamed
4510 // property whose value is hidden properties dictionary. The latter
4511 // property should not be in the list of reguar properties.
4512 CHECK_EQ(1, CompileRun("named_names.length")->Int32Value());
4513 CHECK(CompileRun("named_names[0] == 'a'")->BooleanValue());
4514 CHECK(CompileRun(
4515 "obj_mirror.property('a').value().value() == 1")->BooleanValue());
4516
4517 // Object created by t0 will become hidden prototype of object 'obj'.
4518 v8::Handle<v8::FunctionTemplate> t0 = v8::FunctionTemplate::New();
4519 t0->InstanceTemplate()->Set(v8::String::New("b"), v8::Number::New(2));
4520 t0->SetHiddenPrototype(true);
4521 v8::Handle<v8::FunctionTemplate> t1 = v8::FunctionTemplate::New();
4522 t1->InstanceTemplate()->Set(v8::String::New("c"), v8::Number::New(3));
4523
4524 // Create proto objects, add hidden properties to them and set them on
4525 // the global object.
4526 v8::Handle<v8::Object> protoObj = t0->GetFunction()->NewInstance();
4527 protoObj->SetHiddenValue(v8::String::New("v8::test-debug::b"),
4528 v8::Int32::New(12));
4529 env->Global()->Set(v8::String::New("protoObj"), protoObj);
4530 v8::Handle<v8::Object> grandProtoObj = t1->GetFunction()->NewInstance();
4531 grandProtoObj->SetHiddenValue(v8::String::New("v8::test-debug::c"),
4532 v8::Int32::New(13));
4533 env->Global()->Set(v8::String::New("grandProtoObj"), grandProtoObj);
4534
4535 // Setting prototypes: obj->protoObj->grandProtoObj
4536 protoObj->Set(v8::String::New("__proto__"), grandProtoObj);
4537 obj->Set(v8::String::New("__proto__"), protoObj);
4538
4539 // Get mirror for the object with property getter.
4540 CompileRun("var obj_mirror = debug.MakeMirror(obj);");
4541 CHECK(CompileRun(
4542 "obj_mirror instanceof debug.ObjectMirror")->BooleanValue());
4543 CompileRun("var named_names = obj_mirror.propertyNames();");
4544 // There should be exactly two properties - one from the object itself and
4545 // another from its hidden prototype.
4546 CHECK_EQ(2, CompileRun("named_names.length")->Int32Value());
4547 CHECK(CompileRun("named_names.sort(); named_names[0] == 'a' &&"
4548 "named_names[1] == 'b'")->BooleanValue());
4549 CHECK(CompileRun(
4550 "obj_mirror.property('a').value().value() == 1")->BooleanValue());
4551 CHECK(CompileRun(
4552 "obj_mirror.property('b').value().value() == 2")->BooleanValue());
4553}
4554
Steve Blocka7e24c12009-10-30 11:49:00 +00004555
4556// Multithreaded tests of JSON debugger protocol
4557
4558// Support classes
4559
Steve Blocka7e24c12009-10-30 11:49:00 +00004560// Provides synchronization between k threads, where k is an input to the
4561// constructor. The Wait() call blocks a thread until it is called for the
4562// k'th time, then all calls return. Each ThreadBarrier object can only
4563// be used once.
4564class ThreadBarrier {
4565 public:
4566 explicit ThreadBarrier(int num_threads);
4567 ~ThreadBarrier();
4568 void Wait();
4569 private:
4570 int num_threads_;
4571 int num_blocked_;
4572 v8::internal::Mutex* lock_;
4573 v8::internal::Semaphore* sem_;
4574 bool invalid_;
4575};
4576
4577ThreadBarrier::ThreadBarrier(int num_threads)
4578 : num_threads_(num_threads), num_blocked_(0) {
4579 lock_ = OS::CreateMutex();
4580 sem_ = OS::CreateSemaphore(0);
4581 invalid_ = false; // A barrier may only be used once. Then it is invalid.
4582}
4583
4584// Do not call, due to race condition with Wait().
4585// Could be resolved with Pthread condition variables.
4586ThreadBarrier::~ThreadBarrier() {
4587 lock_->Lock();
4588 delete lock_;
4589 delete sem_;
4590}
4591
4592void ThreadBarrier::Wait() {
4593 lock_->Lock();
4594 CHECK(!invalid_);
4595 if (num_blocked_ == num_threads_ - 1) {
4596 // Signal and unblock all waiting threads.
4597 for (int i = 0; i < num_threads_ - 1; ++i) {
4598 sem_->Signal();
4599 }
4600 invalid_ = true;
4601 printf("BARRIER\n\n");
4602 fflush(stdout);
4603 lock_->Unlock();
4604 } else { // Wait for the semaphore.
4605 ++num_blocked_;
4606 lock_->Unlock(); // Potential race condition with destructor because
4607 sem_->Wait(); // these two lines are not atomic.
4608 }
4609}
4610
4611// A set containing enough barriers and semaphores for any of the tests.
4612class Barriers {
4613 public:
4614 Barriers();
4615 void Initialize();
4616 ThreadBarrier barrier_1;
4617 ThreadBarrier barrier_2;
4618 ThreadBarrier barrier_3;
4619 ThreadBarrier barrier_4;
4620 ThreadBarrier barrier_5;
4621 v8::internal::Semaphore* semaphore_1;
4622 v8::internal::Semaphore* semaphore_2;
4623};
4624
4625Barriers::Barriers() : barrier_1(2), barrier_2(2),
4626 barrier_3(2), barrier_4(2), barrier_5(2) {}
4627
4628void Barriers::Initialize() {
4629 semaphore_1 = OS::CreateSemaphore(0);
4630 semaphore_2 = OS::CreateSemaphore(0);
4631}
4632
4633
4634// We match parts of the message to decide if it is a break message.
4635bool IsBreakEventMessage(char *message) {
4636 const char* type_event = "\"type\":\"event\"";
4637 const char* event_break = "\"event\":\"break\"";
4638 // Does the message contain both type:event and event:break?
4639 return strstr(message, type_event) != NULL &&
4640 strstr(message, event_break) != NULL;
4641}
4642
4643
Steve Block3ce2e202009-11-05 08:53:23 +00004644// We match parts of the message to decide if it is a exception message.
4645bool IsExceptionEventMessage(char *message) {
4646 const char* type_event = "\"type\":\"event\"";
4647 const char* event_exception = "\"event\":\"exception\"";
4648 // Does the message contain both type:event and event:exception?
4649 return strstr(message, type_event) != NULL &&
4650 strstr(message, event_exception) != NULL;
4651}
4652
4653
4654// We match the message wether it is an evaluate response message.
4655bool IsEvaluateResponseMessage(char* message) {
4656 const char* type_response = "\"type\":\"response\"";
4657 const char* command_evaluate = "\"command\":\"evaluate\"";
4658 // Does the message contain both type:response and command:evaluate?
4659 return strstr(message, type_response) != NULL &&
4660 strstr(message, command_evaluate) != NULL;
4661}
4662
4663
Andrei Popescu402d9372010-02-26 13:31:12 +00004664static int StringToInt(const char* s) {
4665 return atoi(s); // NOLINT
4666}
4667
4668
Steve Block3ce2e202009-11-05 08:53:23 +00004669// We match parts of the message to get evaluate result int value.
4670int GetEvaluateIntResult(char *message) {
4671 const char* value = "\"value\":";
4672 char* pos = strstr(message, value);
4673 if (pos == NULL) {
4674 return -1;
4675 }
4676 int res = -1;
Andrei Popescu402d9372010-02-26 13:31:12 +00004677 res = StringToInt(pos + strlen(value));
Steve Block3ce2e202009-11-05 08:53:23 +00004678 return res;
4679}
4680
4681
4682// We match parts of the message to get hit breakpoint id.
4683int GetBreakpointIdFromBreakEventMessage(char *message) {
4684 const char* breakpoints = "\"breakpoints\":[";
4685 char* pos = strstr(message, breakpoints);
4686 if (pos == NULL) {
4687 return -1;
4688 }
4689 int res = -1;
Andrei Popescu402d9372010-02-26 13:31:12 +00004690 res = StringToInt(pos + strlen(breakpoints));
Steve Block3ce2e202009-11-05 08:53:23 +00004691 return res;
4692}
4693
4694
Leon Clarked91b9f72010-01-27 17:25:45 +00004695// We match parts of the message to get total frames number.
4696int GetTotalFramesInt(char *message) {
4697 const char* prefix = "\"totalFrames\":";
4698 char* pos = strstr(message, prefix);
4699 if (pos == NULL) {
4700 return -1;
4701 }
4702 pos += strlen(prefix);
Andrei Popescu402d9372010-02-26 13:31:12 +00004703 int res = StringToInt(pos);
Leon Clarked91b9f72010-01-27 17:25:45 +00004704 return res;
4705}
4706
4707
Iain Merrick9ac36c92010-09-13 15:29:50 +01004708// We match parts of the message to get source line.
4709int GetSourceLineFromBreakEventMessage(char *message) {
4710 const char* source_line = "\"sourceLine\":";
4711 char* pos = strstr(message, source_line);
4712 if (pos == NULL) {
4713 return -1;
4714 }
4715 int res = -1;
4716 res = StringToInt(pos + strlen(source_line));
4717 return res;
4718}
4719
Steve Blocka7e24c12009-10-30 11:49:00 +00004720/* Test MessageQueues */
4721/* Tests the message queues that hold debugger commands and
4722 * response messages to the debugger. Fills queues and makes
4723 * them grow.
4724 */
4725Barriers message_queue_barriers;
4726
4727// This is the debugger thread, that executes no v8 calls except
4728// placing JSON debugger commands in the queue.
4729class MessageQueueDebuggerThread : public v8::internal::Thread {
4730 public:
Steve Block44f0eee2011-05-26 01:26:41 +01004731 explicit MessageQueueDebuggerThread(v8::internal::Isolate* isolate)
4732 : Thread(isolate, "MessageQueueDebuggerThread") { }
Steve Blocka7e24c12009-10-30 11:49:00 +00004733 void Run();
4734};
4735
4736static void MessageHandler(const uint16_t* message, int length,
4737 v8::Debug::ClientData* client_data) {
4738 static char print_buffer[1000];
4739 Utf16ToAscii(message, length, print_buffer);
4740 if (IsBreakEventMessage(print_buffer)) {
4741 // Lets test script wait until break occurs to send commands.
4742 // Signals when a break is reported.
4743 message_queue_barriers.semaphore_2->Signal();
4744 }
4745
4746 // Allow message handler to block on a semaphore, to test queueing of
4747 // messages while blocked.
4748 message_queue_barriers.semaphore_1->Wait();
Steve Blocka7e24c12009-10-30 11:49:00 +00004749}
4750
4751void MessageQueueDebuggerThread::Run() {
4752 const int kBufferSize = 1000;
4753 uint16_t buffer_1[kBufferSize];
4754 uint16_t buffer_2[kBufferSize];
4755 const char* command_1 =
4756 "{\"seq\":117,"
4757 "\"type\":\"request\","
4758 "\"command\":\"evaluate\","
4759 "\"arguments\":{\"expression\":\"1+2\"}}";
4760 const char* command_2 =
4761 "{\"seq\":118,"
4762 "\"type\":\"request\","
4763 "\"command\":\"evaluate\","
4764 "\"arguments\":{\"expression\":\"1+a\"}}";
4765 const char* command_3 =
4766 "{\"seq\":119,"
4767 "\"type\":\"request\","
4768 "\"command\":\"evaluate\","
4769 "\"arguments\":{\"expression\":\"c.d * b\"}}";
4770 const char* command_continue =
4771 "{\"seq\":106,"
4772 "\"type\":\"request\","
4773 "\"command\":\"continue\"}";
4774 const char* command_single_step =
4775 "{\"seq\":107,"
4776 "\"type\":\"request\","
4777 "\"command\":\"continue\","
4778 "\"arguments\":{\"stepaction\":\"next\"}}";
4779
4780 /* Interleaved sequence of actions by the two threads:*/
4781 // Main thread compiles and runs source_1
4782 message_queue_barriers.semaphore_1->Signal();
4783 message_queue_barriers.barrier_1.Wait();
4784 // Post 6 commands, filling the command queue and making it expand.
4785 // These calls return immediately, but the commands stay on the queue
4786 // until the execution of source_2.
4787 // Note: AsciiToUtf16 executes before SendCommand, so command is copied
4788 // to buffer before buffer is sent to SendCommand.
4789 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1));
4790 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2));
4791 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
4792 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
4793 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
4794 message_queue_barriers.barrier_2.Wait();
4795 // Main thread compiles and runs source_2.
4796 // Queued commands are executed at the start of compilation of source_2(
4797 // beforeCompile event).
4798 // Free the message handler to process all the messages from the queue. 7
4799 // messages are expected: 2 afterCompile events and 5 responses.
4800 // All the commands added so far will fail to execute as long as call stack
4801 // is empty on beforeCompile event.
4802 for (int i = 0; i < 6 ; ++i) {
4803 message_queue_barriers.semaphore_1->Signal();
4804 }
4805 message_queue_barriers.barrier_3.Wait();
4806 // Main thread compiles and runs source_3.
4807 // Don't stop in the afterCompile handler.
4808 message_queue_barriers.semaphore_1->Signal();
4809 // source_3 includes a debugger statement, which causes a break event.
4810 // Wait on break event from hitting "debugger" statement
4811 message_queue_barriers.semaphore_2->Wait();
4812 // These should execute after the "debugger" statement in source_2
4813 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_1, buffer_1));
4814 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_2, buffer_2));
4815 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_3, buffer_2));
4816 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_single_step, buffer_2));
4817 // Run after 2 break events, 4 responses.
4818 for (int i = 0; i < 6 ; ++i) {
4819 message_queue_barriers.semaphore_1->Signal();
4820 }
4821 // Wait on break event after a single step executes.
4822 message_queue_barriers.semaphore_2->Wait();
4823 v8::Debug::SendCommand(buffer_1, AsciiToUtf16(command_2, buffer_1));
4824 v8::Debug::SendCommand(buffer_2, AsciiToUtf16(command_continue, buffer_2));
4825 // Run after 2 responses.
4826 for (int i = 0; i < 2 ; ++i) {
4827 message_queue_barriers.semaphore_1->Signal();
4828 }
4829 // Main thread continues running source_3 to end, waits for this thread.
4830}
4831
Steve Blocka7e24c12009-10-30 11:49:00 +00004832
4833// This thread runs the v8 engine.
4834TEST(MessageQueues) {
Steve Block44f0eee2011-05-26 01:26:41 +01004835 MessageQueueDebuggerThread message_queue_debugger_thread(
4836 i::Isolate::Current());
4837
Steve Blocka7e24c12009-10-30 11:49:00 +00004838 // Create a V8 environment
4839 v8::HandleScope scope;
4840 DebugLocalContext env;
4841 message_queue_barriers.Initialize();
4842 v8::Debug::SetMessageHandler(MessageHandler);
4843 message_queue_debugger_thread.Start();
4844
4845 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
4846 const char* source_2 = "e = 17;";
4847 const char* source_3 = "a = 4; debugger; a = 5; a = 6; a = 7;";
4848
4849 // See MessageQueueDebuggerThread::Run for interleaved sequence of
4850 // API calls and events in the two threads.
4851 CompileRun(source_1);
4852 message_queue_barriers.barrier_1.Wait();
4853 message_queue_barriers.barrier_2.Wait();
4854 CompileRun(source_2);
4855 message_queue_barriers.barrier_3.Wait();
4856 CompileRun(source_3);
4857 message_queue_debugger_thread.Join();
4858 fflush(stdout);
4859}
4860
4861
4862class TestClientData : public v8::Debug::ClientData {
4863 public:
4864 TestClientData() {
4865 constructor_call_counter++;
4866 }
4867 virtual ~TestClientData() {
4868 destructor_call_counter++;
4869 }
4870
4871 static void ResetCounters() {
4872 constructor_call_counter = 0;
4873 destructor_call_counter = 0;
4874 }
4875
4876 static int constructor_call_counter;
4877 static int destructor_call_counter;
4878};
4879
4880int TestClientData::constructor_call_counter = 0;
4881int TestClientData::destructor_call_counter = 0;
4882
4883
4884// Tests that MessageQueue doesn't destroy client data when expands and
4885// does destroy when it dies.
4886TEST(MessageQueueExpandAndDestroy) {
4887 TestClientData::ResetCounters();
4888 { // Create a scope for the queue.
4889 CommandMessageQueue queue(1);
4890 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4891 new TestClientData()));
4892 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4893 new TestClientData()));
4894 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4895 new TestClientData()));
4896 CHECK_EQ(0, TestClientData::destructor_call_counter);
4897 queue.Get().Dispose();
4898 CHECK_EQ(1, TestClientData::destructor_call_counter);
4899 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4900 new TestClientData()));
4901 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4902 new TestClientData()));
4903 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4904 new TestClientData()));
4905 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4906 new TestClientData()));
4907 queue.Put(CommandMessage::New(Vector<uint16_t>::empty(),
4908 new TestClientData()));
4909 CHECK_EQ(1, TestClientData::destructor_call_counter);
4910 queue.Get().Dispose();
4911 CHECK_EQ(2, TestClientData::destructor_call_counter);
4912 }
4913 // All the client data should be destroyed when the queue is destroyed.
4914 CHECK_EQ(TestClientData::destructor_call_counter,
4915 TestClientData::destructor_call_counter);
4916}
4917
4918
4919static int handled_client_data_instances_count = 0;
4920static void MessageHandlerCountingClientData(
4921 const v8::Debug::Message& message) {
4922 if (message.GetClientData() != NULL) {
4923 handled_client_data_instances_count++;
4924 }
4925}
4926
4927
4928// Tests that all client data passed to the debugger are sent to the handler.
4929TEST(SendClientDataToHandler) {
4930 // Create a V8 environment
4931 v8::HandleScope scope;
4932 DebugLocalContext env;
4933 TestClientData::ResetCounters();
4934 handled_client_data_instances_count = 0;
4935 v8::Debug::SetMessageHandler2(MessageHandlerCountingClientData);
4936 const char* source_1 = "a = 3; b = 4; c = new Object(); c.d = 5;";
4937 const int kBufferSize = 1000;
4938 uint16_t buffer[kBufferSize];
4939 const char* command_1 =
4940 "{\"seq\":117,"
4941 "\"type\":\"request\","
4942 "\"command\":\"evaluate\","
4943 "\"arguments\":{\"expression\":\"1+2\"}}";
4944 const char* command_2 =
4945 "{\"seq\":118,"
4946 "\"type\":\"request\","
4947 "\"command\":\"evaluate\","
4948 "\"arguments\":{\"expression\":\"1+a\"}}";
4949 const char* command_continue =
4950 "{\"seq\":106,"
4951 "\"type\":\"request\","
4952 "\"command\":\"continue\"}";
4953
4954 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer),
4955 new TestClientData());
4956 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer), NULL);
4957 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer),
4958 new TestClientData());
4959 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer),
4960 new TestClientData());
4961 // All the messages will be processed on beforeCompile event.
4962 CompileRun(source_1);
4963 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer));
4964 CHECK_EQ(3, TestClientData::constructor_call_counter);
4965 CHECK_EQ(TestClientData::constructor_call_counter,
4966 handled_client_data_instances_count);
4967 CHECK_EQ(TestClientData::constructor_call_counter,
4968 TestClientData::destructor_call_counter);
4969}
4970
4971
4972/* Test ThreadedDebugging */
4973/* This test interrupts a running infinite loop that is
4974 * occupying the v8 thread by a break command from the
4975 * debugger thread. It then changes the value of a
4976 * global object, to make the loop terminate.
4977 */
4978
4979Barriers threaded_debugging_barriers;
4980
4981class V8Thread : public v8::internal::Thread {
4982 public:
Steve Block44f0eee2011-05-26 01:26:41 +01004983 explicit V8Thread(v8::internal::Isolate* isolate)
4984 : Thread(isolate, "V8Thread") { }
Steve Blocka7e24c12009-10-30 11:49:00 +00004985 void Run();
4986};
4987
4988class DebuggerThread : public v8::internal::Thread {
4989 public:
Steve Block44f0eee2011-05-26 01:26:41 +01004990 explicit DebuggerThread(v8::internal::Isolate* isolate)
4991 : Thread(isolate, "DebuggerThread") { }
Steve Blocka7e24c12009-10-30 11:49:00 +00004992 void Run();
4993};
4994
4995
4996static v8::Handle<v8::Value> ThreadedAtBarrier1(const v8::Arguments& args) {
4997 threaded_debugging_barriers.barrier_1.Wait();
4998 return v8::Undefined();
4999}
5000
5001
5002static void ThreadedMessageHandler(const v8::Debug::Message& message) {
5003 static char print_buffer[1000];
5004 v8::String::Value json(message.GetJSON());
5005 Utf16ToAscii(*json, json.length(), print_buffer);
5006 if (IsBreakEventMessage(print_buffer)) {
Iain Merrick9ac36c92010-09-13 15:29:50 +01005007 // Check that we are inside the while loop.
5008 int source_line = GetSourceLineFromBreakEventMessage(print_buffer);
5009 CHECK(8 <= source_line && source_line <= 13);
Steve Blocka7e24c12009-10-30 11:49:00 +00005010 threaded_debugging_barriers.barrier_2.Wait();
5011 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005012}
5013
5014
5015void V8Thread::Run() {
5016 const char* source =
5017 "flag = true;\n"
5018 "function bar( new_value ) {\n"
5019 " flag = new_value;\n"
5020 " return \"Return from bar(\" + new_value + \")\";\n"
5021 "}\n"
5022 "\n"
5023 "function foo() {\n"
5024 " var x = 1;\n"
5025 " while ( flag == true ) {\n"
5026 " if ( x == 1 ) {\n"
5027 " ThreadedAtBarrier1();\n"
5028 " }\n"
5029 " x = x + 1;\n"
5030 " }\n"
5031 "}\n"
5032 "\n"
5033 "foo();\n";
5034
5035 v8::HandleScope scope;
5036 DebugLocalContext env;
5037 v8::Debug::SetMessageHandler2(&ThreadedMessageHandler);
5038 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
5039 global_template->Set(v8::String::New("ThreadedAtBarrier1"),
5040 v8::FunctionTemplate::New(ThreadedAtBarrier1));
5041 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template);
5042 v8::Context::Scope context_scope(context);
5043
5044 CompileRun(source);
5045}
5046
5047void DebuggerThread::Run() {
5048 const int kBufSize = 1000;
5049 uint16_t buffer[kBufSize];
5050
5051 const char* command_1 = "{\"seq\":102,"
5052 "\"type\":\"request\","
5053 "\"command\":\"evaluate\","
5054 "\"arguments\":{\"expression\":\"bar(false)\"}}";
5055 const char* command_2 = "{\"seq\":103,"
5056 "\"type\":\"request\","
5057 "\"command\":\"continue\"}";
5058
5059 threaded_debugging_barriers.barrier_1.Wait();
5060 v8::Debug::DebugBreak();
5061 threaded_debugging_barriers.barrier_2.Wait();
5062 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
5063 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
5064}
5065
Steve Blocka7e24c12009-10-30 11:49:00 +00005066
5067TEST(ThreadedDebugging) {
Steve Block44f0eee2011-05-26 01:26:41 +01005068 DebuggerThread debugger_thread(i::Isolate::Current());
5069 V8Thread v8_thread(i::Isolate::Current());
5070
Steve Blocka7e24c12009-10-30 11:49:00 +00005071 // Create a V8 environment
5072 threaded_debugging_barriers.Initialize();
5073
5074 v8_thread.Start();
5075 debugger_thread.Start();
5076
5077 v8_thread.Join();
5078 debugger_thread.Join();
5079}
5080
5081/* Test RecursiveBreakpoints */
5082/* In this test, the debugger evaluates a function with a breakpoint, after
5083 * hitting a breakpoint in another function. We do this with both values
5084 * of the flag enabling recursive breakpoints, and verify that the second
5085 * breakpoint is hit when enabled, and missed when disabled.
5086 */
5087
5088class BreakpointsV8Thread : public v8::internal::Thread {
5089 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005090 explicit BreakpointsV8Thread(v8::internal::Isolate* isolate)
5091 : Thread(isolate, "BreakpointsV8Thread") { }
Steve Blocka7e24c12009-10-30 11:49:00 +00005092 void Run();
5093};
5094
5095class BreakpointsDebuggerThread : public v8::internal::Thread {
5096 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005097 explicit BreakpointsDebuggerThread(v8::internal::Isolate* isolate,
5098 bool global_evaluate)
5099 : Thread(isolate, "BreakpointsDebuggerThread"),
5100 global_evaluate_(global_evaluate) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00005101 void Run();
Leon Clarked91b9f72010-01-27 17:25:45 +00005102
5103 private:
5104 bool global_evaluate_;
Steve Blocka7e24c12009-10-30 11:49:00 +00005105};
5106
5107
5108Barriers* breakpoints_barriers;
Steve Block3ce2e202009-11-05 08:53:23 +00005109int break_event_breakpoint_id;
5110int evaluate_int_result;
Steve Blocka7e24c12009-10-30 11:49:00 +00005111
5112static void BreakpointsMessageHandler(const v8::Debug::Message& message) {
5113 static char print_buffer[1000];
5114 v8::String::Value json(message.GetJSON());
5115 Utf16ToAscii(*json, json.length(), print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00005116
Steve Blocka7e24c12009-10-30 11:49:00 +00005117 if (IsBreakEventMessage(print_buffer)) {
Steve Block3ce2e202009-11-05 08:53:23 +00005118 break_event_breakpoint_id =
5119 GetBreakpointIdFromBreakEventMessage(print_buffer);
5120 breakpoints_barriers->semaphore_1->Signal();
5121 } else if (IsEvaluateResponseMessage(print_buffer)) {
5122 evaluate_int_result = GetEvaluateIntResult(print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00005123 breakpoints_barriers->semaphore_1->Signal();
5124 }
5125}
5126
5127
5128void BreakpointsV8Thread::Run() {
5129 const char* source_1 = "var y_global = 3;\n"
5130 "function cat( new_value ) {\n"
5131 " var x = new_value;\n"
Steve Block3ce2e202009-11-05 08:53:23 +00005132 " y_global = y_global + 4;\n"
Steve Blocka7e24c12009-10-30 11:49:00 +00005133 " x = 3 * x + 1;\n"
Steve Block3ce2e202009-11-05 08:53:23 +00005134 " y_global = y_global + 5;\n"
Steve Blocka7e24c12009-10-30 11:49:00 +00005135 " return x;\n"
5136 "}\n"
5137 "\n"
5138 "function dog() {\n"
5139 " var x = 1;\n"
5140 " x = y_global;"
5141 " var z = 3;"
5142 " x += 100;\n"
5143 " return x;\n"
5144 "}\n"
5145 "\n";
5146 const char* source_2 = "cat(17);\n"
5147 "cat(19);\n";
5148
5149 v8::HandleScope scope;
5150 DebugLocalContext env;
5151 v8::Debug::SetMessageHandler2(&BreakpointsMessageHandler);
5152
5153 CompileRun(source_1);
5154 breakpoints_barriers->barrier_1.Wait();
5155 breakpoints_barriers->barrier_2.Wait();
5156 CompileRun(source_2);
5157}
5158
5159
5160void BreakpointsDebuggerThread::Run() {
5161 const int kBufSize = 1000;
5162 uint16_t buffer[kBufSize];
5163
5164 const char* command_1 = "{\"seq\":101,"
5165 "\"type\":\"request\","
5166 "\"command\":\"setbreakpoint\","
5167 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
5168 const char* command_2 = "{\"seq\":102,"
5169 "\"type\":\"request\","
5170 "\"command\":\"setbreakpoint\","
5171 "\"arguments\":{\"type\":\"function\",\"target\":\"dog\",\"line\":3}}";
Leon Clarked91b9f72010-01-27 17:25:45 +00005172 const char* command_3;
5173 if (this->global_evaluate_) {
5174 command_3 = "{\"seq\":103,"
5175 "\"type\":\"request\","
5176 "\"command\":\"evaluate\","
5177 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false,"
5178 "\"global\":true}}";
5179 } else {
5180 command_3 = "{\"seq\":103,"
5181 "\"type\":\"request\","
5182 "\"command\":\"evaluate\","
5183 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":false}}";
5184 }
5185 const char* command_4;
5186 if (this->global_evaluate_) {
5187 command_4 = "{\"seq\":104,"
5188 "\"type\":\"request\","
5189 "\"command\":\"evaluate\","
5190 "\"arguments\":{\"expression\":\"100 + 8\",\"disable_break\":true,"
5191 "\"global\":true}}";
5192 } else {
5193 command_4 = "{\"seq\":104,"
5194 "\"type\":\"request\","
5195 "\"command\":\"evaluate\","
5196 "\"arguments\":{\"expression\":\"x + 1\",\"disable_break\":true}}";
5197 }
Steve Block3ce2e202009-11-05 08:53:23 +00005198 const char* command_5 = "{\"seq\":105,"
Steve Blocka7e24c12009-10-30 11:49:00 +00005199 "\"type\":\"request\","
5200 "\"command\":\"continue\"}";
Steve Block3ce2e202009-11-05 08:53:23 +00005201 const char* command_6 = "{\"seq\":106,"
Steve Blocka7e24c12009-10-30 11:49:00 +00005202 "\"type\":\"request\","
5203 "\"command\":\"continue\"}";
Leon Clarked91b9f72010-01-27 17:25:45 +00005204 const char* command_7;
5205 if (this->global_evaluate_) {
5206 command_7 = "{\"seq\":107,"
5207 "\"type\":\"request\","
5208 "\"command\":\"evaluate\","
5209 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true,"
5210 "\"global\":true}}";
5211 } else {
5212 command_7 = "{\"seq\":107,"
5213 "\"type\":\"request\","
5214 "\"command\":\"evaluate\","
5215 "\"arguments\":{\"expression\":\"dog()\",\"disable_break\":true}}";
5216 }
Steve Block3ce2e202009-11-05 08:53:23 +00005217 const char* command_8 = "{\"seq\":108,"
Steve Blocka7e24c12009-10-30 11:49:00 +00005218 "\"type\":\"request\","
5219 "\"command\":\"continue\"}";
5220
5221
5222 // v8 thread initializes, runs source_1
5223 breakpoints_barriers->barrier_1.Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00005224 // 1:Set breakpoint in cat() (will get id 1).
Steve Blocka7e24c12009-10-30 11:49:00 +00005225 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00005226 // 2:Set breakpoint in dog() (will get id 2).
Steve Blocka7e24c12009-10-30 11:49:00 +00005227 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
5228 breakpoints_barriers->barrier_2.Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00005229 // V8 thread starts compiling source_2.
Steve Blocka7e24c12009-10-30 11:49:00 +00005230 // Automatic break happens, to run queued commands
5231 // breakpoints_barriers->semaphore_1->Wait();
5232 // Commands 1 through 3 run, thread continues.
5233 // v8 thread runs source_2 to breakpoint in cat().
5234 // message callback receives break event.
5235 breakpoints_barriers->semaphore_1->Wait();
Steve Block3ce2e202009-11-05 08:53:23 +00005236 // Must have hit breakpoint #1.
5237 CHECK_EQ(1, break_event_breakpoint_id);
Steve Blocka7e24c12009-10-30 11:49:00 +00005238 // 4:Evaluate dog() (which has a breakpoint).
5239 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_3, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00005240 // V8 thread hits breakpoint in dog().
Steve Blocka7e24c12009-10-30 11:49:00 +00005241 breakpoints_barriers->semaphore_1->Wait(); // wait for break event
Steve Block3ce2e202009-11-05 08:53:23 +00005242 // Must have hit breakpoint #2.
5243 CHECK_EQ(2, break_event_breakpoint_id);
5244 // 5:Evaluate (x + 1).
Steve Blocka7e24c12009-10-30 11:49:00 +00005245 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_4, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00005246 // Evaluate (x + 1) finishes.
5247 breakpoints_barriers->semaphore_1->Wait();
5248 // Must have result 108.
5249 CHECK_EQ(108, evaluate_int_result);
5250 // 6:Continue evaluation of dog().
Steve Blocka7e24c12009-10-30 11:49:00 +00005251 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_5, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00005252 // Evaluate dog() finishes.
5253 breakpoints_barriers->semaphore_1->Wait();
5254 // Must have result 107.
5255 CHECK_EQ(107, evaluate_int_result);
Steve Blocka7e24c12009-10-30 11:49:00 +00005256 // 7:Continue evaluation of source_2, finish cat(17), hit breakpoint
5257 // in cat(19).
5258 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_6, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00005259 // Message callback gets break event.
Steve Blocka7e24c12009-10-30 11:49:00 +00005260 breakpoints_barriers->semaphore_1->Wait(); // wait for break event
Steve Block3ce2e202009-11-05 08:53:23 +00005261 // Must have hit breakpoint #1.
5262 CHECK_EQ(1, break_event_breakpoint_id);
5263 // 8: Evaluate dog() with breaks disabled.
Steve Blocka7e24c12009-10-30 11:49:00 +00005264 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_7, buffer));
Steve Block3ce2e202009-11-05 08:53:23 +00005265 // Evaluate dog() finishes.
5266 breakpoints_barriers->semaphore_1->Wait();
5267 // Must have result 116.
5268 CHECK_EQ(116, evaluate_int_result);
Steve Blocka7e24c12009-10-30 11:49:00 +00005269 // 9: Continue evaluation of source2, reach end.
5270 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_8, buffer));
5271}
5272
Leon Clarked91b9f72010-01-27 17:25:45 +00005273void TestRecursiveBreakpointsGeneric(bool global_evaluate) {
Leon Clarkeeab96aa2010-01-27 16:31:12 +00005274 i::FLAG_debugger_auto_break = true;
Leon Clarke888f6722010-01-27 15:57:47 +00005275
Steve Block44f0eee2011-05-26 01:26:41 +01005276 BreakpointsDebuggerThread breakpoints_debugger_thread(i::Isolate::Current(),
5277 global_evaluate);
5278 BreakpointsV8Thread breakpoints_v8_thread(i::Isolate::Current());
Leon Clarked91b9f72010-01-27 17:25:45 +00005279
Steve Blocka7e24c12009-10-30 11:49:00 +00005280 // Create a V8 environment
5281 Barriers stack_allocated_breakpoints_barriers;
5282 stack_allocated_breakpoints_barriers.Initialize();
5283 breakpoints_barriers = &stack_allocated_breakpoints_barriers;
5284
5285 breakpoints_v8_thread.Start();
5286 breakpoints_debugger_thread.Start();
5287
5288 breakpoints_v8_thread.Join();
5289 breakpoints_debugger_thread.Join();
5290}
5291
Leon Clarked91b9f72010-01-27 17:25:45 +00005292TEST(RecursiveBreakpoints) {
5293 TestRecursiveBreakpointsGeneric(false);
5294}
5295
5296TEST(RecursiveBreakpointsGlobal) {
5297 TestRecursiveBreakpointsGeneric(true);
5298}
5299
Steve Blocka7e24c12009-10-30 11:49:00 +00005300
5301static void DummyDebugEventListener(v8::DebugEvent event,
5302 v8::Handle<v8::Object> exec_state,
5303 v8::Handle<v8::Object> event_data,
5304 v8::Handle<v8::Value> data) {
5305}
5306
5307
5308TEST(SetDebugEventListenerOnUninitializedVM) {
5309 v8::Debug::SetDebugEventListener(DummyDebugEventListener);
5310}
5311
5312
5313static void DummyMessageHandler(const v8::Debug::Message& message) {
5314}
5315
5316
5317TEST(SetMessageHandlerOnUninitializedVM) {
5318 v8::Debug::SetMessageHandler2(DummyMessageHandler);
5319}
5320
5321
5322TEST(DebugBreakOnUninitializedVM) {
5323 v8::Debug::DebugBreak();
5324}
5325
5326
5327TEST(SendCommandToUninitializedVM) {
5328 const char* dummy_command = "{}";
5329 uint16_t dummy_buffer[80];
5330 int dummy_length = AsciiToUtf16(dummy_command, dummy_buffer);
5331 v8::Debug::SendCommand(dummy_buffer, dummy_length);
5332}
5333
5334
5335// Source for a JavaScript function which returns the data parameter of a
5336// function called in the context of the debugger. If no data parameter is
5337// passed it throws an exception.
5338static const char* debugger_call_with_data_source =
5339 "function debugger_call_with_data(exec_state, data) {"
5340 " if (data) return data;"
5341 " throw 'No data!'"
5342 "}";
5343v8::Handle<v8::Function> debugger_call_with_data;
5344
5345
5346// Source for a JavaScript function which returns the data parameter of a
5347// function called in the context of the debugger. If no data parameter is
5348// passed it throws an exception.
5349static const char* debugger_call_with_closure_source =
5350 "var x = 3;"
5351 "(function (exec_state) {"
5352 " if (exec_state.y) return x - 1;"
5353 " exec_state.y = x;"
5354 " return exec_state.y"
5355 "})";
5356v8::Handle<v8::Function> debugger_call_with_closure;
5357
5358// Function to retrieve the number of JavaScript frames by calling a JavaScript
5359// in the debugger.
5360static v8::Handle<v8::Value> CheckFrameCount(const v8::Arguments& args) {
5361 CHECK(v8::Debug::Call(frame_count)->IsNumber());
5362 CHECK_EQ(args[0]->Int32Value(),
5363 v8::Debug::Call(frame_count)->Int32Value());
5364 return v8::Undefined();
5365}
5366
5367
5368// Function to retrieve the source line of the top JavaScript frame by calling a
5369// JavaScript function in the debugger.
5370static v8::Handle<v8::Value> CheckSourceLine(const v8::Arguments& args) {
5371 CHECK(v8::Debug::Call(frame_source_line)->IsNumber());
5372 CHECK_EQ(args[0]->Int32Value(),
5373 v8::Debug::Call(frame_source_line)->Int32Value());
5374 return v8::Undefined();
5375}
5376
5377
5378// Function to test passing an additional parameter to a JavaScript function
5379// called in the debugger. It also tests that functions called in the debugger
5380// can throw exceptions.
5381static v8::Handle<v8::Value> CheckDataParameter(const v8::Arguments& args) {
5382 v8::Handle<v8::String> data = v8::String::New("Test");
5383 CHECK(v8::Debug::Call(debugger_call_with_data, data)->IsString());
5384
5385 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
5386 CHECK(v8::Debug::Call(debugger_call_with_data).IsEmpty());
5387
5388 v8::TryCatch catcher;
5389 v8::Debug::Call(debugger_call_with_data);
5390 CHECK(catcher.HasCaught());
5391 CHECK(catcher.Exception()->IsString());
5392
5393 return v8::Undefined();
5394}
5395
5396
5397// Function to test using a JavaScript with closure in the debugger.
5398static v8::Handle<v8::Value> CheckClosure(const v8::Arguments& args) {
5399 CHECK(v8::Debug::Call(debugger_call_with_closure)->IsNumber());
5400 CHECK_EQ(3, v8::Debug::Call(debugger_call_with_closure)->Int32Value());
5401 return v8::Undefined();
5402}
5403
5404
5405// Test functions called through the debugger.
5406TEST(CallFunctionInDebugger) {
5407 // Create and enter a context with the functions CheckFrameCount,
5408 // CheckSourceLine and CheckDataParameter installed.
5409 v8::HandleScope scope;
5410 v8::Handle<v8::ObjectTemplate> global_template = v8::ObjectTemplate::New();
5411 global_template->Set(v8::String::New("CheckFrameCount"),
5412 v8::FunctionTemplate::New(CheckFrameCount));
5413 global_template->Set(v8::String::New("CheckSourceLine"),
5414 v8::FunctionTemplate::New(CheckSourceLine));
5415 global_template->Set(v8::String::New("CheckDataParameter"),
5416 v8::FunctionTemplate::New(CheckDataParameter));
5417 global_template->Set(v8::String::New("CheckClosure"),
5418 v8::FunctionTemplate::New(CheckClosure));
5419 v8::Handle<v8::Context> context = v8::Context::New(NULL, global_template);
5420 v8::Context::Scope context_scope(context);
5421
5422 // Compile a function for checking the number of JavaScript frames.
5423 v8::Script::Compile(v8::String::New(frame_count_source))->Run();
5424 frame_count = v8::Local<v8::Function>::Cast(
5425 context->Global()->Get(v8::String::New("frame_count")));
5426
5427 // Compile a function for returning the source line for the top frame.
5428 v8::Script::Compile(v8::String::New(frame_source_line_source))->Run();
5429 frame_source_line = v8::Local<v8::Function>::Cast(
5430 context->Global()->Get(v8::String::New("frame_source_line")));
5431
5432 // Compile a function returning the data parameter.
5433 v8::Script::Compile(v8::String::New(debugger_call_with_data_source))->Run();
5434 debugger_call_with_data = v8::Local<v8::Function>::Cast(
5435 context->Global()->Get(v8::String::New("debugger_call_with_data")));
5436
5437 // Compile a function capturing closure.
5438 debugger_call_with_closure = v8::Local<v8::Function>::Cast(
5439 v8::Script::Compile(
5440 v8::String::New(debugger_call_with_closure_source))->Run());
5441
Steve Block6ded16b2010-05-10 14:33:55 +01005442 // Calling a function through the debugger returns 0 frames if there are
5443 // no JavaScript frames.
5444 CHECK_EQ(v8::Integer::New(0), v8::Debug::Call(frame_count));
Steve Blocka7e24c12009-10-30 11:49:00 +00005445
5446 // Test that the number of frames can be retrieved.
5447 v8::Script::Compile(v8::String::New("CheckFrameCount(1)"))->Run();
5448 v8::Script::Compile(v8::String::New("function f() {"
5449 " CheckFrameCount(2);"
5450 "}; f()"))->Run();
5451
5452 // Test that the source line can be retrieved.
5453 v8::Script::Compile(v8::String::New("CheckSourceLine(0)"))->Run();
5454 v8::Script::Compile(v8::String::New("function f() {\n"
5455 " CheckSourceLine(1)\n"
5456 " CheckSourceLine(2)\n"
5457 " CheckSourceLine(3)\n"
5458 "}; f()"))->Run();
5459
5460 // Test that a parameter can be passed to a function called in the debugger.
5461 v8::Script::Compile(v8::String::New("CheckDataParameter()"))->Run();
5462
5463 // Test that a function with closure can be run in the debugger.
5464 v8::Script::Compile(v8::String::New("CheckClosure()"))->Run();
5465
5466
5467 // Test that the source line is correct when there is a line offset.
5468 v8::ScriptOrigin origin(v8::String::New("test"),
5469 v8::Integer::New(7));
5470 v8::Script::Compile(v8::String::New("CheckSourceLine(7)"), &origin)->Run();
5471 v8::Script::Compile(v8::String::New("function f() {\n"
5472 " CheckSourceLine(8)\n"
5473 " CheckSourceLine(9)\n"
5474 " CheckSourceLine(10)\n"
5475 "}; f()"), &origin)->Run();
5476}
5477
5478
5479// Debugger message handler which counts the number of breaks.
5480static void SendContinueCommand();
5481static void MessageHandlerBreakPointHitCount(
5482 const v8::Debug::Message& message) {
5483 if (message.IsEvent() && message.GetEvent() == v8::Break) {
5484 // Count the number of breaks.
5485 break_point_hit_count++;
5486
5487 SendContinueCommand();
5488 }
5489}
5490
5491
5492// Test that clearing the debug event listener actually clears all break points
5493// and related information.
5494TEST(DebuggerUnload) {
5495 DebugLocalContext env;
5496
5497 // Check debugger is unloaded before it is used.
5498 CheckDebuggerUnloaded();
5499
5500 // Set a debug event listener.
5501 break_point_hit_count = 0;
5502 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
5503 v8::Undefined());
5504 {
5505 v8::HandleScope scope;
5506 // Create a couple of functions for the test.
5507 v8::Local<v8::Function> foo =
5508 CompileFunction(&env, "function foo(){x=1}", "foo");
5509 v8::Local<v8::Function> bar =
5510 CompileFunction(&env, "function bar(){y=2}", "bar");
5511
5512 // Set some break points.
5513 SetBreakPoint(foo, 0);
5514 SetBreakPoint(foo, 4);
5515 SetBreakPoint(bar, 0);
5516 SetBreakPoint(bar, 4);
5517
5518 // Make sure that the break points are there.
5519 break_point_hit_count = 0;
5520 foo->Call(env->Global(), 0, NULL);
5521 CHECK_EQ(2, break_point_hit_count);
5522 bar->Call(env->Global(), 0, NULL);
5523 CHECK_EQ(4, break_point_hit_count);
5524 }
5525
5526 // Remove the debug event listener without clearing breakpoints. Do this
5527 // outside a handle scope.
5528 v8::Debug::SetDebugEventListener(NULL);
5529 CheckDebuggerUnloaded(true);
5530
5531 // Now set a debug message handler.
5532 break_point_hit_count = 0;
5533 v8::Debug::SetMessageHandler2(MessageHandlerBreakPointHitCount);
5534 {
5535 v8::HandleScope scope;
5536
5537 // Get the test functions again.
5538 v8::Local<v8::Function> foo =
5539 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
5540 v8::Local<v8::Function> bar =
5541 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("foo")));
5542
5543 foo->Call(env->Global(), 0, NULL);
5544 CHECK_EQ(0, break_point_hit_count);
5545
5546 // Set break points and run again.
5547 SetBreakPoint(foo, 0);
5548 SetBreakPoint(foo, 4);
5549 foo->Call(env->Global(), 0, NULL);
5550 CHECK_EQ(2, break_point_hit_count);
5551 }
5552
5553 // Remove the debug message handler without clearing breakpoints. Do this
5554 // outside a handle scope.
5555 v8::Debug::SetMessageHandler2(NULL);
5556 CheckDebuggerUnloaded(true);
5557}
5558
5559
5560// Sends continue command to the debugger.
5561static void SendContinueCommand() {
5562 const int kBufferSize = 1000;
5563 uint16_t buffer[kBufferSize];
5564 const char* command_continue =
5565 "{\"seq\":0,"
5566 "\"type\":\"request\","
5567 "\"command\":\"continue\"}";
5568
5569 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_continue, buffer));
5570}
5571
5572
5573// Debugger message handler which counts the number of times it is called.
5574static int message_handler_hit_count = 0;
5575static void MessageHandlerHitCount(const v8::Debug::Message& message) {
5576 message_handler_hit_count++;
5577
Steve Block3ce2e202009-11-05 08:53:23 +00005578 static char print_buffer[1000];
5579 v8::String::Value json(message.GetJSON());
5580 Utf16ToAscii(*json, json.length(), print_buffer);
5581 if (IsExceptionEventMessage(print_buffer)) {
5582 // Send a continue command for exception events.
5583 SendContinueCommand();
5584 }
Steve Blocka7e24c12009-10-30 11:49:00 +00005585}
5586
5587
5588// Test clearing the debug message handler.
5589TEST(DebuggerClearMessageHandler) {
5590 v8::HandleScope scope;
5591 DebugLocalContext env;
5592
5593 // Check debugger is unloaded before it is used.
5594 CheckDebuggerUnloaded();
5595
5596 // Set a debug message handler.
5597 v8::Debug::SetMessageHandler2(MessageHandlerHitCount);
5598
5599 // Run code to throw a unhandled exception. This should end up in the message
5600 // handler.
5601 CompileRun("throw 1");
5602
5603 // The message handler should be called.
5604 CHECK_GT(message_handler_hit_count, 0);
5605
5606 // Clear debug message handler.
5607 message_handler_hit_count = 0;
5608 v8::Debug::SetMessageHandler(NULL);
5609
5610 // Run code to throw a unhandled exception. This should end up in the message
5611 // handler.
5612 CompileRun("throw 1");
5613
5614 // The message handler should not be called more.
5615 CHECK_EQ(0, message_handler_hit_count);
5616
5617 CheckDebuggerUnloaded(true);
5618}
5619
5620
5621// Debugger message handler which clears the message handler while active.
5622static void MessageHandlerClearingMessageHandler(
5623 const v8::Debug::Message& message) {
5624 message_handler_hit_count++;
5625
5626 // Clear debug message handler.
5627 v8::Debug::SetMessageHandler(NULL);
5628}
5629
5630
5631// Test clearing the debug message handler while processing a debug event.
5632TEST(DebuggerClearMessageHandlerWhileActive) {
5633 v8::HandleScope scope;
5634 DebugLocalContext env;
5635
5636 // Check debugger is unloaded before it is used.
5637 CheckDebuggerUnloaded();
5638
5639 // Set a debug message handler.
5640 v8::Debug::SetMessageHandler2(MessageHandlerClearingMessageHandler);
5641
5642 // Run code to throw a unhandled exception. This should end up in the message
5643 // handler.
5644 CompileRun("throw 1");
5645
5646 // The message handler should be called.
5647 CHECK_EQ(1, message_handler_hit_count);
5648
5649 CheckDebuggerUnloaded(true);
5650}
5651
5652
5653/* Test DebuggerHostDispatch */
5654/* In this test, the debugger waits for a command on a breakpoint
5655 * and is dispatching host commands while in the infinite loop.
5656 */
5657
5658class HostDispatchV8Thread : public v8::internal::Thread {
5659 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005660 explicit HostDispatchV8Thread(v8::internal::Isolate* isolate)
5661 : Thread(isolate, "HostDispatchV8Thread") { }
Steve Blocka7e24c12009-10-30 11:49:00 +00005662 void Run();
5663};
5664
5665class HostDispatchDebuggerThread : public v8::internal::Thread {
5666 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005667 explicit HostDispatchDebuggerThread(v8::internal::Isolate* isolate)
5668 : Thread(isolate, "HostDispatchDebuggerThread") { }
Steve Blocka7e24c12009-10-30 11:49:00 +00005669 void Run();
5670};
5671
5672Barriers* host_dispatch_barriers;
5673
5674static void HostDispatchMessageHandler(const v8::Debug::Message& message) {
5675 static char print_buffer[1000];
5676 v8::String::Value json(message.GetJSON());
5677 Utf16ToAscii(*json, json.length(), print_buffer);
Steve Blocka7e24c12009-10-30 11:49:00 +00005678}
5679
5680
5681static void HostDispatchDispatchHandler() {
5682 host_dispatch_barriers->semaphore_1->Signal();
5683}
5684
5685
5686void HostDispatchV8Thread::Run() {
5687 const char* source_1 = "var y_global = 3;\n"
5688 "function cat( new_value ) {\n"
5689 " var x = new_value;\n"
5690 " y_global = 4;\n"
5691 " x = 3 * x + 1;\n"
5692 " y_global = 5;\n"
5693 " return x;\n"
5694 "}\n"
5695 "\n";
5696 const char* source_2 = "cat(17);\n";
5697
5698 v8::HandleScope scope;
5699 DebugLocalContext env;
5700
5701 // Setup message and host dispatch handlers.
5702 v8::Debug::SetMessageHandler2(HostDispatchMessageHandler);
5703 v8::Debug::SetHostDispatchHandler(HostDispatchDispatchHandler, 10 /* ms */);
5704
5705 CompileRun(source_1);
5706 host_dispatch_barriers->barrier_1.Wait();
5707 host_dispatch_barriers->barrier_2.Wait();
5708 CompileRun(source_2);
5709}
5710
5711
5712void HostDispatchDebuggerThread::Run() {
5713 const int kBufSize = 1000;
5714 uint16_t buffer[kBufSize];
5715
5716 const char* command_1 = "{\"seq\":101,"
5717 "\"type\":\"request\","
5718 "\"command\":\"setbreakpoint\","
5719 "\"arguments\":{\"type\":\"function\",\"target\":\"cat\",\"line\":3}}";
5720 const char* command_2 = "{\"seq\":102,"
5721 "\"type\":\"request\","
5722 "\"command\":\"continue\"}";
5723
5724 // v8 thread initializes, runs source_1
5725 host_dispatch_barriers->barrier_1.Wait();
5726 // 1: Set breakpoint in cat().
5727 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_1, buffer));
5728
5729 host_dispatch_barriers->barrier_2.Wait();
5730 // v8 thread starts compiling source_2.
5731 // Break happens, to run queued commands and host dispatches.
5732 // Wait for host dispatch to be processed.
5733 host_dispatch_barriers->semaphore_1->Wait();
5734 // 2: Continue evaluation
5735 v8::Debug::SendCommand(buffer, AsciiToUtf16(command_2, buffer));
5736}
5737
Steve Blocka7e24c12009-10-30 11:49:00 +00005738
5739TEST(DebuggerHostDispatch) {
Steve Block44f0eee2011-05-26 01:26:41 +01005740 HostDispatchDebuggerThread host_dispatch_debugger_thread(
5741 i::Isolate::Current());
5742 HostDispatchV8Thread host_dispatch_v8_thread(i::Isolate::Current());
Steve Blocka7e24c12009-10-30 11:49:00 +00005743 i::FLAG_debugger_auto_break = true;
5744
5745 // Create a V8 environment
5746 Barriers stack_allocated_host_dispatch_barriers;
5747 stack_allocated_host_dispatch_barriers.Initialize();
5748 host_dispatch_barriers = &stack_allocated_host_dispatch_barriers;
5749
5750 host_dispatch_v8_thread.Start();
5751 host_dispatch_debugger_thread.Start();
5752
5753 host_dispatch_v8_thread.Join();
5754 host_dispatch_debugger_thread.Join();
5755}
5756
5757
Steve Blockd0582a62009-12-15 09:54:21 +00005758/* Test DebugMessageDispatch */
5759/* In this test, the V8 thread waits for a message from the debug thread.
5760 * The DebugMessageDispatchHandler is executed from the debugger thread
5761 * which signals the V8 thread to wake up.
5762 */
5763
5764class DebugMessageDispatchV8Thread : public v8::internal::Thread {
5765 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005766 explicit DebugMessageDispatchV8Thread(v8::internal::Isolate* isolate)
5767 : Thread(isolate, "DebugMessageDispatchV8Thread") { }
Steve Blockd0582a62009-12-15 09:54:21 +00005768 void Run();
5769};
5770
5771class DebugMessageDispatchDebuggerThread : public v8::internal::Thread {
5772 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005773 explicit DebugMessageDispatchDebuggerThread(v8::internal::Isolate* isolate)
5774 : Thread(isolate, "DebugMessageDispatchDebuggerThread") { }
Steve Blockd0582a62009-12-15 09:54:21 +00005775 void Run();
5776};
5777
5778Barriers* debug_message_dispatch_barriers;
5779
5780
5781static void DebugMessageHandler() {
5782 debug_message_dispatch_barriers->semaphore_1->Signal();
5783}
5784
5785
5786void DebugMessageDispatchV8Thread::Run() {
5787 v8::HandleScope scope;
5788 DebugLocalContext env;
5789
5790 // Setup debug message dispatch handler.
5791 v8::Debug::SetDebugMessageDispatchHandler(DebugMessageHandler);
5792
5793 CompileRun("var y = 1 + 2;\n");
5794 debug_message_dispatch_barriers->barrier_1.Wait();
5795 debug_message_dispatch_barriers->semaphore_1->Wait();
5796 debug_message_dispatch_barriers->barrier_2.Wait();
5797}
5798
5799
5800void DebugMessageDispatchDebuggerThread::Run() {
5801 debug_message_dispatch_barriers->barrier_1.Wait();
5802 SendContinueCommand();
5803 debug_message_dispatch_barriers->barrier_2.Wait();
5804}
5805
Steve Blockd0582a62009-12-15 09:54:21 +00005806
5807TEST(DebuggerDebugMessageDispatch) {
Steve Block44f0eee2011-05-26 01:26:41 +01005808 DebugMessageDispatchDebuggerThread debug_message_dispatch_debugger_thread(
5809 i::Isolate::Current());
5810 DebugMessageDispatchV8Thread debug_message_dispatch_v8_thread(
5811 i::Isolate::Current());
5812
Steve Blockd0582a62009-12-15 09:54:21 +00005813 i::FLAG_debugger_auto_break = true;
5814
5815 // Create a V8 environment
5816 Barriers stack_allocated_debug_message_dispatch_barriers;
5817 stack_allocated_debug_message_dispatch_barriers.Initialize();
5818 debug_message_dispatch_barriers =
5819 &stack_allocated_debug_message_dispatch_barriers;
5820
5821 debug_message_dispatch_v8_thread.Start();
5822 debug_message_dispatch_debugger_thread.Start();
5823
5824 debug_message_dispatch_v8_thread.Join();
5825 debug_message_dispatch_debugger_thread.Join();
5826}
5827
5828
Steve Blocka7e24c12009-10-30 11:49:00 +00005829TEST(DebuggerAgent) {
Steve Block44f0eee2011-05-26 01:26:41 +01005830 i::Debugger* debugger = i::Isolate::Current()->debugger();
Steve Blocka7e24c12009-10-30 11:49:00 +00005831 // Make sure these ports is not used by other tests to allow tests to run in
5832 // parallel.
5833 const int kPort1 = 5858;
5834 const int kPort2 = 5857;
5835 const int kPort3 = 5856;
5836
5837 // Make a string with the port2 number.
5838 const int kPortBufferLen = 6;
5839 char port2_str[kPortBufferLen];
5840 OS::SNPrintF(i::Vector<char>(port2_str, kPortBufferLen), "%d", kPort2);
5841
5842 bool ok;
5843
5844 // Initialize the socket library.
5845 i::Socket::Setup();
5846
5847 // Test starting and stopping the agent without any client connection.
Steve Block44f0eee2011-05-26 01:26:41 +01005848 debugger->StartAgent("test", kPort1);
5849 debugger->StopAgent();
Steve Blocka7e24c12009-10-30 11:49:00 +00005850
5851 // Test starting the agent, connecting a client and shutting down the agent
5852 // with the client connected.
Steve Block44f0eee2011-05-26 01:26:41 +01005853 ok = debugger->StartAgent("test", kPort2);
Steve Blocka7e24c12009-10-30 11:49:00 +00005854 CHECK(ok);
Steve Block44f0eee2011-05-26 01:26:41 +01005855 debugger->WaitForAgent();
Steve Blocka7e24c12009-10-30 11:49:00 +00005856 i::Socket* client = i::OS::CreateSocket();
5857 ok = client->Connect("localhost", port2_str);
5858 CHECK(ok);
Steve Block44f0eee2011-05-26 01:26:41 +01005859 debugger->StopAgent();
Steve Blocka7e24c12009-10-30 11:49:00 +00005860 delete client;
5861
5862 // Test starting and stopping the agent with the required port already
5863 // occoupied.
5864 i::Socket* server = i::OS::CreateSocket();
5865 server->Bind(kPort3);
5866
Steve Block44f0eee2011-05-26 01:26:41 +01005867 debugger->StartAgent("test", kPort3);
5868 debugger->StopAgent();
Steve Blocka7e24c12009-10-30 11:49:00 +00005869
5870 delete server;
5871}
5872
5873
5874class DebuggerAgentProtocolServerThread : public i::Thread {
5875 public:
Steve Block44f0eee2011-05-26 01:26:41 +01005876 explicit DebuggerAgentProtocolServerThread(i::Isolate* isolate, int port)
5877 : Thread(isolate, "DebuggerAgentProtocolServerThread"),
5878 port_(port),
5879 server_(NULL),
5880 client_(NULL),
Steve Blocka7e24c12009-10-30 11:49:00 +00005881 listening_(OS::CreateSemaphore(0)) {
5882 }
5883 ~DebuggerAgentProtocolServerThread() {
5884 // Close both sockets.
5885 delete client_;
5886 delete server_;
5887 delete listening_;
5888 }
5889
5890 void Run();
5891 void WaitForListening() { listening_->Wait(); }
5892 char* body() { return *body_; }
5893
5894 private:
5895 int port_;
5896 i::SmartPointer<char> body_;
5897 i::Socket* server_; // Server socket used for bind/accept.
5898 i::Socket* client_; // Single client connection used by the test.
5899 i::Semaphore* listening_; // Signalled when the server is in listen mode.
5900};
5901
5902
5903void DebuggerAgentProtocolServerThread::Run() {
5904 bool ok;
5905
5906 // Create the server socket and bind it to the requested port.
5907 server_ = i::OS::CreateSocket();
5908 CHECK(server_ != NULL);
5909 ok = server_->Bind(port_);
5910 CHECK(ok);
5911
5912 // Listen for new connections.
5913 ok = server_->Listen(1);
5914 CHECK(ok);
5915 listening_->Signal();
5916
5917 // Accept a connection.
5918 client_ = server_->Accept();
5919 CHECK(client_ != NULL);
5920
5921 // Receive a debugger agent protocol message.
5922 i::DebuggerAgentUtil::ReceiveMessage(client_);
5923}
5924
5925
5926TEST(DebuggerAgentProtocolOverflowHeader) {
5927 // Make sure this port is not used by other tests to allow tests to run in
5928 // parallel.
5929 const int kPort = 5860;
5930 static const char* kLocalhost = "localhost";
5931
5932 // Make a string with the port number.
5933 const int kPortBufferLen = 6;
5934 char port_str[kPortBufferLen];
5935 OS::SNPrintF(i::Vector<char>(port_str, kPortBufferLen), "%d", kPort);
5936
5937 // Initialize the socket library.
5938 i::Socket::Setup();
5939
5940 // Create a socket server to receive a debugger agent message.
5941 DebuggerAgentProtocolServerThread* server =
Steve Block44f0eee2011-05-26 01:26:41 +01005942 new DebuggerAgentProtocolServerThread(i::Isolate::Current(), kPort);
Steve Blocka7e24c12009-10-30 11:49:00 +00005943 server->Start();
5944 server->WaitForListening();
5945
5946 // Connect.
5947 i::Socket* client = i::OS::CreateSocket();
5948 CHECK(client != NULL);
5949 bool ok = client->Connect(kLocalhost, port_str);
5950 CHECK(ok);
5951
5952 // Send headers which overflow the receive buffer.
5953 static const int kBufferSize = 1000;
5954 char buffer[kBufferSize];
5955
5956 // Long key and short value: XXXX....XXXX:0\r\n.
5957 for (int i = 0; i < kBufferSize - 4; i++) {
5958 buffer[i] = 'X';
5959 }
5960 buffer[kBufferSize - 4] = ':';
5961 buffer[kBufferSize - 3] = '0';
5962 buffer[kBufferSize - 2] = '\r';
5963 buffer[kBufferSize - 1] = '\n';
5964 client->Send(buffer, kBufferSize);
5965
5966 // Short key and long value: X:XXXX....XXXX\r\n.
5967 buffer[0] = 'X';
5968 buffer[1] = ':';
5969 for (int i = 2; i < kBufferSize - 2; i++) {
5970 buffer[i] = 'X';
5971 }
5972 buffer[kBufferSize - 2] = '\r';
5973 buffer[kBufferSize - 1] = '\n';
5974 client->Send(buffer, kBufferSize);
5975
5976 // Add empty body to request.
5977 const char* content_length_zero_header = "Content-Length:0\r\n";
Steve Blockd0582a62009-12-15 09:54:21 +00005978 client->Send(content_length_zero_header,
5979 StrLength(content_length_zero_header));
Steve Blocka7e24c12009-10-30 11:49:00 +00005980 client->Send("\r\n", 2);
5981
5982 // Wait until data is received.
5983 server->Join();
5984
5985 // Check for empty body.
5986 CHECK(server->body() == NULL);
5987
5988 // Close the client before the server to avoid TIME_WAIT issues.
5989 client->Shutdown();
5990 delete client;
5991 delete server;
5992}
5993
5994
5995// Test for issue http://code.google.com/p/v8/issues/detail?id=289.
5996// Make sure that DebugGetLoadedScripts doesn't return scripts
5997// with disposed external source.
5998class EmptyExternalStringResource : public v8::String::ExternalStringResource {
5999 public:
6000 EmptyExternalStringResource() { empty_[0] = 0; }
6001 virtual ~EmptyExternalStringResource() {}
6002 virtual size_t length() const { return empty_.length(); }
6003 virtual const uint16_t* data() const { return empty_.start(); }
6004 private:
6005 ::v8::internal::EmbeddedVector<uint16_t, 1> empty_;
6006};
6007
6008
6009TEST(DebugGetLoadedScripts) {
6010 v8::HandleScope scope;
6011 DebugLocalContext env;
6012 env.ExposeDebug();
6013
6014 EmptyExternalStringResource source_ext_str;
6015 v8::Local<v8::String> source = v8::String::NewExternal(&source_ext_str);
6016 v8::Handle<v8::Script> evil_script = v8::Script::Compile(source);
6017 Handle<i::ExternalTwoByteString> i_source(
6018 i::ExternalTwoByteString::cast(*v8::Utils::OpenHandle(*source)));
6019 // This situation can happen if source was an external string disposed
6020 // by its owner.
6021 i_source->set_resource(0);
6022
6023 bool allow_natives_syntax = i::FLAG_allow_natives_syntax;
6024 i::FLAG_allow_natives_syntax = true;
6025 CompileRun(
6026 "var scripts = %DebugGetLoadedScripts();"
6027 "var count = scripts.length;"
6028 "for (var i = 0; i < count; ++i) {"
6029 " scripts[i].line_ends;"
6030 "}");
6031 // Must not crash while accessing line_ends.
6032 i::FLAG_allow_natives_syntax = allow_natives_syntax;
6033
6034 // Some scripts are retrieved - at least the number of native scripts.
6035 CHECK_GT((*env)->Global()->Get(v8::String::New("count"))->Int32Value(), 8);
6036}
6037
6038
6039// Test script break points set on lines.
6040TEST(ScriptNameAndData) {
6041 v8::HandleScope scope;
6042 DebugLocalContext env;
6043 env.ExposeDebug();
6044
6045 // Create functions for retrieving script name and data for the function on
6046 // the top frame when hitting a break point.
6047 frame_script_name = CompileFunction(&env,
6048 frame_script_name_source,
6049 "frame_script_name");
6050 frame_script_data = CompileFunction(&env,
6051 frame_script_data_source,
6052 "frame_script_data");
Andrei Popescu402d9372010-02-26 13:31:12 +00006053 compiled_script_data = CompileFunction(&env,
6054 compiled_script_data_source,
6055 "compiled_script_data");
Steve Blocka7e24c12009-10-30 11:49:00 +00006056
6057 v8::Debug::SetDebugEventListener(DebugEventBreakPointHitCount,
6058 v8::Undefined());
6059
6060 // Test function source.
6061 v8::Local<v8::String> script = v8::String::New(
6062 "function f() {\n"
6063 " debugger;\n"
6064 "}\n");
6065
6066 v8::ScriptOrigin origin1 = v8::ScriptOrigin(v8::String::New("name"));
6067 v8::Handle<v8::Script> script1 = v8::Script::Compile(script, &origin1);
6068 script1->SetData(v8::String::New("data"));
6069 script1->Run();
6070 v8::Local<v8::Function> f;
6071 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6072
6073 f->Call(env->Global(), 0, NULL);
6074 CHECK_EQ(1, break_point_hit_count);
6075 CHECK_EQ("name", last_script_name_hit);
6076 CHECK_EQ("data", last_script_data_hit);
6077
6078 // Compile the same script again without setting data. As the compilation
6079 // cache is disabled when debugging expect the data to be missing.
6080 v8::Script::Compile(script, &origin1)->Run();
6081 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6082 f->Call(env->Global(), 0, NULL);
6083 CHECK_EQ(2, break_point_hit_count);
6084 CHECK_EQ("name", last_script_name_hit);
6085 CHECK_EQ("", last_script_data_hit); // Undefined results in empty string.
6086
6087 v8::Local<v8::String> data_obj_source = v8::String::New(
6088 "({ a: 'abc',\n"
6089 " b: 123,\n"
6090 " toString: function() { return this.a + ' ' + this.b; }\n"
6091 "})\n");
6092 v8::Local<v8::Value> data_obj = v8::Script::Compile(data_obj_source)->Run();
6093 v8::ScriptOrigin origin2 = v8::ScriptOrigin(v8::String::New("new name"));
6094 v8::Handle<v8::Script> script2 = v8::Script::Compile(script, &origin2);
6095 script2->Run();
Steve Blockd0582a62009-12-15 09:54:21 +00006096 script2->SetData(data_obj->ToString());
Steve Blocka7e24c12009-10-30 11:49:00 +00006097 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6098 f->Call(env->Global(), 0, NULL);
6099 CHECK_EQ(3, break_point_hit_count);
6100 CHECK_EQ("new name", last_script_name_hit);
6101 CHECK_EQ("abc 123", last_script_data_hit);
Andrei Popescu402d9372010-02-26 13:31:12 +00006102
6103 v8::Handle<v8::Script> script3 =
6104 v8::Script::Compile(script, &origin2, NULL,
6105 v8::String::New("in compile"));
6106 CHECK_EQ("in compile", last_script_data_hit);
6107 script3->Run();
6108 f = v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6109 f->Call(env->Global(), 0, NULL);
6110 CHECK_EQ(4, break_point_hit_count);
6111 CHECK_EQ("in compile", last_script_data_hit);
Steve Blocka7e24c12009-10-30 11:49:00 +00006112}
6113
6114
6115static v8::Persistent<v8::Context> expected_context;
6116static v8::Handle<v8::Value> expected_context_data;
6117
6118
6119// Check that the expected context is the one generating the debug event.
6120static void ContextCheckMessageHandler(const v8::Debug::Message& message) {
6121 CHECK(message.GetEventContext() == expected_context);
6122 CHECK(message.GetEventContext()->GetData()->StrictEquals(
6123 expected_context_data));
6124 message_handler_hit_count++;
6125
Steve Block3ce2e202009-11-05 08:53:23 +00006126 static char print_buffer[1000];
6127 v8::String::Value json(message.GetJSON());
6128 Utf16ToAscii(*json, json.length(), print_buffer);
6129
Steve Blocka7e24c12009-10-30 11:49:00 +00006130 // Send a continue command for break events.
Steve Block3ce2e202009-11-05 08:53:23 +00006131 if (IsBreakEventMessage(print_buffer)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006132 SendContinueCommand();
6133 }
6134}
6135
6136
6137// Test which creates two contexts and sets different embedder data on each.
6138// Checks that this data is set correctly and that when the debug message
6139// handler is called the expected context is the one active.
6140TEST(ContextData) {
6141 v8::HandleScope scope;
6142
6143 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler);
6144
6145 // Create two contexts.
6146 v8::Persistent<v8::Context> context_1;
6147 v8::Persistent<v8::Context> context_2;
6148 v8::Handle<v8::ObjectTemplate> global_template =
6149 v8::Handle<v8::ObjectTemplate>();
6150 v8::Handle<v8::Value> global_object = v8::Handle<v8::Value>();
6151 context_1 = v8::Context::New(NULL, global_template, global_object);
6152 context_2 = v8::Context::New(NULL, global_template, global_object);
6153
6154 // Default data value is undefined.
6155 CHECK(context_1->GetData()->IsUndefined());
6156 CHECK(context_2->GetData()->IsUndefined());
6157
6158 // Set and check different data values.
Steve Blockd0582a62009-12-15 09:54:21 +00006159 v8::Handle<v8::String> data_1 = v8::String::New("1");
6160 v8::Handle<v8::String> data_2 = v8::String::New("2");
Steve Blocka7e24c12009-10-30 11:49:00 +00006161 context_1->SetData(data_1);
6162 context_2->SetData(data_2);
6163 CHECK(context_1->GetData()->StrictEquals(data_1));
6164 CHECK(context_2->GetData()->StrictEquals(data_2));
6165
6166 // Simple test function which causes a break.
6167 const char* source = "function f() { debugger; }";
6168
6169 // Enter and run function in the first context.
6170 {
6171 v8::Context::Scope context_scope(context_1);
6172 expected_context = context_1;
6173 expected_context_data = data_1;
6174 v8::Local<v8::Function> f = CompileFunction(source, "f");
6175 f->Call(context_1->Global(), 0, NULL);
6176 }
6177
6178
6179 // Enter and run function in the second context.
6180 {
6181 v8::Context::Scope context_scope(context_2);
6182 expected_context = context_2;
6183 expected_context_data = data_2;
6184 v8::Local<v8::Function> f = CompileFunction(source, "f");
6185 f->Call(context_2->Global(), 0, NULL);
6186 }
6187
6188 // Two times compile event and two times break event.
6189 CHECK_GT(message_handler_hit_count, 4);
6190
6191 v8::Debug::SetMessageHandler2(NULL);
6192 CheckDebuggerUnloaded();
6193}
6194
6195
6196// Debug message handler which issues a debug break when it hits a break event.
6197static int message_handler_break_hit_count = 0;
6198static void DebugBreakMessageHandler(const v8::Debug::Message& message) {
6199 // Schedule a debug break for break events.
6200 if (message.IsEvent() && message.GetEvent() == v8::Break) {
6201 message_handler_break_hit_count++;
6202 if (message_handler_break_hit_count == 1) {
6203 v8::Debug::DebugBreak();
6204 }
6205 }
6206
6207 // Issue a continue command if this event will not cause the VM to start
6208 // running.
6209 if (!message.WillStartRunning()) {
6210 SendContinueCommand();
6211 }
6212}
6213
6214
6215// Test that a debug break can be scheduled while in a message handler.
6216TEST(DebugBreakInMessageHandler) {
6217 v8::HandleScope scope;
6218 DebugLocalContext env;
6219
6220 v8::Debug::SetMessageHandler2(DebugBreakMessageHandler);
6221
6222 // Test functions.
6223 const char* script = "function f() { debugger; g(); } function g() { }";
6224 CompileRun(script);
6225 v8::Local<v8::Function> f =
6226 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6227 v8::Local<v8::Function> g =
6228 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("g")));
6229
6230 // Call f then g. The debugger statement in f will casue a break which will
6231 // cause another break.
6232 f->Call(env->Global(), 0, NULL);
6233 CHECK_EQ(2, message_handler_break_hit_count);
6234 // Calling g will not cause any additional breaks.
6235 g->Call(env->Global(), 0, NULL);
6236 CHECK_EQ(2, message_handler_break_hit_count);
6237}
6238
6239
Steve Block6ded16b2010-05-10 14:33:55 +01006240#ifndef V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00006241// Debug event handler which gets the function on the top frame and schedules a
6242// break a number of times.
6243static void DebugEventDebugBreak(
6244 v8::DebugEvent event,
6245 v8::Handle<v8::Object> exec_state,
6246 v8::Handle<v8::Object> event_data,
6247 v8::Handle<v8::Value> data) {
6248
6249 if (event == v8::Break) {
6250 break_point_hit_count++;
6251
6252 // Get the name of the top frame function.
6253 if (!frame_function_name.IsEmpty()) {
6254 // Get the name of the function.
Ben Murdochb0fe1622011-05-05 13:52:32 +01006255 const int argc = 2;
6256 v8::Handle<v8::Value> argv[argc] = { exec_state, v8::Integer::New(0) };
Steve Blocka7e24c12009-10-30 11:49:00 +00006257 v8::Handle<v8::Value> result = frame_function_name->Call(exec_state,
6258 argc, argv);
6259 if (result->IsUndefined()) {
6260 last_function_hit[0] = '\0';
6261 } else {
6262 CHECK(result->IsString());
6263 v8::Handle<v8::String> function_name(result->ToString());
6264 function_name->WriteAscii(last_function_hit);
6265 }
6266 }
6267
6268 // Keep forcing breaks.
6269 if (break_point_hit_count < 20) {
6270 v8::Debug::DebugBreak();
6271 }
6272 }
6273}
6274
6275
6276TEST(RegExpDebugBreak) {
6277 // This test only applies to native regexps.
6278 v8::HandleScope scope;
6279 DebugLocalContext env;
6280
6281 // Create a function for checking the function when hitting a break point.
6282 frame_function_name = CompileFunction(&env,
6283 frame_function_name_source,
6284 "frame_function_name");
6285
6286 // Test RegExp which matches white spaces and comments at the begining of a
6287 // source line.
6288 const char* script =
6289 "var sourceLineBeginningSkip = /^(?:[ \\v\\h]*(?:\\/\\*.*?\\*\\/)*)*/;\n"
6290 "function f(s) { return s.match(sourceLineBeginningSkip)[0].length; }";
6291
6292 v8::Local<v8::Function> f = CompileFunction(script, "f");
6293 const int argc = 1;
6294 v8::Handle<v8::Value> argv[argc] = { v8::String::New(" /* xxx */ a=0;") };
6295 v8::Local<v8::Value> result = f->Call(env->Global(), argc, argv);
6296 CHECK_EQ(12, result->Int32Value());
6297
6298 v8::Debug::SetDebugEventListener(DebugEventDebugBreak);
6299 v8::Debug::DebugBreak();
6300 result = f->Call(env->Global(), argc, argv);
6301
6302 // Check that there was only one break event. Matching RegExp should not
6303 // cause Break events.
6304 CHECK_EQ(1, break_point_hit_count);
6305 CHECK_EQ("f", last_function_hit);
6306}
Steve Block6ded16b2010-05-10 14:33:55 +01006307#endif // V8_INTERPRETED_REGEXP
Steve Blocka7e24c12009-10-30 11:49:00 +00006308
6309
6310// Common part of EvalContextData and NestedBreakEventContextData tests.
6311static void ExecuteScriptForContextCheck() {
6312 // Create a context.
6313 v8::Persistent<v8::Context> context_1;
6314 v8::Handle<v8::ObjectTemplate> global_template =
6315 v8::Handle<v8::ObjectTemplate>();
Ben Murdoch257744e2011-11-30 15:57:28 +00006316 context_1 = v8::Context::New(NULL, global_template);
Steve Blocka7e24c12009-10-30 11:49:00 +00006317
6318 // Default data value is undefined.
6319 CHECK(context_1->GetData()->IsUndefined());
6320
6321 // Set and check a data value.
Steve Blockd0582a62009-12-15 09:54:21 +00006322 v8::Handle<v8::String> data_1 = v8::String::New("1");
Steve Blocka7e24c12009-10-30 11:49:00 +00006323 context_1->SetData(data_1);
6324 CHECK(context_1->GetData()->StrictEquals(data_1));
6325
6326 // Simple test function with eval that causes a break.
6327 const char* source = "function f() { eval('debugger;'); }";
6328
6329 // Enter and run function in the context.
6330 {
6331 v8::Context::Scope context_scope(context_1);
6332 expected_context = context_1;
6333 expected_context_data = data_1;
6334 v8::Local<v8::Function> f = CompileFunction(source, "f");
6335 f->Call(context_1->Global(), 0, NULL);
6336 }
6337}
6338
6339
6340// Test which creates a context and sets embedder data on it. Checks that this
6341// data is set correctly and that when the debug message handler is called for
6342// break event in an eval statement the expected context is the one returned by
6343// Message.GetEventContext.
6344TEST(EvalContextData) {
6345 v8::HandleScope scope;
6346 v8::Debug::SetMessageHandler2(ContextCheckMessageHandler);
6347
6348 ExecuteScriptForContextCheck();
6349
6350 // One time compile event and one time break event.
6351 CHECK_GT(message_handler_hit_count, 2);
6352 v8::Debug::SetMessageHandler2(NULL);
6353 CheckDebuggerUnloaded();
6354}
6355
6356
6357static bool sent_eval = false;
6358static int break_count = 0;
6359static int continue_command_send_count = 0;
6360// Check that the expected context is the one generating the debug event
6361// including the case of nested break event.
6362static void DebugEvalContextCheckMessageHandler(
6363 const v8::Debug::Message& message) {
6364 CHECK(message.GetEventContext() == expected_context);
6365 CHECK(message.GetEventContext()->GetData()->StrictEquals(
6366 expected_context_data));
6367 message_handler_hit_count++;
6368
Steve Block3ce2e202009-11-05 08:53:23 +00006369 static char print_buffer[1000];
6370 v8::String::Value json(message.GetJSON());
6371 Utf16ToAscii(*json, json.length(), print_buffer);
6372
6373 if (IsBreakEventMessage(print_buffer)) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006374 break_count++;
6375 if (!sent_eval) {
6376 sent_eval = true;
6377
6378 const int kBufferSize = 1000;
6379 uint16_t buffer[kBufferSize];
6380 const char* eval_command =
Ben Murdoch257744e2011-11-30 15:57:28 +00006381 "{\"seq\":0,"
6382 "\"type\":\"request\","
6383 "\"command\":\"evaluate\","
6384 "\"arguments\":{\"expression\":\"debugger;\","
6385 "\"global\":true,\"disable_break\":false}}";
Steve Blocka7e24c12009-10-30 11:49:00 +00006386
6387 // Send evaluate command.
6388 v8::Debug::SendCommand(buffer, AsciiToUtf16(eval_command, buffer));
6389 return;
6390 } else {
6391 // It's a break event caused by the evaluation request above.
6392 SendContinueCommand();
6393 continue_command_send_count++;
6394 }
Steve Block3ce2e202009-11-05 08:53:23 +00006395 } else if (IsEvaluateResponseMessage(print_buffer) &&
6396 continue_command_send_count < 2) {
Steve Blocka7e24c12009-10-30 11:49:00 +00006397 // Response to the evaluation request. We're still on the breakpoint so
6398 // send continue.
6399 SendContinueCommand();
6400 continue_command_send_count++;
6401 }
6402}
6403
6404
6405// Tests that context returned for break event is correct when the event occurs
6406// in 'evaluate' debugger request.
6407TEST(NestedBreakEventContextData) {
6408 v8::HandleScope scope;
6409 break_count = 0;
6410 message_handler_hit_count = 0;
6411 v8::Debug::SetMessageHandler2(DebugEvalContextCheckMessageHandler);
6412
6413 ExecuteScriptForContextCheck();
6414
6415 // One time compile event and two times break event.
6416 CHECK_GT(message_handler_hit_count, 3);
6417
6418 // One break from the source and another from the evaluate request.
6419 CHECK_EQ(break_count, 2);
6420 v8::Debug::SetMessageHandler2(NULL);
6421 CheckDebuggerUnloaded();
6422}
6423
6424
6425// Debug event listener which counts the script collected events.
6426int script_collected_count = 0;
6427static void DebugEventScriptCollectedEvent(v8::DebugEvent event,
6428 v8::Handle<v8::Object> exec_state,
6429 v8::Handle<v8::Object> event_data,
6430 v8::Handle<v8::Value> data) {
6431 // Count the number of breaks.
6432 if (event == v8::ScriptCollected) {
6433 script_collected_count++;
6434 }
6435}
6436
6437
6438// Test that scripts collected are reported through the debug event listener.
6439TEST(ScriptCollectedEvent) {
Steve Block44f0eee2011-05-26 01:26:41 +01006440 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +00006441 break_point_hit_count = 0;
6442 script_collected_count = 0;
6443 v8::HandleScope scope;
6444 DebugLocalContext env;
6445
6446 // Request the loaded scripts to initialize the debugger script cache.
Steve Block44f0eee2011-05-26 01:26:41 +01006447 debug->GetLoadedScripts();
Steve Blocka7e24c12009-10-30 11:49:00 +00006448
6449 // Do garbage collection to ensure that only the script in this test will be
6450 // collected afterwards.
Steve Block44f0eee2011-05-26 01:26:41 +01006451 HEAP->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00006452
6453 script_collected_count = 0;
6454 v8::Debug::SetDebugEventListener(DebugEventScriptCollectedEvent,
6455 v8::Undefined());
6456 {
6457 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run();
6458 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run();
6459 }
6460
6461 // Do garbage collection to collect the script above which is no longer
6462 // referenced.
Steve Block44f0eee2011-05-26 01:26:41 +01006463 HEAP->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00006464
6465 CHECK_EQ(2, script_collected_count);
6466
6467 v8::Debug::SetDebugEventListener(NULL);
6468 CheckDebuggerUnloaded();
6469}
6470
6471
6472// Debug event listener which counts the script collected events.
6473int script_collected_message_count = 0;
6474static void ScriptCollectedMessageHandler(const v8::Debug::Message& message) {
6475 // Count the number of scripts collected.
6476 if (message.IsEvent() && message.GetEvent() == v8::ScriptCollected) {
6477 script_collected_message_count++;
6478 v8::Handle<v8::Context> context = message.GetEventContext();
6479 CHECK(context.IsEmpty());
6480 }
6481}
6482
6483
6484// Test that GetEventContext doesn't fail and return empty handle for
6485// ScriptCollected events.
6486TEST(ScriptCollectedEventContext) {
Steve Block44f0eee2011-05-26 01:26:41 +01006487 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blocka7e24c12009-10-30 11:49:00 +00006488 script_collected_message_count = 0;
6489 v8::HandleScope scope;
6490
6491 { // Scope for the DebugLocalContext.
6492 DebugLocalContext env;
6493
6494 // Request the loaded scripts to initialize the debugger script cache.
Steve Block44f0eee2011-05-26 01:26:41 +01006495 debug->GetLoadedScripts();
Steve Blocka7e24c12009-10-30 11:49:00 +00006496
6497 // Do garbage collection to ensure that only the script in this test will be
6498 // collected afterwards.
Steve Block44f0eee2011-05-26 01:26:41 +01006499 HEAP->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00006500
6501 v8::Debug::SetMessageHandler2(ScriptCollectedMessageHandler);
6502 {
6503 v8::Script::Compile(v8::String::New("eval('a=1')"))->Run();
6504 v8::Script::Compile(v8::String::New("eval('a=2')"))->Run();
6505 }
6506 }
6507
6508 // Do garbage collection to collect the script above which is no longer
6509 // referenced.
Steve Block44f0eee2011-05-26 01:26:41 +01006510 HEAP->CollectAllGarbage(false);
Steve Blocka7e24c12009-10-30 11:49:00 +00006511
6512 CHECK_EQ(2, script_collected_message_count);
6513
6514 v8::Debug::SetMessageHandler2(NULL);
6515}
6516
6517
6518// Debug event listener which counts the after compile events.
6519int after_compile_message_count = 0;
6520static void AfterCompileMessageHandler(const v8::Debug::Message& message) {
6521 // Count the number of scripts collected.
6522 if (message.IsEvent()) {
6523 if (message.GetEvent() == v8::AfterCompile) {
6524 after_compile_message_count++;
6525 } else if (message.GetEvent() == v8::Break) {
6526 SendContinueCommand();
6527 }
6528 }
6529}
6530
6531
6532// Tests that after compile event is sent as many times as there are scripts
6533// compiled.
6534TEST(AfterCompileMessageWhenMessageHandlerIsReset) {
6535 v8::HandleScope scope;
6536 DebugLocalContext env;
6537 after_compile_message_count = 0;
6538 const char* script = "var a=1";
6539
6540 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
6541 v8::Script::Compile(v8::String::New(script))->Run();
6542 v8::Debug::SetMessageHandler2(NULL);
6543
6544 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
6545 v8::Debug::DebugBreak();
6546 v8::Script::Compile(v8::String::New(script))->Run();
6547
6548 // Setting listener to NULL should cause debugger unload.
6549 v8::Debug::SetMessageHandler2(NULL);
6550 CheckDebuggerUnloaded();
6551
6552 // Compilation cache should be disabled when debugger is active.
6553 CHECK_EQ(2, after_compile_message_count);
6554}
6555
6556
6557// Tests that break event is sent when message handler is reset.
6558TEST(BreakMessageWhenMessageHandlerIsReset) {
6559 v8::HandleScope scope;
6560 DebugLocalContext env;
6561 after_compile_message_count = 0;
6562 const char* script = "function f() {};";
6563
6564 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
6565 v8::Script::Compile(v8::String::New(script))->Run();
6566 v8::Debug::SetMessageHandler2(NULL);
6567
6568 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
6569 v8::Debug::DebugBreak();
6570 v8::Local<v8::Function> f =
6571 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6572 f->Call(env->Global(), 0, NULL);
6573
6574 // Setting message handler to NULL should cause debugger unload.
6575 v8::Debug::SetMessageHandler2(NULL);
6576 CheckDebuggerUnloaded();
6577
6578 // Compilation cache should be disabled when debugger is active.
6579 CHECK_EQ(1, after_compile_message_count);
6580}
6581
6582
6583static int exception_event_count = 0;
6584static void ExceptionMessageHandler(const v8::Debug::Message& message) {
6585 if (message.IsEvent() && message.GetEvent() == v8::Exception) {
6586 exception_event_count++;
6587 SendContinueCommand();
6588 }
6589}
6590
6591
6592// Tests that exception event is sent when message handler is reset.
6593TEST(ExceptionMessageWhenMessageHandlerIsReset) {
6594 v8::HandleScope scope;
6595 DebugLocalContext env;
Ben Murdoch086aeea2011-05-13 15:57:08 +01006596
6597 // For this test, we want to break on uncaught exceptions:
6598 ChangeBreakOnException(false, true);
6599
Steve Blocka7e24c12009-10-30 11:49:00 +00006600 exception_event_count = 0;
6601 const char* script = "function f() {throw new Error()};";
6602
6603 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
6604 v8::Script::Compile(v8::String::New(script))->Run();
6605 v8::Debug::SetMessageHandler2(NULL);
6606
6607 v8::Debug::SetMessageHandler2(ExceptionMessageHandler);
6608 v8::Local<v8::Function> f =
6609 v8::Local<v8::Function>::Cast(env->Global()->Get(v8::String::New("f")));
6610 f->Call(env->Global(), 0, NULL);
6611
6612 // Setting message handler to NULL should cause debugger unload.
6613 v8::Debug::SetMessageHandler2(NULL);
6614 CheckDebuggerUnloaded();
6615
6616 CHECK_EQ(1, exception_event_count);
6617}
6618
6619
6620// Tests after compile event is sent when there are some provisional
6621// breakpoints out of the scripts lines range.
6622TEST(ProvisionalBreakpointOnLineOutOfRange) {
6623 v8::HandleScope scope;
6624 DebugLocalContext env;
6625 env.ExposeDebug();
6626 const char* script = "function f() {};";
6627 const char* resource_name = "test_resource";
6628
6629 // Set a couple of provisional breakpoint on lines out of the script lines
6630 // range.
6631 int sbp1 = SetScriptBreakPointByNameFromJS(resource_name, 3,
6632 -1 /* no column */);
6633 int sbp2 = SetScriptBreakPointByNameFromJS(resource_name, 5, 5);
6634
6635 after_compile_message_count = 0;
6636 v8::Debug::SetMessageHandler2(AfterCompileMessageHandler);
6637
6638 v8::ScriptOrigin origin(
6639 v8::String::New(resource_name),
6640 v8::Integer::New(10),
6641 v8::Integer::New(1));
6642 // Compile a script whose first line number is greater than the breakpoints'
6643 // lines.
6644 v8::Script::Compile(v8::String::New(script), &origin)->Run();
6645
6646 // If the script is compiled successfully there is exactly one after compile
6647 // event. In case of an exception in debugger code after compile event is not
6648 // sent.
6649 CHECK_EQ(1, after_compile_message_count);
6650
6651 ClearBreakPointFromJS(sbp1);
6652 ClearBreakPointFromJS(sbp2);
6653 v8::Debug::SetMessageHandler2(NULL);
6654}
6655
6656
6657static void BreakMessageHandler(const v8::Debug::Message& message) {
Steve Block44f0eee2011-05-26 01:26:41 +01006658 i::Isolate* isolate = i::Isolate::Current();
Steve Blocka7e24c12009-10-30 11:49:00 +00006659 if (message.IsEvent() && message.GetEvent() == v8::Break) {
6660 // Count the number of breaks.
6661 break_point_hit_count++;
6662
6663 v8::HandleScope scope;
6664 v8::Handle<v8::String> json = message.GetJSON();
6665
6666 SendContinueCommand();
6667 } else if (message.IsEvent() && message.GetEvent() == v8::AfterCompile) {
6668 v8::HandleScope scope;
6669
Steve Block44f0eee2011-05-26 01:26:41 +01006670 bool is_debug_break = isolate->stack_guard()->IsDebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00006671 // Force DebugBreak flag while serializer is working.
Steve Block44f0eee2011-05-26 01:26:41 +01006672 isolate->stack_guard()->DebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00006673
6674 // Force serialization to trigger some internal JS execution.
6675 v8::Handle<v8::String> json = message.GetJSON();
6676
6677 // Restore previous state.
6678 if (is_debug_break) {
Steve Block44f0eee2011-05-26 01:26:41 +01006679 isolate->stack_guard()->DebugBreak();
Steve Blocka7e24c12009-10-30 11:49:00 +00006680 } else {
Steve Block44f0eee2011-05-26 01:26:41 +01006681 isolate->stack_guard()->Continue(i::DEBUGBREAK);
Steve Blocka7e24c12009-10-30 11:49:00 +00006682 }
6683 }
6684}
6685
6686
6687// Test that if DebugBreak is forced it is ignored when code from
6688// debug-delay.js is executed.
6689TEST(NoDebugBreakInAfterCompileMessageHandler) {
6690 v8::HandleScope scope;
6691 DebugLocalContext env;
6692
6693 // Register a debug event listener which sets the break flag and counts.
6694 v8::Debug::SetMessageHandler2(BreakMessageHandler);
6695
6696 // Set the debug break flag.
6697 v8::Debug::DebugBreak();
6698
6699 // Create a function for testing stepping.
6700 const char* src = "function f() { eval('var x = 10;'); } ";
6701 v8::Local<v8::Function> f = CompileFunction(&env, src, "f");
6702
6703 // There should be only one break event.
6704 CHECK_EQ(1, break_point_hit_count);
6705
6706 // Set the debug break flag again.
6707 v8::Debug::DebugBreak();
6708 f->Call(env->Global(), 0, NULL);
6709 // There should be one more break event when the script is evaluated in 'f'.
6710 CHECK_EQ(2, break_point_hit_count);
6711
6712 // Get rid of the debug message handler.
6713 v8::Debug::SetMessageHandler2(NULL);
6714 CheckDebuggerUnloaded();
6715}
6716
6717
Leon Clarkee46be812010-01-19 14:06:41 +00006718static int counting_message_handler_counter;
6719
6720static void CountingMessageHandler(const v8::Debug::Message& message) {
6721 counting_message_handler_counter++;
6722}
6723
6724// Test that debug messages get processed when ProcessDebugMessages is called.
6725TEST(ProcessDebugMessages) {
6726 v8::HandleScope scope;
6727 DebugLocalContext env;
6728
6729 counting_message_handler_counter = 0;
6730
6731 v8::Debug::SetMessageHandler2(CountingMessageHandler);
6732
6733 const int kBufferSize = 1000;
6734 uint16_t buffer[kBufferSize];
6735 const char* scripts_command =
6736 "{\"seq\":0,"
6737 "\"type\":\"request\","
6738 "\"command\":\"scripts\"}";
6739
6740 // Send scripts command.
6741 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
6742
6743 CHECK_EQ(0, counting_message_handler_counter);
6744 v8::Debug::ProcessDebugMessages();
6745 // At least one message should come
6746 CHECK_GE(counting_message_handler_counter, 1);
6747
6748 counting_message_handler_counter = 0;
6749
6750 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
6751 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
6752 CHECK_EQ(0, counting_message_handler_counter);
6753 v8::Debug::ProcessDebugMessages();
6754 // At least two messages should come
6755 CHECK_GE(counting_message_handler_counter, 2);
6756
6757 // Get rid of the debug message handler.
6758 v8::Debug::SetMessageHandler2(NULL);
6759 CheckDebuggerUnloaded();
6760}
6761
6762
Steve Block6ded16b2010-05-10 14:33:55 +01006763struct BacktraceData {
Leon Clarked91b9f72010-01-27 17:25:45 +00006764 static int frame_counter;
6765 static void MessageHandler(const v8::Debug::Message& message) {
6766 char print_buffer[1000];
6767 v8::String::Value json(message.GetJSON());
6768 Utf16ToAscii(*json, json.length(), print_buffer, 1000);
6769
6770 if (strstr(print_buffer, "backtrace") == NULL) {
6771 return;
6772 }
6773 frame_counter = GetTotalFramesInt(print_buffer);
6774 }
6775};
6776
Steve Block6ded16b2010-05-10 14:33:55 +01006777int BacktraceData::frame_counter;
Leon Clarked91b9f72010-01-27 17:25:45 +00006778
6779
6780// Test that debug messages get processed when ProcessDebugMessages is called.
6781TEST(Backtrace) {
6782 v8::HandleScope scope;
6783 DebugLocalContext env;
6784
Steve Block6ded16b2010-05-10 14:33:55 +01006785 v8::Debug::SetMessageHandler2(BacktraceData::MessageHandler);
Leon Clarked91b9f72010-01-27 17:25:45 +00006786
6787 const int kBufferSize = 1000;
6788 uint16_t buffer[kBufferSize];
6789 const char* scripts_command =
6790 "{\"seq\":0,"
6791 "\"type\":\"request\","
6792 "\"command\":\"backtrace\"}";
6793
6794 // Check backtrace from ProcessDebugMessages.
Steve Block6ded16b2010-05-10 14:33:55 +01006795 BacktraceData::frame_counter = -10;
Leon Clarked91b9f72010-01-27 17:25:45 +00006796 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
6797 v8::Debug::ProcessDebugMessages();
Steve Block6ded16b2010-05-10 14:33:55 +01006798 CHECK_EQ(BacktraceData::frame_counter, 0);
Leon Clarked91b9f72010-01-27 17:25:45 +00006799
6800 v8::Handle<v8::String> void0 = v8::String::New("void(0)");
6801 v8::Handle<v8::Script> script = v8::Script::Compile(void0, void0);
6802
6803 // Check backtrace from "void(0)" script.
Steve Block6ded16b2010-05-10 14:33:55 +01006804 BacktraceData::frame_counter = -10;
Leon Clarked91b9f72010-01-27 17:25:45 +00006805 v8::Debug::SendCommand(buffer, AsciiToUtf16(scripts_command, buffer));
6806 script->Run();
Steve Block6ded16b2010-05-10 14:33:55 +01006807 CHECK_EQ(BacktraceData::frame_counter, 1);
Leon Clarked91b9f72010-01-27 17:25:45 +00006808
6809 // Get rid of the debug message handler.
6810 v8::Debug::SetMessageHandler2(NULL);
6811 CheckDebuggerUnloaded();
6812}
6813
6814
Steve Blocka7e24c12009-10-30 11:49:00 +00006815TEST(GetMirror) {
6816 v8::HandleScope scope;
6817 DebugLocalContext env;
6818 v8::Handle<v8::Value> obj = v8::Debug::GetMirror(v8::String::New("hodja"));
6819 v8::Handle<v8::Function> run_test = v8::Handle<v8::Function>::Cast(
6820 v8::Script::New(
6821 v8::String::New(
6822 "function runTest(mirror) {"
6823 " return mirror.isString() && (mirror.length() == 5);"
6824 "}"
6825 ""
6826 "runTest;"))->Run());
6827 v8::Handle<v8::Value> result = run_test->Call(env->Global(), 1, &obj);
6828 CHECK(result->IsTrue());
6829}
Steve Blockd0582a62009-12-15 09:54:21 +00006830
6831
6832// Test that the debug break flag works with function.apply.
6833TEST(DebugBreakFunctionApply) {
6834 v8::HandleScope scope;
6835 DebugLocalContext env;
6836
6837 // Create a function for testing breaking in apply.
6838 v8::Local<v8::Function> foo = CompileFunction(
6839 &env,
6840 "function baz(x) { }"
6841 "function bar(x) { baz(); }"
6842 "function foo(){ bar.apply(this, [1]); }",
6843 "foo");
6844
6845 // Register a debug event listener which steps and counts.
6846 v8::Debug::SetDebugEventListener(DebugEventBreakMax);
6847
6848 // Set the debug break flag before calling the code using function.apply.
6849 v8::Debug::DebugBreak();
6850
6851 // Limit the number of debug breaks. This is a regression test for issue 493
6852 // where this test would enter an infinite loop.
6853 break_point_hit_count = 0;
6854 max_break_point_hit_count = 10000; // 10000 => infinite loop.
6855 foo->Call(env->Global(), 0, NULL);
6856
6857 // When keeping the debug break several break will happen.
6858 CHECK_EQ(3, break_point_hit_count);
6859
6860 v8::Debug::SetDebugEventListener(NULL);
6861 CheckDebuggerUnloaded();
6862}
6863
6864
6865v8::Handle<v8::Context> debugee_context;
6866v8::Handle<v8::Context> debugger_context;
6867
6868
6869// Property getter that checks that current and calling contexts
6870// are both the debugee contexts.
6871static v8::Handle<v8::Value> NamedGetterWithCallingContextCheck(
6872 v8::Local<v8::String> name,
6873 const v8::AccessorInfo& info) {
6874 CHECK_EQ(0, strcmp(*v8::String::AsciiValue(name), "a"));
6875 v8::Handle<v8::Context> current = v8::Context::GetCurrent();
6876 CHECK(current == debugee_context);
6877 CHECK(current != debugger_context);
6878 v8::Handle<v8::Context> calling = v8::Context::GetCalling();
6879 CHECK(calling == debugee_context);
6880 CHECK(calling != debugger_context);
6881 return v8::Int32::New(1);
6882}
6883
6884
6885// Debug event listener that checks if the first argument of a function is
6886// an object with property 'a' == 1. If the property has custom accessor
6887// this handler will eventually invoke it.
6888static void DebugEventGetAtgumentPropertyValue(
6889 v8::DebugEvent event,
6890 v8::Handle<v8::Object> exec_state,
6891 v8::Handle<v8::Object> event_data,
6892 v8::Handle<v8::Value> data) {
6893 if (event == v8::Break) {
6894 break_point_hit_count++;
6895 CHECK(debugger_context == v8::Context::GetCurrent());
6896 v8::Handle<v8::Function> func(v8::Function::Cast(*CompileRun(
6897 "(function(exec_state) {\n"
6898 " return (exec_state.frame(0).argumentValue(0).property('a').\n"
6899 " value().value() == 1);\n"
6900 "})")));
6901 const int argc = 1;
6902 v8::Handle<v8::Value> argv[argc] = { exec_state };
6903 v8::Handle<v8::Value> result = func->Call(exec_state, argc, argv);
6904 CHECK(result->IsTrue());
6905 }
6906}
6907
6908
6909TEST(CallingContextIsNotDebugContext) {
Steve Block44f0eee2011-05-26 01:26:41 +01006910 v8::internal::Debug* debug = v8::internal::Isolate::Current()->debug();
Steve Blockd0582a62009-12-15 09:54:21 +00006911 // Create and enter a debugee context.
6912 v8::HandleScope scope;
6913 DebugLocalContext env;
6914 env.ExposeDebug();
6915
6916 // Save handles to the debugger and debugee contexts to be used in
6917 // NamedGetterWithCallingContextCheck.
6918 debugee_context = v8::Local<v8::Context>(*env);
Steve Block44f0eee2011-05-26 01:26:41 +01006919 debugger_context = v8::Utils::ToLocal(debug->debug_context());
Steve Blockd0582a62009-12-15 09:54:21 +00006920
6921 // Create object with 'a' property accessor.
6922 v8::Handle<v8::ObjectTemplate> named = v8::ObjectTemplate::New();
6923 named->SetAccessor(v8::String::New("a"),
6924 NamedGetterWithCallingContextCheck);
6925 env->Global()->Set(v8::String::New("obj"),
6926 named->NewInstance());
6927
6928 // Register the debug event listener
6929 v8::Debug::SetDebugEventListener(DebugEventGetAtgumentPropertyValue);
6930
6931 // Create a function that invokes debugger.
6932 v8::Local<v8::Function> foo = CompileFunction(
6933 &env,
6934 "function bar(x) { debugger; }"
6935 "function foo(){ bar(obj); }",
6936 "foo");
6937
6938 break_point_hit_count = 0;
6939 foo->Call(env->Global(), 0, NULL);
6940 CHECK_EQ(1, break_point_hit_count);
6941
6942 v8::Debug::SetDebugEventListener(NULL);
6943 debugee_context = v8::Handle<v8::Context>();
6944 debugger_context = v8::Handle<v8::Context>();
6945 CheckDebuggerUnloaded();
6946}
Steve Block6ded16b2010-05-10 14:33:55 +01006947
6948
6949TEST(DebugContextIsPreservedBetweenAccesses) {
6950 v8::HandleScope scope;
6951 v8::Local<v8::Context> context1 = v8::Debug::GetDebugContext();
6952 v8::Local<v8::Context> context2 = v8::Debug::GetDebugContext();
6953 CHECK_EQ(*context1, *context2);
Leon Clarkef7060e22010-06-03 12:02:55 +01006954}
6955
6956
6957static v8::Handle<v8::Value> expected_callback_data;
6958static void DebugEventContextChecker(const v8::Debug::EventDetails& details) {
6959 CHECK(details.GetEventContext() == expected_context);
6960 CHECK_EQ(expected_callback_data, details.GetCallbackData());
6961}
6962
6963// Check that event details contain context where debug event occured.
6964TEST(DebugEventContext) {
6965 v8::HandleScope scope;
6966 expected_callback_data = v8::Int32::New(2010);
6967 v8::Debug::SetDebugEventListener2(DebugEventContextChecker,
6968 expected_callback_data);
6969 expected_context = v8::Context::New();
6970 v8::Context::Scope context_scope(expected_context);
6971 v8::Script::Compile(v8::String::New("(function(){debugger;})();"))->Run();
6972 expected_context.Dispose();
6973 expected_context.Clear();
6974 v8::Debug::SetDebugEventListener(NULL);
6975 expected_context_data = v8::Handle<v8::Value>();
Steve Block6ded16b2010-05-10 14:33:55 +01006976 CheckDebuggerUnloaded();
6977}
Leon Clarkef7060e22010-06-03 12:02:55 +01006978
Ben Murdoch3bec4d22010-07-22 14:51:16 +01006979
6980static void* expected_break_data;
6981static bool was_debug_break_called;
6982static bool was_debug_event_called;
6983static void DebugEventBreakDataChecker(const v8::Debug::EventDetails& details) {
6984 if (details.GetEvent() == v8::BreakForCommand) {
6985 CHECK_EQ(expected_break_data, details.GetClientData());
6986 was_debug_event_called = true;
6987 } else if (details.GetEvent() == v8::Break) {
6988 was_debug_break_called = true;
6989 }
6990}
6991
Ben Murdochb0fe1622011-05-05 13:52:32 +01006992
Ben Murdoch3bec4d22010-07-22 14:51:16 +01006993// Check that event details contain context where debug event occured.
6994TEST(DebugEventBreakData) {
6995 v8::HandleScope scope;
6996 DebugLocalContext env;
6997 v8::Debug::SetDebugEventListener2(DebugEventBreakDataChecker);
6998
6999 TestClientData::constructor_call_counter = 0;
7000 TestClientData::destructor_call_counter = 0;
7001
7002 expected_break_data = NULL;
7003 was_debug_event_called = false;
7004 was_debug_break_called = false;
7005 v8::Debug::DebugBreakForCommand();
7006 v8::Script::Compile(v8::String::New("(function(x){return x;})(1);"))->Run();
7007 CHECK(was_debug_event_called);
7008 CHECK(!was_debug_break_called);
7009
7010 TestClientData* data1 = new TestClientData();
7011 expected_break_data = data1;
7012 was_debug_event_called = false;
7013 was_debug_break_called = false;
7014 v8::Debug::DebugBreakForCommand(data1);
7015 v8::Script::Compile(v8::String::New("(function(x){return x+1;})(1);"))->Run();
7016 CHECK(was_debug_event_called);
7017 CHECK(!was_debug_break_called);
7018
7019 expected_break_data = NULL;
7020 was_debug_event_called = false;
7021 was_debug_break_called = false;
7022 v8::Debug::DebugBreak();
7023 v8::Script::Compile(v8::String::New("(function(x){return x+2;})(1);"))->Run();
7024 CHECK(!was_debug_event_called);
7025 CHECK(was_debug_break_called);
7026
7027 TestClientData* data2 = new TestClientData();
7028 expected_break_data = data2;
7029 was_debug_event_called = false;
7030 was_debug_break_called = false;
7031 v8::Debug::DebugBreak();
7032 v8::Debug::DebugBreakForCommand(data2);
7033 v8::Script::Compile(v8::String::New("(function(x){return x+3;})(1);"))->Run();
7034 CHECK(was_debug_event_called);
7035 CHECK(was_debug_break_called);
7036
7037 CHECK_EQ(2, TestClientData::constructor_call_counter);
7038 CHECK_EQ(TestClientData::constructor_call_counter,
7039 TestClientData::destructor_call_counter);
7040
7041 v8::Debug::SetDebugEventListener(NULL);
7042 CheckDebuggerUnloaded();
7043}
7044
Ben Murdochb0fe1622011-05-05 13:52:32 +01007045static bool debug_event_break_deoptimize_done = false;
7046
7047static void DebugEventBreakDeoptimize(v8::DebugEvent event,
7048 v8::Handle<v8::Object> exec_state,
7049 v8::Handle<v8::Object> event_data,
7050 v8::Handle<v8::Value> data) {
7051 if (event == v8::Break) {
7052 if (!frame_function_name.IsEmpty()) {
7053 // Get the name of the function.
7054 const int argc = 2;
7055 v8::Handle<v8::Value> argv[argc] = { exec_state, v8::Integer::New(0) };
7056 v8::Handle<v8::Value> result =
7057 frame_function_name->Call(exec_state, argc, argv);
7058 if (!result->IsUndefined()) {
7059 char fn[80];
7060 CHECK(result->IsString());
7061 v8::Handle<v8::String> function_name(result->ToString());
7062 function_name->WriteAscii(fn);
7063 if (strcmp(fn, "bar") == 0) {
7064 i::Deoptimizer::DeoptimizeAll();
7065 debug_event_break_deoptimize_done = true;
7066 }
7067 }
7068 }
7069
7070 v8::Debug::DebugBreak();
7071 }
7072}
7073
7074
7075// Test deoptimization when execution is broken using the debug break stack
7076// check interrupt.
7077TEST(DeoptimizeDuringDebugBreak) {
7078 v8::HandleScope scope;
7079 DebugLocalContext env;
7080 env.ExposeDebug();
7081
7082 // Create a function for checking the function when hitting a break point.
7083 frame_function_name = CompileFunction(&env,
7084 frame_function_name_source,
7085 "frame_function_name");
7086
7087
7088 // Set a debug event listener which will keep interrupting execution until
7089 // debug break. When inside function bar it will deoptimize all functions.
7090 // This tests lazy deoptimization bailout for the stack check, as the first
7091 // time in function bar when using debug break and no break points will be at
7092 // the initial stack check.
7093 v8::Debug::SetDebugEventListener(DebugEventBreakDeoptimize,
7094 v8::Undefined());
7095
7096 // Compile and run function bar which will optimize it for some flag settings.
7097 v8::Script::Compile(v8::String::New("function bar(){}; bar()"))->Run();
7098
7099 // Set debug break and call bar again.
7100 v8::Debug::DebugBreak();
7101 v8::Script::Compile(v8::String::New("bar()"))->Run();
7102
7103 CHECK(debug_event_break_deoptimize_done);
7104
7105 v8::Debug::SetDebugEventListener(NULL);
7106}
7107
7108
7109static void DebugEventBreakWithOptimizedStack(v8::DebugEvent event,
7110 v8::Handle<v8::Object> exec_state,
7111 v8::Handle<v8::Object> event_data,
7112 v8::Handle<v8::Value> data) {
7113 if (event == v8::Break) {
7114 if (!frame_function_name.IsEmpty()) {
7115 for (int i = 0; i < 2; i++) {
7116 const int argc = 2;
7117 v8::Handle<v8::Value> argv[argc] = { exec_state, v8::Integer::New(i) };
7118 // Get the name of the function in frame i.
7119 v8::Handle<v8::Value> result =
7120 frame_function_name->Call(exec_state, argc, argv);
7121 CHECK(result->IsString());
7122 v8::Handle<v8::String> function_name(result->ToString());
7123 CHECK(function_name->Equals(v8::String::New("loop")));
7124 // Get the name of the first argument in frame i.
7125 result = frame_argument_name->Call(exec_state, argc, argv);
7126 CHECK(result->IsString());
7127 v8::Handle<v8::String> argument_name(result->ToString());
7128 CHECK(argument_name->Equals(v8::String::New("count")));
7129 // Get the value of the first argument in frame i. If the
7130 // funtion is optimized the value will be undefined, otherwise
7131 // the value will be '1 - i'.
7132 //
7133 // TODO(3141533): We should be able to get the real value for
7134 // optimized frames.
7135 result = frame_argument_value->Call(exec_state, argc, argv);
7136 CHECK(result->IsUndefined() || (result->Int32Value() == 1 - i));
7137 // Get the name of the first local variable.
7138 result = frame_local_name->Call(exec_state, argc, argv);
7139 CHECK(result->IsString());
7140 v8::Handle<v8::String> local_name(result->ToString());
7141 CHECK(local_name->Equals(v8::String::New("local")));
7142 // Get the value of the first local variable. If the function
7143 // is optimized the value will be undefined, otherwise it will
7144 // be 42.
7145 //
7146 // TODO(3141533): We should be able to get the real value for
7147 // optimized frames.
7148 result = frame_local_value->Call(exec_state, argc, argv);
7149 CHECK(result->IsUndefined() || (result->Int32Value() == 42));
7150 }
7151 }
7152 }
7153}
7154
7155
7156static v8::Handle<v8::Value> ScheduleBreak(const v8::Arguments& args) {
7157 v8::Debug::SetDebugEventListener(DebugEventBreakWithOptimizedStack,
7158 v8::Undefined());
7159 v8::Debug::DebugBreak();
7160 return v8::Undefined();
7161}
7162
7163
7164TEST(DebugBreakStackInspection) {
7165 v8::HandleScope scope;
7166 DebugLocalContext env;
7167
7168 frame_function_name =
7169 CompileFunction(&env, frame_function_name_source, "frame_function_name");
7170 frame_argument_name =
7171 CompileFunction(&env, frame_argument_name_source, "frame_argument_name");
7172 frame_argument_value = CompileFunction(&env,
7173 frame_argument_value_source,
7174 "frame_argument_value");
7175 frame_local_name =
7176 CompileFunction(&env, frame_local_name_source, "frame_local_name");
7177 frame_local_value =
7178 CompileFunction(&env, frame_local_value_source, "frame_local_value");
7179
7180 v8::Handle<v8::FunctionTemplate> schedule_break_template =
7181 v8::FunctionTemplate::New(ScheduleBreak);
7182 v8::Handle<v8::Function> schedule_break =
7183 schedule_break_template->GetFunction();
7184 env->Global()->Set(v8_str("scheduleBreak"), schedule_break);
7185
7186 const char* src =
7187 "function loop(count) {"
7188 " var local = 42;"
7189 " if (count < 1) { scheduleBreak(); loop(count + 1); }"
7190 "}"
7191 "loop(0);";
7192 v8::Script::Compile(v8::String::New(src))->Run();
7193}
7194
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08007195
7196// Test that setting the terminate execution flag during debug break processing.
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08007197static void TestDebugBreakInLoop(const char* loop_head,
7198 const char** loop_bodies,
7199 const char* loop_tail) {
7200 // Receive 100 breaks for each test and then terminate JavaScript execution.
7201 static int count = 0;
7202
7203 for (int i = 0; loop_bodies[i] != NULL; i++) {
7204 count++;
7205 max_break_point_hit_count = count * 100;
7206 terminate_after_max_break_point_hit = true;
7207
7208 EmbeddedVector<char, 1024> buffer;
7209 OS::SNPrintF(buffer,
7210 "function f() {%s%s%s}",
7211 loop_head, loop_bodies[i], loop_tail);
7212
7213 // Function with infinite loop.
7214 CompileRun(buffer.start());
7215
7216 // Set the debug break to enter the debugger as soon as possible.
7217 v8::Debug::DebugBreak();
7218
7219 // Call function with infinite loop.
7220 CompileRun("f();");
7221 CHECK_EQ(count * 100, break_point_hit_count);
7222
7223 CHECK(!v8::V8::IsExecutionTerminating());
7224 }
7225}
7226
7227
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08007228TEST(DebugBreakLoop) {
7229 v8::HandleScope scope;
7230 DebugLocalContext env;
7231
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08007232 // Register a debug event listener which sets the break flag and counts.
7233 v8::Debug::SetDebugEventListener(DebugEventBreakMax);
7234
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08007235 CompileRun("var a = 1;");
7236 CompileRun("function g() { }");
7237 CompileRun("function h() { }");
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08007238
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08007239 const char* loop_bodies[] = {
7240 "",
7241 "g()",
7242 "if (a == 0) { g() }",
7243 "if (a == 1) { g() }",
7244 "if (a == 0) { g() } else { h() }",
7245 "if (a == 0) { continue }",
7246 "if (a == 1) { continue }",
7247 "switch (a) { case 1: g(); }",
7248 "switch (a) { case 1: continue; }",
7249 "switch (a) { case 1: g(); break; default: h() }",
7250 "switch (a) { case 1: continue; break; default: h() }",
7251 NULL
7252 };
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08007253
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08007254 TestDebugBreakInLoop("while (true) {", loop_bodies, "}");
7255 TestDebugBreakInLoop("while (a == 1) {", loop_bodies, "}");
7256
7257 TestDebugBreakInLoop("do {", loop_bodies, "} while (true)");
7258 TestDebugBreakInLoop("do {", loop_bodies, "} while (a == 1)");
7259
7260 TestDebugBreakInLoop("for (;;) {", loop_bodies, "}");
7261 TestDebugBreakInLoop("for (;a == 1;) {", loop_bodies, "}");
Teng-Hui Zhu3e5fa292010-11-09 16:16:48 -08007262
7263 // Get rid of the debug event listener.
7264 v8::Debug::SetDebugEventListener(NULL);
7265 CheckDebuggerUnloaded();
7266}
7267
7268
Kristian Monsen9dcf7e22010-06-28 14:14:28 +01007269#endif // ENABLE_DEBUGGER_SUPPORT