blob: 8cb95efd061a89bd1409f4339e0f4bb6b205eb91 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "code-stubs.h"
ager@chromium.org5c838252010-02-19 08:53:10 +000034#include "codegen.h"
kasperl@chromium.org71affb52009-05-26 05:44:31 +000035#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036#include "compiler.h"
37#include "debug.h"
38#include "execution.h"
39#include "global-handles.h"
ager@chromium.org65dad4b2009-04-23 08:48:43 +000040#include "ic.h"
41#include "ic-inl.h"
ager@chromium.orgce5e87b2010-03-10 10:24:18 +000042#include "messages.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043#include "natives.h"
44#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000045#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046
ager@chromium.org5ec48922009-05-05 07:25:34 +000047#include "../include/v8-debug.h"
48
kasperl@chromium.org71affb52009-05-26 05:44:31 +000049namespace v8 {
50namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051
ager@chromium.org65dad4b2009-04-23 08:48:43 +000052#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000053static void PrintLn(v8::Local<v8::Value> value) {
54 v8::Local<v8::String> s = value->ToString();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000055 ScopedVector<char> data(s->Length() + 1);
56 if (data.start() == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057 V8::FatalProcessOutOfMemory("PrintLn");
58 return;
59 }
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000060 s->WriteAscii(data.start());
61 PrintF("%s\n", data.start());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000062}
63
64
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065static Handle<Code> ComputeCallDebugBreak(int argc) {
66 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
67}
68
69
70static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
71 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
72}
73
74
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000075static v8::Handle<v8::Context> GetDebugEventContext() {
76 Handle<Context> context = Debug::debugger_entry()->GetContext();
77 // Top::context() may have been NULL when "script collected" event occured.
78 if (*context == NULL) {
79 return v8::Local<v8::Context>();
80 }
81 Handle<Context> global_context(context->global_context());
82 return v8::Utils::ToLocal(global_context);
83}
84
85
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000086BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
87 BreakLocatorType type) {
88 debug_info_ = debug_info;
89 type_ = type;
90 reloc_iterator_ = NULL;
91 reloc_iterator_original_ = NULL;
92 Reset(); // Initialize the rest of the member variables.
93}
94
95
96BreakLocationIterator::~BreakLocationIterator() {
97 ASSERT(reloc_iterator_ != NULL);
98 ASSERT(reloc_iterator_original_ != NULL);
99 delete reloc_iterator_;
100 delete reloc_iterator_original_;
101}
102
103
104void BreakLocationIterator::Next() {
105 AssertNoAllocation nogc;
106 ASSERT(!RinfoDone());
107
108 // Iterate through reloc info for code and original code stopping at each
109 // breakable code target.
110 bool first = break_point_ == -1;
111 while (!RinfoDone()) {
112 if (!first) RinfoNext();
113 first = false;
114 if (RinfoDone()) return;
115
ager@chromium.org236ad962008-09-25 09:45:57 +0000116 // Whenever a statement position or (plain) position is passed update the
117 // current value of these.
118 if (RelocInfo::IsPosition(rmode())) {
119 if (RelocInfo::IsStatementPosition(rmode())) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000120 statement_position_ = static_cast<int>(
121 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000122 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000123 // Always update the position as we don't want that to be before the
124 // statement position.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000125 position_ = static_cast<int>(
126 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000127 ASSERT(position_ >= 0);
128 ASSERT(statement_position_ >= 0);
129 }
130
131 // Check for breakable code target. Look in the original code as setting
132 // break points can cause the code targets in the running (debugged) code to
133 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000134 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000135 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000136 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000137 if ((code->is_inline_cache_stub() &&
138 code->kind() != Code::BINARY_OP_IC) ||
139 RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000140 break_point_++;
141 return;
142 }
143 if (code->kind() == Code::STUB) {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000144 if (IsDebuggerStatement()) {
145 break_point_++;
146 return;
147 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000148 if (type_ == ALL_BREAK_LOCATIONS) {
149 if (Debug::IsBreakStub(code)) {
150 break_point_++;
151 return;
152 }
153 } else {
154 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
155 if (Debug::IsSourceBreakStub(code)) {
156 break_point_++;
157 return;
158 }
159 }
160 }
161 }
162
163 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000164 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000165 // Set the positions to the end of the function.
166 if (debug_info_->shared()->HasSourceCode()) {
167 position_ = debug_info_->shared()->end_position() -
168 debug_info_->shared()->start_position();
169 } else {
170 position_ = 0;
171 }
172 statement_position_ = position_;
173 break_point_++;
174 return;
175 }
176 }
177}
178
179
180void BreakLocationIterator::Next(int count) {
181 while (count > 0) {
182 Next();
183 count--;
184 }
185}
186
187
188// Find the break point closest to the supplied address.
189void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
190 // Run through all break points to locate the one closest to the address.
191 int closest_break_point = 0;
192 int distance = kMaxInt;
193 while (!Done()) {
194 // Check if this break point is closer that what was previously found.
195 if (this->pc() < pc && pc - this->pc() < distance) {
196 closest_break_point = break_point();
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000197 distance = static_cast<int>(pc - this->pc());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000198 // Check whether we can't get any closer.
199 if (distance == 0) break;
200 }
201 Next();
202 }
203
204 // Move to the break point found.
205 Reset();
206 Next(closest_break_point);
207}
208
209
210// Find the break point closest to the supplied source position.
211void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
212 // Run through all break points to locate the one closest to the source
213 // position.
214 int closest_break_point = 0;
215 int distance = kMaxInt;
216 while (!Done()) {
217 // Check if this break point is closer that what was previously found.
218 if (position <= statement_position() &&
219 statement_position() - position < distance) {
220 closest_break_point = break_point();
221 distance = statement_position() - position;
222 // Check whether we can't get any closer.
223 if (distance == 0) break;
224 }
225 Next();
226 }
227
228 // Move to the break point found.
229 Reset();
230 Next(closest_break_point);
231}
232
233
234void BreakLocationIterator::Reset() {
235 // Create relocation iterators for the two code objects.
236 if (reloc_iterator_ != NULL) delete reloc_iterator_;
237 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
238 reloc_iterator_ = new RelocIterator(debug_info_->code());
239 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
240
241 // Position at the first break point.
242 break_point_ = -1;
243 position_ = 1;
244 statement_position_ = 1;
245 Next();
246}
247
248
249bool BreakLocationIterator::Done() const {
250 return RinfoDone();
251}
252
253
254void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
255 // If there is not already a real break point here patch code with debug
256 // break.
257 if (!HasBreakPoint()) {
258 SetDebugBreak();
259 }
ager@chromium.orga1645e22009-09-09 19:27:10 +0000260 ASSERT(IsDebugBreak() || IsDebuggerStatement());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000261 // Set the break point information.
262 DebugInfo::SetBreakPoint(debug_info_, code_position(),
263 position(), statement_position(),
264 break_point_object);
265}
266
267
268void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
269 // Clear the break point information.
270 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
271 // If there are no more break points here remove the debug break.
272 if (!HasBreakPoint()) {
273 ClearDebugBreak();
274 ASSERT(!IsDebugBreak());
275 }
276}
277
278
279void BreakLocationIterator::SetOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000280 // Debugger statement always calls debugger. No need to modify it.
281 if (IsDebuggerStatement()) {
282 return;
283 }
284
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000285 // If there is a real break point here no more to do.
286 if (HasBreakPoint()) {
287 ASSERT(IsDebugBreak());
288 return;
289 }
290
291 // Patch code with debug break.
292 SetDebugBreak();
293}
294
295
296void BreakLocationIterator::ClearOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000297 // Debugger statement always calls debugger. No need to modify it.
298 if (IsDebuggerStatement()) {
299 return;
300 }
301
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000302 // If there is a real break point here no more to do.
303 if (HasBreakPoint()) {
304 ASSERT(IsDebugBreak());
305 return;
306 }
307
308 // Patch code removing debug break.
309 ClearDebugBreak();
310 ASSERT(!IsDebugBreak());
311}
312
313
314void BreakLocationIterator::SetDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000315 // Debugger statement always calls debugger. No need to modify it.
316 if (IsDebuggerStatement()) {
317 return;
318 }
319
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000320 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000321 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000322 // function twice might happen when stepping in a function with an exception
323 // handler as the handler and the function is the same.
324 if (IsDebugBreak()) {
325 return;
326 }
327
ager@chromium.org236ad962008-09-25 09:45:57 +0000328 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000329 // Patch the frame exit code with a break point.
330 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000331 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000332 // Patch the IC call.
333 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000334 }
335 ASSERT(IsDebugBreak());
336}
337
338
339void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000340 // Debugger statement always calls debugger. No need to modify it.
341 if (IsDebuggerStatement()) {
342 return;
343 }
344
ager@chromium.org236ad962008-09-25 09:45:57 +0000345 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000346 // Restore the frame exit code.
347 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000348 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000349 // Patch the IC call.
350 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000351 }
352 ASSERT(!IsDebugBreak());
353}
354
355
356void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000357 HandleScope scope;
358
ager@chromium.orga1645e22009-09-09 19:27:10 +0000359 // Step in can only be prepared if currently positioned on an IC call,
360 // construct call or CallFunction stub call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000361 Address target = rinfo()->target_address();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000362 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000363 if (code->is_call_stub()) {
364 // Step in through IC call is handled by the runtime system. Therefore make
365 // sure that the any current IC is cleared and the runtime system is
366 // called. If the executing code has a debug break at the location change
367 // the call in the original code as it is the code there that will be
368 // executed in place of the debug break call.
369 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
370 if (IsDebugBreak()) {
371 original_rinfo()->set_target_address(stub->entry());
372 } else {
373 rinfo()->set_target_address(stub->entry());
374 }
375 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000376#ifdef DEBUG
377 // All the following stuff is needed only for assertion checks so the code
378 // is wrapped in ifdef.
379 Handle<Code> maybe_call_function_stub = code;
380 if (IsDebugBreak()) {
381 Address original_target = original_rinfo()->target_address();
382 maybe_call_function_stub =
383 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
384 }
385 bool is_call_function_stub =
386 (maybe_call_function_stub->kind() == Code::STUB &&
387 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
388
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000389 // Step in through construct call requires no changes to the running code.
390 // Step in through getters/setters should already be prepared as well
391 // because caller of this function (Debug::PrepareStep) is expected to
392 // flood the top frame's function with one shot breakpoints.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000393 // Step in through CallFunction stub should also be prepared by caller of
394 // this function (Debug::PrepareStep) which should flood target function
395 // with breakpoints.
396 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
397 || is_call_function_stub);
398#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000399 }
400}
401
402
403// Check whether the break point is at a position which will exit the function.
404bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000405 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000406}
407
408
409bool BreakLocationIterator::HasBreakPoint() {
410 return debug_info_->HasBreakPoint(code_position());
411}
412
413
414// Check whether there is a debug break at the current position.
415bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000416 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000417 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418 } else {
419 return Debug::IsDebugBreak(rinfo()->target_address());
420 }
421}
422
423
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000424void BreakLocationIterator::SetDebugBreakAtIC() {
425 // Patch the original code with the current address as the current address
426 // might have changed by the inline caching since the code was copied.
427 original_rinfo()->set_target_address(rinfo()->target_address());
428
429 RelocInfo::Mode mode = rmode();
430 if (RelocInfo::IsCodeTarget(mode)) {
431 Address target = rinfo()->target_address();
432 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
433
434 // Patch the code to invoke the builtin debug break function matching the
435 // calling convention used by the call site.
436 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
437 rinfo()->set_target_address(dbgbrk_code->entry());
438
439 // For stubs that refer back to an inlined version clear the cached map for
440 // the inlined case to always go through the IC. As long as the break point
441 // is set the patching performed by the runtime system will take place in
442 // the code copy and will therefore have no effect on the running code
443 // keeping it from using the inlined code.
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000444 if (code->is_keyed_load_stub()) {
445 KeyedLoadIC::ClearInlinedVersion(pc());
446 } else if (code->is_keyed_store_stub()) {
447 KeyedStoreIC::ClearInlinedVersion(pc());
448 } else if (code->is_load_stub()) {
449 LoadIC::ClearInlinedVersion(pc());
450 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000451 }
452}
453
454
455void BreakLocationIterator::ClearDebugBreakAtIC() {
456 // Patch the code to the original invoke.
457 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000458
459 RelocInfo::Mode mode = rmode();
460 if (RelocInfo::IsCodeTarget(mode)) {
461 Address target = original_rinfo()->target_address();
462 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
463
464 // Restore the inlined version of keyed stores to get back to the
465 // fast case. We need to patch back the keyed store because no
466 // patching happens when running normally. For keyed loads, the
467 // map check will get patched back when running normally after ICs
468 // have been cleared at GC.
469 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
470 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000471}
472
473
ager@chromium.orga1645e22009-09-09 19:27:10 +0000474bool BreakLocationIterator::IsDebuggerStatement() {
ager@chromium.org5c838252010-02-19 08:53:10 +0000475 return RelocInfo::DEBUG_BREAK == rmode();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000476}
477
478
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000479Object* BreakLocationIterator::BreakPointObjects() {
480 return debug_info_->GetBreakPointObjects(code_position());
481}
482
483
ager@chromium.org381abbb2009-02-25 13:23:22 +0000484// Clear out all the debug break code. This is ONLY supposed to be used when
485// shutting down the debugger as it will leave the break point information in
486// DebugInfo even though the code is patched back to the non break point state.
487void BreakLocationIterator::ClearAllDebugBreak() {
488 while (!Done()) {
489 ClearDebugBreak();
490 Next();
491 }
492}
493
494
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000495bool BreakLocationIterator::RinfoDone() const {
496 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
497 return reloc_iterator_->done();
498}
499
500
501void BreakLocationIterator::RinfoNext() {
502 reloc_iterator_->next();
503 reloc_iterator_original_->next();
504#ifdef DEBUG
505 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
506 if (!reloc_iterator_->done()) {
507 ASSERT(rmode() == original_rmode());
508 }
509#endif
510}
511
512
513bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000514ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000515DebugInfoListNode* Debug::debug_info_list_ = NULL;
516
517
518// Threading support.
519void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000520 thread_local_.break_count_ = 0;
521 thread_local_.break_id_ = 0;
522 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000523 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000524 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000525 thread_local_.step_count_ = 0;
526 thread_local_.last_fp_ = 0;
527 thread_local_.step_into_fp_ = 0;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000528 thread_local_.step_out_fp_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000529 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000530 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000531 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000532}
533
534
535JSCallerSavedBuffer Debug::registers_;
536Debug::ThreadLocal Debug::thread_local_;
537
538
539char* Debug::ArchiveDebug(char* storage) {
540 char* to = storage;
541 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
542 to += sizeof(ThreadLocal);
543 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
544 ThreadInit();
545 ASSERT(to <= storage + ArchiveSpacePerThread());
546 return storage + ArchiveSpacePerThread();
547}
548
549
550char* Debug::RestoreDebug(char* storage) {
551 char* from = storage;
552 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
553 from += sizeof(ThreadLocal);
554 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
555 ASSERT(from <= storage + ArchiveSpacePerThread());
556 return storage + ArchiveSpacePerThread();
557}
558
559
560int Debug::ArchiveSpacePerThread() {
561 return sizeof(ThreadLocal) + sizeof(registers_);
562}
563
564
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000565// Default break enabled.
566bool Debug::disable_break_ = false;
567
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568// Default call debugger on uncaught exception.
569bool Debug::break_on_exception_ = false;
570bool Debug::break_on_uncaught_exception_ = true;
571
572Handle<Context> Debug::debug_context_ = Handle<Context>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000573Code* Debug::debug_break_return_ = NULL;
574
575
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000576void ScriptCache::Add(Handle<Script> script) {
577 // Create an entry in the hash map for the script.
578 int id = Smi::cast(script->id())->value();
579 HashMap::Entry* entry =
580 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
581 if (entry->value != NULL) {
582 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
583 return;
584 }
585
586 // Globalize the script object, make it weak and use the location of the
587 // global handle as the value in the hash map.
588 Handle<Script> script_ =
589 Handle<Script>::cast((GlobalHandles::Create(*script)));
590 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
591 this, ScriptCache::HandleWeakScript);
592 entry->value = script_.location();
593}
594
595
596Handle<FixedArray> ScriptCache::GetScripts() {
597 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
598 int count = 0;
599 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
600 ASSERT(entry->value != NULL);
601 if (entry->value != NULL) {
602 instances->set(count, *reinterpret_cast<Script**>(entry->value));
603 count++;
604 }
605 }
606 return instances;
607}
608
609
610void ScriptCache::ProcessCollectedScripts() {
611 for (int i = 0; i < collected_scripts_.length(); i++) {
612 Debugger::OnScriptCollected(collected_scripts_[i]);
613 }
614 collected_scripts_.Clear();
615}
616
617
618void ScriptCache::Clear() {
619 // Iterate the script cache to get rid of all the weak handles.
620 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
621 ASSERT(entry != NULL);
622 Object** location = reinterpret_cast<Object**>(entry->value);
623 ASSERT((*location)->IsScript());
624 GlobalHandles::ClearWeakness(location);
625 GlobalHandles::Destroy(location);
626 }
627 // Clear the content of the hash map.
628 HashMap::Clear();
629}
630
631
632void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
633 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
634 // Find the location of the global handle.
635 Script** location =
636 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
637 ASSERT((*location)->IsScript());
638
639 // Remove the entry from the cache.
640 int id = Smi::cast((*location)->id())->value();
641 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
642 script_cache->collected_scripts_.Add(id);
643
644 // Clear the weak handle.
645 obj.Dispose();
646 obj.Clear();
647}
648
649
650void Debug::Setup(bool create_heap_objects) {
651 ThreadInit();
652 if (create_heap_objects) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000653 // Get code to handle debug break on return.
654 debug_break_return_ =
655 Builtins::builtin(Builtins::Return_DebugBreak);
656 ASSERT(debug_break_return_->IsCode());
657 }
658}
659
660
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000661void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000662 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
663 RemoveDebugInfo(node->debug_info());
664#ifdef DEBUG
665 node = Debug::debug_info_list_;
666 while (node != NULL) {
667 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
668 node = node->next();
669 }
670#endif
671}
672
673
674DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
675 // Globalize the request debug info object and make it weak.
676 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
677 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
678 this, Debug::HandleWeakDebugInfo);
679}
680
681
682DebugInfoListNode::~DebugInfoListNode() {
683 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
684}
685
686
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000687bool Debug::CompileDebuggerScript(int index) {
688 HandleScope scope;
689
kasper.lund44510672008-07-25 07:37:58 +0000690 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000691 if (index == -1) {
692 return false;
693 }
kasper.lund44510672008-07-25 07:37:58 +0000694
695 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000696 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
697 Vector<const char> name = Natives::GetScriptName(index);
698 Handle<String> script_name = Factory::NewStringFromAscii(name);
699
700 // Compile the script.
701 bool allow_natives_syntax = FLAG_allow_natives_syntax;
702 FLAG_allow_natives_syntax = true;
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000703 Handle<SharedFunctionInfo> function_info;
704 function_info = Compiler::Compile(source_code,
705 script_name,
706 0, 0, NULL, NULL,
707 Handle<String>::null(),
708 NATIVES_CODE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000709 FLAG_allow_natives_syntax = allow_natives_syntax;
710
711 // Silently ignore stack overflows during compilation.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000712 if (function_info.is_null()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000713 ASSERT(Top::has_pending_exception());
714 Top::clear_pending_exception();
715 return false;
716 }
717
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000718 // Execute the shared function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000719 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000720 bool caught_exception = false;
721 Handle<JSFunction> function =
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000722 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
kasper.lund44510672008-07-25 07:37:58 +0000723 Handle<Object> result =
724 Execution::TryCall(function, Handle<Object>(context->global()),
725 0, NULL, &caught_exception);
726
727 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000728 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000729 Handle<Object> message = MessageHandler::MakeMessageObject(
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000730 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000731 Handle<String>());
732 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000733 return false;
734 }
735
kasper.lund44510672008-07-25 07:37:58 +0000736 // Mark this script as native and return successfully.
737 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000738 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000739 return true;
740}
741
742
743bool Debug::Load() {
744 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000745 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000746
kasper.lund44510672008-07-25 07:37:58 +0000747 // Bail out if we're already in the process of compiling the native
748 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000749 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
750 return false;
751 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000752
753 // Disable breakpoints and interrupts while compiling and running the
754 // debugger scripts including the context creation code.
755 DisableBreak disable(true);
756 PostponeInterruptsScope postpone;
757
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758 // Create the debugger context.
759 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000760 Handle<Context> context =
761 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
762 v8::Handle<ObjectTemplate>(),
763 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000764
kasper.lund44510672008-07-25 07:37:58 +0000765 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000767 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000768
769 // Expose the builtins object in the debugger context.
770 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
771 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
772 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773
774 // Compile the JavaScript for the debugger in the debugger context.
775 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000776 bool caught_exception =
777 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
778 !CompileDebuggerScript(Natives::GetIndex("debug"));
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000779
780 if (FLAG_enable_liveedit) {
781 caught_exception = caught_exception ||
782 !CompileDebuggerScript(Natives::GetIndex("liveedit"));
783 }
784
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000785 Debugger::set_compiling_natives(false);
786
mads.s.agercbaa0602008-08-14 13:41:48 +0000787 // Make sure we mark the debugger as not loading before we might
788 // return.
789 Debugger::set_loading_debugger(false);
790
kasper.lund44510672008-07-25 07:37:58 +0000791 // Check for caught exceptions.
792 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000793
794 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000795 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000796
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797 return true;
798}
799
800
801void Debug::Unload() {
802 // Return debugger is not loaded.
803 if (!IsLoaded()) {
804 return;
805 }
806
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000807 // Clear the script cache.
808 DestroyScriptCache();
809
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000810 // Clear debugger context global handle.
811 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
812 debug_context_ = Handle<Context>();
813}
814
815
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000816// Set the flag indicating that preemption happened during debugging.
817void Debug::PreemptionWhileInDebugger() {
818 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000819 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000820}
821
822
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000823void Debug::Iterate(ObjectVisitor* v) {
vegorov@chromium.orgf8372902010-03-15 10:26:20 +0000824 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000825}
826
827
828Object* Debug::Break(Arguments args) {
829 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000830 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000831
ager@chromium.org357bf652010-04-12 11:30:10 +0000832 thread_local_.frames_are_dropped_ = false;
833
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000834 // Get the top-most JavaScript frame.
835 JavaScriptFrameIterator it;
836 JavaScriptFrame* frame = it.frame();
837
838 // Just continue if breaks are disabled or debugger cannot be loaded.
839 if (disable_break() || !Load()) {
840 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000841 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000842 }
843
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000844 // Enter the debugger.
845 EnterDebugger debugger;
846 if (debugger.FailedToEnter()) {
847 return Heap::undefined_value();
848 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000849
kasper.lund44510672008-07-25 07:37:58 +0000850 // Postpone interrupt during breakpoint processing.
851 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000852
853 // Get the debug info (create it if it does not exist).
854 Handle<SharedFunctionInfo> shared =
855 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
856 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
857
858 // Find the break point where execution has stopped.
859 BreakLocationIterator break_location_iterator(debug_info,
860 ALL_BREAK_LOCATIONS);
861 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
862
863 // Check whether step next reached a new statement.
864 if (!StepNextContinue(&break_location_iterator, frame)) {
865 // Decrease steps left if performing multiple steps.
866 if (thread_local_.step_count_ > 0) {
867 thread_local_.step_count_--;
868 }
869 }
870
871 // If there is one or more real break points check whether any of these are
872 // triggered.
873 Handle<Object> break_points_hit(Heap::undefined_value());
874 if (break_location_iterator.HasBreakPoint()) {
875 Handle<Object> break_point_objects =
876 Handle<Object>(break_location_iterator.BreakPointObjects());
877 break_points_hit = CheckBreakPoints(break_point_objects);
878 }
879
ager@chromium.orga1645e22009-09-09 19:27:10 +0000880 // If step out is active skip everything until the frame where we need to step
881 // out to is reached, unless real breakpoint is hit.
882 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
883 break_points_hit->IsUndefined() ) {
884 // Step count should always be 0 for StepOut.
885 ASSERT(thread_local_.step_count_ == 0);
886 } else if (!break_points_hit->IsUndefined() ||
887 (thread_local_.last_step_action_ != StepNone &&
888 thread_local_.step_count_ == 0)) {
889 // Notify debugger if a real break point is triggered or if performing
890 // single stepping with no more steps to perform. Otherwise do another step.
891
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000892 // Clear all current stepping setup.
893 ClearStepping();
894
895 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000896 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000897 } else if (thread_local_.last_step_action_ != StepNone) {
898 // Hold on to last step action as it is cleared by the call to
899 // ClearStepping.
900 StepAction step_action = thread_local_.last_step_action_;
901 int step_count = thread_local_.step_count_;
902
903 // Clear all current stepping setup.
904 ClearStepping();
905
906 // Set up for the remaining steps.
907 PrepareStep(step_action, step_count);
908 }
909
ager@chromium.org357bf652010-04-12 11:30:10 +0000910 if (thread_local_.frames_are_dropped_) {
911 // We must have been calling IC stub. Do not return there anymore.
912 Code* plain_return = Builtins::builtin(Builtins::PlainReturn_LiveEdit);
913 thread_local_.after_break_target_ = plain_return->entry();
914 } else {
915 SetAfterBreakTarget(frame);
916 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000917
mads.s.ager31e71382008-08-13 09:32:07 +0000918 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000919}
920
921
922// Check the break point objects for whether one or more are actually
923// triggered. This function returns a JSArray with the break point objects
924// which is triggered.
925Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
926 int break_points_hit_count = 0;
927 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
928
v8.team.kasperl727e9952008-09-02 14:56:44 +0000929 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000930 ASSERT(!break_point_objects->IsUndefined());
931 if (break_point_objects->IsFixedArray()) {
932 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
933 for (int i = 0; i < array->length(); i++) {
934 Handle<Object> o(array->get(i));
935 if (CheckBreakPoint(o)) {
936 break_points_hit->SetElement(break_points_hit_count++, *o);
937 }
938 }
939 } else {
940 if (CheckBreakPoint(break_point_objects)) {
941 break_points_hit->SetElement(break_points_hit_count++,
942 *break_point_objects);
943 }
944 }
945
946 // Return undefined if no break points where triggered.
947 if (break_points_hit_count == 0) {
948 return Factory::undefined_value();
949 }
950 return break_points_hit;
951}
952
953
954// Check whether a single break point object is triggered.
955bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000956 HandleScope scope;
957
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958 // Ignore check if break point object is not a JSObject.
959 if (!break_point_object->IsJSObject()) return true;
960
961 // Get the function CheckBreakPoint (defined in debug.js).
962 Handle<JSFunction> check_break_point =
963 Handle<JSFunction>(JSFunction::cast(
964 debug_context()->global()->GetProperty(
965 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
966
967 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000968 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000969
970 // Call HandleBreakPointx.
971 bool caught_exception = false;
972 const int argc = 2;
973 Object** argv[argc] = {
974 break_id.location(),
975 reinterpret_cast<Object**>(break_point_object.location())
976 };
977 Handle<Object> result = Execution::TryCall(check_break_point,
978 Top::builtins(), argc, argv,
979 &caught_exception);
980
981 // If exception or non boolean result handle as not triggered
982 if (caught_exception || !result->IsBoolean()) {
983 return false;
984 }
985
986 // Return whether the break point is triggered.
987 return *result == Heap::true_value();
988}
989
990
991// Check whether the function has debug information.
992bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
993 return !shared->debug_info()->IsUndefined();
994}
995
996
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000997// Return the debug info for this function. EnsureDebugInfo must be called
998// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000999Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001000 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001001 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
1002}
1003
1004
1005void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
1006 int source_position,
1007 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001008 HandleScope scope;
1009
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001010 if (!EnsureDebugInfo(shared)) {
1011 // Return if retrieving debug info failed.
1012 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001013 }
1014
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001015 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001016 // Source positions starts with zero.
1017 ASSERT(source_position >= 0);
1018
1019 // Find the break point and change it.
1020 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1021 it.FindBreakLocationFromPosition(source_position);
1022 it.SetBreakPoint(break_point_object);
1023
1024 // At least one active break point now.
1025 ASSERT(debug_info->GetBreakPointCount() > 0);
1026}
1027
1028
1029void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001030 HandleScope scope;
1031
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001032 DebugInfoListNode* node = debug_info_list_;
1033 while (node != NULL) {
1034 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1035 break_point_object);
1036 if (!result->IsUndefined()) {
1037 // Get information in the break point.
1038 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1039 Handle<DebugInfo> debug_info = node->debug_info();
1040 Handle<SharedFunctionInfo> shared(debug_info->shared());
1041 int source_position = break_point_info->statement_position()->value();
1042
1043 // Source positions starts with zero.
1044 ASSERT(source_position >= 0);
1045
1046 // Find the break point and clear it.
1047 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1048 it.FindBreakLocationFromPosition(source_position);
1049 it.ClearBreakPoint(break_point_object);
1050
1051 // If there are no more break points left remove the debug info for this
1052 // function.
1053 if (debug_info->GetBreakPointCount() == 0) {
1054 RemoveDebugInfo(debug_info);
1055 }
1056
1057 return;
1058 }
1059 node = node->next();
1060 }
1061}
1062
1063
ager@chromium.org381abbb2009-02-25 13:23:22 +00001064void Debug::ClearAllBreakPoints() {
1065 DebugInfoListNode* node = debug_info_list_;
1066 while (node != NULL) {
1067 // Remove all debug break code.
1068 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1069 it.ClearAllDebugBreak();
1070 node = node->next();
1071 }
1072
1073 // Remove all debug info.
1074 while (debug_info_list_ != NULL) {
1075 RemoveDebugInfo(debug_info_list_->debug_info());
1076 }
1077}
1078
1079
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001080void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001081 // Make sure the function has setup the debug info.
1082 if (!EnsureDebugInfo(shared)) {
1083 // Return if we failed to retrieve the debug info.
1084 return;
1085 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001086
1087 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001088 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001089 while (!it.Done()) {
1090 it.SetOneShot();
1091 it.Next();
1092 }
1093}
1094
1095
1096void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001097 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001098 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001099 if (id == StackFrame::NO_ID) {
1100 // If there is no JavaScript stack don't do anything.
1101 return;
1102 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001103 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1104 JavaScriptFrame* frame = it.frame();
1105 if (frame->HasHandler()) {
1106 Handle<SharedFunctionInfo> shared =
1107 Handle<SharedFunctionInfo>(
1108 JSFunction::cast(frame->function())->shared());
1109 // Flood the function with the catch block with break points
1110 FloodWithOneShot(shared);
1111 return;
1112 }
1113 }
1114}
1115
1116
1117void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1118 if (type == BreakUncaughtException) {
1119 break_on_uncaught_exception_ = enable;
1120 } else {
1121 break_on_exception_ = enable;
1122 }
1123}
1124
1125
1126void Debug::PrepareStep(StepAction step_action, int step_count) {
1127 HandleScope scope;
1128 ASSERT(Debug::InDebugger());
1129
1130 // Remember this step action and count.
1131 thread_local_.last_step_action_ = step_action;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001132 if (step_action == StepOut) {
1133 // For step out target frame will be found on the stack so there is no need
1134 // to set step counter for it. It's expected to always be 0 for StepOut.
1135 thread_local_.step_count_ = 0;
1136 } else {
1137 thread_local_.step_count_ = step_count;
1138 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001139
1140 // Get the frame where the execution has stopped and skip the debug frame if
1141 // any. The debug frame will only be present if execution was stopped due to
1142 // hitting a break point. In other situations (e.g. unhandled exception) the
1143 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001144 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001145 if (id == StackFrame::NO_ID) {
1146 // If there is no JavaScript stack don't do anything.
1147 return;
1148 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001149 JavaScriptFrameIterator frames_it(id);
1150 JavaScriptFrame* frame = frames_it.frame();
1151
1152 // First of all ensure there is one-shot break points in the top handler
1153 // if any.
1154 FloodHandlerWithOneShot();
1155
1156 // If the function on the top frame is unresolved perform step out. This will
1157 // be the case when calling unknown functions and having the debugger stopped
1158 // in an unhandled exception.
1159 if (!frame->function()->IsJSFunction()) {
1160 // Step out: Find the calling JavaScript frame and flood it with
1161 // breakpoints.
1162 frames_it.Advance();
1163 // Fill the function to return to with one-shot break points.
1164 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1165 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1166 return;
1167 }
1168
1169 // Get the debug info (create it if it does not exist).
1170 Handle<SharedFunctionInfo> shared =
1171 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001172 if (!EnsureDebugInfo(shared)) {
1173 // Return if ensuring debug info failed.
1174 return;
1175 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001176 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1177
1178 // Find the break location where execution has stopped.
1179 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1180 it.FindBreakLocationFromAddress(frame->pc());
1181
1182 // Compute whether or not the target is a call target.
1183 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001184 bool is_load_or_store = false;
1185 bool is_inline_cache_stub = false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001186 Handle<Code> call_function_stub;
ager@chromium.org236ad962008-09-25 09:45:57 +00001187 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001188 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001189 Code* code = Code::GetCodeFromTargetAddress(target);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001190 if (code->is_call_stub()) {
1191 is_call_target = true;
1192 }
1193 if (code->is_inline_cache_stub()) {
1194 is_inline_cache_stub = true;
1195 is_load_or_store = !is_call_target;
1196 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001197
1198 // Check if target code is CallFunction stub.
1199 Code* maybe_call_function_stub = code;
1200 // If there is a breakpoint at this line look at the original code to
1201 // check if it is a CallFunction stub.
1202 if (it.IsDebugBreak()) {
1203 Address original_target = it.original_rinfo()->target_address();
1204 maybe_call_function_stub =
1205 Code::GetCodeFromTargetAddress(original_target);
1206 }
1207 if (maybe_call_function_stub->kind() == Code::STUB &&
1208 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1209 // Save reference to the code as we may need it to find out arguments
1210 // count for 'step in' later.
1211 call_function_stub = Handle<Code>(maybe_call_function_stub);
1212 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001213 }
1214
v8.team.kasperl727e9952008-09-02 14:56:44 +00001215 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001216 if (it.IsExit() || step_action == StepOut) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001217 if (step_action == StepOut) {
1218 // Skip step_count frames starting with the current one.
1219 while (step_count-- > 0 && !frames_it.done()) {
1220 frames_it.Advance();
1221 }
1222 } else {
1223 ASSERT(it.IsExit());
1224 frames_it.Advance();
1225 }
1226 // Skip builtin functions on the stack.
1227 while (!frames_it.done() &&
1228 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1229 frames_it.Advance();
1230 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001231 // Step out: If there is a JavaScript caller frame, we need to
1232 // flood it with breakpoints.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001233 if (!frames_it.done()) {
1234 // Fill the function to return to with one-shot break points.
1235 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1236 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001237 // Set target frame pointer.
1238 ActivateStepOut(frames_it.frame());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001239 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001240 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1241 !call_function_stub.is_null())
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001242 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001243 // Step next or step min.
1244
1245 // Fill the current function with one-shot break points.
1246 FloodWithOneShot(shared);
1247
1248 // Remember source position and frame to handle step next.
1249 thread_local_.last_statement_position_ =
1250 debug_info->code()->SourceStatementPosition(frame->pc());
1251 thread_local_.last_fp_ = frame->fp();
1252 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001253 // If it's CallFunction stub ensure target function is compiled and flood
1254 // it with one shot breakpoints.
1255 if (!call_function_stub.is_null()) {
1256 // Find out number of arguments from the stub minor key.
1257 // Reverse lookup required as the minor key cannot be retrieved
1258 // from the code object.
1259 Handle<Object> obj(
1260 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1261 ASSERT(*obj != Heap::undefined_value());
1262 ASSERT(obj->IsSmi());
1263 // Get the STUB key and extract major and minor key.
1264 uint32_t key = Smi::cast(*obj)->value();
1265 // Argc in the stub is the number of arguments passed - not the
1266 // expected arguments of the called function.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001267 int call_function_arg_count =
1268 CallFunctionStub::ExtractArgcFromMinorKey(
1269 CodeStub::MinorKeyFromKey(key));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001270 ASSERT(call_function_stub->major_key() ==
1271 CodeStub::MajorKeyFromKey(key));
1272
1273 // Find target function on the expression stack.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001274 // Expression stack looks like this (top to bottom):
ager@chromium.orga1645e22009-09-09 19:27:10 +00001275 // argN
1276 // ...
1277 // arg0
1278 // Receiver
1279 // Function to call
1280 int expressions_count = frame->ComputeExpressionsCount();
1281 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1282 Object* fun = frame->GetExpression(
1283 expressions_count - 2 - call_function_arg_count);
1284 if (fun->IsJSFunction()) {
1285 Handle<JSFunction> js_function(JSFunction::cast(fun));
1286 // Don't step into builtins.
1287 if (!js_function->IsBuiltin()) {
1288 // It will also compile target function if it's not compiled yet.
1289 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1290 }
1291 }
1292 }
1293
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001294 // Fill the current function with one-shot break points even for step in on
1295 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001296 // which step in will not stop. It also prepares for stepping in
1297 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001298 FloodWithOneShot(shared);
1299
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001300 if (is_load_or_store) {
1301 // Remember source position and frame to handle step in getter/setter. If
1302 // there is a custom getter/setter it will be handled in
1303 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1304 // propagated on the next Debug::Break.
1305 thread_local_.last_statement_position_ =
1306 debug_info->code()->SourceStatementPosition(frame->pc());
1307 thread_local_.last_fp_ = frame->fp();
1308 }
1309
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001310 // Step in or Step in min
1311 it.PrepareStepIn();
1312 ActivateStepIn(frame);
1313 }
1314}
1315
1316
1317// Check whether the current debug break should be reported to the debugger. It
1318// is used to have step next and step in only report break back to the debugger
1319// if on a different frame or in a different statement. In some situations
1320// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001321// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001322// steps before reporting break back to the debugger.
1323bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1324 JavaScriptFrame* frame) {
1325 // If the step last action was step next or step in make sure that a new
1326 // statement is hit.
1327 if (thread_local_.last_step_action_ == StepNext ||
1328 thread_local_.last_step_action_ == StepIn) {
1329 // Never continue if returning from function.
1330 if (break_location_iterator->IsExit()) return false;
1331
1332 // Continue if we are still on the same frame and in the same statement.
1333 int current_statement_position =
1334 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1335 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001336 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001337 }
1338
1339 // No step next action - don't continue.
1340 return false;
1341}
1342
1343
1344// Check whether the code object at the specified address is a debug break code
1345// object.
1346bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001347 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001348 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001349}
1350
1351
1352// Check whether a code stub with the specified major key is a possible break
1353// point location when looking for source break locations.
1354bool Debug::IsSourceBreakStub(Code* code) {
1355 CodeStub::Major major_key = code->major_key();
1356 return major_key == CodeStub::CallFunction;
1357}
1358
1359
1360// Check whether a code stub with the specified major key is a possible break
1361// location.
1362bool Debug::IsBreakStub(Code* code) {
1363 CodeStub::Major major_key = code->major_key();
1364 return major_key == CodeStub::CallFunction ||
1365 major_key == CodeStub::StackCheck;
1366}
1367
1368
1369// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001370Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001371 // Find the builtin debug break function matching the calling convention
1372 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001373 if (code->is_inline_cache_stub()) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001374 switch (code->kind()) {
1375 case Code::CALL_IC:
1376 return ComputeCallDebugBreak(code->arguments_count());
1377
1378 case Code::LOAD_IC:
1379 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1380
1381 case Code::STORE_IC:
1382 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1383
1384 case Code::KEYED_LOAD_IC:
1385 return Handle<Code>(
1386 Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1387
1388 case Code::KEYED_STORE_IC:
1389 return Handle<Code>(
1390 Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1391
1392 default:
1393 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001394 }
1395 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001396 if (RelocInfo::IsConstructCall(mode)) {
1397 Handle<Code> result =
1398 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1399 return result;
1400 }
1401 if (code->kind() == Code::STUB) {
1402 ASSERT(code->major_key() == CodeStub::CallFunction ||
1403 code->major_key() == CodeStub::StackCheck);
1404 Handle<Code> result =
1405 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1406 return result;
1407 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001408
1409 UNREACHABLE();
1410 return Handle<Code>::null();
1411}
1412
1413
1414// Simple function for returning the source positions for active break points.
1415Handle<Object> Debug::GetSourceBreakLocations(
1416 Handle<SharedFunctionInfo> shared) {
1417 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1418 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1419 if (debug_info->GetBreakPointCount() == 0) {
1420 return Handle<Object>(Heap::undefined_value());
1421 }
1422 Handle<FixedArray> locations =
1423 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1424 int count = 0;
1425 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1426 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1427 BreakPointInfo* break_point_info =
1428 BreakPointInfo::cast(debug_info->break_points()->get(i));
1429 if (break_point_info->GetBreakPointCount() > 0) {
1430 locations->set(count++, break_point_info->statement_position());
1431 }
1432 }
1433 }
1434 return locations;
1435}
1436
1437
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001438void Debug::NewBreak(StackFrame::Id break_frame_id) {
1439 thread_local_.break_frame_id_ = break_frame_id;
1440 thread_local_.break_id_ = ++thread_local_.break_count_;
1441}
1442
1443
1444void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1445 thread_local_.break_frame_id_ = break_frame_id;
1446 thread_local_.break_id_ = break_id;
1447}
1448
1449
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001450// Handle stepping into a function.
1451void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001452 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001453 Address fp,
1454 bool is_constructor) {
1455 // If the frame pointer is not supplied by the caller find it.
1456 if (fp == 0) {
1457 StackFrameIterator it;
1458 it.Advance();
1459 // For constructor functions skip another frame.
1460 if (is_constructor) {
1461 ASSERT(it.frame()->is_construct());
1462 it.Advance();
1463 }
1464 fp = it.frame()->fp();
1465 }
1466
1467 // Flood the function with one-shot break points if it is called from where
1468 // step into was requested.
1469 if (fp == Debug::step_in_fp()) {
1470 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001471 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001472 if (function->shared()->code() ==
1473 Builtins::builtin(Builtins::FunctionApply) ||
1474 function->shared()->code() ==
1475 Builtins::builtin(Builtins::FunctionCall)) {
1476 // Handle function.apply and function.call separately to flood the
1477 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001478 // Builtins::FunctionCall. The receiver of call/apply is the target
1479 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001480 if (!holder.is_null() && holder->IsJSFunction() &&
1481 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001482 Handle<SharedFunctionInfo> shared_info(
1483 JSFunction::cast(*holder)->shared());
1484 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001485 }
1486 } else {
1487 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1488 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001489 }
1490 }
1491}
1492
1493
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001494void Debug::ClearStepping() {
1495 // Clear the various stepping setup.
1496 ClearOneShot();
1497 ClearStepIn();
ager@chromium.orga1645e22009-09-09 19:27:10 +00001498 ClearStepOut();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001499 ClearStepNext();
1500
1501 // Clear multiple step counter.
1502 thread_local_.step_count_ = 0;
1503}
1504
1505// Clears all the one-shot break points that are currently set. Normally this
1506// function is called each time a break point is hit as one shot break points
1507// are used to support stepping.
1508void Debug::ClearOneShot() {
1509 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001510 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001511 // removed from the list.
1512
1513 DebugInfoListNode* node = debug_info_list_;
1514 while (node != NULL) {
1515 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1516 while (!it.Done()) {
1517 it.ClearOneShot();
1518 it.Next();
1519 }
1520 node = node->next();
1521 }
1522}
1523
1524
1525void Debug::ActivateStepIn(StackFrame* frame) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001526 ASSERT(!StepOutActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001527 thread_local_.step_into_fp_ = frame->fp();
1528}
1529
1530
1531void Debug::ClearStepIn() {
1532 thread_local_.step_into_fp_ = 0;
1533}
1534
1535
ager@chromium.orga1645e22009-09-09 19:27:10 +00001536void Debug::ActivateStepOut(StackFrame* frame) {
1537 ASSERT(!StepInActive());
1538 thread_local_.step_out_fp_ = frame->fp();
1539}
1540
1541
1542void Debug::ClearStepOut() {
1543 thread_local_.step_out_fp_ = 0;
1544}
1545
1546
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001547void Debug::ClearStepNext() {
1548 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001549 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001550 thread_local_.last_fp_ = 0;
1551}
1552
1553
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001554// Ensures the debug information is present for shared.
1555bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1556 // Return if we already have the debug info for shared.
1557 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001558
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001559 // Ensure shared in compiled. Return false if this failed.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001560 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001561
1562 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001563 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001564
1565 // Add debug info to the list.
1566 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1567 node->set_next(debug_info_list_);
1568 debug_info_list_ = node;
1569
1570 // Now there is at least one break point.
1571 has_break_points_ = true;
1572
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001573 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001574}
1575
1576
1577void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1578 ASSERT(debug_info_list_ != NULL);
1579 // Run through the debug info objects to find this one and remove it.
1580 DebugInfoListNode* prev = NULL;
1581 DebugInfoListNode* current = debug_info_list_;
1582 while (current != NULL) {
1583 if (*current->debug_info() == *debug_info) {
1584 // Unlink from list. If prev is NULL we are looking at the first element.
1585 if (prev == NULL) {
1586 debug_info_list_ = current->next();
1587 } else {
1588 prev->set_next(current->next());
1589 }
1590 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1591 delete current;
1592
1593 // If there are no more debug info objects there are not more break
1594 // points.
1595 has_break_points_ = debug_info_list_ != NULL;
1596
1597 return;
1598 }
1599 // Move to next in list.
1600 prev = current;
1601 current = current->next();
1602 }
1603 UNREACHABLE();
1604}
1605
1606
1607void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001608 HandleScope scope;
1609
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001610 // Get the executing function in which the debug break occurred.
1611 Handle<SharedFunctionInfo> shared =
1612 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001613 if (!EnsureDebugInfo(shared)) {
1614 // Return if we failed to retrieve the debug info.
1615 return;
1616 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001617 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1618 Handle<Code> code(debug_info->code());
1619 Handle<Code> original_code(debug_info->original_code());
1620#ifdef DEBUG
1621 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001622 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001623 ASSERT(frame_code.is_identical_to(code));
1624#endif
1625
1626 // Find the call address in the running code. This address holds the call to
1627 // either a DebugBreakXXX or to the debug break return entry code if the
1628 // break point is still active after processing the break point.
ager@chromium.org4af710e2009-09-15 12:20:11 +00001629 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001630
1631 // Check if the location is at JS exit.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001632 bool at_js_return = false;
1633 bool break_at_js_return_active = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001634 RelocIterator it(debug_info->code());
1635 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001636 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001637 at_js_return = (it.rinfo()->pc() ==
1638 addr - Assembler::kPatchReturnSequenceAddressOffset);
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001639 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001640 }
1641 it.next();
1642 }
1643
1644 // Handle the jump to continue execution after break point depending on the
1645 // break location.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001646 if (at_js_return) {
1647 // If the break point as return is still active jump to the corresponding
1648 // place in the original code. If not the break point was removed during
1649 // break point processing.
1650 if (break_at_js_return_active) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001651 addr += original_code->instruction_start() - code->instruction_start();
1652 }
1653
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001654 // Move back to where the call instruction sequence started.
1655 thread_local_.after_break_target_ =
1656 addr - Assembler::kPatchReturnSequenceAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001657 } else {
1658 // Check if there still is a debug break call at the target address. If the
1659 // break point has been removed it will have disappeared. If it have
1660 // disappeared don't try to look in the original code as the running code
1661 // will have the right address. This takes care of the case where the last
1662 // break point is removed from the function and therefore no "original code"
1663 // is available. If the debug break call is still there find the address in
1664 // the original code.
1665 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1666 // If the break point is still there find the call address which was
1667 // overwritten in the original code by the call to DebugBreakXXX.
1668
1669 // Find the corresponding address in the original code.
1670 addr += original_code->instruction_start() - code->instruction_start();
1671 }
1672
1673 // Install jump to the call address in the original code. This will be the
1674 // call which was overwritten by the call to DebugBreakXXX.
1675 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1676 }
1677}
1678
1679
ager@chromium.org357bf652010-04-12 11:30:10 +00001680void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id) {
1681 thread_local_.frames_are_dropped_ = true;
1682 thread_local_.break_frame_id_ = new_break_frame_id;
1683}
1684
1685
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001686bool Debug::IsDebugGlobal(GlobalObject* global) {
1687 return IsLoaded() && global == Debug::debug_context()->global();
1688}
1689
1690
ager@chromium.org32912102009-01-16 10:38:43 +00001691void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001692 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001693 ASSERT(Top::context() == *Debug::debug_context());
1694
1695 // Clear the mirror cache.
1696 Handle<String> function_name =
1697 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1698 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1699 ASSERT(fun->IsJSFunction());
1700 bool caught_exception;
1701 Handle<Object> js_object = Execution::TryCall(
1702 Handle<JSFunction>::cast(fun),
1703 Handle<JSObject>(Debug::debug_context()->global()),
1704 0, NULL, &caught_exception);
1705}
1706
1707
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001708void Debug::CreateScriptCache() {
1709 HandleScope scope;
1710
1711 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1712 // rid of all the cached script wrappers and the second gets rid of the
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00001713 // scripts which are no longer referenced.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001714 Heap::CollectAllGarbage(false);
1715 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001716
1717 ASSERT(script_cache_ == NULL);
1718 script_cache_ = new ScriptCache();
1719
1720 // Scan heap for Script objects.
1721 int count = 0;
1722 HeapIterator iterator;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001723 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +00001724 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001725 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1726 count++;
1727 }
1728 }
1729}
1730
1731
1732void Debug::DestroyScriptCache() {
1733 // Get rid of the script cache if it was created.
1734 if (script_cache_ != NULL) {
1735 delete script_cache_;
1736 script_cache_ = NULL;
1737 }
1738}
1739
1740
1741void Debug::AddScriptToScriptCache(Handle<Script> script) {
1742 if (script_cache_ != NULL) {
1743 script_cache_->Add(script);
1744 }
1745}
1746
1747
1748Handle<FixedArray> Debug::GetLoadedScripts() {
1749 // Create and fill the script cache when the loaded scripts is requested for
1750 // the first time.
1751 if (script_cache_ == NULL) {
1752 CreateScriptCache();
1753 }
1754
1755 // If the script cache is not active just return an empty array.
1756 ASSERT(script_cache_ != NULL);
1757 if (script_cache_ == NULL) {
1758 Factory::NewFixedArray(0);
1759 }
1760
1761 // Perform GC to get unreferenced scripts evicted from the cache before
1762 // returning the content.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001763 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001764
1765 // Get the scripts from the cache.
1766 return script_cache_->GetScripts();
1767}
1768
1769
1770void Debug::AfterGarbageCollection() {
1771 // Generate events for collected scripts.
1772 if (script_cache_ != NULL) {
1773 script_cache_->ProcessCollectedScripts();
1774 }
1775}
1776
1777
ager@chromium.org71daaf62009-04-01 07:22:49 +00001778Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001779Handle<Object> Debugger::event_listener_ = Handle<Object>();
1780Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001781bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001782bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001783bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001784v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001785bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001786v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001787Mutex* Debugger::dispatch_handler_access_ = OS::CreateMutex();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001788v8::Debug::DebugMessageDispatchHandler
1789 Debugger::debug_message_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001790MessageDispatchHelperThread* Debugger::message_dispatch_helper_thread_ = NULL;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001791int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001792DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001793LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001794Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001795
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001796
1797Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1798 int argc, Object*** argv,
1799 bool* caught_exception) {
1800 ASSERT(Top::context() == *Debug::debug_context());
1801
1802 // Create the execution state object.
1803 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1804 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1805 ASSERT(constructor->IsJSFunction());
1806 if (!constructor->IsJSFunction()) {
1807 *caught_exception = true;
1808 return Factory::undefined_value();
1809 }
1810 Handle<Object> js_object = Execution::TryCall(
1811 Handle<JSFunction>::cast(constructor),
1812 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1813 caught_exception);
1814 return js_object;
1815}
1816
1817
1818Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1819 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001820 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001821 const int argc = 1;
1822 Object** argv[argc] = { break_id.location() };
1823 return MakeJSObject(CStrVector("MakeExecutionState"),
1824 argc, argv, caught_exception);
1825}
1826
1827
1828Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1829 Handle<Object> break_points_hit,
1830 bool* caught_exception) {
1831 // Create the new break event object.
1832 const int argc = 2;
1833 Object** argv[argc] = { exec_state.location(),
1834 break_points_hit.location() };
1835 return MakeJSObject(CStrVector("MakeBreakEvent"),
1836 argc,
1837 argv,
1838 caught_exception);
1839}
1840
1841
1842Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1843 Handle<Object> exception,
1844 bool uncaught,
1845 bool* caught_exception) {
1846 // Create the new exception event object.
1847 const int argc = 3;
1848 Object** argv[argc] = { exec_state.location(),
1849 exception.location(),
1850 uncaught ? Factory::true_value().location() :
1851 Factory::false_value().location()};
1852 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1853 argc, argv, caught_exception);
1854}
1855
1856
1857Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1858 bool* caught_exception) {
1859 // Create the new function event object.
1860 const int argc = 1;
1861 Object** argv[argc] = { function.location() };
1862 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1863 argc, argv, caught_exception);
1864}
1865
1866
1867Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001868 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001869 bool* caught_exception) {
1870 // Create the compile event object.
1871 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001872 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001873 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001874 Object** argv[argc] = { exec_state.location(),
1875 script_wrapper.location(),
1876 before ? Factory::true_value().location() :
1877 Factory::false_value().location() };
1878
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001879 return MakeJSObject(CStrVector("MakeCompileEvent"),
1880 argc,
1881 argv,
1882 caught_exception);
1883}
1884
1885
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001886Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1887 bool* caught_exception) {
1888 // Create the script collected event object.
1889 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1890 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1891 const int argc = 2;
1892 Object** argv[argc] = { exec_state.location(), id_object.location() };
1893
1894 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1895 argc,
1896 argv,
1897 caught_exception);
1898}
1899
1900
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001901void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1902 HandleScope scope;
1903
1904 // Bail out based on state or if there is no listener for this event
1905 if (Debug::InDebugger()) return;
1906 if (!Debugger::EventActive(v8::Exception)) return;
1907
1908 // Bail out if exception breaks are not active
1909 if (uncaught) {
1910 // Uncaught exceptions are reported by either flags.
1911 if (!(Debug::break_on_uncaught_exception() ||
1912 Debug::break_on_exception())) return;
1913 } else {
1914 // Caught exceptions are reported is activated.
1915 if (!Debug::break_on_exception()) return;
1916 }
1917
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001918 // Enter the debugger.
1919 EnterDebugger debugger;
1920 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001921
1922 // Clear all current stepping setup.
1923 Debug::ClearStepping();
1924 // Create the event data object.
1925 bool caught_exception = false;
1926 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1927 Handle<Object> event_data;
1928 if (!caught_exception) {
1929 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1930 &caught_exception);
1931 }
1932 // Bail out and don't call debugger if exception.
1933 if (caught_exception) {
1934 return;
1935 }
1936
ager@chromium.org5ec48922009-05-05 07:25:34 +00001937 // Process debug event.
1938 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001939 // Return to continue execution from where the exception was thrown.
1940}
1941
1942
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001943void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1944 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001945 HandleScope scope;
1946
kasper.lund212ac232008-07-16 07:07:30 +00001947 // Debugger has already been entered by caller.
1948 ASSERT(Top::context() == *Debug::debug_context());
1949
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001950 // Bail out if there is no listener for this event
1951 if (!Debugger::EventActive(v8::Break)) return;
1952
1953 // Debugger must be entered in advance.
1954 ASSERT(Top::context() == *Debug::debug_context());
1955
1956 // Create the event data object.
1957 bool caught_exception = false;
1958 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1959 Handle<Object> event_data;
1960 if (!caught_exception) {
1961 event_data = MakeBreakEvent(exec_state, break_points_hit,
1962 &caught_exception);
1963 }
1964 // Bail out and don't call debugger if exception.
1965 if (caught_exception) {
1966 return;
1967 }
1968
ager@chromium.org5ec48922009-05-05 07:25:34 +00001969 // Process debug event.
1970 ProcessDebugEvent(v8::Break,
1971 Handle<JSObject>::cast(event_data),
1972 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001973}
1974
1975
1976void Debugger::OnBeforeCompile(Handle<Script> script) {
1977 HandleScope scope;
1978
1979 // Bail out based on state or if there is no listener for this event
1980 if (Debug::InDebugger()) return;
1981 if (compiling_natives()) return;
1982 if (!EventActive(v8::BeforeCompile)) return;
1983
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001984 // Enter the debugger.
1985 EnterDebugger debugger;
1986 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001987
1988 // Create the event data object.
1989 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001990 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001991 // Bail out and don't call debugger if exception.
1992 if (caught_exception) {
1993 return;
1994 }
1995
ager@chromium.org5ec48922009-05-05 07:25:34 +00001996 // Process debug event.
1997 ProcessDebugEvent(v8::BeforeCompile,
1998 Handle<JSObject>::cast(event_data),
1999 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002000}
2001
2002
2003// Handle debugger actions when a new script is compiled.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002004void Debugger::OnAfterCompile(Handle<Script> script,
2005 AfterCompileFlags after_compile_flags) {
kasper.lund212ac232008-07-16 07:07:30 +00002006 HandleScope scope;
2007
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002008 // Add the newly compiled script to the script cache.
2009 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002010
2011 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00002012 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002013
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002014 // No compile events while compiling natives.
2015 if (compiling_natives()) return;
2016
iposva@chromium.org245aa852009-02-10 00:49:54 +00002017 // Store whether in debugger before entering debugger.
2018 bool in_debugger = Debug::InDebugger();
2019
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002020 // Enter the debugger.
2021 EnterDebugger debugger;
2022 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002023
2024 // If debugging there might be script break points registered for this
2025 // script. Make sure that these break points are set.
2026
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00002027 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002028 Handle<Object> update_script_break_points =
2029 Handle<Object>(Debug::debug_context()->global()->GetProperty(
2030 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
2031 if (!update_script_break_points->IsJSFunction()) {
2032 return;
2033 }
2034 ASSERT(update_script_break_points->IsJSFunction());
2035
2036 // Wrap the script object in a proper JS object before passing it
2037 // to JavaScript.
2038 Handle<JSValue> wrapper = GetScriptWrapper(script);
2039
2040 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00002041 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002042 const int argc = 1;
2043 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2044 Handle<Object> result = Execution::TryCall(
2045 Handle<JSFunction>::cast(update_script_break_points),
2046 Top::builtins(), argc, argv,
2047 &caught_exception);
2048 if (caught_exception) {
2049 return;
2050 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002051 // Bail out based on state or if there is no listener for this event
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002052 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002053 if (!Debugger::EventActive(v8::AfterCompile)) return;
2054
2055 // Create the compile state object.
2056 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002057 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002058 &caught_exception);
2059 // Bail out and don't call debugger if exception.
2060 if (caught_exception) {
2061 return;
2062 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00002063 // Process debug event.
2064 ProcessDebugEvent(v8::AfterCompile,
2065 Handle<JSObject>::cast(event_data),
2066 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002067}
2068
2069
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002070void Debugger::OnScriptCollected(int id) {
2071 HandleScope scope;
2072
2073 // No more to do if not debugging.
2074 if (!IsDebuggerActive()) return;
2075 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2076
2077 // Enter the debugger.
2078 EnterDebugger debugger;
2079 if (debugger.FailedToEnter()) return;
2080
2081 // Create the script collected state object.
2082 bool caught_exception = false;
2083 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2084 &caught_exception);
2085 // Bail out and don't call debugger if exception.
2086 if (caught_exception) {
2087 return;
2088 }
2089
2090 // Process debug event.
2091 ProcessDebugEvent(v8::ScriptCollected,
2092 Handle<JSObject>::cast(event_data),
2093 true);
2094}
2095
2096
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002097void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002098 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002099 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002100 HandleScope scope;
2101
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002102 // Clear any pending debug break if this is a real break.
2103 if (!auto_continue) {
2104 Debug::clear_interrupt_pending(DEBUGBREAK);
2105 }
2106
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002107 // Create the execution state.
2108 bool caught_exception = false;
2109 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2110 if (caught_exception) {
2111 return;
2112 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002113 // First notify the message handler if any.
2114 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002115 NotifyMessageHandler(event,
2116 Handle<JSObject>::cast(exec_state),
2117 event_data,
2118 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002119 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002120 // Notify registered debug event listener. This can be either a C or a
2121 // JavaScript function.
2122 if (!event_listener_.is_null()) {
2123 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002124 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002125 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +00002126 v8::Debug::EventCallback2 callback =
2127 FUNCTION_CAST<v8::Debug::EventCallback2>(callback_obj->proxy());
2128 EventDetailsImpl event_details(
2129 event,
2130 Handle<JSObject>::cast(exec_state),
2131 event_data,
2132 event_listener_data_);
2133 callback(event_details);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002134 } else {
2135 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002136 ASSERT(event_listener_->IsJSFunction());
2137 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002138
2139 // Invoke the JavaScript debug event listener.
2140 const int argc = 4;
2141 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2142 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002143 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002144 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002145 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2146 argc, argv, &caught_exception);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002147 // Silently ignore exceptions from debug event listeners.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002148 }
2149 }
2150}
2151
2152
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00002153Handle<Context> Debugger::GetDebugContext() {
2154 never_unload_debugger_ = true;
2155 EnterDebugger debugger;
2156 return Debug::debug_context();
2157}
2158
2159
ager@chromium.org71daaf62009-04-01 07:22:49 +00002160void Debugger::UnloadDebugger() {
2161 // Make sure that there are no breakpoints left.
2162 Debug::ClearAllBreakPoints();
2163
2164 // Unload the debugger if feasible.
2165 if (!never_unload_debugger_) {
2166 Debug::Unload();
2167 }
2168
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002169 // Clear the flag indicating that the debugger should be unloaded.
2170 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002171}
2172
2173
ager@chromium.org41826e72009-03-30 13:30:57 +00002174void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002175 Handle<JSObject> exec_state,
2176 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002177 bool auto_continue) {
2178 HandleScope scope;
2179
2180 if (!Debug::Load()) return;
2181
2182 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002183 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002184 switch (event) {
2185 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002186 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002187 break;
2188 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002189 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002190 break;
2191 case v8::BeforeCompile:
2192 break;
2193 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002194 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002195 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002196 case v8::ScriptCollected:
2197 sendEventMessage = true;
2198 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002199 case v8::NewFunction:
2200 break;
2201 default:
2202 UNREACHABLE();
2203 }
2204
ager@chromium.org5ec48922009-05-05 07:25:34 +00002205 // The debug command interrupt flag might have been set when the command was
2206 // added. It should be enough to clear the flag only once while we are in the
2207 // debugger.
2208 ASSERT(Debug::InDebugger());
2209 StackGuard::Continue(DEBUGCOMMAND);
2210
2211 // Notify the debugger that a debug event has occurred unless auto continue is
2212 // active in which case no event is send.
2213 if (sendEventMessage) {
2214 MessageImpl message = MessageImpl::NewEvent(
2215 event,
2216 auto_continue,
2217 Handle<JSObject>::cast(exec_state),
2218 Handle<JSObject>::cast(event_data));
2219 InvokeMessageHandler(message);
2220 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002221
2222 // If auto continue don't make the event cause a break, but process messages
2223 // in the queue if any. For script collected events don't even process
2224 // messages in the queue as the execution state might not be what is expected
2225 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002226 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002227 return;
2228 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002229
ager@chromium.org41826e72009-03-30 13:30:57 +00002230 v8::TryCatch try_catch;
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002231
2232 // DebugCommandProcessor goes here.
2233 v8::Local<v8::Object> cmd_processor;
2234 {
2235 v8::Local<v8::Object> api_exec_state =
2236 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2237 v8::Local<v8::String> fun_name =
2238 v8::String::New("debugCommandProcessor");
2239 v8::Local<v8::Function> fun =
2240 v8::Function::Cast(*api_exec_state->Get(fun_name));
2241
2242 v8::Handle<v8::Boolean> running =
2243 auto_continue ? v8::True() : v8::False();
2244 static const int kArgc = 1;
2245 v8::Handle<Value> argv[kArgc] = { running };
2246 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2247 if (try_catch.HasCaught()) {
2248 PrintLn(try_catch.Exception());
2249 return;
2250 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002251 }
2252
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002253 bool running = auto_continue;
2254
ager@chromium.org41826e72009-03-30 13:30:57 +00002255 // Process requests from the debugger.
2256 while (true) {
2257 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002258 if (Debugger::host_dispatch_handler_) {
2259 // In case there is a host dispatch - do periodic dispatches.
2260 if (!command_received_->Wait(host_dispatch_micros_)) {
2261 // Timout expired, do the dispatch.
2262 Debugger::host_dispatch_handler_();
2263 continue;
2264 }
2265 } else {
2266 // In case there is no host dispatch - just wait.
2267 command_received_->Wait();
2268 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002269
ager@chromium.org41826e72009-03-30 13:30:57 +00002270 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002271 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002272 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002273 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002274 // Delete command text and user data.
2275 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002276 return;
2277 }
2278
ager@chromium.org41826e72009-03-30 13:30:57 +00002279 // Invoke JavaScript to process the debug request.
2280 v8::Local<v8::String> fun_name;
2281 v8::Local<v8::Function> fun;
2282 v8::Local<v8::Value> request;
2283 v8::TryCatch try_catch;
2284 fun_name = v8::String::New("processDebugRequest");
2285 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002286
2287 request = v8::String::New(command.text().start(),
2288 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002289 static const int kArgc = 1;
2290 v8::Handle<Value> argv[kArgc] = { request };
2291 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2292
2293 // Get the response.
2294 v8::Local<v8::String> response;
ager@chromium.org41826e72009-03-30 13:30:57 +00002295 if (!try_catch.HasCaught()) {
2296 // Get response string.
2297 if (!response_val->IsUndefined()) {
2298 response = v8::String::Cast(*response_val);
2299 } else {
2300 response = v8::String::New("");
2301 }
2302
2303 // Log the JSON request/response.
2304 if (FLAG_trace_debug_json) {
2305 PrintLn(request);
2306 PrintLn(response);
2307 }
2308
2309 // Get the running state.
2310 fun_name = v8::String::New("isRunning");
2311 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2312 static const int kArgc = 1;
2313 v8::Handle<Value> argv[kArgc] = { response };
2314 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2315 if (!try_catch.HasCaught()) {
2316 running = running_val->ToBoolean()->Value();
2317 }
2318 } else {
2319 // In case of failure the result text is the exception text.
2320 response = try_catch.Exception()->ToString();
2321 }
2322
ager@chromium.org41826e72009-03-30 13:30:57 +00002323 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002324 MessageImpl message = MessageImpl::NewResponse(
2325 event,
2326 running,
2327 Handle<JSObject>::cast(exec_state),
2328 Handle<JSObject>::cast(event_data),
2329 Handle<String>(Utils::OpenHandle(*response)),
2330 command.client_data());
2331 InvokeMessageHandler(message);
2332 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002333
2334 // Return from debug event processing if either the VM is put into the
2335 // runnning state (through a continue command) or auto continue is active
2336 // and there are no more commands queued.
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002337 if (running && !HasCommands()) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002338 return;
2339 }
2340 }
2341}
2342
2343
iposva@chromium.org245aa852009-02-10 00:49:54 +00002344void Debugger::SetEventListener(Handle<Object> callback,
2345 Handle<Object> data) {
2346 HandleScope scope;
2347
2348 // Clear the global handles for the event listener and the event listener data
2349 // object.
2350 if (!event_listener_.is_null()) {
2351 GlobalHandles::Destroy(
2352 reinterpret_cast<Object**>(event_listener_.location()));
2353 event_listener_ = Handle<Object>();
2354 }
2355 if (!event_listener_data_.is_null()) {
2356 GlobalHandles::Destroy(
2357 reinterpret_cast<Object**>(event_listener_data_.location()));
2358 event_listener_data_ = Handle<Object>();
2359 }
2360
2361 // If there is a new debug event listener register it together with its data
2362 // object.
2363 if (!callback->IsUndefined() && !callback->IsNull()) {
2364 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2365 if (data.is_null()) {
2366 data = Factory::undefined_value();
2367 }
2368 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2369 }
2370
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002371 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002372}
2373
2374
ager@chromium.org5ec48922009-05-05 07:25:34 +00002375void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002376 ScopedLock with(debugger_access_);
2377
ager@chromium.org381abbb2009-02-25 13:23:22 +00002378 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002379 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002380 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002381 // Send an empty command to the debugger if in a break to make JavaScript
2382 // run again if the debugger is closed.
2383 if (Debug::InDebugger()) {
2384 ProcessCommand(Vector<const uint16_t>::empty());
2385 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002386 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002387}
2388
2389
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002390void Debugger::ListenersChanged() {
2391 if (IsDebuggerActive()) {
2392 // Disable the compilation cache when the debugger is active.
2393 CompilationCache::Disable();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002394 debugger_unload_pending_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002395 } else {
2396 CompilationCache::Enable();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002397 // Unload the debugger if event listener and message handler cleared.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002398 // Schedule this for later, because we may be in non-V8 thread.
2399 debugger_unload_pending_ = true;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002400 }
2401}
2402
2403
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002404void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2405 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002406 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002407 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002408}
2409
2410
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002411void Debugger::SetDebugMessageDispatchHandler(
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002412 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2413 ScopedLock with(dispatch_handler_access_);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002414 debug_message_dispatch_handler_ = handler;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002415
2416 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2417 message_dispatch_helper_thread_ = new MessageDispatchHelperThread;
2418 message_dispatch_helper_thread_->Start();
2419 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002420}
2421
2422
ager@chromium.org41826e72009-03-30 13:30:57 +00002423// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002424// public API.
2425void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002426 ScopedLock with(debugger_access_);
2427
ager@chromium.org381abbb2009-02-25 13:23:22 +00002428 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002429 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002430 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002431}
2432
2433
2434// Puts a command coming from the public API on the queue. Creates
2435// a copy of the command string managed by the debugger. Up to this
2436// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002437// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002438void Debugger::ProcessCommand(Vector<const uint16_t> command,
2439 v8::Debug::ClientData* client_data) {
2440 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002441 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002442 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002443 command.length()),
2444 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002445 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002446 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002447 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002448
2449 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002450 if (!Debug::InDebugger()) {
2451 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002452 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002453
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002454 MessageDispatchHelperThread* dispatch_thread;
2455 {
2456 ScopedLock with(dispatch_handler_access_);
2457 dispatch_thread = message_dispatch_helper_thread_;
2458 }
2459
2460 if (dispatch_thread == NULL) {
2461 CallMessageDispatchHandler();
2462 } else {
2463 dispatch_thread->Schedule();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002464 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002465}
2466
2467
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002468bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002469 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002470}
2471
2472
ager@chromium.org71daaf62009-04-01 07:22:49 +00002473bool Debugger::IsDebuggerActive() {
2474 ScopedLock with(debugger_access_);
2475
2476 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002477}
2478
2479
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002480Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2481 Handle<Object> data,
2482 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002483 // When calling functions in the debugger prevent it from beeing unloaded.
2484 Debugger::never_unload_debugger_ = true;
2485
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002486 // Enter the debugger.
2487 EnterDebugger debugger;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00002488 if (debugger.FailedToEnter()) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002489 return Factory::undefined_value();
2490 }
2491
2492 // Create the execution state.
2493 bool caught_exception = false;
2494 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2495 if (caught_exception) {
2496 return Factory::undefined_value();
2497 }
2498
2499 static const int kArgc = 2;
2500 Object** argv[kArgc] = { exec_state.location(), data.location() };
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00002501 Handle<Object> result = Execution::Call(
2502 fun,
2503 Handle<Object>(Debug::debug_context_->global_proxy()),
2504 kArgc,
2505 argv,
2506 pending_exception);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002507 return result;
2508}
2509
2510
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002511static void StubMessageHandler2(const v8::Debug::Message& message) {
2512 // Simply ignore message.
2513}
2514
2515
2516bool Debugger::StartAgent(const char* name, int port,
2517 bool wait_for_connection) {
2518 if (wait_for_connection) {
2519 // Suspend V8 if it is already running or set V8 to suspend whenever
2520 // it starts.
2521 // Provide stub message handler; V8 auto-continues each suspend
2522 // when there is no message handler; we doesn't need it.
2523 // Once become suspended, V8 will stay so indefinitely long, until remote
2524 // debugger connects and issues "continue" command.
2525 Debugger::message_handler_ = StubMessageHandler2;
2526 v8::Debug::DebugBreak();
2527 }
2528
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002529 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002530 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002531 agent_->Start();
2532 return true;
2533 }
2534
2535 return false;
2536}
2537
2538
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002539void Debugger::StopAgent() {
2540 if (agent_ != NULL) {
2541 agent_->Shutdown();
2542 agent_->Join();
2543 delete agent_;
2544 agent_ = NULL;
2545 }
2546}
2547
2548
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002549void Debugger::WaitForAgent() {
2550 if (agent_ != NULL)
2551 agent_->WaitUntilListening();
2552}
2553
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002554
2555void Debugger::CallMessageDispatchHandler() {
2556 v8::Debug::DebugMessageDispatchHandler handler;
2557 {
2558 ScopedLock with(dispatch_handler_access_);
2559 handler = Debugger::debug_message_dispatch_handler_;
2560 }
2561 if (handler != NULL) {
2562 handler();
2563 }
2564}
2565
2566
ager@chromium.org5ec48922009-05-05 07:25:34 +00002567MessageImpl MessageImpl::NewEvent(DebugEvent event,
2568 bool running,
2569 Handle<JSObject> exec_state,
2570 Handle<JSObject> event_data) {
2571 MessageImpl message(true, event, running,
2572 exec_state, event_data, Handle<String>(), NULL);
2573 return message;
2574}
2575
2576
2577MessageImpl MessageImpl::NewResponse(DebugEvent event,
2578 bool running,
2579 Handle<JSObject> exec_state,
2580 Handle<JSObject> event_data,
2581 Handle<String> response_json,
2582 v8::Debug::ClientData* client_data) {
2583 MessageImpl message(false, event, running,
2584 exec_state, event_data, response_json, client_data);
2585 return message;
2586}
2587
2588
2589MessageImpl::MessageImpl(bool is_event,
2590 DebugEvent event,
2591 bool running,
2592 Handle<JSObject> exec_state,
2593 Handle<JSObject> event_data,
2594 Handle<String> response_json,
2595 v8::Debug::ClientData* client_data)
2596 : is_event_(is_event),
2597 event_(event),
2598 running_(running),
2599 exec_state_(exec_state),
2600 event_data_(event_data),
2601 response_json_(response_json),
2602 client_data_(client_data) {}
2603
2604
2605bool MessageImpl::IsEvent() const {
2606 return is_event_;
2607}
2608
2609
2610bool MessageImpl::IsResponse() const {
2611 return !is_event_;
2612}
2613
2614
2615DebugEvent MessageImpl::GetEvent() const {
2616 return event_;
2617}
2618
2619
2620bool MessageImpl::WillStartRunning() const {
2621 return running_;
2622}
2623
2624
2625v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2626 return v8::Utils::ToLocal(exec_state_);
2627}
2628
2629
2630v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2631 return v8::Utils::ToLocal(event_data_);
2632}
2633
2634
2635v8::Handle<v8::String> MessageImpl::GetJSON() const {
2636 v8::HandleScope scope;
2637
2638 if (IsEvent()) {
2639 // Call toJSONProtocol on the debug event object.
2640 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2641 if (!fun->IsJSFunction()) {
2642 return v8::Handle<v8::String>();
2643 }
2644 bool caught_exception;
2645 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2646 event_data_,
2647 0, NULL, &caught_exception);
2648 if (caught_exception || !json->IsString()) {
2649 return v8::Handle<v8::String>();
2650 }
2651 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2652 } else {
2653 return v8::Utils::ToLocal(response_json_);
2654 }
2655}
2656
2657
2658v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +00002659 v8::Handle<v8::Context> context = GetDebugEventContext();
2660 // Top::context() may be NULL when "script collected" event occures.
2661 ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
2662 return GetDebugEventContext();
ager@chromium.org5ec48922009-05-05 07:25:34 +00002663}
2664
2665
2666v8::Debug::ClientData* MessageImpl::GetClientData() const {
2667 return client_data_;
2668}
2669
2670
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +00002671EventDetailsImpl::EventDetailsImpl(DebugEvent event,
2672 Handle<JSObject> exec_state,
2673 Handle<JSObject> event_data,
2674 Handle<Object> callback_data)
2675 : event_(event),
2676 exec_state_(exec_state),
2677 event_data_(event_data),
2678 callback_data_(callback_data) {}
2679
2680
2681DebugEvent EventDetailsImpl::GetEvent() const {
2682 return event_;
2683}
2684
2685
2686v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
2687 return v8::Utils::ToLocal(exec_state_);
2688}
2689
2690
2691v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
2692 return v8::Utils::ToLocal(event_data_);
2693}
2694
2695
2696v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
2697 return GetDebugEventContext();
2698}
2699
2700
2701v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
2702 return v8::Utils::ToLocal(callback_data_);
2703}
2704
2705
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002706CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2707 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002708}
2709
2710
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002711CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2712 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002713 : text_(text),
2714 client_data_(data) {
2715}
2716
2717
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002718CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002719}
2720
2721
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002722void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002723 text_.Dispose();
2724 delete client_data_;
2725 client_data_ = NULL;
2726}
2727
2728
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002729CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2730 v8::Debug::ClientData* data) {
2731 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002732}
2733
2734
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002735CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2736 size_(size) {
2737 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002738}
2739
2740
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002741CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002742 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002743 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002744 m.Dispose();
2745 }
kasper.lund7276f142008-07-30 08:49:36 +00002746 DeleteArray(messages_);
2747}
2748
2749
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002750CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002751 ASSERT(!IsEmpty());
2752 int result = start_;
2753 start_ = (start_ + 1) % size_;
2754 return messages_[result];
2755}
2756
2757
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002758void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002759 if ((end_ + 1) % size_ == start_) {
2760 Expand();
2761 }
2762 messages_[end_] = message;
2763 end_ = (end_ + 1) % size_;
2764}
2765
2766
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002767void CommandMessageQueue::Expand() {
2768 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002769 while (!IsEmpty()) {
2770 new_queue.Put(Get());
2771 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002772 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002773 *this = new_queue;
2774 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002775 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2776 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002777 // Automatic destructor called on new_queue, freeing array_to_free.
2778}
2779
2780
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002781LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2782 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002783 lock_ = OS::CreateMutex();
2784}
2785
2786
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002787LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002788 delete lock_;
2789}
2790
2791
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002792bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002793 ScopedLock sl(lock_);
2794 return queue_.IsEmpty();
2795}
2796
2797
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002798CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002799 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002800 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002801 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002802 return result;
2803}
2804
2805
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002806void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002807 ScopedLock sl(lock_);
2808 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002809 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002810}
2811
2812
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002813void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002814 ScopedLock sl(lock_);
2815 queue_.Clear();
2816}
2817
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002818
2819MessageDispatchHelperThread::MessageDispatchHelperThread()
2820 : sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
2821 already_signalled_(false) {
2822}
2823
2824
2825MessageDispatchHelperThread::~MessageDispatchHelperThread() {
2826 delete mutex_;
2827 delete sem_;
2828}
2829
2830
2831void MessageDispatchHelperThread::Schedule() {
2832 {
2833 ScopedLock lock(mutex_);
2834 if (already_signalled_) {
2835 return;
2836 }
2837 already_signalled_ = true;
2838 }
2839 sem_->Signal();
2840}
2841
2842
2843void MessageDispatchHelperThread::Run() {
2844 while (true) {
2845 sem_->Wait();
2846 {
2847 ScopedLock lock(mutex_);
2848 already_signalled_ = false;
2849 }
2850 {
2851 Locker locker;
2852 Debugger::CallMessageDispatchHandler();
2853 }
2854 }
2855}
2856
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002857#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002858
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002859} } // namespace v8::internal