blob: ca20a65b65200759cd065773365a04f776e30dfb [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
lrn@chromium.org1af7e1b2010-06-07 11:12:01 +000065static Handle<Code> ComputeCallDebugBreak(int argc, Code::Kind kind) {
66 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc, kind), Code);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000067}
68
69
lrn@chromium.org1af7e1b2010-06-07 11:12:01 +000070static Handle<Code> ComputeCallDebugPrepareStepIn(int argc, Code::Kind kind) {
71 CALL_HEAP_FUNCTION(
72 StubCache::ComputeCallDebugPrepareStepIn(argc, kind), Code);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000073}
74
75
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +000076static v8::Handle<v8::Context> GetDebugEventContext() {
77 Handle<Context> context = Debug::debugger_entry()->GetContext();
78 // Top::context() may have been NULL when "script collected" event occured.
79 if (*context == NULL) {
80 return v8::Local<v8::Context>();
81 }
82 Handle<Context> global_context(context->global_context());
83 return v8::Utils::ToLocal(global_context);
84}
85
86
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000087BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
88 BreakLocatorType type) {
89 debug_info_ = debug_info;
90 type_ = type;
91 reloc_iterator_ = NULL;
92 reloc_iterator_original_ = NULL;
93 Reset(); // Initialize the rest of the member variables.
94}
95
96
97BreakLocationIterator::~BreakLocationIterator() {
98 ASSERT(reloc_iterator_ != NULL);
99 ASSERT(reloc_iterator_original_ != NULL);
100 delete reloc_iterator_;
101 delete reloc_iterator_original_;
102}
103
104
105void BreakLocationIterator::Next() {
106 AssertNoAllocation nogc;
107 ASSERT(!RinfoDone());
108
109 // Iterate through reloc info for code and original code stopping at each
110 // breakable code target.
111 bool first = break_point_ == -1;
112 while (!RinfoDone()) {
113 if (!first) RinfoNext();
114 first = false;
115 if (RinfoDone()) return;
116
ager@chromium.org236ad962008-09-25 09:45:57 +0000117 // Whenever a statement position or (plain) position is passed update the
118 // current value of these.
119 if (RelocInfo::IsPosition(rmode())) {
120 if (RelocInfo::IsStatementPosition(rmode())) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000121 statement_position_ = static_cast<int>(
122 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000123 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000124 // Always update the position as we don't want that to be before the
125 // statement position.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000126 position_ = static_cast<int>(
127 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128 ASSERT(position_ >= 0);
129 ASSERT(statement_position_ >= 0);
130 }
131
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000132 if (IsDebugBreakSlot()) {
133 // There is always a possible break point at a debug break slot.
134 break_point_++;
135 return;
136 } else if (RelocInfo::IsCodeTarget(rmode())) {
137 // Check for breakable code target. Look in the original code as setting
138 // break points can cause the code targets in the running (debugged) code
139 // to be of a different kind than in the original code.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000140 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000141 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000142 if ((code->is_inline_cache_stub() &&
143 code->kind() != Code::BINARY_OP_IC) ||
144 RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000145 break_point_++;
146 return;
147 }
148 if (code->kind() == Code::STUB) {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000149 if (IsDebuggerStatement()) {
150 break_point_++;
151 return;
152 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000153 if (type_ == ALL_BREAK_LOCATIONS) {
154 if (Debug::IsBreakStub(code)) {
155 break_point_++;
156 return;
157 }
158 } else {
159 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
160 if (Debug::IsSourceBreakStub(code)) {
161 break_point_++;
162 return;
163 }
164 }
165 }
166 }
167
168 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000169 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000170 // Set the positions to the end of the function.
171 if (debug_info_->shared()->HasSourceCode()) {
172 position_ = debug_info_->shared()->end_position() -
173 debug_info_->shared()->start_position();
174 } else {
175 position_ = 0;
176 }
177 statement_position_ = position_;
178 break_point_++;
179 return;
180 }
181 }
182}
183
184
185void BreakLocationIterator::Next(int count) {
186 while (count > 0) {
187 Next();
188 count--;
189 }
190}
191
192
193// Find the break point closest to the supplied address.
194void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
195 // Run through all break points to locate the one closest to the address.
196 int closest_break_point = 0;
197 int distance = kMaxInt;
198 while (!Done()) {
199 // Check if this break point is closer that what was previously found.
200 if (this->pc() < pc && pc - this->pc() < distance) {
201 closest_break_point = break_point();
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000202 distance = static_cast<int>(pc - this->pc());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000203 // Check whether we can't get any closer.
204 if (distance == 0) break;
205 }
206 Next();
207 }
208
209 // Move to the break point found.
210 Reset();
211 Next(closest_break_point);
212}
213
214
215// Find the break point closest to the supplied source position.
216void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
217 // Run through all break points to locate the one closest to the source
218 // position.
219 int closest_break_point = 0;
220 int distance = kMaxInt;
221 while (!Done()) {
222 // Check if this break point is closer that what was previously found.
223 if (position <= statement_position() &&
224 statement_position() - position < distance) {
225 closest_break_point = break_point();
226 distance = statement_position() - position;
227 // Check whether we can't get any closer.
228 if (distance == 0) break;
229 }
230 Next();
231 }
232
233 // Move to the break point found.
234 Reset();
235 Next(closest_break_point);
236}
237
238
239void BreakLocationIterator::Reset() {
240 // Create relocation iterators for the two code objects.
241 if (reloc_iterator_ != NULL) delete reloc_iterator_;
242 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
243 reloc_iterator_ = new RelocIterator(debug_info_->code());
244 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
245
246 // Position at the first break point.
247 break_point_ = -1;
248 position_ = 1;
249 statement_position_ = 1;
250 Next();
251}
252
253
254bool BreakLocationIterator::Done() const {
255 return RinfoDone();
256}
257
258
259void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
260 // If there is not already a real break point here patch code with debug
261 // break.
262 if (!HasBreakPoint()) {
263 SetDebugBreak();
264 }
ager@chromium.orga1645e22009-09-09 19:27:10 +0000265 ASSERT(IsDebugBreak() || IsDebuggerStatement());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000266 // Set the break point information.
267 DebugInfo::SetBreakPoint(debug_info_, code_position(),
268 position(), statement_position(),
269 break_point_object);
270}
271
272
273void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
274 // Clear the break point information.
275 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
276 // If there are no more break points here remove the debug break.
277 if (!HasBreakPoint()) {
278 ClearDebugBreak();
279 ASSERT(!IsDebugBreak());
280 }
281}
282
283
284void BreakLocationIterator::SetOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000285 // Debugger statement always calls debugger. No need to modify it.
286 if (IsDebuggerStatement()) {
287 return;
288 }
289
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290 // If there is a real break point here no more to do.
291 if (HasBreakPoint()) {
292 ASSERT(IsDebugBreak());
293 return;
294 }
295
296 // Patch code with debug break.
297 SetDebugBreak();
298}
299
300
301void BreakLocationIterator::ClearOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000302 // Debugger statement always calls debugger. No need to modify it.
303 if (IsDebuggerStatement()) {
304 return;
305 }
306
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000307 // If there is a real break point here no more to do.
308 if (HasBreakPoint()) {
309 ASSERT(IsDebugBreak());
310 return;
311 }
312
313 // Patch code removing debug break.
314 ClearDebugBreak();
315 ASSERT(!IsDebugBreak());
316}
317
318
319void BreakLocationIterator::SetDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000320 // Debugger statement always calls debugger. No need to modify it.
321 if (IsDebuggerStatement()) {
322 return;
323 }
324
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000325 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000326 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000327 // function twice might happen when stepping in a function with an exception
328 // handler as the handler and the function is the same.
329 if (IsDebugBreak()) {
330 return;
331 }
332
ager@chromium.org236ad962008-09-25 09:45:57 +0000333 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000334 // Patch the frame exit code with a break point.
335 SetDebugBreakAtReturn();
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000336 } else if (IsDebugBreakSlot()) {
337 // Patch the code in the break slot.
338 SetDebugBreakAtSlot();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000340 // Patch the IC call.
341 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342 }
343 ASSERT(IsDebugBreak());
344}
345
346
347void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000348 // Debugger statement always calls debugger. No need to modify it.
349 if (IsDebuggerStatement()) {
350 return;
351 }
352
ager@chromium.org236ad962008-09-25 09:45:57 +0000353 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000354 // Restore the frame exit code.
355 ClearDebugBreakAtReturn();
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000356 } else if (IsDebugBreakSlot()) {
357 // Restore the code in the break slot.
358 ClearDebugBreakAtSlot();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000359 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000360 // Patch the IC call.
361 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000362 }
363 ASSERT(!IsDebugBreak());
364}
365
366
367void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000368 HandleScope scope;
369
ager@chromium.orga1645e22009-09-09 19:27:10 +0000370 // Step in can only be prepared if currently positioned on an IC call,
371 // construct call or CallFunction stub call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000372 Address target = rinfo()->target_address();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000373 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
lrn@chromium.org1af7e1b2010-06-07 11:12:01 +0000374 if (code->is_call_stub() || code->is_keyed_call_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000375 // Step in through IC call is handled by the runtime system. Therefore make
376 // sure that the any current IC is cleared and the runtime system is
377 // called. If the executing code has a debug break at the location change
378 // the call in the original code as it is the code there that will be
379 // executed in place of the debug break call.
lrn@chromium.org1af7e1b2010-06-07 11:12:01 +0000380 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count(),
381 code->kind());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000382 if (IsDebugBreak()) {
383 original_rinfo()->set_target_address(stub->entry());
384 } else {
385 rinfo()->set_target_address(stub->entry());
386 }
387 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000388#ifdef DEBUG
389 // All the following stuff is needed only for assertion checks so the code
390 // is wrapped in ifdef.
391 Handle<Code> maybe_call_function_stub = code;
392 if (IsDebugBreak()) {
393 Address original_target = original_rinfo()->target_address();
394 maybe_call_function_stub =
395 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
396 }
397 bool is_call_function_stub =
398 (maybe_call_function_stub->kind() == Code::STUB &&
399 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
400
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000401 // Step in through construct call requires no changes to the running code.
402 // Step in through getters/setters should already be prepared as well
403 // because caller of this function (Debug::PrepareStep) is expected to
404 // flood the top frame's function with one shot breakpoints.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000405 // Step in through CallFunction stub should also be prepared by caller of
406 // this function (Debug::PrepareStep) which should flood target function
407 // with breakpoints.
408 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
409 || is_call_function_stub);
410#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000411 }
412}
413
414
415// Check whether the break point is at a position which will exit the function.
416bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000417 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000418}
419
420
421bool BreakLocationIterator::HasBreakPoint() {
422 return debug_info_->HasBreakPoint(code_position());
423}
424
425
426// Check whether there is a debug break at the current position.
427bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000428 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000429 return IsDebugBreakAtReturn();
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000430 } else if (IsDebugBreakSlot()) {
431 return IsDebugBreakAtSlot();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000432 } else {
433 return Debug::IsDebugBreak(rinfo()->target_address());
434 }
435}
436
437
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000438void BreakLocationIterator::SetDebugBreakAtIC() {
439 // Patch the original code with the current address as the current address
440 // might have changed by the inline caching since the code was copied.
441 original_rinfo()->set_target_address(rinfo()->target_address());
442
443 RelocInfo::Mode mode = rmode();
444 if (RelocInfo::IsCodeTarget(mode)) {
445 Address target = rinfo()->target_address();
446 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
447
448 // Patch the code to invoke the builtin debug break function matching the
449 // calling convention used by the call site.
450 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
451 rinfo()->set_target_address(dbgbrk_code->entry());
452
453 // For stubs that refer back to an inlined version clear the cached map for
454 // the inlined case to always go through the IC. As long as the break point
455 // is set the patching performed by the runtime system will take place in
456 // the code copy and will therefore have no effect on the running code
457 // keeping it from using the inlined code.
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000458 if (code->is_keyed_load_stub()) {
459 KeyedLoadIC::ClearInlinedVersion(pc());
460 } else if (code->is_keyed_store_stub()) {
461 KeyedStoreIC::ClearInlinedVersion(pc());
462 } else if (code->is_load_stub()) {
463 LoadIC::ClearInlinedVersion(pc());
464 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000465 }
466}
467
468
469void BreakLocationIterator::ClearDebugBreakAtIC() {
470 // Patch the code to the original invoke.
471 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000472
473 RelocInfo::Mode mode = rmode();
474 if (RelocInfo::IsCodeTarget(mode)) {
475 Address target = original_rinfo()->target_address();
476 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
477
478 // Restore the inlined version of keyed stores to get back to the
479 // fast case. We need to patch back the keyed store because no
480 // patching happens when running normally. For keyed loads, the
481 // map check will get patched back when running normally after ICs
482 // have been cleared at GC.
483 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
484 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000485}
486
487
ager@chromium.orga1645e22009-09-09 19:27:10 +0000488bool BreakLocationIterator::IsDebuggerStatement() {
ager@chromium.org5c838252010-02-19 08:53:10 +0000489 return RelocInfo::DEBUG_BREAK == rmode();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000490}
491
492
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000493bool BreakLocationIterator::IsDebugBreakSlot() {
494 return RelocInfo::DEBUG_BREAK_SLOT == rmode();
495}
496
497
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000498Object* BreakLocationIterator::BreakPointObjects() {
499 return debug_info_->GetBreakPointObjects(code_position());
500}
501
502
ager@chromium.org381abbb2009-02-25 13:23:22 +0000503// Clear out all the debug break code. This is ONLY supposed to be used when
504// shutting down the debugger as it will leave the break point information in
505// DebugInfo even though the code is patched back to the non break point state.
506void BreakLocationIterator::ClearAllDebugBreak() {
507 while (!Done()) {
508 ClearDebugBreak();
509 Next();
510 }
511}
512
513
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514bool BreakLocationIterator::RinfoDone() const {
515 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
516 return reloc_iterator_->done();
517}
518
519
520void BreakLocationIterator::RinfoNext() {
521 reloc_iterator_->next();
522 reloc_iterator_original_->next();
523#ifdef DEBUG
524 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
525 if (!reloc_iterator_->done()) {
526 ASSERT(rmode() == original_rmode());
527 }
528#endif
529}
530
531
532bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000533ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000534DebugInfoListNode* Debug::debug_info_list_ = NULL;
535
536
537// Threading support.
538void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000539 thread_local_.break_count_ = 0;
540 thread_local_.break_id_ = 0;
541 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000542 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000543 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000544 thread_local_.step_count_ = 0;
545 thread_local_.last_fp_ = 0;
546 thread_local_.step_into_fp_ = 0;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000547 thread_local_.step_out_fp_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000548 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000549 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000550 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000551}
552
553
554JSCallerSavedBuffer Debug::registers_;
555Debug::ThreadLocal Debug::thread_local_;
556
557
558char* Debug::ArchiveDebug(char* storage) {
559 char* to = storage;
560 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
561 to += sizeof(ThreadLocal);
562 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
563 ThreadInit();
564 ASSERT(to <= storage + ArchiveSpacePerThread());
565 return storage + ArchiveSpacePerThread();
566}
567
568
569char* Debug::RestoreDebug(char* storage) {
570 char* from = storage;
571 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
572 from += sizeof(ThreadLocal);
573 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
574 ASSERT(from <= storage + ArchiveSpacePerThread());
575 return storage + ArchiveSpacePerThread();
576}
577
578
579int Debug::ArchiveSpacePerThread() {
580 return sizeof(ThreadLocal) + sizeof(registers_);
581}
582
583
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000584// Default break enabled.
585bool Debug::disable_break_ = false;
586
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000587// Default call debugger on uncaught exception.
588bool Debug::break_on_exception_ = false;
589bool Debug::break_on_uncaught_exception_ = true;
590
591Handle<Context> Debug::debug_context_ = Handle<Context>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000592Code* Debug::debug_break_return_ = NULL;
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000593Code* Debug::debug_break_slot_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000594
595
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000596void ScriptCache::Add(Handle<Script> script) {
597 // Create an entry in the hash map for the script.
598 int id = Smi::cast(script->id())->value();
599 HashMap::Entry* entry =
600 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
601 if (entry->value != NULL) {
602 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
603 return;
604 }
605
606 // Globalize the script object, make it weak and use the location of the
607 // global handle as the value in the hash map.
608 Handle<Script> script_ =
609 Handle<Script>::cast((GlobalHandles::Create(*script)));
610 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
611 this, ScriptCache::HandleWeakScript);
612 entry->value = script_.location();
613}
614
615
616Handle<FixedArray> ScriptCache::GetScripts() {
617 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
618 int count = 0;
619 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
620 ASSERT(entry->value != NULL);
621 if (entry->value != NULL) {
622 instances->set(count, *reinterpret_cast<Script**>(entry->value));
623 count++;
624 }
625 }
626 return instances;
627}
628
629
630void ScriptCache::ProcessCollectedScripts() {
631 for (int i = 0; i < collected_scripts_.length(); i++) {
632 Debugger::OnScriptCollected(collected_scripts_[i]);
633 }
634 collected_scripts_.Clear();
635}
636
637
638void ScriptCache::Clear() {
639 // Iterate the script cache to get rid of all the weak handles.
640 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
641 ASSERT(entry != NULL);
642 Object** location = reinterpret_cast<Object**>(entry->value);
643 ASSERT((*location)->IsScript());
644 GlobalHandles::ClearWeakness(location);
645 GlobalHandles::Destroy(location);
646 }
647 // Clear the content of the hash map.
648 HashMap::Clear();
649}
650
651
652void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
653 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
654 // Find the location of the global handle.
655 Script** location =
656 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
657 ASSERT((*location)->IsScript());
658
659 // Remove the entry from the cache.
660 int id = Smi::cast((*location)->id())->value();
661 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
662 script_cache->collected_scripts_.Add(id);
663
664 // Clear the weak handle.
665 obj.Dispose();
666 obj.Clear();
667}
668
669
670void Debug::Setup(bool create_heap_objects) {
671 ThreadInit();
672 if (create_heap_objects) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000673 // Get code to handle debug break on return.
674 debug_break_return_ =
675 Builtins::builtin(Builtins::Return_DebugBreak);
676 ASSERT(debug_break_return_->IsCode());
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000677 // Get code to handle debug break in debug break slots.
678 debug_break_slot_ =
679 Builtins::builtin(Builtins::Slot_DebugBreak);
680 ASSERT(debug_break_slot_->IsCode());
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000681 }
682}
683
684
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000685void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000686 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
687 RemoveDebugInfo(node->debug_info());
688#ifdef DEBUG
689 node = Debug::debug_info_list_;
690 while (node != NULL) {
691 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
692 node = node->next();
693 }
694#endif
695}
696
697
698DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
699 // Globalize the request debug info object and make it weak.
700 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
701 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
702 this, Debug::HandleWeakDebugInfo);
703}
704
705
706DebugInfoListNode::~DebugInfoListNode() {
707 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
708}
709
710
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000711bool Debug::CompileDebuggerScript(int index) {
712 HandleScope scope;
713
kasper.lund44510672008-07-25 07:37:58 +0000714 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000715 if (index == -1) {
716 return false;
717 }
kasper.lund44510672008-07-25 07:37:58 +0000718
719 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000720 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
721 Vector<const char> name = Natives::GetScriptName(index);
722 Handle<String> script_name = Factory::NewStringFromAscii(name);
723
724 // Compile the script.
725 bool allow_natives_syntax = FLAG_allow_natives_syntax;
726 FLAG_allow_natives_syntax = true;
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000727 Handle<SharedFunctionInfo> function_info;
728 function_info = Compiler::Compile(source_code,
729 script_name,
730 0, 0, NULL, NULL,
731 Handle<String>::null(),
732 NATIVES_CODE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000733 FLAG_allow_natives_syntax = allow_natives_syntax;
734
735 // Silently ignore stack overflows during compilation.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000736 if (function_info.is_null()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000737 ASSERT(Top::has_pending_exception());
738 Top::clear_pending_exception();
739 return false;
740 }
741
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000742 // Execute the shared function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000743 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000744 bool caught_exception = false;
745 Handle<JSFunction> function =
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000746 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
kasper.lund44510672008-07-25 07:37:58 +0000747 Handle<Object> result =
748 Execution::TryCall(function, Handle<Object>(context->global()),
749 0, NULL, &caught_exception);
750
751 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000752 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000753 Handle<Object> message = MessageHandler::MakeMessageObject(
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000754 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000755 Handle<String>());
756 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000757 return false;
758 }
759
kasper.lund44510672008-07-25 07:37:58 +0000760 // Mark this script as native and return successfully.
761 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000762 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000763 return true;
764}
765
766
767bool Debug::Load() {
768 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000769 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000770
kasper.lund44510672008-07-25 07:37:58 +0000771 // Bail out if we're already in the process of compiling the native
772 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000773 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
774 return false;
775 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000776
777 // Disable breakpoints and interrupts while compiling and running the
778 // debugger scripts including the context creation code.
779 DisableBreak disable(true);
780 PostponeInterruptsScope postpone;
781
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000782 // Create the debugger context.
783 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000784 Handle<Context> context =
785 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
786 v8::Handle<ObjectTemplate>(),
787 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000788
kasper.lund44510672008-07-25 07:37:58 +0000789 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000790 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000791 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000792
793 // Expose the builtins object in the debugger context.
794 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
795 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
796 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000797
798 // Compile the JavaScript for the debugger in the debugger context.
799 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000800 bool caught_exception =
801 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
802 !CompileDebuggerScript(Natives::GetIndex("debug"));
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000803
804 if (FLAG_enable_liveedit) {
805 caught_exception = caught_exception ||
806 !CompileDebuggerScript(Natives::GetIndex("liveedit"));
807 }
808
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000809 Debugger::set_compiling_natives(false);
810
mads.s.agercbaa0602008-08-14 13:41:48 +0000811 // Make sure we mark the debugger as not loading before we might
812 // return.
813 Debugger::set_loading_debugger(false);
814
kasper.lund44510672008-07-25 07:37:58 +0000815 // Check for caught exceptions.
816 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000817
818 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000819 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000820
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000821 return true;
822}
823
824
825void Debug::Unload() {
826 // Return debugger is not loaded.
827 if (!IsLoaded()) {
828 return;
829 }
830
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000831 // Clear the script cache.
832 DestroyScriptCache();
833
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000834 // Clear debugger context global handle.
835 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
836 debug_context_ = Handle<Context>();
837}
838
839
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000840// Set the flag indicating that preemption happened during debugging.
841void Debug::PreemptionWhileInDebugger() {
842 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000843 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000844}
845
846
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000847void Debug::Iterate(ObjectVisitor* v) {
vegorov@chromium.orgf8372902010-03-15 10:26:20 +0000848 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_return_)));
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +0000849 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_slot_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000850}
851
852
853Object* Debug::Break(Arguments args) {
854 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000855 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000856
ager@chromium.org357bf652010-04-12 11:30:10 +0000857 thread_local_.frames_are_dropped_ = false;
858
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000859 // Get the top-most JavaScript frame.
860 JavaScriptFrameIterator it;
861 JavaScriptFrame* frame = it.frame();
862
863 // Just continue if breaks are disabled or debugger cannot be loaded.
864 if (disable_break() || !Load()) {
865 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000866 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000867 }
868
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000869 // Enter the debugger.
870 EnterDebugger debugger;
871 if (debugger.FailedToEnter()) {
872 return Heap::undefined_value();
873 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000874
kasper.lund44510672008-07-25 07:37:58 +0000875 // Postpone interrupt during breakpoint processing.
876 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000877
878 // Get the debug info (create it if it does not exist).
879 Handle<SharedFunctionInfo> shared =
880 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
881 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
882
883 // Find the break point where execution has stopped.
884 BreakLocationIterator break_location_iterator(debug_info,
885 ALL_BREAK_LOCATIONS);
886 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
887
888 // Check whether step next reached a new statement.
889 if (!StepNextContinue(&break_location_iterator, frame)) {
890 // Decrease steps left if performing multiple steps.
891 if (thread_local_.step_count_ > 0) {
892 thread_local_.step_count_--;
893 }
894 }
895
896 // If there is one or more real break points check whether any of these are
897 // triggered.
898 Handle<Object> break_points_hit(Heap::undefined_value());
899 if (break_location_iterator.HasBreakPoint()) {
900 Handle<Object> break_point_objects =
901 Handle<Object>(break_location_iterator.BreakPointObjects());
902 break_points_hit = CheckBreakPoints(break_point_objects);
903 }
904
ager@chromium.orga1645e22009-09-09 19:27:10 +0000905 // If step out is active skip everything until the frame where we need to step
906 // out to is reached, unless real breakpoint is hit.
907 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
908 break_points_hit->IsUndefined() ) {
909 // Step count should always be 0 for StepOut.
910 ASSERT(thread_local_.step_count_ == 0);
911 } else if (!break_points_hit->IsUndefined() ||
912 (thread_local_.last_step_action_ != StepNone &&
913 thread_local_.step_count_ == 0)) {
914 // Notify debugger if a real break point is triggered or if performing
915 // single stepping with no more steps to perform. Otherwise do another step.
916
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000917 // Clear all current stepping setup.
918 ClearStepping();
919
920 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000921 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000922 } else if (thread_local_.last_step_action_ != StepNone) {
923 // Hold on to last step action as it is cleared by the call to
924 // ClearStepping.
925 StepAction step_action = thread_local_.last_step_action_;
926 int step_count = thread_local_.step_count_;
927
928 // Clear all current stepping setup.
929 ClearStepping();
930
931 // Set up for the remaining steps.
932 PrepareStep(step_action, step_count);
933 }
934
ager@chromium.org357bf652010-04-12 11:30:10 +0000935 if (thread_local_.frames_are_dropped_) {
936 // We must have been calling IC stub. Do not return there anymore.
937 Code* plain_return = Builtins::builtin(Builtins::PlainReturn_LiveEdit);
938 thread_local_.after_break_target_ = plain_return->entry();
939 } else {
940 SetAfterBreakTarget(frame);
941 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000942
mads.s.ager31e71382008-08-13 09:32:07 +0000943 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000944}
945
946
947// Check the break point objects for whether one or more are actually
948// triggered. This function returns a JSArray with the break point objects
949// which is triggered.
950Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
951 int break_points_hit_count = 0;
952 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
953
v8.team.kasperl727e9952008-09-02 14:56:44 +0000954 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000955 ASSERT(!break_point_objects->IsUndefined());
956 if (break_point_objects->IsFixedArray()) {
957 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
958 for (int i = 0; i < array->length(); i++) {
959 Handle<Object> o(array->get(i));
960 if (CheckBreakPoint(o)) {
961 break_points_hit->SetElement(break_points_hit_count++, *o);
962 }
963 }
964 } else {
965 if (CheckBreakPoint(break_point_objects)) {
966 break_points_hit->SetElement(break_points_hit_count++,
967 *break_point_objects);
968 }
969 }
970
971 // Return undefined if no break points where triggered.
972 if (break_points_hit_count == 0) {
973 return Factory::undefined_value();
974 }
975 return break_points_hit;
976}
977
978
979// Check whether a single break point object is triggered.
980bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000981 HandleScope scope;
982
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000983 // Ignore check if break point object is not a JSObject.
984 if (!break_point_object->IsJSObject()) return true;
985
986 // Get the function CheckBreakPoint (defined in debug.js).
987 Handle<JSFunction> check_break_point =
988 Handle<JSFunction>(JSFunction::cast(
989 debug_context()->global()->GetProperty(
990 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
991
992 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000993 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000994
995 // Call HandleBreakPointx.
996 bool caught_exception = false;
997 const int argc = 2;
998 Object** argv[argc] = {
999 break_id.location(),
1000 reinterpret_cast<Object**>(break_point_object.location())
1001 };
1002 Handle<Object> result = Execution::TryCall(check_break_point,
1003 Top::builtins(), argc, argv,
1004 &caught_exception);
1005
1006 // If exception or non boolean result handle as not triggered
1007 if (caught_exception || !result->IsBoolean()) {
1008 return false;
1009 }
1010
1011 // Return whether the break point is triggered.
1012 return *result == Heap::true_value();
1013}
1014
1015
1016// Check whether the function has debug information.
1017bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
1018 return !shared->debug_info()->IsUndefined();
1019}
1020
1021
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001022// Return the debug info for this function. EnsureDebugInfo must be called
1023// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001024Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001025 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001026 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
1027}
1028
1029
1030void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
1031 int source_position,
1032 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001033 HandleScope scope;
1034
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001035 if (!EnsureDebugInfo(shared)) {
1036 // Return if retrieving debug info failed.
1037 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001038 }
1039
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001040 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001041 // Source positions starts with zero.
1042 ASSERT(source_position >= 0);
1043
1044 // Find the break point and change it.
1045 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1046 it.FindBreakLocationFromPosition(source_position);
1047 it.SetBreakPoint(break_point_object);
1048
1049 // At least one active break point now.
1050 ASSERT(debug_info->GetBreakPointCount() > 0);
1051}
1052
1053
1054void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001055 HandleScope scope;
1056
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001057 DebugInfoListNode* node = debug_info_list_;
1058 while (node != NULL) {
1059 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1060 break_point_object);
1061 if (!result->IsUndefined()) {
1062 // Get information in the break point.
1063 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1064 Handle<DebugInfo> debug_info = node->debug_info();
1065 Handle<SharedFunctionInfo> shared(debug_info->shared());
1066 int source_position = break_point_info->statement_position()->value();
1067
1068 // Source positions starts with zero.
1069 ASSERT(source_position >= 0);
1070
1071 // Find the break point and clear it.
1072 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1073 it.FindBreakLocationFromPosition(source_position);
1074 it.ClearBreakPoint(break_point_object);
1075
1076 // If there are no more break points left remove the debug info for this
1077 // function.
1078 if (debug_info->GetBreakPointCount() == 0) {
1079 RemoveDebugInfo(debug_info);
1080 }
1081
1082 return;
1083 }
1084 node = node->next();
1085 }
1086}
1087
1088
ager@chromium.org381abbb2009-02-25 13:23:22 +00001089void Debug::ClearAllBreakPoints() {
1090 DebugInfoListNode* node = debug_info_list_;
1091 while (node != NULL) {
1092 // Remove all debug break code.
1093 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1094 it.ClearAllDebugBreak();
1095 node = node->next();
1096 }
1097
1098 // Remove all debug info.
1099 while (debug_info_list_ != NULL) {
1100 RemoveDebugInfo(debug_info_list_->debug_info());
1101 }
1102}
1103
1104
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001105void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001106 // Make sure the function has setup the debug info.
1107 if (!EnsureDebugInfo(shared)) {
1108 // Return if we failed to retrieve the debug info.
1109 return;
1110 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001111
1112 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001113 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001114 while (!it.Done()) {
1115 it.SetOneShot();
1116 it.Next();
1117 }
1118}
1119
1120
1121void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001122 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001123 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001124 if (id == StackFrame::NO_ID) {
1125 // If there is no JavaScript stack don't do anything.
1126 return;
1127 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001128 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1129 JavaScriptFrame* frame = it.frame();
1130 if (frame->HasHandler()) {
1131 Handle<SharedFunctionInfo> shared =
1132 Handle<SharedFunctionInfo>(
1133 JSFunction::cast(frame->function())->shared());
1134 // Flood the function with the catch block with break points
1135 FloodWithOneShot(shared);
1136 return;
1137 }
1138 }
1139}
1140
1141
1142void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1143 if (type == BreakUncaughtException) {
1144 break_on_uncaught_exception_ = enable;
1145 } else {
1146 break_on_exception_ = enable;
1147 }
1148}
1149
1150
1151void Debug::PrepareStep(StepAction step_action, int step_count) {
1152 HandleScope scope;
1153 ASSERT(Debug::InDebugger());
1154
1155 // Remember this step action and count.
1156 thread_local_.last_step_action_ = step_action;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001157 if (step_action == StepOut) {
1158 // For step out target frame will be found on the stack so there is no need
1159 // to set step counter for it. It's expected to always be 0 for StepOut.
1160 thread_local_.step_count_ = 0;
1161 } else {
1162 thread_local_.step_count_ = step_count;
1163 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001164
1165 // Get the frame where the execution has stopped and skip the debug frame if
1166 // any. The debug frame will only be present if execution was stopped due to
1167 // hitting a break point. In other situations (e.g. unhandled exception) the
1168 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001169 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001170 if (id == StackFrame::NO_ID) {
1171 // If there is no JavaScript stack don't do anything.
1172 return;
1173 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001174 JavaScriptFrameIterator frames_it(id);
1175 JavaScriptFrame* frame = frames_it.frame();
1176
1177 // First of all ensure there is one-shot break points in the top handler
1178 // if any.
1179 FloodHandlerWithOneShot();
1180
1181 // If the function on the top frame is unresolved perform step out. This will
1182 // be the case when calling unknown functions and having the debugger stopped
1183 // in an unhandled exception.
1184 if (!frame->function()->IsJSFunction()) {
1185 // Step out: Find the calling JavaScript frame and flood it with
1186 // breakpoints.
1187 frames_it.Advance();
1188 // Fill the function to return to with one-shot break points.
1189 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1190 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1191 return;
1192 }
1193
1194 // Get the debug info (create it if it does not exist).
1195 Handle<SharedFunctionInfo> shared =
1196 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001197 if (!EnsureDebugInfo(shared)) {
1198 // Return if ensuring debug info failed.
1199 return;
1200 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001201 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1202
1203 // Find the break location where execution has stopped.
1204 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1205 it.FindBreakLocationFromAddress(frame->pc());
1206
1207 // Compute whether or not the target is a call target.
1208 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001209 bool is_load_or_store = false;
1210 bool is_inline_cache_stub = false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001211 Handle<Code> call_function_stub;
ager@chromium.org236ad962008-09-25 09:45:57 +00001212 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001213 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001214 Code* code = Code::GetCodeFromTargetAddress(target);
lrn@chromium.org1af7e1b2010-06-07 11:12:01 +00001215 if (code->is_call_stub() || code->is_keyed_call_stub()) {
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001216 is_call_target = true;
1217 }
1218 if (code->is_inline_cache_stub()) {
1219 is_inline_cache_stub = true;
1220 is_load_or_store = !is_call_target;
1221 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001222
1223 // Check if target code is CallFunction stub.
1224 Code* maybe_call_function_stub = code;
1225 // If there is a breakpoint at this line look at the original code to
1226 // check if it is a CallFunction stub.
1227 if (it.IsDebugBreak()) {
1228 Address original_target = it.original_rinfo()->target_address();
1229 maybe_call_function_stub =
1230 Code::GetCodeFromTargetAddress(original_target);
1231 }
1232 if (maybe_call_function_stub->kind() == Code::STUB &&
1233 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1234 // Save reference to the code as we may need it to find out arguments
1235 // count for 'step in' later.
1236 call_function_stub = Handle<Code>(maybe_call_function_stub);
1237 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001238 }
1239
v8.team.kasperl727e9952008-09-02 14:56:44 +00001240 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001241 if (it.IsExit() || step_action == StepOut) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001242 if (step_action == StepOut) {
1243 // Skip step_count frames starting with the current one.
1244 while (step_count-- > 0 && !frames_it.done()) {
1245 frames_it.Advance();
1246 }
1247 } else {
1248 ASSERT(it.IsExit());
1249 frames_it.Advance();
1250 }
1251 // Skip builtin functions on the stack.
1252 while (!frames_it.done() &&
1253 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1254 frames_it.Advance();
1255 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001256 // Step out: If there is a JavaScript caller frame, we need to
1257 // flood it with breakpoints.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001258 if (!frames_it.done()) {
1259 // Fill the function to return to with one-shot break points.
1260 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1261 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001262 // Set target frame pointer.
1263 ActivateStepOut(frames_it.frame());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001264 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001265 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1266 !call_function_stub.is_null())
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001267 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001268 // Step next or step min.
1269
1270 // Fill the current function with one-shot break points.
1271 FloodWithOneShot(shared);
1272
1273 // Remember source position and frame to handle step next.
1274 thread_local_.last_statement_position_ =
1275 debug_info->code()->SourceStatementPosition(frame->pc());
1276 thread_local_.last_fp_ = frame->fp();
1277 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001278 // If it's CallFunction stub ensure target function is compiled and flood
1279 // it with one shot breakpoints.
1280 if (!call_function_stub.is_null()) {
1281 // Find out number of arguments from the stub minor key.
1282 // Reverse lookup required as the minor key cannot be retrieved
1283 // from the code object.
1284 Handle<Object> obj(
1285 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1286 ASSERT(*obj != Heap::undefined_value());
1287 ASSERT(obj->IsSmi());
1288 // Get the STUB key and extract major and minor key.
1289 uint32_t key = Smi::cast(*obj)->value();
1290 // Argc in the stub is the number of arguments passed - not the
1291 // expected arguments of the called function.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001292 int call_function_arg_count =
1293 CallFunctionStub::ExtractArgcFromMinorKey(
1294 CodeStub::MinorKeyFromKey(key));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001295 ASSERT(call_function_stub->major_key() ==
1296 CodeStub::MajorKeyFromKey(key));
1297
1298 // Find target function on the expression stack.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001299 // Expression stack looks like this (top to bottom):
ager@chromium.orga1645e22009-09-09 19:27:10 +00001300 // argN
1301 // ...
1302 // arg0
1303 // Receiver
1304 // Function to call
1305 int expressions_count = frame->ComputeExpressionsCount();
1306 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1307 Object* fun = frame->GetExpression(
1308 expressions_count - 2 - call_function_arg_count);
1309 if (fun->IsJSFunction()) {
1310 Handle<JSFunction> js_function(JSFunction::cast(fun));
1311 // Don't step into builtins.
1312 if (!js_function->IsBuiltin()) {
1313 // It will also compile target function if it's not compiled yet.
1314 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1315 }
1316 }
1317 }
1318
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001319 // Fill the current function with one-shot break points even for step in on
1320 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001321 // which step in will not stop. It also prepares for stepping in
1322 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001323 FloodWithOneShot(shared);
1324
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001325 if (is_load_or_store) {
1326 // Remember source position and frame to handle step in getter/setter. If
1327 // there is a custom getter/setter it will be handled in
1328 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1329 // propagated on the next Debug::Break.
1330 thread_local_.last_statement_position_ =
1331 debug_info->code()->SourceStatementPosition(frame->pc());
1332 thread_local_.last_fp_ = frame->fp();
1333 }
1334
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001335 // Step in or Step in min
1336 it.PrepareStepIn();
1337 ActivateStepIn(frame);
1338 }
1339}
1340
1341
1342// Check whether the current debug break should be reported to the debugger. It
1343// is used to have step next and step in only report break back to the debugger
1344// if on a different frame or in a different statement. In some situations
1345// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001346// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001347// steps before reporting break back to the debugger.
1348bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1349 JavaScriptFrame* frame) {
1350 // If the step last action was step next or step in make sure that a new
1351 // statement is hit.
1352 if (thread_local_.last_step_action_ == StepNext ||
1353 thread_local_.last_step_action_ == StepIn) {
1354 // Never continue if returning from function.
1355 if (break_location_iterator->IsExit()) return false;
1356
1357 // Continue if we are still on the same frame and in the same statement.
1358 int current_statement_position =
1359 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1360 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001361 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001362 }
1363
1364 // No step next action - don't continue.
1365 return false;
1366}
1367
1368
1369// Check whether the code object at the specified address is a debug break code
1370// object.
1371bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001372 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001373 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374}
1375
1376
1377// Check whether a code stub with the specified major key is a possible break
1378// point location when looking for source break locations.
1379bool Debug::IsSourceBreakStub(Code* code) {
1380 CodeStub::Major major_key = code->major_key();
1381 return major_key == CodeStub::CallFunction;
1382}
1383
1384
1385// Check whether a code stub with the specified major key is a possible break
1386// location.
1387bool Debug::IsBreakStub(Code* code) {
1388 CodeStub::Major major_key = code->major_key();
1389 return major_key == CodeStub::CallFunction ||
1390 major_key == CodeStub::StackCheck;
1391}
1392
1393
1394// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001395Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001396 // Find the builtin debug break function matching the calling convention
1397 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001398 if (code->is_inline_cache_stub()) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001399 switch (code->kind()) {
1400 case Code::CALL_IC:
lrn@chromium.org1af7e1b2010-06-07 11:12:01 +00001401 case Code::KEYED_CALL_IC:
1402 return ComputeCallDebugBreak(code->arguments_count(), code->kind());
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001403
1404 case Code::LOAD_IC:
1405 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1406
1407 case Code::STORE_IC:
1408 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1409
1410 case Code::KEYED_LOAD_IC:
1411 return Handle<Code>(
1412 Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1413
1414 case Code::KEYED_STORE_IC:
1415 return Handle<Code>(
1416 Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1417
1418 default:
1419 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420 }
1421 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001422 if (RelocInfo::IsConstructCall(mode)) {
1423 Handle<Code> result =
1424 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1425 return result;
1426 }
1427 if (code->kind() == Code::STUB) {
1428 ASSERT(code->major_key() == CodeStub::CallFunction ||
1429 code->major_key() == CodeStub::StackCheck);
1430 Handle<Code> result =
1431 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1432 return result;
1433 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001434
1435 UNREACHABLE();
1436 return Handle<Code>::null();
1437}
1438
1439
1440// Simple function for returning the source positions for active break points.
1441Handle<Object> Debug::GetSourceBreakLocations(
1442 Handle<SharedFunctionInfo> shared) {
1443 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1444 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1445 if (debug_info->GetBreakPointCount() == 0) {
1446 return Handle<Object>(Heap::undefined_value());
1447 }
1448 Handle<FixedArray> locations =
1449 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1450 int count = 0;
1451 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1452 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1453 BreakPointInfo* break_point_info =
1454 BreakPointInfo::cast(debug_info->break_points()->get(i));
1455 if (break_point_info->GetBreakPointCount() > 0) {
1456 locations->set(count++, break_point_info->statement_position());
1457 }
1458 }
1459 }
1460 return locations;
1461}
1462
1463
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001464void Debug::NewBreak(StackFrame::Id break_frame_id) {
1465 thread_local_.break_frame_id_ = break_frame_id;
1466 thread_local_.break_id_ = ++thread_local_.break_count_;
1467}
1468
1469
1470void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1471 thread_local_.break_frame_id_ = break_frame_id;
1472 thread_local_.break_id_ = break_id;
1473}
1474
1475
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001476// Handle stepping into a function.
1477void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001478 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001479 Address fp,
1480 bool is_constructor) {
1481 // If the frame pointer is not supplied by the caller find it.
1482 if (fp == 0) {
1483 StackFrameIterator it;
1484 it.Advance();
1485 // For constructor functions skip another frame.
1486 if (is_constructor) {
1487 ASSERT(it.frame()->is_construct());
1488 it.Advance();
1489 }
1490 fp = it.frame()->fp();
1491 }
1492
1493 // Flood the function with one-shot break points if it is called from where
1494 // step into was requested.
1495 if (fp == Debug::step_in_fp()) {
1496 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001497 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001498 if (function->shared()->code() ==
1499 Builtins::builtin(Builtins::FunctionApply) ||
1500 function->shared()->code() ==
1501 Builtins::builtin(Builtins::FunctionCall)) {
1502 // Handle function.apply and function.call separately to flood the
1503 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001504 // Builtins::FunctionCall. The receiver of call/apply is the target
1505 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001506 if (!holder.is_null() && holder->IsJSFunction() &&
1507 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001508 Handle<SharedFunctionInfo> shared_info(
1509 JSFunction::cast(*holder)->shared());
1510 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001511 }
1512 } else {
1513 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1514 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001515 }
1516 }
1517}
1518
1519
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001520void Debug::ClearStepping() {
1521 // Clear the various stepping setup.
1522 ClearOneShot();
1523 ClearStepIn();
ager@chromium.orga1645e22009-09-09 19:27:10 +00001524 ClearStepOut();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001525 ClearStepNext();
1526
1527 // Clear multiple step counter.
1528 thread_local_.step_count_ = 0;
1529}
1530
1531// Clears all the one-shot break points that are currently set. Normally this
1532// function is called each time a break point is hit as one shot break points
1533// are used to support stepping.
1534void Debug::ClearOneShot() {
1535 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001536 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001537 // removed from the list.
1538
1539 DebugInfoListNode* node = debug_info_list_;
1540 while (node != NULL) {
1541 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1542 while (!it.Done()) {
1543 it.ClearOneShot();
1544 it.Next();
1545 }
1546 node = node->next();
1547 }
1548}
1549
1550
1551void Debug::ActivateStepIn(StackFrame* frame) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001552 ASSERT(!StepOutActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001553 thread_local_.step_into_fp_ = frame->fp();
1554}
1555
1556
1557void Debug::ClearStepIn() {
1558 thread_local_.step_into_fp_ = 0;
1559}
1560
1561
ager@chromium.orga1645e22009-09-09 19:27:10 +00001562void Debug::ActivateStepOut(StackFrame* frame) {
1563 ASSERT(!StepInActive());
1564 thread_local_.step_out_fp_ = frame->fp();
1565}
1566
1567
1568void Debug::ClearStepOut() {
1569 thread_local_.step_out_fp_ = 0;
1570}
1571
1572
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001573void Debug::ClearStepNext() {
1574 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001575 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001576 thread_local_.last_fp_ = 0;
1577}
1578
1579
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001580// Ensures the debug information is present for shared.
1581bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1582 // Return if we already have the debug info for shared.
1583 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001585 // Ensure shared in compiled. Return false if this failed.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001586 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001587
1588 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001589 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001590
1591 // Add debug info to the list.
1592 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1593 node->set_next(debug_info_list_);
1594 debug_info_list_ = node;
1595
1596 // Now there is at least one break point.
1597 has_break_points_ = true;
1598
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001599 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001600}
1601
1602
1603void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1604 ASSERT(debug_info_list_ != NULL);
1605 // Run through the debug info objects to find this one and remove it.
1606 DebugInfoListNode* prev = NULL;
1607 DebugInfoListNode* current = debug_info_list_;
1608 while (current != NULL) {
1609 if (*current->debug_info() == *debug_info) {
1610 // Unlink from list. If prev is NULL we are looking at the first element.
1611 if (prev == NULL) {
1612 debug_info_list_ = current->next();
1613 } else {
1614 prev->set_next(current->next());
1615 }
1616 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1617 delete current;
1618
1619 // If there are no more debug info objects there are not more break
1620 // points.
1621 has_break_points_ = debug_info_list_ != NULL;
1622
1623 return;
1624 }
1625 // Move to next in list.
1626 prev = current;
1627 current = current->next();
1628 }
1629 UNREACHABLE();
1630}
1631
1632
1633void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001634 HandleScope scope;
1635
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001636 // Get the executing function in which the debug break occurred.
1637 Handle<SharedFunctionInfo> shared =
1638 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001639 if (!EnsureDebugInfo(shared)) {
1640 // Return if we failed to retrieve the debug info.
1641 return;
1642 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001643 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1644 Handle<Code> code(debug_info->code());
1645 Handle<Code> original_code(debug_info->original_code());
1646#ifdef DEBUG
1647 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001648 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001649 ASSERT(frame_code.is_identical_to(code));
1650#endif
1651
1652 // Find the call address in the running code. This address holds the call to
1653 // either a DebugBreakXXX or to the debug break return entry code if the
1654 // break point is still active after processing the break point.
ager@chromium.org4af710e2009-09-15 12:20:11 +00001655 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001656
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001657 // Check if the location is at JS exit or debug break slot.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001658 bool at_js_return = false;
1659 bool break_at_js_return_active = false;
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001660 bool at_debug_break_slot = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001661 RelocIterator it(debug_info->code());
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001662 while (!it.done() && !at_js_return && !at_debug_break_slot) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001663 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001664 at_js_return = (it.rinfo()->pc() ==
1665 addr - Assembler::kPatchReturnSequenceAddressOffset);
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001666 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001667 }
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001668 if (RelocInfo::IsDebugBreakSlot(it.rinfo()->rmode())) {
1669 at_debug_break_slot = (it.rinfo()->pc() ==
1670 addr - Assembler::kPatchDebugBreakSlotAddressOffset);
1671 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001672 it.next();
1673 }
1674
1675 // Handle the jump to continue execution after break point depending on the
1676 // break location.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001677 if (at_js_return) {
1678 // If the break point as return is still active jump to the corresponding
1679 // place in the original code. If not the break point was removed during
1680 // break point processing.
1681 if (break_at_js_return_active) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001682 addr += original_code->instruction_start() - code->instruction_start();
1683 }
1684
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001685 // Move back to where the call instruction sequence started.
1686 thread_local_.after_break_target_ =
1687 addr - Assembler::kPatchReturnSequenceAddressOffset;
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001688 } else if (at_debug_break_slot) {
1689 // Address of where the debug break slot starts.
1690 addr = addr - Assembler::kPatchDebugBreakSlotAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001691
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001692 // Continue just after the slot.
1693 thread_local_.after_break_target_ = addr + Assembler::kDebugBreakSlotLength;
1694 } else if (IsDebugBreak(Assembler::target_address_at(addr))) {
1695 // We now know that there is still a debug break call at the target address,
1696 // so the break point is still there and the original code will hold the
1697 // address to jump to in order to complete the call which is replaced by a
1698 // call to DebugBreakXXX.
1699
1700 // Find the corresponding address in the original code.
1701 addr += original_code->instruction_start() - code->instruction_start();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001702
1703 // Install jump to the call address in the original code. This will be the
1704 // call which was overwritten by the call to DebugBreakXXX.
1705 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
vegorov@chromium.org2356e6f2010-06-09 09:38:56 +00001706 } else {
1707 // There is no longer a break point present. Don't try to look in the
1708 // original code as the running code will have the right address. This takes
1709 // care of the case where the last break point is removed from the function
1710 // and therefore no "original code" is available.
1711 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 }
1713}
1714
1715
ager@chromium.org357bf652010-04-12 11:30:10 +00001716void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id) {
1717 thread_local_.frames_are_dropped_ = true;
1718 thread_local_.break_frame_id_ = new_break_frame_id;
1719}
1720
1721
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722bool Debug::IsDebugGlobal(GlobalObject* global) {
1723 return IsLoaded() && global == Debug::debug_context()->global();
1724}
1725
1726
ager@chromium.org32912102009-01-16 10:38:43 +00001727void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001728 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001729 ASSERT(Top::context() == *Debug::debug_context());
1730
1731 // Clear the mirror cache.
1732 Handle<String> function_name =
1733 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1734 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1735 ASSERT(fun->IsJSFunction());
1736 bool caught_exception;
1737 Handle<Object> js_object = Execution::TryCall(
1738 Handle<JSFunction>::cast(fun),
1739 Handle<JSObject>(Debug::debug_context()->global()),
1740 0, NULL, &caught_exception);
1741}
1742
1743
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001744void Debug::CreateScriptCache() {
1745 HandleScope scope;
1746
1747 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1748 // rid of all the cached script wrappers and the second gets rid of the
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00001749 // scripts which are no longer referenced.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001750 Heap::CollectAllGarbage(false);
1751 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001752
1753 ASSERT(script_cache_ == NULL);
1754 script_cache_ = new ScriptCache();
1755
1756 // Scan heap for Script objects.
1757 int count = 0;
1758 HeapIterator iterator;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001759 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +00001760 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001761 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1762 count++;
1763 }
1764 }
1765}
1766
1767
1768void Debug::DestroyScriptCache() {
1769 // Get rid of the script cache if it was created.
1770 if (script_cache_ != NULL) {
1771 delete script_cache_;
1772 script_cache_ = NULL;
1773 }
1774}
1775
1776
1777void Debug::AddScriptToScriptCache(Handle<Script> script) {
1778 if (script_cache_ != NULL) {
1779 script_cache_->Add(script);
1780 }
1781}
1782
1783
1784Handle<FixedArray> Debug::GetLoadedScripts() {
1785 // Create and fill the script cache when the loaded scripts is requested for
1786 // the first time.
1787 if (script_cache_ == NULL) {
1788 CreateScriptCache();
1789 }
1790
1791 // If the script cache is not active just return an empty array.
1792 ASSERT(script_cache_ != NULL);
1793 if (script_cache_ == NULL) {
1794 Factory::NewFixedArray(0);
1795 }
1796
1797 // Perform GC to get unreferenced scripts evicted from the cache before
1798 // returning the content.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001799 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001800
1801 // Get the scripts from the cache.
1802 return script_cache_->GetScripts();
1803}
1804
1805
1806void Debug::AfterGarbageCollection() {
1807 // Generate events for collected scripts.
1808 if (script_cache_ != NULL) {
1809 script_cache_->ProcessCollectedScripts();
1810 }
1811}
1812
1813
ager@chromium.org71daaf62009-04-01 07:22:49 +00001814Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001815Handle<Object> Debugger::event_listener_ = Handle<Object>();
1816Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001817bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001818bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001819bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001820v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001821bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001822v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001823Mutex* Debugger::dispatch_handler_access_ = OS::CreateMutex();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001824v8::Debug::DebugMessageDispatchHandler
1825 Debugger::debug_message_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001826MessageDispatchHelperThread* Debugger::message_dispatch_helper_thread_ = NULL;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001827int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001828DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001829LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001830Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001831
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001832
1833Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1834 int argc, Object*** argv,
1835 bool* caught_exception) {
1836 ASSERT(Top::context() == *Debug::debug_context());
1837
1838 // Create the execution state object.
1839 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1840 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1841 ASSERT(constructor->IsJSFunction());
1842 if (!constructor->IsJSFunction()) {
1843 *caught_exception = true;
1844 return Factory::undefined_value();
1845 }
1846 Handle<Object> js_object = Execution::TryCall(
1847 Handle<JSFunction>::cast(constructor),
1848 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1849 caught_exception);
1850 return js_object;
1851}
1852
1853
1854Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1855 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001856 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001857 const int argc = 1;
1858 Object** argv[argc] = { break_id.location() };
1859 return MakeJSObject(CStrVector("MakeExecutionState"),
1860 argc, argv, caught_exception);
1861}
1862
1863
1864Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1865 Handle<Object> break_points_hit,
1866 bool* caught_exception) {
1867 // Create the new break event object.
1868 const int argc = 2;
1869 Object** argv[argc] = { exec_state.location(),
1870 break_points_hit.location() };
1871 return MakeJSObject(CStrVector("MakeBreakEvent"),
1872 argc,
1873 argv,
1874 caught_exception);
1875}
1876
1877
1878Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1879 Handle<Object> exception,
1880 bool uncaught,
1881 bool* caught_exception) {
1882 // Create the new exception event object.
1883 const int argc = 3;
1884 Object** argv[argc] = { exec_state.location(),
1885 exception.location(),
1886 uncaught ? Factory::true_value().location() :
1887 Factory::false_value().location()};
1888 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1889 argc, argv, caught_exception);
1890}
1891
1892
1893Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1894 bool* caught_exception) {
1895 // Create the new function event object.
1896 const int argc = 1;
1897 Object** argv[argc] = { function.location() };
1898 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1899 argc, argv, caught_exception);
1900}
1901
1902
1903Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001904 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001905 bool* caught_exception) {
1906 // Create the compile event object.
1907 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001908 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001909 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001910 Object** argv[argc] = { exec_state.location(),
1911 script_wrapper.location(),
1912 before ? Factory::true_value().location() :
1913 Factory::false_value().location() };
1914
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001915 return MakeJSObject(CStrVector("MakeCompileEvent"),
1916 argc,
1917 argv,
1918 caught_exception);
1919}
1920
1921
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001922Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1923 bool* caught_exception) {
1924 // Create the script collected event object.
1925 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1926 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1927 const int argc = 2;
1928 Object** argv[argc] = { exec_state.location(), id_object.location() };
1929
1930 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1931 argc,
1932 argv,
1933 caught_exception);
1934}
1935
1936
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001937void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1938 HandleScope scope;
1939
1940 // Bail out based on state or if there is no listener for this event
1941 if (Debug::InDebugger()) return;
1942 if (!Debugger::EventActive(v8::Exception)) return;
1943
1944 // Bail out if exception breaks are not active
1945 if (uncaught) {
1946 // Uncaught exceptions are reported by either flags.
1947 if (!(Debug::break_on_uncaught_exception() ||
1948 Debug::break_on_exception())) return;
1949 } else {
1950 // Caught exceptions are reported is activated.
1951 if (!Debug::break_on_exception()) return;
1952 }
1953
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001954 // Enter the debugger.
1955 EnterDebugger debugger;
1956 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001957
1958 // Clear all current stepping setup.
1959 Debug::ClearStepping();
1960 // Create the event data object.
1961 bool caught_exception = false;
1962 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1963 Handle<Object> event_data;
1964 if (!caught_exception) {
1965 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1966 &caught_exception);
1967 }
1968 // Bail out and don't call debugger if exception.
1969 if (caught_exception) {
1970 return;
1971 }
1972
ager@chromium.org5ec48922009-05-05 07:25:34 +00001973 // Process debug event.
1974 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001975 // Return to continue execution from where the exception was thrown.
1976}
1977
1978
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001979void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1980 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001981 HandleScope scope;
1982
kasper.lund212ac232008-07-16 07:07:30 +00001983 // Debugger has already been entered by caller.
1984 ASSERT(Top::context() == *Debug::debug_context());
1985
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001986 // Bail out if there is no listener for this event
1987 if (!Debugger::EventActive(v8::Break)) return;
1988
1989 // Debugger must be entered in advance.
1990 ASSERT(Top::context() == *Debug::debug_context());
1991
1992 // Create the event data object.
1993 bool caught_exception = false;
1994 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1995 Handle<Object> event_data;
1996 if (!caught_exception) {
1997 event_data = MakeBreakEvent(exec_state, break_points_hit,
1998 &caught_exception);
1999 }
2000 // Bail out and don't call debugger if exception.
2001 if (caught_exception) {
2002 return;
2003 }
2004
ager@chromium.org5ec48922009-05-05 07:25:34 +00002005 // Process debug event.
2006 ProcessDebugEvent(v8::Break,
2007 Handle<JSObject>::cast(event_data),
2008 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002009}
2010
2011
2012void Debugger::OnBeforeCompile(Handle<Script> script) {
2013 HandleScope scope;
2014
2015 // Bail out based on state or if there is no listener for this event
2016 if (Debug::InDebugger()) return;
2017 if (compiling_natives()) return;
2018 if (!EventActive(v8::BeforeCompile)) return;
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 // Create the event data object.
2025 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00002026 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002027 // Bail out and don't call debugger if exception.
2028 if (caught_exception) {
2029 return;
2030 }
2031
ager@chromium.org5ec48922009-05-05 07:25:34 +00002032 // Process debug event.
2033 ProcessDebugEvent(v8::BeforeCompile,
2034 Handle<JSObject>::cast(event_data),
2035 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002036}
2037
2038
2039// Handle debugger actions when a new script is compiled.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002040void Debugger::OnAfterCompile(Handle<Script> script,
2041 AfterCompileFlags after_compile_flags) {
kasper.lund212ac232008-07-16 07:07:30 +00002042 HandleScope scope;
2043
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002044 // Add the newly compiled script to the script cache.
2045 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002046
2047 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00002048 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002049
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002050 // No compile events while compiling natives.
2051 if (compiling_natives()) return;
2052
iposva@chromium.org245aa852009-02-10 00:49:54 +00002053 // Store whether in debugger before entering debugger.
2054 bool in_debugger = Debug::InDebugger();
2055
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002056 // Enter the debugger.
2057 EnterDebugger debugger;
2058 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002059
2060 // If debugging there might be script break points registered for this
2061 // script. Make sure that these break points are set.
2062
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00002063 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002064 Handle<Object> update_script_break_points =
2065 Handle<Object>(Debug::debug_context()->global()->GetProperty(
2066 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
2067 if (!update_script_break_points->IsJSFunction()) {
2068 return;
2069 }
2070 ASSERT(update_script_break_points->IsJSFunction());
2071
2072 // Wrap the script object in a proper JS object before passing it
2073 // to JavaScript.
2074 Handle<JSValue> wrapper = GetScriptWrapper(script);
2075
2076 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00002077 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002078 const int argc = 1;
2079 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2080 Handle<Object> result = Execution::TryCall(
2081 Handle<JSFunction>::cast(update_script_break_points),
2082 Top::builtins(), argc, argv,
2083 &caught_exception);
2084 if (caught_exception) {
2085 return;
2086 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002087 // Bail out based on state or if there is no listener for this event
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002088 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002089 if (!Debugger::EventActive(v8::AfterCompile)) return;
2090
2091 // Create the compile state object.
2092 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002093 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002094 &caught_exception);
2095 // Bail out and don't call debugger if exception.
2096 if (caught_exception) {
2097 return;
2098 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00002099 // Process debug event.
2100 ProcessDebugEvent(v8::AfterCompile,
2101 Handle<JSObject>::cast(event_data),
2102 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002103}
2104
2105
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002106void Debugger::OnScriptCollected(int id) {
2107 HandleScope scope;
2108
2109 // No more to do if not debugging.
2110 if (!IsDebuggerActive()) return;
2111 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2112
2113 // Enter the debugger.
2114 EnterDebugger debugger;
2115 if (debugger.FailedToEnter()) return;
2116
2117 // Create the script collected state object.
2118 bool caught_exception = false;
2119 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2120 &caught_exception);
2121 // Bail out and don't call debugger if exception.
2122 if (caught_exception) {
2123 return;
2124 }
2125
2126 // Process debug event.
2127 ProcessDebugEvent(v8::ScriptCollected,
2128 Handle<JSObject>::cast(event_data),
2129 true);
2130}
2131
2132
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002133void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002134 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002135 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002136 HandleScope scope;
2137
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002138 // Clear any pending debug break if this is a real break.
2139 if (!auto_continue) {
2140 Debug::clear_interrupt_pending(DEBUGBREAK);
2141 }
2142
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002143 // Create the execution state.
2144 bool caught_exception = false;
2145 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2146 if (caught_exception) {
2147 return;
2148 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002149 // First notify the message handler if any.
2150 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002151 NotifyMessageHandler(event,
2152 Handle<JSObject>::cast(exec_state),
2153 event_data,
2154 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002155 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002156 // Notify registered debug event listener. This can be either a C or a
2157 // JavaScript function.
2158 if (!event_listener_.is_null()) {
2159 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002160 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002161 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +00002162 v8::Debug::EventCallback2 callback =
2163 FUNCTION_CAST<v8::Debug::EventCallback2>(callback_obj->proxy());
2164 EventDetailsImpl event_details(
2165 event,
2166 Handle<JSObject>::cast(exec_state),
2167 event_data,
2168 event_listener_data_);
2169 callback(event_details);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002170 } else {
2171 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002172 ASSERT(event_listener_->IsJSFunction());
2173 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002174
2175 // Invoke the JavaScript debug event listener.
2176 const int argc = 4;
2177 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2178 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002179 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002180 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002181 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2182 argc, argv, &caught_exception);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002183 // Silently ignore exceptions from debug event listeners.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002184 }
2185 }
2186}
2187
2188
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00002189Handle<Context> Debugger::GetDebugContext() {
2190 never_unload_debugger_ = true;
2191 EnterDebugger debugger;
2192 return Debug::debug_context();
2193}
2194
2195
ager@chromium.org71daaf62009-04-01 07:22:49 +00002196void Debugger::UnloadDebugger() {
2197 // Make sure that there are no breakpoints left.
2198 Debug::ClearAllBreakPoints();
2199
2200 // Unload the debugger if feasible.
2201 if (!never_unload_debugger_) {
2202 Debug::Unload();
2203 }
2204
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002205 // Clear the flag indicating that the debugger should be unloaded.
2206 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002207}
2208
2209
ager@chromium.org41826e72009-03-30 13:30:57 +00002210void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002211 Handle<JSObject> exec_state,
2212 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002213 bool auto_continue) {
2214 HandleScope scope;
2215
2216 if (!Debug::Load()) return;
2217
2218 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002219 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002220 switch (event) {
2221 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002222 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002223 break;
2224 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002225 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002226 break;
2227 case v8::BeforeCompile:
2228 break;
2229 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002230 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002231 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002232 case v8::ScriptCollected:
2233 sendEventMessage = true;
2234 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002235 case v8::NewFunction:
2236 break;
2237 default:
2238 UNREACHABLE();
2239 }
2240
ager@chromium.org5ec48922009-05-05 07:25:34 +00002241 // The debug command interrupt flag might have been set when the command was
2242 // added. It should be enough to clear the flag only once while we are in the
2243 // debugger.
2244 ASSERT(Debug::InDebugger());
2245 StackGuard::Continue(DEBUGCOMMAND);
2246
2247 // Notify the debugger that a debug event has occurred unless auto continue is
2248 // active in which case no event is send.
2249 if (sendEventMessage) {
2250 MessageImpl message = MessageImpl::NewEvent(
2251 event,
2252 auto_continue,
2253 Handle<JSObject>::cast(exec_state),
2254 Handle<JSObject>::cast(event_data));
2255 InvokeMessageHandler(message);
2256 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002257
2258 // If auto continue don't make the event cause a break, but process messages
2259 // in the queue if any. For script collected events don't even process
2260 // messages in the queue as the execution state might not be what is expected
2261 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002262 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002263 return;
2264 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002265
ager@chromium.org41826e72009-03-30 13:30:57 +00002266 v8::TryCatch try_catch;
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002267
2268 // DebugCommandProcessor goes here.
2269 v8::Local<v8::Object> cmd_processor;
2270 {
2271 v8::Local<v8::Object> api_exec_state =
2272 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2273 v8::Local<v8::String> fun_name =
2274 v8::String::New("debugCommandProcessor");
2275 v8::Local<v8::Function> fun =
2276 v8::Function::Cast(*api_exec_state->Get(fun_name));
2277
2278 v8::Handle<v8::Boolean> running =
2279 auto_continue ? v8::True() : v8::False();
2280 static const int kArgc = 1;
2281 v8::Handle<Value> argv[kArgc] = { running };
2282 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2283 if (try_catch.HasCaught()) {
2284 PrintLn(try_catch.Exception());
2285 return;
2286 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002287 }
2288
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002289 bool running = auto_continue;
2290
ager@chromium.org41826e72009-03-30 13:30:57 +00002291 // Process requests from the debugger.
2292 while (true) {
2293 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002294 if (Debugger::host_dispatch_handler_) {
2295 // In case there is a host dispatch - do periodic dispatches.
2296 if (!command_received_->Wait(host_dispatch_micros_)) {
2297 // Timout expired, do the dispatch.
2298 Debugger::host_dispatch_handler_();
2299 continue;
2300 }
2301 } else {
2302 // In case there is no host dispatch - just wait.
2303 command_received_->Wait();
2304 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002305
ager@chromium.org41826e72009-03-30 13:30:57 +00002306 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002307 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002308 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002309 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002310 // Delete command text and user data.
2311 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002312 return;
2313 }
2314
ager@chromium.org41826e72009-03-30 13:30:57 +00002315 // Invoke JavaScript to process the debug request.
2316 v8::Local<v8::String> fun_name;
2317 v8::Local<v8::Function> fun;
2318 v8::Local<v8::Value> request;
2319 v8::TryCatch try_catch;
2320 fun_name = v8::String::New("processDebugRequest");
2321 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002322
2323 request = v8::String::New(command.text().start(),
2324 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002325 static const int kArgc = 1;
2326 v8::Handle<Value> argv[kArgc] = { request };
2327 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2328
2329 // Get the response.
2330 v8::Local<v8::String> response;
ager@chromium.org41826e72009-03-30 13:30:57 +00002331 if (!try_catch.HasCaught()) {
2332 // Get response string.
2333 if (!response_val->IsUndefined()) {
2334 response = v8::String::Cast(*response_val);
2335 } else {
2336 response = v8::String::New("");
2337 }
2338
2339 // Log the JSON request/response.
2340 if (FLAG_trace_debug_json) {
2341 PrintLn(request);
2342 PrintLn(response);
2343 }
2344
2345 // Get the running state.
2346 fun_name = v8::String::New("isRunning");
2347 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2348 static const int kArgc = 1;
2349 v8::Handle<Value> argv[kArgc] = { response };
2350 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2351 if (!try_catch.HasCaught()) {
2352 running = running_val->ToBoolean()->Value();
2353 }
2354 } else {
2355 // In case of failure the result text is the exception text.
2356 response = try_catch.Exception()->ToString();
2357 }
2358
ager@chromium.org41826e72009-03-30 13:30:57 +00002359 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002360 MessageImpl message = MessageImpl::NewResponse(
2361 event,
2362 running,
2363 Handle<JSObject>::cast(exec_state),
2364 Handle<JSObject>::cast(event_data),
2365 Handle<String>(Utils::OpenHandle(*response)),
2366 command.client_data());
2367 InvokeMessageHandler(message);
2368 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002369
2370 // Return from debug event processing if either the VM is put into the
2371 // runnning state (through a continue command) or auto continue is active
2372 // and there are no more commands queued.
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002373 if (running && !HasCommands()) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002374 return;
2375 }
2376 }
2377}
2378
2379
iposva@chromium.org245aa852009-02-10 00:49:54 +00002380void Debugger::SetEventListener(Handle<Object> callback,
2381 Handle<Object> data) {
2382 HandleScope scope;
2383
2384 // Clear the global handles for the event listener and the event listener data
2385 // object.
2386 if (!event_listener_.is_null()) {
2387 GlobalHandles::Destroy(
2388 reinterpret_cast<Object**>(event_listener_.location()));
2389 event_listener_ = Handle<Object>();
2390 }
2391 if (!event_listener_data_.is_null()) {
2392 GlobalHandles::Destroy(
2393 reinterpret_cast<Object**>(event_listener_data_.location()));
2394 event_listener_data_ = Handle<Object>();
2395 }
2396
2397 // If there is a new debug event listener register it together with its data
2398 // object.
2399 if (!callback->IsUndefined() && !callback->IsNull()) {
2400 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2401 if (data.is_null()) {
2402 data = Factory::undefined_value();
2403 }
2404 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2405 }
2406
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002407 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002408}
2409
2410
ager@chromium.org5ec48922009-05-05 07:25:34 +00002411void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002412 ScopedLock with(debugger_access_);
2413
ager@chromium.org381abbb2009-02-25 13:23:22 +00002414 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002415 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002416 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002417 // Send an empty command to the debugger if in a break to make JavaScript
2418 // run again if the debugger is closed.
2419 if (Debug::InDebugger()) {
2420 ProcessCommand(Vector<const uint16_t>::empty());
2421 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002422 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002423}
2424
2425
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002426void Debugger::ListenersChanged() {
2427 if (IsDebuggerActive()) {
2428 // Disable the compilation cache when the debugger is active.
2429 CompilationCache::Disable();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002430 debugger_unload_pending_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002431 } else {
2432 CompilationCache::Enable();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002433 // Unload the debugger if event listener and message handler cleared.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002434 // Schedule this for later, because we may be in non-V8 thread.
2435 debugger_unload_pending_ = true;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002436 }
2437}
2438
2439
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002440void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2441 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002442 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002443 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002444}
2445
2446
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002447void Debugger::SetDebugMessageDispatchHandler(
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002448 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2449 ScopedLock with(dispatch_handler_access_);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002450 debug_message_dispatch_handler_ = handler;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002451
2452 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2453 message_dispatch_helper_thread_ = new MessageDispatchHelperThread;
2454 message_dispatch_helper_thread_->Start();
2455 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002456}
2457
2458
ager@chromium.org41826e72009-03-30 13:30:57 +00002459// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002460// public API.
2461void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002462 ScopedLock with(debugger_access_);
2463
ager@chromium.org381abbb2009-02-25 13:23:22 +00002464 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002465 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002466 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002467}
2468
2469
2470// Puts a command coming from the public API on the queue. Creates
2471// a copy of the command string managed by the debugger. Up to this
2472// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002473// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002474void Debugger::ProcessCommand(Vector<const uint16_t> command,
2475 v8::Debug::ClientData* client_data) {
2476 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002477 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002478 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002479 command.length()),
2480 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002481 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002482 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002483 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002484
2485 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002486 if (!Debug::InDebugger()) {
2487 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002488 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002489
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002490 MessageDispatchHelperThread* dispatch_thread;
2491 {
2492 ScopedLock with(dispatch_handler_access_);
2493 dispatch_thread = message_dispatch_helper_thread_;
2494 }
2495
2496 if (dispatch_thread == NULL) {
2497 CallMessageDispatchHandler();
2498 } else {
2499 dispatch_thread->Schedule();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002500 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002501}
2502
2503
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002504bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002505 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002506}
2507
2508
ager@chromium.org71daaf62009-04-01 07:22:49 +00002509bool Debugger::IsDebuggerActive() {
2510 ScopedLock with(debugger_access_);
2511
2512 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002513}
2514
2515
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002516Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2517 Handle<Object> data,
2518 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002519 // When calling functions in the debugger prevent it from beeing unloaded.
2520 Debugger::never_unload_debugger_ = true;
2521
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002522 // Enter the debugger.
2523 EnterDebugger debugger;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00002524 if (debugger.FailedToEnter()) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002525 return Factory::undefined_value();
2526 }
2527
2528 // Create the execution state.
2529 bool caught_exception = false;
2530 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2531 if (caught_exception) {
2532 return Factory::undefined_value();
2533 }
2534
2535 static const int kArgc = 2;
2536 Object** argv[kArgc] = { exec_state.location(), data.location() };
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00002537 Handle<Object> result = Execution::Call(
2538 fun,
2539 Handle<Object>(Debug::debug_context_->global_proxy()),
2540 kArgc,
2541 argv,
2542 pending_exception);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002543 return result;
2544}
2545
2546
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002547static void StubMessageHandler2(const v8::Debug::Message& message) {
2548 // Simply ignore message.
2549}
2550
2551
2552bool Debugger::StartAgent(const char* name, int port,
2553 bool wait_for_connection) {
2554 if (wait_for_connection) {
2555 // Suspend V8 if it is already running or set V8 to suspend whenever
2556 // it starts.
2557 // Provide stub message handler; V8 auto-continues each suspend
2558 // when there is no message handler; we doesn't need it.
2559 // Once become suspended, V8 will stay so indefinitely long, until remote
2560 // debugger connects and issues "continue" command.
2561 Debugger::message_handler_ = StubMessageHandler2;
2562 v8::Debug::DebugBreak();
2563 }
2564
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002565 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002566 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002567 agent_->Start();
2568 return true;
2569 }
2570
2571 return false;
2572}
2573
2574
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002575void Debugger::StopAgent() {
2576 if (agent_ != NULL) {
2577 agent_->Shutdown();
2578 agent_->Join();
2579 delete agent_;
2580 agent_ = NULL;
2581 }
2582}
2583
2584
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002585void Debugger::WaitForAgent() {
2586 if (agent_ != NULL)
2587 agent_->WaitUntilListening();
2588}
2589
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002590
2591void Debugger::CallMessageDispatchHandler() {
2592 v8::Debug::DebugMessageDispatchHandler handler;
2593 {
2594 ScopedLock with(dispatch_handler_access_);
2595 handler = Debugger::debug_message_dispatch_handler_;
2596 }
2597 if (handler != NULL) {
2598 handler();
2599 }
2600}
2601
2602
ager@chromium.org5ec48922009-05-05 07:25:34 +00002603MessageImpl MessageImpl::NewEvent(DebugEvent event,
2604 bool running,
2605 Handle<JSObject> exec_state,
2606 Handle<JSObject> event_data) {
2607 MessageImpl message(true, event, running,
2608 exec_state, event_data, Handle<String>(), NULL);
2609 return message;
2610}
2611
2612
2613MessageImpl MessageImpl::NewResponse(DebugEvent event,
2614 bool running,
2615 Handle<JSObject> exec_state,
2616 Handle<JSObject> event_data,
2617 Handle<String> response_json,
2618 v8::Debug::ClientData* client_data) {
2619 MessageImpl message(false, event, running,
2620 exec_state, event_data, response_json, client_data);
2621 return message;
2622}
2623
2624
2625MessageImpl::MessageImpl(bool is_event,
2626 DebugEvent event,
2627 bool running,
2628 Handle<JSObject> exec_state,
2629 Handle<JSObject> event_data,
2630 Handle<String> response_json,
2631 v8::Debug::ClientData* client_data)
2632 : is_event_(is_event),
2633 event_(event),
2634 running_(running),
2635 exec_state_(exec_state),
2636 event_data_(event_data),
2637 response_json_(response_json),
2638 client_data_(client_data) {}
2639
2640
2641bool MessageImpl::IsEvent() const {
2642 return is_event_;
2643}
2644
2645
2646bool MessageImpl::IsResponse() const {
2647 return !is_event_;
2648}
2649
2650
2651DebugEvent MessageImpl::GetEvent() const {
2652 return event_;
2653}
2654
2655
2656bool MessageImpl::WillStartRunning() const {
2657 return running_;
2658}
2659
2660
2661v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2662 return v8::Utils::ToLocal(exec_state_);
2663}
2664
2665
2666v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2667 return v8::Utils::ToLocal(event_data_);
2668}
2669
2670
2671v8::Handle<v8::String> MessageImpl::GetJSON() const {
2672 v8::HandleScope scope;
2673
2674 if (IsEvent()) {
2675 // Call toJSONProtocol on the debug event object.
2676 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2677 if (!fun->IsJSFunction()) {
2678 return v8::Handle<v8::String>();
2679 }
2680 bool caught_exception;
2681 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2682 event_data_,
2683 0, NULL, &caught_exception);
2684 if (caught_exception || !json->IsString()) {
2685 return v8::Handle<v8::String>();
2686 }
2687 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2688 } else {
2689 return v8::Utils::ToLocal(response_json_);
2690 }
2691}
2692
2693
2694v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +00002695 v8::Handle<v8::Context> context = GetDebugEventContext();
2696 // Top::context() may be NULL when "script collected" event occures.
2697 ASSERT(!context.IsEmpty() || event_ == v8::ScriptCollected);
2698 return GetDebugEventContext();
ager@chromium.org5ec48922009-05-05 07:25:34 +00002699}
2700
2701
2702v8::Debug::ClientData* MessageImpl::GetClientData() const {
2703 return client_data_;
2704}
2705
2706
erik.corry@gmail.com9dfbea42010-05-21 12:58:28 +00002707EventDetailsImpl::EventDetailsImpl(DebugEvent event,
2708 Handle<JSObject> exec_state,
2709 Handle<JSObject> event_data,
2710 Handle<Object> callback_data)
2711 : event_(event),
2712 exec_state_(exec_state),
2713 event_data_(event_data),
2714 callback_data_(callback_data) {}
2715
2716
2717DebugEvent EventDetailsImpl::GetEvent() const {
2718 return event_;
2719}
2720
2721
2722v8::Handle<v8::Object> EventDetailsImpl::GetExecutionState() const {
2723 return v8::Utils::ToLocal(exec_state_);
2724}
2725
2726
2727v8::Handle<v8::Object> EventDetailsImpl::GetEventData() const {
2728 return v8::Utils::ToLocal(event_data_);
2729}
2730
2731
2732v8::Handle<v8::Context> EventDetailsImpl::GetEventContext() const {
2733 return GetDebugEventContext();
2734}
2735
2736
2737v8::Handle<v8::Value> EventDetailsImpl::GetCallbackData() const {
2738 return v8::Utils::ToLocal(callback_data_);
2739}
2740
2741
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002742CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2743 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002744}
2745
2746
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002747CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2748 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002749 : text_(text),
2750 client_data_(data) {
2751}
2752
2753
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002754CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002755}
2756
2757
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002758void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002759 text_.Dispose();
2760 delete client_data_;
2761 client_data_ = NULL;
2762}
2763
2764
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002765CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2766 v8::Debug::ClientData* data) {
2767 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002768}
2769
2770
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002771CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2772 size_(size) {
2773 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002774}
2775
2776
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002777CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002778 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002779 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002780 m.Dispose();
2781 }
kasper.lund7276f142008-07-30 08:49:36 +00002782 DeleteArray(messages_);
2783}
2784
2785
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002786CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002787 ASSERT(!IsEmpty());
2788 int result = start_;
2789 start_ = (start_ + 1) % size_;
2790 return messages_[result];
2791}
2792
2793
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002794void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002795 if ((end_ + 1) % size_ == start_) {
2796 Expand();
2797 }
2798 messages_[end_] = message;
2799 end_ = (end_ + 1) % size_;
2800}
2801
2802
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002803void CommandMessageQueue::Expand() {
2804 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002805 while (!IsEmpty()) {
2806 new_queue.Put(Get());
2807 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002808 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002809 *this = new_queue;
2810 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002811 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2812 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002813 // Automatic destructor called on new_queue, freeing array_to_free.
2814}
2815
2816
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002817LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2818 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002819 lock_ = OS::CreateMutex();
2820}
2821
2822
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002823LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002824 delete lock_;
2825}
2826
2827
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002828bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002829 ScopedLock sl(lock_);
2830 return queue_.IsEmpty();
2831}
2832
2833
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002834CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002835 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002836 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002837 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002838 return result;
2839}
2840
2841
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002842void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002843 ScopedLock sl(lock_);
2844 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002845 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002846}
2847
2848
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002849void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002850 ScopedLock sl(lock_);
2851 queue_.Clear();
2852}
2853
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002854
2855MessageDispatchHelperThread::MessageDispatchHelperThread()
2856 : sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
2857 already_signalled_(false) {
2858}
2859
2860
2861MessageDispatchHelperThread::~MessageDispatchHelperThread() {
2862 delete mutex_;
2863 delete sem_;
2864}
2865
2866
2867void MessageDispatchHelperThread::Schedule() {
2868 {
2869 ScopedLock lock(mutex_);
2870 if (already_signalled_) {
2871 return;
2872 }
2873 already_signalled_ = true;
2874 }
2875 sem_->Signal();
2876}
2877
2878
2879void MessageDispatchHelperThread::Run() {
2880 while (true) {
2881 sem_->Wait();
2882 {
2883 ScopedLock lock(mutex_);
2884 already_signalled_ = false;
2885 }
2886 {
2887 Locker locker;
2888 Debugger::CallMessageDispatchHandler();
2889 }
2890 }
2891}
2892
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002893#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002894
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002895} } // namespace v8::internal