blob: bf1f893b7d301e71ce3b489b7aec13e3edccaab2 [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "code-stubs.h"
ager@chromium.org5c838252010-02-19 08:53:10 +000034#include "codegen.h"
kasperl@chromium.org71affb52009-05-26 05:44:31 +000035#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036#include "compiler.h"
37#include "debug.h"
38#include "execution.h"
39#include "global-handles.h"
ager@chromium.org65dad4b2009-04-23 08:48:43 +000040#include "ic.h"
41#include "ic-inl.h"
ager@chromium.orgce5e87b2010-03-10 10:24:18 +000042#include "messages.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043#include "natives.h"
44#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000045#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000046
ager@chromium.org5ec48922009-05-05 07:25:34 +000047#include "../include/v8-debug.h"
48
kasperl@chromium.org71affb52009-05-26 05:44:31 +000049namespace v8 {
50namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051
ager@chromium.org65dad4b2009-04-23 08:48:43 +000052#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000053static void PrintLn(v8::Local<v8::Value> value) {
54 v8::Local<v8::String> s = value->ToString();
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000055 ScopedVector<char> data(s->Length() + 1);
56 if (data.start() == NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057 V8::FatalProcessOutOfMemory("PrintLn");
58 return;
59 }
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +000060 s->WriteAscii(data.start());
61 PrintF("%s\n", data.start());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000062}
63
64
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065static Handle<Code> ComputeCallDebugBreak(int argc) {
66 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
67}
68
69
70static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
71 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
72}
73
74
75BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
76 BreakLocatorType type) {
77 debug_info_ = debug_info;
78 type_ = type;
79 reloc_iterator_ = NULL;
80 reloc_iterator_original_ = NULL;
81 Reset(); // Initialize the rest of the member variables.
82}
83
84
85BreakLocationIterator::~BreakLocationIterator() {
86 ASSERT(reloc_iterator_ != NULL);
87 ASSERT(reloc_iterator_original_ != NULL);
88 delete reloc_iterator_;
89 delete reloc_iterator_original_;
90}
91
92
93void BreakLocationIterator::Next() {
94 AssertNoAllocation nogc;
95 ASSERT(!RinfoDone());
96
97 // Iterate through reloc info for code and original code stopping at each
98 // breakable code target.
99 bool first = break_point_ == -1;
100 while (!RinfoDone()) {
101 if (!first) RinfoNext();
102 first = false;
103 if (RinfoDone()) return;
104
ager@chromium.org236ad962008-09-25 09:45:57 +0000105 // Whenever a statement position or (plain) position is passed update the
106 // current value of these.
107 if (RelocInfo::IsPosition(rmode())) {
108 if (RelocInfo::IsStatementPosition(rmode())) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000109 statement_position_ = static_cast<int>(
110 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000111 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000112 // Always update the position as we don't want that to be before the
113 // statement position.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000114 position_ = static_cast<int>(
115 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000116 ASSERT(position_ >= 0);
117 ASSERT(statement_position_ >= 0);
118 }
119
120 // Check for breakable code target. Look in the original code as setting
121 // break points can cause the code targets in the running (debugged) code to
122 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000123 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000124 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000125 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000126 if ((code->is_inline_cache_stub() &&
127 code->kind() != Code::BINARY_OP_IC) ||
128 RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000129 break_point_++;
130 return;
131 }
132 if (code->kind() == Code::STUB) {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000133 if (IsDebuggerStatement()) {
134 break_point_++;
135 return;
136 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000137 if (type_ == ALL_BREAK_LOCATIONS) {
138 if (Debug::IsBreakStub(code)) {
139 break_point_++;
140 return;
141 }
142 } else {
143 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
144 if (Debug::IsSourceBreakStub(code)) {
145 break_point_++;
146 return;
147 }
148 }
149 }
150 }
151
152 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000153 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000154 // Set the positions to the end of the function.
155 if (debug_info_->shared()->HasSourceCode()) {
156 position_ = debug_info_->shared()->end_position() -
157 debug_info_->shared()->start_position();
158 } else {
159 position_ = 0;
160 }
161 statement_position_ = position_;
162 break_point_++;
163 return;
164 }
165 }
166}
167
168
169void BreakLocationIterator::Next(int count) {
170 while (count > 0) {
171 Next();
172 count--;
173 }
174}
175
176
177// Find the break point closest to the supplied address.
178void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
179 // Run through all break points to locate the one closest to the address.
180 int closest_break_point = 0;
181 int distance = kMaxInt;
182 while (!Done()) {
183 // Check if this break point is closer that what was previously found.
184 if (this->pc() < pc && pc - this->pc() < distance) {
185 closest_break_point = break_point();
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000186 distance = static_cast<int>(pc - this->pc());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000187 // Check whether we can't get any closer.
188 if (distance == 0) break;
189 }
190 Next();
191 }
192
193 // Move to the break point found.
194 Reset();
195 Next(closest_break_point);
196}
197
198
199// Find the break point closest to the supplied source position.
200void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
201 // Run through all break points to locate the one closest to the source
202 // position.
203 int closest_break_point = 0;
204 int distance = kMaxInt;
205 while (!Done()) {
206 // Check if this break point is closer that what was previously found.
207 if (position <= statement_position() &&
208 statement_position() - position < distance) {
209 closest_break_point = break_point();
210 distance = statement_position() - position;
211 // Check whether we can't get any closer.
212 if (distance == 0) break;
213 }
214 Next();
215 }
216
217 // Move to the break point found.
218 Reset();
219 Next(closest_break_point);
220}
221
222
223void BreakLocationIterator::Reset() {
224 // Create relocation iterators for the two code objects.
225 if (reloc_iterator_ != NULL) delete reloc_iterator_;
226 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
227 reloc_iterator_ = new RelocIterator(debug_info_->code());
228 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
229
230 // Position at the first break point.
231 break_point_ = -1;
232 position_ = 1;
233 statement_position_ = 1;
234 Next();
235}
236
237
238bool BreakLocationIterator::Done() const {
239 return RinfoDone();
240}
241
242
243void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
244 // If there is not already a real break point here patch code with debug
245 // break.
246 if (!HasBreakPoint()) {
247 SetDebugBreak();
248 }
ager@chromium.orga1645e22009-09-09 19:27:10 +0000249 ASSERT(IsDebugBreak() || IsDebuggerStatement());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000250 // Set the break point information.
251 DebugInfo::SetBreakPoint(debug_info_, code_position(),
252 position(), statement_position(),
253 break_point_object);
254}
255
256
257void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
258 // Clear the break point information.
259 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
260 // If there are no more break points here remove the debug break.
261 if (!HasBreakPoint()) {
262 ClearDebugBreak();
263 ASSERT(!IsDebugBreak());
264 }
265}
266
267
268void BreakLocationIterator::SetOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000269 // Debugger statement always calls debugger. No need to modify it.
270 if (IsDebuggerStatement()) {
271 return;
272 }
273
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000274 // If there is a real break point here no more to do.
275 if (HasBreakPoint()) {
276 ASSERT(IsDebugBreak());
277 return;
278 }
279
280 // Patch code with debug break.
281 SetDebugBreak();
282}
283
284
285void BreakLocationIterator::ClearOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000286 // Debugger statement always calls debugger. No need to modify it.
287 if (IsDebuggerStatement()) {
288 return;
289 }
290
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000291 // If there is a real break point here no more to do.
292 if (HasBreakPoint()) {
293 ASSERT(IsDebugBreak());
294 return;
295 }
296
297 // Patch code removing debug break.
298 ClearDebugBreak();
299 ASSERT(!IsDebugBreak());
300}
301
302
303void BreakLocationIterator::SetDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000304 // Debugger statement always calls debugger. No need to modify it.
305 if (IsDebuggerStatement()) {
306 return;
307 }
308
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000310 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000311 // function twice might happen when stepping in a function with an exception
312 // handler as the handler and the function is the same.
313 if (IsDebugBreak()) {
314 return;
315 }
316
ager@chromium.org236ad962008-09-25 09:45:57 +0000317 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000318 // Patch the frame exit code with a break point.
319 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000320 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000321 // Patch the IC call.
322 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000323 }
324 ASSERT(IsDebugBreak());
325}
326
327
328void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000329 // Debugger statement always calls debugger. No need to modify it.
330 if (IsDebuggerStatement()) {
331 return;
332 }
333
ager@chromium.org236ad962008-09-25 09:45:57 +0000334 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000335 // Restore the frame exit code.
336 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000337 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000338 // Patch the IC call.
339 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000340 }
341 ASSERT(!IsDebugBreak());
342}
343
344
345void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000346 HandleScope scope;
347
ager@chromium.orga1645e22009-09-09 19:27:10 +0000348 // Step in can only be prepared if currently positioned on an IC call,
349 // construct call or CallFunction stub call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000350 Address target = rinfo()->target_address();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000351 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000352 if (code->is_call_stub()) {
353 // Step in through IC call is handled by the runtime system. Therefore make
354 // sure that the any current IC is cleared and the runtime system is
355 // called. If the executing code has a debug break at the location change
356 // the call in the original code as it is the code there that will be
357 // executed in place of the debug break call.
358 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
359 if (IsDebugBreak()) {
360 original_rinfo()->set_target_address(stub->entry());
361 } else {
362 rinfo()->set_target_address(stub->entry());
363 }
364 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000365#ifdef DEBUG
366 // All the following stuff is needed only for assertion checks so the code
367 // is wrapped in ifdef.
368 Handle<Code> maybe_call_function_stub = code;
369 if (IsDebugBreak()) {
370 Address original_target = original_rinfo()->target_address();
371 maybe_call_function_stub =
372 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
373 }
374 bool is_call_function_stub =
375 (maybe_call_function_stub->kind() == Code::STUB &&
376 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
377
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000378 // Step in through construct call requires no changes to the running code.
379 // Step in through getters/setters should already be prepared as well
380 // because caller of this function (Debug::PrepareStep) is expected to
381 // flood the top frame's function with one shot breakpoints.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000382 // Step in through CallFunction stub should also be prepared by caller of
383 // this function (Debug::PrepareStep) which should flood target function
384 // with breakpoints.
385 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
386 || is_call_function_stub);
387#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000388 }
389}
390
391
392// Check whether the break point is at a position which will exit the function.
393bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000394 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000395}
396
397
398bool BreakLocationIterator::HasBreakPoint() {
399 return debug_info_->HasBreakPoint(code_position());
400}
401
402
403// Check whether there is a debug break at the current position.
404bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000405 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000406 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000407 } else {
408 return Debug::IsDebugBreak(rinfo()->target_address());
409 }
410}
411
412
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000413void BreakLocationIterator::SetDebugBreakAtIC() {
414 // Patch the original code with the current address as the current address
415 // might have changed by the inline caching since the code was copied.
416 original_rinfo()->set_target_address(rinfo()->target_address());
417
418 RelocInfo::Mode mode = rmode();
419 if (RelocInfo::IsCodeTarget(mode)) {
420 Address target = rinfo()->target_address();
421 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
422
423 // Patch the code to invoke the builtin debug break function matching the
424 // calling convention used by the call site.
425 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
426 rinfo()->set_target_address(dbgbrk_code->entry());
427
428 // For stubs that refer back to an inlined version clear the cached map for
429 // the inlined case to always go through the IC. As long as the break point
430 // is set the patching performed by the runtime system will take place in
431 // the code copy and will therefore have no effect on the running code
432 // keeping it from using the inlined code.
sgjesse@chromium.org720dc0b2010-05-10 09:25:39 +0000433 if (code->is_keyed_load_stub()) {
434 KeyedLoadIC::ClearInlinedVersion(pc());
435 } else if (code->is_keyed_store_stub()) {
436 KeyedStoreIC::ClearInlinedVersion(pc());
437 } else if (code->is_load_stub()) {
438 LoadIC::ClearInlinedVersion(pc());
439 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000440 }
441}
442
443
444void BreakLocationIterator::ClearDebugBreakAtIC() {
445 // Patch the code to the original invoke.
446 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000447
448 RelocInfo::Mode mode = rmode();
449 if (RelocInfo::IsCodeTarget(mode)) {
450 Address target = original_rinfo()->target_address();
451 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
452
453 // Restore the inlined version of keyed stores to get back to the
454 // fast case. We need to patch back the keyed store because no
455 // patching happens when running normally. For keyed loads, the
456 // map check will get patched back when running normally after ICs
457 // have been cleared at GC.
458 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
459 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000460}
461
462
ager@chromium.orga1645e22009-09-09 19:27:10 +0000463bool BreakLocationIterator::IsDebuggerStatement() {
ager@chromium.org5c838252010-02-19 08:53:10 +0000464 return RelocInfo::DEBUG_BREAK == rmode();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000465}
466
467
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000468Object* BreakLocationIterator::BreakPointObjects() {
469 return debug_info_->GetBreakPointObjects(code_position());
470}
471
472
ager@chromium.org381abbb2009-02-25 13:23:22 +0000473// Clear out all the debug break code. This is ONLY supposed to be used when
474// shutting down the debugger as it will leave the break point information in
475// DebugInfo even though the code is patched back to the non break point state.
476void BreakLocationIterator::ClearAllDebugBreak() {
477 while (!Done()) {
478 ClearDebugBreak();
479 Next();
480 }
481}
482
483
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000484bool BreakLocationIterator::RinfoDone() const {
485 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
486 return reloc_iterator_->done();
487}
488
489
490void BreakLocationIterator::RinfoNext() {
491 reloc_iterator_->next();
492 reloc_iterator_original_->next();
493#ifdef DEBUG
494 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
495 if (!reloc_iterator_->done()) {
496 ASSERT(rmode() == original_rmode());
497 }
498#endif
499}
500
501
502bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000503ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000504DebugInfoListNode* Debug::debug_info_list_ = NULL;
505
506
507// Threading support.
508void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000509 thread_local_.break_count_ = 0;
510 thread_local_.break_id_ = 0;
511 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000512 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000513 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514 thread_local_.step_count_ = 0;
515 thread_local_.last_fp_ = 0;
516 thread_local_.step_into_fp_ = 0;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000517 thread_local_.step_out_fp_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000518 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000519 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000520 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000521}
522
523
524JSCallerSavedBuffer Debug::registers_;
525Debug::ThreadLocal Debug::thread_local_;
526
527
528char* Debug::ArchiveDebug(char* storage) {
529 char* to = storage;
530 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
531 to += sizeof(ThreadLocal);
532 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
533 ThreadInit();
534 ASSERT(to <= storage + ArchiveSpacePerThread());
535 return storage + ArchiveSpacePerThread();
536}
537
538
539char* Debug::RestoreDebug(char* storage) {
540 char* from = storage;
541 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
542 from += sizeof(ThreadLocal);
543 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
544 ASSERT(from <= storage + ArchiveSpacePerThread());
545 return storage + ArchiveSpacePerThread();
546}
547
548
549int Debug::ArchiveSpacePerThread() {
550 return sizeof(ThreadLocal) + sizeof(registers_);
551}
552
553
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000554// Default break enabled.
555bool Debug::disable_break_ = false;
556
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000557// Default call debugger on uncaught exception.
558bool Debug::break_on_exception_ = false;
559bool Debug::break_on_uncaught_exception_ = true;
560
561Handle<Context> Debug::debug_context_ = Handle<Context>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000562Code* Debug::debug_break_return_ = NULL;
563
564
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000565void ScriptCache::Add(Handle<Script> script) {
566 // Create an entry in the hash map for the script.
567 int id = Smi::cast(script->id())->value();
568 HashMap::Entry* entry =
569 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
570 if (entry->value != NULL) {
571 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
572 return;
573 }
574
575 // Globalize the script object, make it weak and use the location of the
576 // global handle as the value in the hash map.
577 Handle<Script> script_ =
578 Handle<Script>::cast((GlobalHandles::Create(*script)));
579 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
580 this, ScriptCache::HandleWeakScript);
581 entry->value = script_.location();
582}
583
584
585Handle<FixedArray> ScriptCache::GetScripts() {
586 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
587 int count = 0;
588 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
589 ASSERT(entry->value != NULL);
590 if (entry->value != NULL) {
591 instances->set(count, *reinterpret_cast<Script**>(entry->value));
592 count++;
593 }
594 }
595 return instances;
596}
597
598
599void ScriptCache::ProcessCollectedScripts() {
600 for (int i = 0; i < collected_scripts_.length(); i++) {
601 Debugger::OnScriptCollected(collected_scripts_[i]);
602 }
603 collected_scripts_.Clear();
604}
605
606
607void ScriptCache::Clear() {
608 // Iterate the script cache to get rid of all the weak handles.
609 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
610 ASSERT(entry != NULL);
611 Object** location = reinterpret_cast<Object**>(entry->value);
612 ASSERT((*location)->IsScript());
613 GlobalHandles::ClearWeakness(location);
614 GlobalHandles::Destroy(location);
615 }
616 // Clear the content of the hash map.
617 HashMap::Clear();
618}
619
620
621void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
622 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
623 // Find the location of the global handle.
624 Script** location =
625 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
626 ASSERT((*location)->IsScript());
627
628 // Remove the entry from the cache.
629 int id = Smi::cast((*location)->id())->value();
630 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
631 script_cache->collected_scripts_.Add(id);
632
633 // Clear the weak handle.
634 obj.Dispose();
635 obj.Clear();
636}
637
638
639void Debug::Setup(bool create_heap_objects) {
640 ThreadInit();
641 if (create_heap_objects) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000642 // Get code to handle debug break on return.
643 debug_break_return_ =
644 Builtins::builtin(Builtins::Return_DebugBreak);
645 ASSERT(debug_break_return_->IsCode());
646 }
647}
648
649
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000650void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000651 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
652 RemoveDebugInfo(node->debug_info());
653#ifdef DEBUG
654 node = Debug::debug_info_list_;
655 while (node != NULL) {
656 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
657 node = node->next();
658 }
659#endif
660}
661
662
663DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
664 // Globalize the request debug info object and make it weak.
665 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
666 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
667 this, Debug::HandleWeakDebugInfo);
668}
669
670
671DebugInfoListNode::~DebugInfoListNode() {
672 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
673}
674
675
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000676bool Debug::CompileDebuggerScript(int index) {
677 HandleScope scope;
678
kasper.lund44510672008-07-25 07:37:58 +0000679 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680 if (index == -1) {
681 return false;
682 }
kasper.lund44510672008-07-25 07:37:58 +0000683
684 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000685 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
686 Vector<const char> name = Natives::GetScriptName(index);
687 Handle<String> script_name = Factory::NewStringFromAscii(name);
688
689 // Compile the script.
690 bool allow_natives_syntax = FLAG_allow_natives_syntax;
691 FLAG_allow_natives_syntax = true;
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000692 Handle<SharedFunctionInfo> function_info;
693 function_info = Compiler::Compile(source_code,
694 script_name,
695 0, 0, NULL, NULL,
696 Handle<String>::null(),
697 NATIVES_CODE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000698 FLAG_allow_natives_syntax = allow_natives_syntax;
699
700 // Silently ignore stack overflows during compilation.
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000701 if (function_info.is_null()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000702 ASSERT(Top::has_pending_exception());
703 Top::clear_pending_exception();
704 return false;
705 }
706
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000707 // Execute the shared function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000708 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000709 bool caught_exception = false;
710 Handle<JSFunction> function =
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +0000711 Factory::NewFunctionFromSharedFunctionInfo(function_info, context);
kasper.lund44510672008-07-25 07:37:58 +0000712 Handle<Object> result =
713 Execution::TryCall(function, Handle<Object>(context->global()),
714 0, NULL, &caught_exception);
715
716 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000717 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000718 Handle<Object> message = MessageHandler::MakeMessageObject(
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000719 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000720 Handle<String>());
721 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000722 return false;
723 }
724
kasper.lund44510672008-07-25 07:37:58 +0000725 // Mark this script as native and return successfully.
726 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000727 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000728 return true;
729}
730
731
732bool Debug::Load() {
733 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000734 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000735
kasper.lund44510672008-07-25 07:37:58 +0000736 // Bail out if we're already in the process of compiling the native
737 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000738 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
739 return false;
740 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000741
742 // Disable breakpoints and interrupts while compiling and running the
743 // debugger scripts including the context creation code.
744 DisableBreak disable(true);
745 PostponeInterruptsScope postpone;
746
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000747 // Create the debugger context.
748 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000749 Handle<Context> context =
750 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
751 v8::Handle<ObjectTemplate>(),
752 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000753
kasper.lund44510672008-07-25 07:37:58 +0000754 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000755 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000756 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000757
758 // Expose the builtins object in the debugger context.
759 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
760 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
761 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000762
763 // Compile the JavaScript for the debugger in the debugger context.
764 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000765 bool caught_exception =
766 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
767 !CompileDebuggerScript(Natives::GetIndex("debug"));
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000768
769 if (FLAG_enable_liveedit) {
770 caught_exception = caught_exception ||
771 !CompileDebuggerScript(Natives::GetIndex("liveedit"));
772 }
773
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000774 Debugger::set_compiling_natives(false);
775
mads.s.agercbaa0602008-08-14 13:41:48 +0000776 // Make sure we mark the debugger as not loading before we might
777 // return.
778 Debugger::set_loading_debugger(false);
779
kasper.lund44510672008-07-25 07:37:58 +0000780 // Check for caught exceptions.
781 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000782
783 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000784 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000785
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786 return true;
787}
788
789
790void Debug::Unload() {
791 // Return debugger is not loaded.
792 if (!IsLoaded()) {
793 return;
794 }
795
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000796 // Clear the script cache.
797 DestroyScriptCache();
798
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000799 // Clear debugger context global handle.
800 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
801 debug_context_ = Handle<Context>();
802}
803
804
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000805// Set the flag indicating that preemption happened during debugging.
806void Debug::PreemptionWhileInDebugger() {
807 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000808 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000809}
810
811
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000812void Debug::Iterate(ObjectVisitor* v) {
vegorov@chromium.orgf8372902010-03-15 10:26:20 +0000813 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000814}
815
816
817Object* Debug::Break(Arguments args) {
818 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000819 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000820
ager@chromium.org357bf652010-04-12 11:30:10 +0000821 thread_local_.frames_are_dropped_ = false;
822
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000823 // Get the top-most JavaScript frame.
824 JavaScriptFrameIterator it;
825 JavaScriptFrame* frame = it.frame();
826
827 // Just continue if breaks are disabled or debugger cannot be loaded.
828 if (disable_break() || !Load()) {
829 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000830 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000831 }
832
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000833 // Enter the debugger.
834 EnterDebugger debugger;
835 if (debugger.FailedToEnter()) {
836 return Heap::undefined_value();
837 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838
kasper.lund44510672008-07-25 07:37:58 +0000839 // Postpone interrupt during breakpoint processing.
840 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000841
842 // Get the debug info (create it if it does not exist).
843 Handle<SharedFunctionInfo> shared =
844 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
845 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
846
847 // Find the break point where execution has stopped.
848 BreakLocationIterator break_location_iterator(debug_info,
849 ALL_BREAK_LOCATIONS);
850 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
851
852 // Check whether step next reached a new statement.
853 if (!StepNextContinue(&break_location_iterator, frame)) {
854 // Decrease steps left if performing multiple steps.
855 if (thread_local_.step_count_ > 0) {
856 thread_local_.step_count_--;
857 }
858 }
859
860 // If there is one or more real break points check whether any of these are
861 // triggered.
862 Handle<Object> break_points_hit(Heap::undefined_value());
863 if (break_location_iterator.HasBreakPoint()) {
864 Handle<Object> break_point_objects =
865 Handle<Object>(break_location_iterator.BreakPointObjects());
866 break_points_hit = CheckBreakPoints(break_point_objects);
867 }
868
ager@chromium.orga1645e22009-09-09 19:27:10 +0000869 // If step out is active skip everything until the frame where we need to step
870 // out to is reached, unless real breakpoint is hit.
871 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
872 break_points_hit->IsUndefined() ) {
873 // Step count should always be 0 for StepOut.
874 ASSERT(thread_local_.step_count_ == 0);
875 } else if (!break_points_hit->IsUndefined() ||
876 (thread_local_.last_step_action_ != StepNone &&
877 thread_local_.step_count_ == 0)) {
878 // Notify debugger if a real break point is triggered or if performing
879 // single stepping with no more steps to perform. Otherwise do another step.
880
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000881 // Clear all current stepping setup.
882 ClearStepping();
883
884 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000885 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000886 } else if (thread_local_.last_step_action_ != StepNone) {
887 // Hold on to last step action as it is cleared by the call to
888 // ClearStepping.
889 StepAction step_action = thread_local_.last_step_action_;
890 int step_count = thread_local_.step_count_;
891
892 // Clear all current stepping setup.
893 ClearStepping();
894
895 // Set up for the remaining steps.
896 PrepareStep(step_action, step_count);
897 }
898
ager@chromium.org357bf652010-04-12 11:30:10 +0000899 if (thread_local_.frames_are_dropped_) {
900 // We must have been calling IC stub. Do not return there anymore.
901 Code* plain_return = Builtins::builtin(Builtins::PlainReturn_LiveEdit);
902 thread_local_.after_break_target_ = plain_return->entry();
903 } else {
904 SetAfterBreakTarget(frame);
905 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000906
mads.s.ager31e71382008-08-13 09:32:07 +0000907 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000908}
909
910
911// Check the break point objects for whether one or more are actually
912// triggered. This function returns a JSArray with the break point objects
913// which is triggered.
914Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
915 int break_points_hit_count = 0;
916 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
917
v8.team.kasperl727e9952008-09-02 14:56:44 +0000918 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000919 ASSERT(!break_point_objects->IsUndefined());
920 if (break_point_objects->IsFixedArray()) {
921 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
922 for (int i = 0; i < array->length(); i++) {
923 Handle<Object> o(array->get(i));
924 if (CheckBreakPoint(o)) {
925 break_points_hit->SetElement(break_points_hit_count++, *o);
926 }
927 }
928 } else {
929 if (CheckBreakPoint(break_point_objects)) {
930 break_points_hit->SetElement(break_points_hit_count++,
931 *break_point_objects);
932 }
933 }
934
935 // Return undefined if no break points where triggered.
936 if (break_points_hit_count == 0) {
937 return Factory::undefined_value();
938 }
939 return break_points_hit;
940}
941
942
943// Check whether a single break point object is triggered.
944bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000945 HandleScope scope;
946
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000947 // Ignore check if break point object is not a JSObject.
948 if (!break_point_object->IsJSObject()) return true;
949
950 // Get the function CheckBreakPoint (defined in debug.js).
951 Handle<JSFunction> check_break_point =
952 Handle<JSFunction>(JSFunction::cast(
953 debug_context()->global()->GetProperty(
954 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
955
956 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000957 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000958
959 // Call HandleBreakPointx.
960 bool caught_exception = false;
961 const int argc = 2;
962 Object** argv[argc] = {
963 break_id.location(),
964 reinterpret_cast<Object**>(break_point_object.location())
965 };
966 Handle<Object> result = Execution::TryCall(check_break_point,
967 Top::builtins(), argc, argv,
968 &caught_exception);
969
970 // If exception or non boolean result handle as not triggered
971 if (caught_exception || !result->IsBoolean()) {
972 return false;
973 }
974
975 // Return whether the break point is triggered.
976 return *result == Heap::true_value();
977}
978
979
980// Check whether the function has debug information.
981bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
982 return !shared->debug_info()->IsUndefined();
983}
984
985
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000986// Return the debug info for this function. EnsureDebugInfo must be called
987// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000988Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000989 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000990 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
991}
992
993
994void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
995 int source_position,
996 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000997 HandleScope scope;
998
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000999 if (!EnsureDebugInfo(shared)) {
1000 // Return if retrieving debug info failed.
1001 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001002 }
1003
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001004 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001005 // Source positions starts with zero.
1006 ASSERT(source_position >= 0);
1007
1008 // Find the break point and change it.
1009 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1010 it.FindBreakLocationFromPosition(source_position);
1011 it.SetBreakPoint(break_point_object);
1012
1013 // At least one active break point now.
1014 ASSERT(debug_info->GetBreakPointCount() > 0);
1015}
1016
1017
1018void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001019 HandleScope scope;
1020
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001021 DebugInfoListNode* node = debug_info_list_;
1022 while (node != NULL) {
1023 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1024 break_point_object);
1025 if (!result->IsUndefined()) {
1026 // Get information in the break point.
1027 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1028 Handle<DebugInfo> debug_info = node->debug_info();
1029 Handle<SharedFunctionInfo> shared(debug_info->shared());
1030 int source_position = break_point_info->statement_position()->value();
1031
1032 // Source positions starts with zero.
1033 ASSERT(source_position >= 0);
1034
1035 // Find the break point and clear it.
1036 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1037 it.FindBreakLocationFromPosition(source_position);
1038 it.ClearBreakPoint(break_point_object);
1039
1040 // If there are no more break points left remove the debug info for this
1041 // function.
1042 if (debug_info->GetBreakPointCount() == 0) {
1043 RemoveDebugInfo(debug_info);
1044 }
1045
1046 return;
1047 }
1048 node = node->next();
1049 }
1050}
1051
1052
ager@chromium.org381abbb2009-02-25 13:23:22 +00001053void Debug::ClearAllBreakPoints() {
1054 DebugInfoListNode* node = debug_info_list_;
1055 while (node != NULL) {
1056 // Remove all debug break code.
1057 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1058 it.ClearAllDebugBreak();
1059 node = node->next();
1060 }
1061
1062 // Remove all debug info.
1063 while (debug_info_list_ != NULL) {
1064 RemoveDebugInfo(debug_info_list_->debug_info());
1065 }
1066}
1067
1068
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001069void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001070 // Make sure the function has setup the debug info.
1071 if (!EnsureDebugInfo(shared)) {
1072 // Return if we failed to retrieve the debug info.
1073 return;
1074 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001075
1076 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001077 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001078 while (!it.Done()) {
1079 it.SetOneShot();
1080 it.Next();
1081 }
1082}
1083
1084
1085void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001086 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001087 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001088 if (id == StackFrame::NO_ID) {
1089 // If there is no JavaScript stack don't do anything.
1090 return;
1091 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001092 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1093 JavaScriptFrame* frame = it.frame();
1094 if (frame->HasHandler()) {
1095 Handle<SharedFunctionInfo> shared =
1096 Handle<SharedFunctionInfo>(
1097 JSFunction::cast(frame->function())->shared());
1098 // Flood the function with the catch block with break points
1099 FloodWithOneShot(shared);
1100 return;
1101 }
1102 }
1103}
1104
1105
1106void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1107 if (type == BreakUncaughtException) {
1108 break_on_uncaught_exception_ = enable;
1109 } else {
1110 break_on_exception_ = enable;
1111 }
1112}
1113
1114
1115void Debug::PrepareStep(StepAction step_action, int step_count) {
1116 HandleScope scope;
1117 ASSERT(Debug::InDebugger());
1118
1119 // Remember this step action and count.
1120 thread_local_.last_step_action_ = step_action;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001121 if (step_action == StepOut) {
1122 // For step out target frame will be found on the stack so there is no need
1123 // to set step counter for it. It's expected to always be 0 for StepOut.
1124 thread_local_.step_count_ = 0;
1125 } else {
1126 thread_local_.step_count_ = step_count;
1127 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001128
1129 // Get the frame where the execution has stopped and skip the debug frame if
1130 // any. The debug frame will only be present if execution was stopped due to
1131 // hitting a break point. In other situations (e.g. unhandled exception) the
1132 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001133 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001134 if (id == StackFrame::NO_ID) {
1135 // If there is no JavaScript stack don't do anything.
1136 return;
1137 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001138 JavaScriptFrameIterator frames_it(id);
1139 JavaScriptFrame* frame = frames_it.frame();
1140
1141 // First of all ensure there is one-shot break points in the top handler
1142 // if any.
1143 FloodHandlerWithOneShot();
1144
1145 // If the function on the top frame is unresolved perform step out. This will
1146 // be the case when calling unknown functions and having the debugger stopped
1147 // in an unhandled exception.
1148 if (!frame->function()->IsJSFunction()) {
1149 // Step out: Find the calling JavaScript frame and flood it with
1150 // breakpoints.
1151 frames_it.Advance();
1152 // Fill the function to return to with one-shot break points.
1153 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1154 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1155 return;
1156 }
1157
1158 // Get the debug info (create it if it does not exist).
1159 Handle<SharedFunctionInfo> shared =
1160 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001161 if (!EnsureDebugInfo(shared)) {
1162 // Return if ensuring debug info failed.
1163 return;
1164 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001165 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1166
1167 // Find the break location where execution has stopped.
1168 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1169 it.FindBreakLocationFromAddress(frame->pc());
1170
1171 // Compute whether or not the target is a call target.
1172 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001173 bool is_load_or_store = false;
1174 bool is_inline_cache_stub = false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001175 Handle<Code> call_function_stub;
ager@chromium.org236ad962008-09-25 09:45:57 +00001176 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001177 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001178 Code* code = Code::GetCodeFromTargetAddress(target);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001179 if (code->is_call_stub()) {
1180 is_call_target = true;
1181 }
1182 if (code->is_inline_cache_stub()) {
1183 is_inline_cache_stub = true;
1184 is_load_or_store = !is_call_target;
1185 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001186
1187 // Check if target code is CallFunction stub.
1188 Code* maybe_call_function_stub = code;
1189 // If there is a breakpoint at this line look at the original code to
1190 // check if it is a CallFunction stub.
1191 if (it.IsDebugBreak()) {
1192 Address original_target = it.original_rinfo()->target_address();
1193 maybe_call_function_stub =
1194 Code::GetCodeFromTargetAddress(original_target);
1195 }
1196 if (maybe_call_function_stub->kind() == Code::STUB &&
1197 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1198 // Save reference to the code as we may need it to find out arguments
1199 // count for 'step in' later.
1200 call_function_stub = Handle<Code>(maybe_call_function_stub);
1201 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001202 }
1203
v8.team.kasperl727e9952008-09-02 14:56:44 +00001204 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001205 if (it.IsExit() || step_action == StepOut) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001206 if (step_action == StepOut) {
1207 // Skip step_count frames starting with the current one.
1208 while (step_count-- > 0 && !frames_it.done()) {
1209 frames_it.Advance();
1210 }
1211 } else {
1212 ASSERT(it.IsExit());
1213 frames_it.Advance();
1214 }
1215 // Skip builtin functions on the stack.
1216 while (!frames_it.done() &&
1217 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1218 frames_it.Advance();
1219 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001220 // Step out: If there is a JavaScript caller frame, we need to
1221 // flood it with breakpoints.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001222 if (!frames_it.done()) {
1223 // Fill the function to return to with one-shot break points.
1224 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1225 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001226 // Set target frame pointer.
1227 ActivateStepOut(frames_it.frame());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001228 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001229 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1230 !call_function_stub.is_null())
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001231 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001232 // Step next or step min.
1233
1234 // Fill the current function with one-shot break points.
1235 FloodWithOneShot(shared);
1236
1237 // Remember source position and frame to handle step next.
1238 thread_local_.last_statement_position_ =
1239 debug_info->code()->SourceStatementPosition(frame->pc());
1240 thread_local_.last_fp_ = frame->fp();
1241 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001242 // If it's CallFunction stub ensure target function is compiled and flood
1243 // it with one shot breakpoints.
1244 if (!call_function_stub.is_null()) {
1245 // Find out number of arguments from the stub minor key.
1246 // Reverse lookup required as the minor key cannot be retrieved
1247 // from the code object.
1248 Handle<Object> obj(
1249 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1250 ASSERT(*obj != Heap::undefined_value());
1251 ASSERT(obj->IsSmi());
1252 // Get the STUB key and extract major and minor key.
1253 uint32_t key = Smi::cast(*obj)->value();
1254 // Argc in the stub is the number of arguments passed - not the
1255 // expected arguments of the called function.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001256 int call_function_arg_count =
1257 CallFunctionStub::ExtractArgcFromMinorKey(
1258 CodeStub::MinorKeyFromKey(key));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001259 ASSERT(call_function_stub->major_key() ==
1260 CodeStub::MajorKeyFromKey(key));
1261
1262 // Find target function on the expression stack.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001263 // Expression stack looks like this (top to bottom):
ager@chromium.orga1645e22009-09-09 19:27:10 +00001264 // argN
1265 // ...
1266 // arg0
1267 // Receiver
1268 // Function to call
1269 int expressions_count = frame->ComputeExpressionsCount();
1270 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1271 Object* fun = frame->GetExpression(
1272 expressions_count - 2 - call_function_arg_count);
1273 if (fun->IsJSFunction()) {
1274 Handle<JSFunction> js_function(JSFunction::cast(fun));
1275 // Don't step into builtins.
1276 if (!js_function->IsBuiltin()) {
1277 // It will also compile target function if it's not compiled yet.
1278 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1279 }
1280 }
1281 }
1282
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001283 // Fill the current function with one-shot break points even for step in on
1284 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001285 // which step in will not stop. It also prepares for stepping in
1286 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001287 FloodWithOneShot(shared);
1288
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001289 if (is_load_or_store) {
1290 // Remember source position and frame to handle step in getter/setter. If
1291 // there is a custom getter/setter it will be handled in
1292 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1293 // propagated on the next Debug::Break.
1294 thread_local_.last_statement_position_ =
1295 debug_info->code()->SourceStatementPosition(frame->pc());
1296 thread_local_.last_fp_ = frame->fp();
1297 }
1298
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001299 // Step in or Step in min
1300 it.PrepareStepIn();
1301 ActivateStepIn(frame);
1302 }
1303}
1304
1305
1306// Check whether the current debug break should be reported to the debugger. It
1307// is used to have step next and step in only report break back to the debugger
1308// if on a different frame or in a different statement. In some situations
1309// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001310// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001311// steps before reporting break back to the debugger.
1312bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1313 JavaScriptFrame* frame) {
1314 // If the step last action was step next or step in make sure that a new
1315 // statement is hit.
1316 if (thread_local_.last_step_action_ == StepNext ||
1317 thread_local_.last_step_action_ == StepIn) {
1318 // Never continue if returning from function.
1319 if (break_location_iterator->IsExit()) return false;
1320
1321 // Continue if we are still on the same frame and in the same statement.
1322 int current_statement_position =
1323 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1324 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001325 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001326 }
1327
1328 // No step next action - don't continue.
1329 return false;
1330}
1331
1332
1333// Check whether the code object at the specified address is a debug break code
1334// object.
1335bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001336 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001337 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001338}
1339
1340
1341// Check whether a code stub with the specified major key is a possible break
1342// point location when looking for source break locations.
1343bool Debug::IsSourceBreakStub(Code* code) {
1344 CodeStub::Major major_key = code->major_key();
1345 return major_key == CodeStub::CallFunction;
1346}
1347
1348
1349// Check whether a code stub with the specified major key is a possible break
1350// location.
1351bool Debug::IsBreakStub(Code* code) {
1352 CodeStub::Major major_key = code->major_key();
1353 return major_key == CodeStub::CallFunction ||
1354 major_key == CodeStub::StackCheck;
1355}
1356
1357
1358// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001359Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001360 // Find the builtin debug break function matching the calling convention
1361 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001362 if (code->is_inline_cache_stub()) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001363 switch (code->kind()) {
1364 case Code::CALL_IC:
1365 return ComputeCallDebugBreak(code->arguments_count());
1366
1367 case Code::LOAD_IC:
1368 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1369
1370 case Code::STORE_IC:
1371 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1372
1373 case Code::KEYED_LOAD_IC:
1374 return Handle<Code>(
1375 Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1376
1377 case Code::KEYED_STORE_IC:
1378 return Handle<Code>(
1379 Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1380
1381 default:
1382 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001383 }
1384 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001385 if (RelocInfo::IsConstructCall(mode)) {
1386 Handle<Code> result =
1387 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1388 return result;
1389 }
1390 if (code->kind() == Code::STUB) {
1391 ASSERT(code->major_key() == CodeStub::CallFunction ||
1392 code->major_key() == CodeStub::StackCheck);
1393 Handle<Code> result =
1394 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1395 return result;
1396 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001397
1398 UNREACHABLE();
1399 return Handle<Code>::null();
1400}
1401
1402
1403// Simple function for returning the source positions for active break points.
1404Handle<Object> Debug::GetSourceBreakLocations(
1405 Handle<SharedFunctionInfo> shared) {
1406 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1407 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1408 if (debug_info->GetBreakPointCount() == 0) {
1409 return Handle<Object>(Heap::undefined_value());
1410 }
1411 Handle<FixedArray> locations =
1412 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1413 int count = 0;
1414 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1415 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1416 BreakPointInfo* break_point_info =
1417 BreakPointInfo::cast(debug_info->break_points()->get(i));
1418 if (break_point_info->GetBreakPointCount() > 0) {
1419 locations->set(count++, break_point_info->statement_position());
1420 }
1421 }
1422 }
1423 return locations;
1424}
1425
1426
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001427void Debug::NewBreak(StackFrame::Id break_frame_id) {
1428 thread_local_.break_frame_id_ = break_frame_id;
1429 thread_local_.break_id_ = ++thread_local_.break_count_;
1430}
1431
1432
1433void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1434 thread_local_.break_frame_id_ = break_frame_id;
1435 thread_local_.break_id_ = break_id;
1436}
1437
1438
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001439// Handle stepping into a function.
1440void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001441 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001442 Address fp,
1443 bool is_constructor) {
1444 // If the frame pointer is not supplied by the caller find it.
1445 if (fp == 0) {
1446 StackFrameIterator it;
1447 it.Advance();
1448 // For constructor functions skip another frame.
1449 if (is_constructor) {
1450 ASSERT(it.frame()->is_construct());
1451 it.Advance();
1452 }
1453 fp = it.frame()->fp();
1454 }
1455
1456 // Flood the function with one-shot break points if it is called from where
1457 // step into was requested.
1458 if (fp == Debug::step_in_fp()) {
1459 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001460 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001461 if (function->shared()->code() ==
1462 Builtins::builtin(Builtins::FunctionApply) ||
1463 function->shared()->code() ==
1464 Builtins::builtin(Builtins::FunctionCall)) {
1465 // Handle function.apply and function.call separately to flood the
1466 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001467 // Builtins::FunctionCall. The receiver of call/apply is the target
1468 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001469 if (!holder.is_null() && holder->IsJSFunction() &&
1470 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001471 Handle<SharedFunctionInfo> shared_info(
1472 JSFunction::cast(*holder)->shared());
1473 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001474 }
1475 } else {
1476 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1477 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001478 }
1479 }
1480}
1481
1482
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001483void Debug::ClearStepping() {
1484 // Clear the various stepping setup.
1485 ClearOneShot();
1486 ClearStepIn();
ager@chromium.orga1645e22009-09-09 19:27:10 +00001487 ClearStepOut();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001488 ClearStepNext();
1489
1490 // Clear multiple step counter.
1491 thread_local_.step_count_ = 0;
1492}
1493
1494// Clears all the one-shot break points that are currently set. Normally this
1495// function is called each time a break point is hit as one shot break points
1496// are used to support stepping.
1497void Debug::ClearOneShot() {
1498 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001499 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001500 // removed from the list.
1501
1502 DebugInfoListNode* node = debug_info_list_;
1503 while (node != NULL) {
1504 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1505 while (!it.Done()) {
1506 it.ClearOneShot();
1507 it.Next();
1508 }
1509 node = node->next();
1510 }
1511}
1512
1513
1514void Debug::ActivateStepIn(StackFrame* frame) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001515 ASSERT(!StepOutActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001516 thread_local_.step_into_fp_ = frame->fp();
1517}
1518
1519
1520void Debug::ClearStepIn() {
1521 thread_local_.step_into_fp_ = 0;
1522}
1523
1524
ager@chromium.orga1645e22009-09-09 19:27:10 +00001525void Debug::ActivateStepOut(StackFrame* frame) {
1526 ASSERT(!StepInActive());
1527 thread_local_.step_out_fp_ = frame->fp();
1528}
1529
1530
1531void Debug::ClearStepOut() {
1532 thread_local_.step_out_fp_ = 0;
1533}
1534
1535
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001536void Debug::ClearStepNext() {
1537 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001538 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001539 thread_local_.last_fp_ = 0;
1540}
1541
1542
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001543// Ensures the debug information is present for shared.
1544bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1545 // Return if we already have the debug info for shared.
1546 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001547
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001548 // Ensure shared in compiled. Return false if this failed.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001549 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001550
1551 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001552 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001553
1554 // Add debug info to the list.
1555 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1556 node->set_next(debug_info_list_);
1557 debug_info_list_ = node;
1558
1559 // Now there is at least one break point.
1560 has_break_points_ = true;
1561
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001562 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001563}
1564
1565
1566void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1567 ASSERT(debug_info_list_ != NULL);
1568 // Run through the debug info objects to find this one and remove it.
1569 DebugInfoListNode* prev = NULL;
1570 DebugInfoListNode* current = debug_info_list_;
1571 while (current != NULL) {
1572 if (*current->debug_info() == *debug_info) {
1573 // Unlink from list. If prev is NULL we are looking at the first element.
1574 if (prev == NULL) {
1575 debug_info_list_ = current->next();
1576 } else {
1577 prev->set_next(current->next());
1578 }
1579 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1580 delete current;
1581
1582 // If there are no more debug info objects there are not more break
1583 // points.
1584 has_break_points_ = debug_info_list_ != NULL;
1585
1586 return;
1587 }
1588 // Move to next in list.
1589 prev = current;
1590 current = current->next();
1591 }
1592 UNREACHABLE();
1593}
1594
1595
1596void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001597 HandleScope scope;
1598
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001599 // Get the executing function in which the debug break occurred.
1600 Handle<SharedFunctionInfo> shared =
1601 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001602 if (!EnsureDebugInfo(shared)) {
1603 // Return if we failed to retrieve the debug info.
1604 return;
1605 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001606 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1607 Handle<Code> code(debug_info->code());
1608 Handle<Code> original_code(debug_info->original_code());
1609#ifdef DEBUG
1610 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001611 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001612 ASSERT(frame_code.is_identical_to(code));
1613#endif
1614
1615 // Find the call address in the running code. This address holds the call to
1616 // either a DebugBreakXXX or to the debug break return entry code if the
1617 // break point is still active after processing the break point.
ager@chromium.org4af710e2009-09-15 12:20:11 +00001618 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001619
1620 // Check if the location is at JS exit.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001621 bool at_js_return = false;
1622 bool break_at_js_return_active = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001623 RelocIterator it(debug_info->code());
1624 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001625 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001626 at_js_return = (it.rinfo()->pc() ==
1627 addr - Assembler::kPatchReturnSequenceAddressOffset);
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001628 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629 }
1630 it.next();
1631 }
1632
1633 // Handle the jump to continue execution after break point depending on the
1634 // break location.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001635 if (at_js_return) {
1636 // If the break point as return is still active jump to the corresponding
1637 // place in the original code. If not the break point was removed during
1638 // break point processing.
1639 if (break_at_js_return_active) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001640 addr += original_code->instruction_start() - code->instruction_start();
1641 }
1642
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001643 // Move back to where the call instruction sequence started.
1644 thread_local_.after_break_target_ =
1645 addr - Assembler::kPatchReturnSequenceAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001646 } else {
1647 // Check if there still is a debug break call at the target address. If the
1648 // break point has been removed it will have disappeared. If it have
1649 // disappeared don't try to look in the original code as the running code
1650 // will have the right address. This takes care of the case where the last
1651 // break point is removed from the function and therefore no "original code"
1652 // is available. If the debug break call is still there find the address in
1653 // the original code.
1654 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1655 // If the break point is still there find the call address which was
1656 // overwritten in the original code by the call to DebugBreakXXX.
1657
1658 // Find the corresponding address in the original code.
1659 addr += original_code->instruction_start() - code->instruction_start();
1660 }
1661
1662 // Install jump to the call address in the original code. This will be the
1663 // call which was overwritten by the call to DebugBreakXXX.
1664 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1665 }
1666}
1667
1668
ager@chromium.org357bf652010-04-12 11:30:10 +00001669void Debug::FramesHaveBeenDropped(StackFrame::Id new_break_frame_id) {
1670 thread_local_.frames_are_dropped_ = true;
1671 thread_local_.break_frame_id_ = new_break_frame_id;
1672}
1673
1674
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001675bool Debug::IsDebugGlobal(GlobalObject* global) {
1676 return IsLoaded() && global == Debug::debug_context()->global();
1677}
1678
1679
ager@chromium.org32912102009-01-16 10:38:43 +00001680void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001681 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001682 ASSERT(Top::context() == *Debug::debug_context());
1683
1684 // Clear the mirror cache.
1685 Handle<String> function_name =
1686 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1687 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1688 ASSERT(fun->IsJSFunction());
1689 bool caught_exception;
1690 Handle<Object> js_object = Execution::TryCall(
1691 Handle<JSFunction>::cast(fun),
1692 Handle<JSObject>(Debug::debug_context()->global()),
1693 0, NULL, &caught_exception);
1694}
1695
1696
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001697void Debug::CreateScriptCache() {
1698 HandleScope scope;
1699
1700 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1701 // rid of all the cached script wrappers and the second gets rid of the
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00001702 // scripts which are no longer referenced.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001703 Heap::CollectAllGarbage(false);
1704 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001705
1706 ASSERT(script_cache_ == NULL);
1707 script_cache_ = new ScriptCache();
1708
1709 // Scan heap for Script objects.
1710 int count = 0;
1711 HeapIterator iterator;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001712 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +00001713 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001714 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1715 count++;
1716 }
1717 }
1718}
1719
1720
1721void Debug::DestroyScriptCache() {
1722 // Get rid of the script cache if it was created.
1723 if (script_cache_ != NULL) {
1724 delete script_cache_;
1725 script_cache_ = NULL;
1726 }
1727}
1728
1729
1730void Debug::AddScriptToScriptCache(Handle<Script> script) {
1731 if (script_cache_ != NULL) {
1732 script_cache_->Add(script);
1733 }
1734}
1735
1736
1737Handle<FixedArray> Debug::GetLoadedScripts() {
1738 // Create and fill the script cache when the loaded scripts is requested for
1739 // the first time.
1740 if (script_cache_ == NULL) {
1741 CreateScriptCache();
1742 }
1743
1744 // If the script cache is not active just return an empty array.
1745 ASSERT(script_cache_ != NULL);
1746 if (script_cache_ == NULL) {
1747 Factory::NewFixedArray(0);
1748 }
1749
1750 // Perform GC to get unreferenced scripts evicted from the cache before
1751 // returning the content.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001752 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001753
1754 // Get the scripts from the cache.
1755 return script_cache_->GetScripts();
1756}
1757
1758
1759void Debug::AfterGarbageCollection() {
1760 // Generate events for collected scripts.
1761 if (script_cache_ != NULL) {
1762 script_cache_->ProcessCollectedScripts();
1763 }
1764}
1765
1766
ager@chromium.org71daaf62009-04-01 07:22:49 +00001767Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001768Handle<Object> Debugger::event_listener_ = Handle<Object>();
1769Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001770bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001771bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001772bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001773v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001774bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001775v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001776Mutex* Debugger::dispatch_handler_access_ = OS::CreateMutex();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001777v8::Debug::DebugMessageDispatchHandler
1778 Debugger::debug_message_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001779MessageDispatchHelperThread* Debugger::message_dispatch_helper_thread_ = NULL;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001780int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001781DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001782LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001783Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001784
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001785
1786Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1787 int argc, Object*** argv,
1788 bool* caught_exception) {
1789 ASSERT(Top::context() == *Debug::debug_context());
1790
1791 // Create the execution state object.
1792 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1793 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1794 ASSERT(constructor->IsJSFunction());
1795 if (!constructor->IsJSFunction()) {
1796 *caught_exception = true;
1797 return Factory::undefined_value();
1798 }
1799 Handle<Object> js_object = Execution::TryCall(
1800 Handle<JSFunction>::cast(constructor),
1801 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1802 caught_exception);
1803 return js_object;
1804}
1805
1806
1807Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1808 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001809 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001810 const int argc = 1;
1811 Object** argv[argc] = { break_id.location() };
1812 return MakeJSObject(CStrVector("MakeExecutionState"),
1813 argc, argv, caught_exception);
1814}
1815
1816
1817Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1818 Handle<Object> break_points_hit,
1819 bool* caught_exception) {
1820 // Create the new break event object.
1821 const int argc = 2;
1822 Object** argv[argc] = { exec_state.location(),
1823 break_points_hit.location() };
1824 return MakeJSObject(CStrVector("MakeBreakEvent"),
1825 argc,
1826 argv,
1827 caught_exception);
1828}
1829
1830
1831Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1832 Handle<Object> exception,
1833 bool uncaught,
1834 bool* caught_exception) {
1835 // Create the new exception event object.
1836 const int argc = 3;
1837 Object** argv[argc] = { exec_state.location(),
1838 exception.location(),
1839 uncaught ? Factory::true_value().location() :
1840 Factory::false_value().location()};
1841 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1842 argc, argv, caught_exception);
1843}
1844
1845
1846Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1847 bool* caught_exception) {
1848 // Create the new function event object.
1849 const int argc = 1;
1850 Object** argv[argc] = { function.location() };
1851 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1852 argc, argv, caught_exception);
1853}
1854
1855
1856Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001857 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001858 bool* caught_exception) {
1859 // Create the compile event object.
1860 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001861 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001862 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001863 Object** argv[argc] = { exec_state.location(),
1864 script_wrapper.location(),
1865 before ? Factory::true_value().location() :
1866 Factory::false_value().location() };
1867
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001868 return MakeJSObject(CStrVector("MakeCompileEvent"),
1869 argc,
1870 argv,
1871 caught_exception);
1872}
1873
1874
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001875Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1876 bool* caught_exception) {
1877 // Create the script collected event object.
1878 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1879 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1880 const int argc = 2;
1881 Object** argv[argc] = { exec_state.location(), id_object.location() };
1882
1883 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1884 argc,
1885 argv,
1886 caught_exception);
1887}
1888
1889
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001890void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1891 HandleScope scope;
1892
1893 // Bail out based on state or if there is no listener for this event
1894 if (Debug::InDebugger()) return;
1895 if (!Debugger::EventActive(v8::Exception)) return;
1896
1897 // Bail out if exception breaks are not active
1898 if (uncaught) {
1899 // Uncaught exceptions are reported by either flags.
1900 if (!(Debug::break_on_uncaught_exception() ||
1901 Debug::break_on_exception())) return;
1902 } else {
1903 // Caught exceptions are reported is activated.
1904 if (!Debug::break_on_exception()) return;
1905 }
1906
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001907 // Enter the debugger.
1908 EnterDebugger debugger;
1909 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001910
1911 // Clear all current stepping setup.
1912 Debug::ClearStepping();
1913 // Create the event data object.
1914 bool caught_exception = false;
1915 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1916 Handle<Object> event_data;
1917 if (!caught_exception) {
1918 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1919 &caught_exception);
1920 }
1921 // Bail out and don't call debugger if exception.
1922 if (caught_exception) {
1923 return;
1924 }
1925
ager@chromium.org5ec48922009-05-05 07:25:34 +00001926 // Process debug event.
1927 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001928 // Return to continue execution from where the exception was thrown.
1929}
1930
1931
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001932void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1933 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001934 HandleScope scope;
1935
kasper.lund212ac232008-07-16 07:07:30 +00001936 // Debugger has already been entered by caller.
1937 ASSERT(Top::context() == *Debug::debug_context());
1938
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001939 // Bail out if there is no listener for this event
1940 if (!Debugger::EventActive(v8::Break)) return;
1941
1942 // Debugger must be entered in advance.
1943 ASSERT(Top::context() == *Debug::debug_context());
1944
1945 // Create the event data object.
1946 bool caught_exception = false;
1947 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1948 Handle<Object> event_data;
1949 if (!caught_exception) {
1950 event_data = MakeBreakEvent(exec_state, break_points_hit,
1951 &caught_exception);
1952 }
1953 // Bail out and don't call debugger if exception.
1954 if (caught_exception) {
1955 return;
1956 }
1957
ager@chromium.org5ec48922009-05-05 07:25:34 +00001958 // Process debug event.
1959 ProcessDebugEvent(v8::Break,
1960 Handle<JSObject>::cast(event_data),
1961 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001962}
1963
1964
1965void Debugger::OnBeforeCompile(Handle<Script> script) {
1966 HandleScope scope;
1967
1968 // Bail out based on state or if there is no listener for this event
1969 if (Debug::InDebugger()) return;
1970 if (compiling_natives()) return;
1971 if (!EventActive(v8::BeforeCompile)) return;
1972
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001973 // Enter the debugger.
1974 EnterDebugger debugger;
1975 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001976
1977 // Create the event data object.
1978 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001979 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001980 // Bail out and don't call debugger if exception.
1981 if (caught_exception) {
1982 return;
1983 }
1984
ager@chromium.org5ec48922009-05-05 07:25:34 +00001985 // Process debug event.
1986 ProcessDebugEvent(v8::BeforeCompile,
1987 Handle<JSObject>::cast(event_data),
1988 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001989}
1990
1991
1992// Handle debugger actions when a new script is compiled.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001993void Debugger::OnAfterCompile(Handle<Script> script,
1994 AfterCompileFlags after_compile_flags) {
kasper.lund212ac232008-07-16 07:07:30 +00001995 HandleScope scope;
1996
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001997 // Add the newly compiled script to the script cache.
1998 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001999
2000 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00002001 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002002
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002003 // No compile events while compiling natives.
2004 if (compiling_natives()) return;
2005
iposva@chromium.org245aa852009-02-10 00:49:54 +00002006 // Store whether in debugger before entering debugger.
2007 bool in_debugger = Debug::InDebugger();
2008
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002009 // Enter the debugger.
2010 EnterDebugger debugger;
2011 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002012
2013 // If debugging there might be script break points registered for this
2014 // script. Make sure that these break points are set.
2015
kmillikin@chromium.org5d8f0e62010-03-24 08:21:20 +00002016 // Get the function UpdateScriptBreakPoints (defined in debug-debugger.js).
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002017 Handle<Object> update_script_break_points =
2018 Handle<Object>(Debug::debug_context()->global()->GetProperty(
2019 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
2020 if (!update_script_break_points->IsJSFunction()) {
2021 return;
2022 }
2023 ASSERT(update_script_break_points->IsJSFunction());
2024
2025 // Wrap the script object in a proper JS object before passing it
2026 // to JavaScript.
2027 Handle<JSValue> wrapper = GetScriptWrapper(script);
2028
2029 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00002030 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002031 const int argc = 1;
2032 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2033 Handle<Object> result = Execution::TryCall(
2034 Handle<JSFunction>::cast(update_script_break_points),
2035 Top::builtins(), argc, argv,
2036 &caught_exception);
2037 if (caught_exception) {
2038 return;
2039 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002040 // Bail out based on state or if there is no listener for this event
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002041 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002042 if (!Debugger::EventActive(v8::AfterCompile)) return;
2043
2044 // Create the compile state object.
2045 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002046 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002047 &caught_exception);
2048 // Bail out and don't call debugger if exception.
2049 if (caught_exception) {
2050 return;
2051 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00002052 // Process debug event.
2053 ProcessDebugEvent(v8::AfterCompile,
2054 Handle<JSObject>::cast(event_data),
2055 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002056}
2057
2058
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002059void Debugger::OnScriptCollected(int id) {
2060 HandleScope scope;
2061
2062 // No more to do if not debugging.
2063 if (!IsDebuggerActive()) return;
2064 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2065
2066 // Enter the debugger.
2067 EnterDebugger debugger;
2068 if (debugger.FailedToEnter()) return;
2069
2070 // Create the script collected state object.
2071 bool caught_exception = false;
2072 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2073 &caught_exception);
2074 // Bail out and don't call debugger if exception.
2075 if (caught_exception) {
2076 return;
2077 }
2078
2079 // Process debug event.
2080 ProcessDebugEvent(v8::ScriptCollected,
2081 Handle<JSObject>::cast(event_data),
2082 true);
2083}
2084
2085
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002086void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002087 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002088 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002089 HandleScope scope;
2090
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002091 // Clear any pending debug break if this is a real break.
2092 if (!auto_continue) {
2093 Debug::clear_interrupt_pending(DEBUGBREAK);
2094 }
2095
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002096 // Create the execution state.
2097 bool caught_exception = false;
2098 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2099 if (caught_exception) {
2100 return;
2101 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002102 // First notify the message handler if any.
2103 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002104 NotifyMessageHandler(event,
2105 Handle<JSObject>::cast(exec_state),
2106 event_data,
2107 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002108 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002109 // Notify registered debug event listener. This can be either a C or a
2110 // JavaScript function.
2111 if (!event_listener_.is_null()) {
2112 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002113 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002114 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002115 v8::Debug::EventCallback callback =
2116 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002117 callback(event,
2118 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002119 v8::Utils::ToLocal(event_data),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002120 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002121 } else {
2122 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002123 ASSERT(event_listener_->IsJSFunction());
2124 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002125
2126 // Invoke the JavaScript debug event listener.
2127 const int argc = 4;
2128 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2129 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002130 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002131 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002132 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2133 argc, argv, &caught_exception);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002134 // Silently ignore exceptions from debug event listeners.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002135 }
2136 }
2137}
2138
2139
lrn@chromium.orgc34f5802010-04-28 12:53:43 +00002140Handle<Context> Debugger::GetDebugContext() {
2141 never_unload_debugger_ = true;
2142 EnterDebugger debugger;
2143 return Debug::debug_context();
2144}
2145
2146
ager@chromium.org71daaf62009-04-01 07:22:49 +00002147void Debugger::UnloadDebugger() {
2148 // Make sure that there are no breakpoints left.
2149 Debug::ClearAllBreakPoints();
2150
2151 // Unload the debugger if feasible.
2152 if (!never_unload_debugger_) {
2153 Debug::Unload();
2154 }
2155
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002156 // Clear the flag indicating that the debugger should be unloaded.
2157 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002158}
2159
2160
ager@chromium.org41826e72009-03-30 13:30:57 +00002161void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002162 Handle<JSObject> exec_state,
2163 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002164 bool auto_continue) {
2165 HandleScope scope;
2166
2167 if (!Debug::Load()) return;
2168
2169 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002170 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002171 switch (event) {
2172 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002173 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002174 break;
2175 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002176 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002177 break;
2178 case v8::BeforeCompile:
2179 break;
2180 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002181 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002182 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002183 case v8::ScriptCollected:
2184 sendEventMessage = true;
2185 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002186 case v8::NewFunction:
2187 break;
2188 default:
2189 UNREACHABLE();
2190 }
2191
ager@chromium.org5ec48922009-05-05 07:25:34 +00002192 // The debug command interrupt flag might have been set when the command was
2193 // added. It should be enough to clear the flag only once while we are in the
2194 // debugger.
2195 ASSERT(Debug::InDebugger());
2196 StackGuard::Continue(DEBUGCOMMAND);
2197
2198 // Notify the debugger that a debug event has occurred unless auto continue is
2199 // active in which case no event is send.
2200 if (sendEventMessage) {
2201 MessageImpl message = MessageImpl::NewEvent(
2202 event,
2203 auto_continue,
2204 Handle<JSObject>::cast(exec_state),
2205 Handle<JSObject>::cast(event_data));
2206 InvokeMessageHandler(message);
2207 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002208
2209 // If auto continue don't make the event cause a break, but process messages
2210 // in the queue if any. For script collected events don't even process
2211 // messages in the queue as the execution state might not be what is expected
2212 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002213 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002214 return;
2215 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002216
ager@chromium.org41826e72009-03-30 13:30:57 +00002217 v8::TryCatch try_catch;
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002218
2219 // DebugCommandProcessor goes here.
2220 v8::Local<v8::Object> cmd_processor;
2221 {
2222 v8::Local<v8::Object> api_exec_state =
2223 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2224 v8::Local<v8::String> fun_name =
2225 v8::String::New("debugCommandProcessor");
2226 v8::Local<v8::Function> fun =
2227 v8::Function::Cast(*api_exec_state->Get(fun_name));
2228
2229 v8::Handle<v8::Boolean> running =
2230 auto_continue ? v8::True() : v8::False();
2231 static const int kArgc = 1;
2232 v8::Handle<Value> argv[kArgc] = { running };
2233 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2234 if (try_catch.HasCaught()) {
2235 PrintLn(try_catch.Exception());
2236 return;
2237 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002238 }
2239
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002240 bool running = auto_continue;
2241
ager@chromium.org41826e72009-03-30 13:30:57 +00002242 // Process requests from the debugger.
2243 while (true) {
2244 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002245 if (Debugger::host_dispatch_handler_) {
2246 // In case there is a host dispatch - do periodic dispatches.
2247 if (!command_received_->Wait(host_dispatch_micros_)) {
2248 // Timout expired, do the dispatch.
2249 Debugger::host_dispatch_handler_();
2250 continue;
2251 }
2252 } else {
2253 // In case there is no host dispatch - just wait.
2254 command_received_->Wait();
2255 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002256
ager@chromium.org41826e72009-03-30 13:30:57 +00002257 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002258 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002259 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002260 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002261 // Delete command text and user data.
2262 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002263 return;
2264 }
2265
ager@chromium.org41826e72009-03-30 13:30:57 +00002266 // Invoke JavaScript to process the debug request.
2267 v8::Local<v8::String> fun_name;
2268 v8::Local<v8::Function> fun;
2269 v8::Local<v8::Value> request;
2270 v8::TryCatch try_catch;
2271 fun_name = v8::String::New("processDebugRequest");
2272 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002273
2274 request = v8::String::New(command.text().start(),
2275 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002276 static const int kArgc = 1;
2277 v8::Handle<Value> argv[kArgc] = { request };
2278 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2279
2280 // Get the response.
2281 v8::Local<v8::String> response;
ager@chromium.org41826e72009-03-30 13:30:57 +00002282 if (!try_catch.HasCaught()) {
2283 // Get response string.
2284 if (!response_val->IsUndefined()) {
2285 response = v8::String::Cast(*response_val);
2286 } else {
2287 response = v8::String::New("");
2288 }
2289
2290 // Log the JSON request/response.
2291 if (FLAG_trace_debug_json) {
2292 PrintLn(request);
2293 PrintLn(response);
2294 }
2295
2296 // Get the running state.
2297 fun_name = v8::String::New("isRunning");
2298 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2299 static const int kArgc = 1;
2300 v8::Handle<Value> argv[kArgc] = { response };
2301 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2302 if (!try_catch.HasCaught()) {
2303 running = running_val->ToBoolean()->Value();
2304 }
2305 } else {
2306 // In case of failure the result text is the exception text.
2307 response = try_catch.Exception()->ToString();
2308 }
2309
ager@chromium.org41826e72009-03-30 13:30:57 +00002310 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002311 MessageImpl message = MessageImpl::NewResponse(
2312 event,
2313 running,
2314 Handle<JSObject>::cast(exec_state),
2315 Handle<JSObject>::cast(event_data),
2316 Handle<String>(Utils::OpenHandle(*response)),
2317 command.client_data());
2318 InvokeMessageHandler(message);
2319 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002320
2321 // Return from debug event processing if either the VM is put into the
2322 // runnning state (through a continue command) or auto continue is active
2323 // and there are no more commands queued.
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002324 if (running && !HasCommands()) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002325 return;
2326 }
2327 }
2328}
2329
2330
iposva@chromium.org245aa852009-02-10 00:49:54 +00002331void Debugger::SetEventListener(Handle<Object> callback,
2332 Handle<Object> data) {
2333 HandleScope scope;
2334
2335 // Clear the global handles for the event listener and the event listener data
2336 // object.
2337 if (!event_listener_.is_null()) {
2338 GlobalHandles::Destroy(
2339 reinterpret_cast<Object**>(event_listener_.location()));
2340 event_listener_ = Handle<Object>();
2341 }
2342 if (!event_listener_data_.is_null()) {
2343 GlobalHandles::Destroy(
2344 reinterpret_cast<Object**>(event_listener_data_.location()));
2345 event_listener_data_ = Handle<Object>();
2346 }
2347
2348 // If there is a new debug event listener register it together with its data
2349 // object.
2350 if (!callback->IsUndefined() && !callback->IsNull()) {
2351 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2352 if (data.is_null()) {
2353 data = Factory::undefined_value();
2354 }
2355 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2356 }
2357
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002358 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002359}
2360
2361
ager@chromium.org5ec48922009-05-05 07:25:34 +00002362void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002363 ScopedLock with(debugger_access_);
2364
ager@chromium.org381abbb2009-02-25 13:23:22 +00002365 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002366 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002367 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002368 // Send an empty command to the debugger if in a break to make JavaScript
2369 // run again if the debugger is closed.
2370 if (Debug::InDebugger()) {
2371 ProcessCommand(Vector<const uint16_t>::empty());
2372 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002373 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002374}
2375
2376
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002377void Debugger::ListenersChanged() {
2378 if (IsDebuggerActive()) {
2379 // Disable the compilation cache when the debugger is active.
2380 CompilationCache::Disable();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002381 debugger_unload_pending_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002382 } else {
2383 CompilationCache::Enable();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002384 // Unload the debugger if event listener and message handler cleared.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002385 // Schedule this for later, because we may be in non-V8 thread.
2386 debugger_unload_pending_ = true;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002387 }
2388}
2389
2390
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002391void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2392 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002393 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002394 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002395}
2396
2397
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002398void Debugger::SetDebugMessageDispatchHandler(
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002399 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2400 ScopedLock with(dispatch_handler_access_);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002401 debug_message_dispatch_handler_ = handler;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002402
2403 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2404 message_dispatch_helper_thread_ = new MessageDispatchHelperThread;
2405 message_dispatch_helper_thread_->Start();
2406 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002407}
2408
2409
ager@chromium.org41826e72009-03-30 13:30:57 +00002410// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002411// public API.
2412void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002413 ScopedLock with(debugger_access_);
2414
ager@chromium.org381abbb2009-02-25 13:23:22 +00002415 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002416 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002417 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002418}
2419
2420
2421// Puts a command coming from the public API on the queue. Creates
2422// a copy of the command string managed by the debugger. Up to this
2423// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002424// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002425void Debugger::ProcessCommand(Vector<const uint16_t> command,
2426 v8::Debug::ClientData* client_data) {
2427 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002428 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002429 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002430 command.length()),
2431 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002432 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002433 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002434 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002435
2436 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002437 if (!Debug::InDebugger()) {
2438 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002439 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002440
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002441 MessageDispatchHelperThread* dispatch_thread;
2442 {
2443 ScopedLock with(dispatch_handler_access_);
2444 dispatch_thread = message_dispatch_helper_thread_;
2445 }
2446
2447 if (dispatch_thread == NULL) {
2448 CallMessageDispatchHandler();
2449 } else {
2450 dispatch_thread->Schedule();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002451 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002452}
2453
2454
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002455bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002456 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002457}
2458
2459
ager@chromium.org71daaf62009-04-01 07:22:49 +00002460bool Debugger::IsDebuggerActive() {
2461 ScopedLock with(debugger_access_);
2462
2463 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002464}
2465
2466
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002467Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2468 Handle<Object> data,
2469 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002470 // When calling functions in the debugger prevent it from beeing unloaded.
2471 Debugger::never_unload_debugger_ = true;
2472
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002473 // Enter the debugger.
2474 EnterDebugger debugger;
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00002475 if (debugger.FailedToEnter()) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002476 return Factory::undefined_value();
2477 }
2478
2479 // Create the execution state.
2480 bool caught_exception = false;
2481 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2482 if (caught_exception) {
2483 return Factory::undefined_value();
2484 }
2485
2486 static const int kArgc = 2;
2487 Object** argv[kArgc] = { exec_state.location(), data.location() };
sgjesse@chromium.orgdf7a2842010-03-25 14:34:15 +00002488 Handle<Object> result = Execution::Call(
2489 fun,
2490 Handle<Object>(Debug::debug_context_->global_proxy()),
2491 kArgc,
2492 argv,
2493 pending_exception);
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002494 return result;
2495}
2496
2497
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002498static void StubMessageHandler2(const v8::Debug::Message& message) {
2499 // Simply ignore message.
2500}
2501
2502
2503bool Debugger::StartAgent(const char* name, int port,
2504 bool wait_for_connection) {
2505 if (wait_for_connection) {
2506 // Suspend V8 if it is already running or set V8 to suspend whenever
2507 // it starts.
2508 // Provide stub message handler; V8 auto-continues each suspend
2509 // when there is no message handler; we doesn't need it.
2510 // Once become suspended, V8 will stay so indefinitely long, until remote
2511 // debugger connects and issues "continue" command.
2512 Debugger::message_handler_ = StubMessageHandler2;
2513 v8::Debug::DebugBreak();
2514 }
2515
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002516 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002517 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002518 agent_->Start();
2519 return true;
2520 }
2521
2522 return false;
2523}
2524
2525
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002526void Debugger::StopAgent() {
2527 if (agent_ != NULL) {
2528 agent_->Shutdown();
2529 agent_->Join();
2530 delete agent_;
2531 agent_ = NULL;
2532 }
2533}
2534
2535
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002536void Debugger::WaitForAgent() {
2537 if (agent_ != NULL)
2538 agent_->WaitUntilListening();
2539}
2540
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002541
2542void Debugger::CallMessageDispatchHandler() {
2543 v8::Debug::DebugMessageDispatchHandler handler;
2544 {
2545 ScopedLock with(dispatch_handler_access_);
2546 handler = Debugger::debug_message_dispatch_handler_;
2547 }
2548 if (handler != NULL) {
2549 handler();
2550 }
2551}
2552
2553
ager@chromium.org5ec48922009-05-05 07:25:34 +00002554MessageImpl MessageImpl::NewEvent(DebugEvent event,
2555 bool running,
2556 Handle<JSObject> exec_state,
2557 Handle<JSObject> event_data) {
2558 MessageImpl message(true, event, running,
2559 exec_state, event_data, Handle<String>(), NULL);
2560 return message;
2561}
2562
2563
2564MessageImpl MessageImpl::NewResponse(DebugEvent event,
2565 bool running,
2566 Handle<JSObject> exec_state,
2567 Handle<JSObject> event_data,
2568 Handle<String> response_json,
2569 v8::Debug::ClientData* client_data) {
2570 MessageImpl message(false, event, running,
2571 exec_state, event_data, response_json, client_data);
2572 return message;
2573}
2574
2575
2576MessageImpl::MessageImpl(bool is_event,
2577 DebugEvent event,
2578 bool running,
2579 Handle<JSObject> exec_state,
2580 Handle<JSObject> event_data,
2581 Handle<String> response_json,
2582 v8::Debug::ClientData* client_data)
2583 : is_event_(is_event),
2584 event_(event),
2585 running_(running),
2586 exec_state_(exec_state),
2587 event_data_(event_data),
2588 response_json_(response_json),
2589 client_data_(client_data) {}
2590
2591
2592bool MessageImpl::IsEvent() const {
2593 return is_event_;
2594}
2595
2596
2597bool MessageImpl::IsResponse() const {
2598 return !is_event_;
2599}
2600
2601
2602DebugEvent MessageImpl::GetEvent() const {
2603 return event_;
2604}
2605
2606
2607bool MessageImpl::WillStartRunning() const {
2608 return running_;
2609}
2610
2611
2612v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2613 return v8::Utils::ToLocal(exec_state_);
2614}
2615
2616
2617v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2618 return v8::Utils::ToLocal(event_data_);
2619}
2620
2621
2622v8::Handle<v8::String> MessageImpl::GetJSON() const {
2623 v8::HandleScope scope;
2624
2625 if (IsEvent()) {
2626 // Call toJSONProtocol on the debug event object.
2627 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2628 if (!fun->IsJSFunction()) {
2629 return v8::Handle<v8::String>();
2630 }
2631 bool caught_exception;
2632 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2633 event_data_,
2634 0, NULL, &caught_exception);
2635 if (caught_exception || !json->IsString()) {
2636 return v8::Handle<v8::String>();
2637 }
2638 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2639 } else {
2640 return v8::Utils::ToLocal(response_json_);
2641 }
2642}
2643
2644
2645v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002646 Handle<Context> context = Debug::debugger_entry()->GetContext();
2647 // Top::context() may have been NULL when "script collected" event occured.
2648 if (*context == NULL) {
2649 ASSERT(event_ == v8::ScriptCollected);
2650 return v8::Local<v8::Context>();
2651 }
2652 Handle<Context> global_context(context->global_context());
2653 return v8::Utils::ToLocal(global_context);
ager@chromium.org5ec48922009-05-05 07:25:34 +00002654}
2655
2656
2657v8::Debug::ClientData* MessageImpl::GetClientData() const {
2658 return client_data_;
2659}
2660
2661
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002662CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2663 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002664}
2665
2666
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002667CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2668 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002669 : text_(text),
2670 client_data_(data) {
2671}
2672
2673
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002674CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002675}
2676
2677
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002678void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002679 text_.Dispose();
2680 delete client_data_;
2681 client_data_ = NULL;
2682}
2683
2684
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002685CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2686 v8::Debug::ClientData* data) {
2687 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002688}
2689
2690
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002691CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2692 size_(size) {
2693 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002694}
2695
2696
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002697CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002698 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002699 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002700 m.Dispose();
2701 }
kasper.lund7276f142008-07-30 08:49:36 +00002702 DeleteArray(messages_);
2703}
2704
2705
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002706CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002707 ASSERT(!IsEmpty());
2708 int result = start_;
2709 start_ = (start_ + 1) % size_;
2710 return messages_[result];
2711}
2712
2713
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002714void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002715 if ((end_ + 1) % size_ == start_) {
2716 Expand();
2717 }
2718 messages_[end_] = message;
2719 end_ = (end_ + 1) % size_;
2720}
2721
2722
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002723void CommandMessageQueue::Expand() {
2724 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002725 while (!IsEmpty()) {
2726 new_queue.Put(Get());
2727 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002728 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002729 *this = new_queue;
2730 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002731 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2732 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002733 // Automatic destructor called on new_queue, freeing array_to_free.
2734}
2735
2736
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002737LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2738 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002739 lock_ = OS::CreateMutex();
2740}
2741
2742
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002743LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002744 delete lock_;
2745}
2746
2747
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002748bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002749 ScopedLock sl(lock_);
2750 return queue_.IsEmpty();
2751}
2752
2753
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002754CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002755 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002756 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002757 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002758 return result;
2759}
2760
2761
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002762void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002763 ScopedLock sl(lock_);
2764 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002765 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002766}
2767
2768
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002769void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002770 ScopedLock sl(lock_);
2771 queue_.Clear();
2772}
2773
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002774
2775MessageDispatchHelperThread::MessageDispatchHelperThread()
2776 : sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
2777 already_signalled_(false) {
2778}
2779
2780
2781MessageDispatchHelperThread::~MessageDispatchHelperThread() {
2782 delete mutex_;
2783 delete sem_;
2784}
2785
2786
2787void MessageDispatchHelperThread::Schedule() {
2788 {
2789 ScopedLock lock(mutex_);
2790 if (already_signalled_) {
2791 return;
2792 }
2793 already_signalled_ = true;
2794 }
2795 sem_->Signal();
2796}
2797
2798
2799void MessageDispatchHelperThread::Run() {
2800 while (true) {
2801 sem_->Wait();
2802 {
2803 ScopedLock lock(mutex_);
2804 already_signalled_ = false;
2805 }
2806 {
2807 Locker locker;
2808 Debugger::CallMessageDispatchHandler();
2809 }
2810 }
2811}
2812
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002813#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002814
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002815} } // namespace v8::internal