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