blob: 2a7a9c8290e4cf4f3d5fc49f615c8fc51c673925 [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();
55 char* data = NewArray<char>(s->Length() + 1);
56 if (data == NULL) {
57 V8::FatalProcessOutOfMemory("PrintLn");
58 return;
59 }
60 s->WriteAscii(data);
61 PrintF("%s\n", data);
62 DeleteArray(data);
63}
64
65
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000066static Handle<Code> ComputeCallDebugBreak(int argc) {
67 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
68}
69
70
71static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
72 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
73}
74
75
76BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
77 BreakLocatorType type) {
78 debug_info_ = debug_info;
79 type_ = type;
80 reloc_iterator_ = NULL;
81 reloc_iterator_original_ = NULL;
82 Reset(); // Initialize the rest of the member variables.
83}
84
85
86BreakLocationIterator::~BreakLocationIterator() {
87 ASSERT(reloc_iterator_ != NULL);
88 ASSERT(reloc_iterator_original_ != NULL);
89 delete reloc_iterator_;
90 delete reloc_iterator_original_;
91}
92
93
94void BreakLocationIterator::Next() {
95 AssertNoAllocation nogc;
96 ASSERT(!RinfoDone());
97
98 // Iterate through reloc info for code and original code stopping at each
99 // breakable code target.
100 bool first = break_point_ == -1;
101 while (!RinfoDone()) {
102 if (!first) RinfoNext();
103 first = false;
104 if (RinfoDone()) return;
105
ager@chromium.org236ad962008-09-25 09:45:57 +0000106 // Whenever a statement position or (plain) position is passed update the
107 // current value of these.
108 if (RelocInfo::IsPosition(rmode())) {
109 if (RelocInfo::IsStatementPosition(rmode())) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000110 statement_position_ = static_cast<int>(
111 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000112 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000113 // Always update the position as we don't want that to be before the
114 // statement position.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000115 position_ = static_cast<int>(
116 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000117 ASSERT(position_ >= 0);
118 ASSERT(statement_position_ >= 0);
119 }
120
121 // Check for breakable code target. Look in the original code as setting
122 // break points can cause the code targets in the running (debugged) code to
123 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000124 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000125 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000126 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000127 if ((code->is_inline_cache_stub() &&
128 code->kind() != Code::BINARY_OP_IC) ||
129 RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000130 break_point_++;
131 return;
132 }
133 if (code->kind() == Code::STUB) {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000134 if (IsDebuggerStatement()) {
135 break_point_++;
136 return;
137 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000138 if (type_ == ALL_BREAK_LOCATIONS) {
139 if (Debug::IsBreakStub(code)) {
140 break_point_++;
141 return;
142 }
143 } else {
144 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
145 if (Debug::IsSourceBreakStub(code)) {
146 break_point_++;
147 return;
148 }
149 }
150 }
151 }
152
153 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000154 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000155 // Set the positions to the end of the function.
156 if (debug_info_->shared()->HasSourceCode()) {
157 position_ = debug_info_->shared()->end_position() -
158 debug_info_->shared()->start_position();
159 } else {
160 position_ = 0;
161 }
162 statement_position_ = position_;
163 break_point_++;
164 return;
165 }
166 }
167}
168
169
170void BreakLocationIterator::Next(int count) {
171 while (count > 0) {
172 Next();
173 count--;
174 }
175}
176
177
178// Find the break point closest to the supplied address.
179void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
180 // Run through all break points to locate the one closest to the address.
181 int closest_break_point = 0;
182 int distance = kMaxInt;
183 while (!Done()) {
184 // Check if this break point is closer that what was previously found.
185 if (this->pc() < pc && pc - this->pc() < distance) {
186 closest_break_point = break_point();
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000187 distance = static_cast<int>(pc - this->pc());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000188 // Check whether we can't get any closer.
189 if (distance == 0) break;
190 }
191 Next();
192 }
193
194 // Move to the break point found.
195 Reset();
196 Next(closest_break_point);
197}
198
199
200// Find the break point closest to the supplied source position.
201void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
202 // Run through all break points to locate the one closest to the source
203 // position.
204 int closest_break_point = 0;
205 int distance = kMaxInt;
206 while (!Done()) {
207 // Check if this break point is closer that what was previously found.
208 if (position <= statement_position() &&
209 statement_position() - position < distance) {
210 closest_break_point = break_point();
211 distance = statement_position() - position;
212 // Check whether we can't get any closer.
213 if (distance == 0) break;
214 }
215 Next();
216 }
217
218 // Move to the break point found.
219 Reset();
220 Next(closest_break_point);
221}
222
223
224void BreakLocationIterator::Reset() {
225 // Create relocation iterators for the two code objects.
226 if (reloc_iterator_ != NULL) delete reloc_iterator_;
227 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
228 reloc_iterator_ = new RelocIterator(debug_info_->code());
229 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
230
231 // Position at the first break point.
232 break_point_ = -1;
233 position_ = 1;
234 statement_position_ = 1;
235 Next();
236}
237
238
239bool BreakLocationIterator::Done() const {
240 return RinfoDone();
241}
242
243
244void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
245 // If there is not already a real break point here patch code with debug
246 // break.
247 if (!HasBreakPoint()) {
248 SetDebugBreak();
249 }
ager@chromium.orga1645e22009-09-09 19:27:10 +0000250 ASSERT(IsDebugBreak() || IsDebuggerStatement());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000251 // Set the break point information.
252 DebugInfo::SetBreakPoint(debug_info_, code_position(),
253 position(), statement_position(),
254 break_point_object);
255}
256
257
258void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
259 // Clear the break point information.
260 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
261 // If there are no more break points here remove the debug break.
262 if (!HasBreakPoint()) {
263 ClearDebugBreak();
264 ASSERT(!IsDebugBreak());
265 }
266}
267
268
269void BreakLocationIterator::SetOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000270 // Debugger statement always calls debugger. No need to modify it.
271 if (IsDebuggerStatement()) {
272 return;
273 }
274
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000275 // If there is a real break point here no more to do.
276 if (HasBreakPoint()) {
277 ASSERT(IsDebugBreak());
278 return;
279 }
280
281 // Patch code with debug break.
282 SetDebugBreak();
283}
284
285
286void BreakLocationIterator::ClearOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000287 // Debugger statement always calls debugger. No need to modify it.
288 if (IsDebuggerStatement()) {
289 return;
290 }
291
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000292 // If there is a real break point here no more to do.
293 if (HasBreakPoint()) {
294 ASSERT(IsDebugBreak());
295 return;
296 }
297
298 // Patch code removing debug break.
299 ClearDebugBreak();
300 ASSERT(!IsDebugBreak());
301}
302
303
304void BreakLocationIterator::SetDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000305 // Debugger statement always calls debugger. No need to modify it.
306 if (IsDebuggerStatement()) {
307 return;
308 }
309
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000311 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000312 // function twice might happen when stepping in a function with an exception
313 // handler as the handler and the function is the same.
314 if (IsDebugBreak()) {
315 return;
316 }
317
ager@chromium.org236ad962008-09-25 09:45:57 +0000318 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000319 // Patch the frame exit code with a break point.
320 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000321 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000322 // Patch the IC call.
323 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000324 }
325 ASSERT(IsDebugBreak());
326}
327
328
329void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000330 // Debugger statement always calls debugger. No need to modify it.
331 if (IsDebuggerStatement()) {
332 return;
333 }
334
ager@chromium.org236ad962008-09-25 09:45:57 +0000335 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000336 // Restore the frame exit code.
337 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000339 // Patch the IC call.
340 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000341 }
342 ASSERT(!IsDebugBreak());
343}
344
345
346void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000347 HandleScope scope;
348
ager@chromium.orga1645e22009-09-09 19:27:10 +0000349 // Step in can only be prepared if currently positioned on an IC call,
350 // construct call or CallFunction stub call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000351 Address target = rinfo()->target_address();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000352 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000353 if (code->is_call_stub()) {
354 // Step in through IC call is handled by the runtime system. Therefore make
355 // sure that the any current IC is cleared and the runtime system is
356 // called. If the executing code has a debug break at the location change
357 // the call in the original code as it is the code there that will be
358 // executed in place of the debug break call.
359 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
360 if (IsDebugBreak()) {
361 original_rinfo()->set_target_address(stub->entry());
362 } else {
363 rinfo()->set_target_address(stub->entry());
364 }
365 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000366#ifdef DEBUG
367 // All the following stuff is needed only for assertion checks so the code
368 // is wrapped in ifdef.
369 Handle<Code> maybe_call_function_stub = code;
370 if (IsDebugBreak()) {
371 Address original_target = original_rinfo()->target_address();
372 maybe_call_function_stub =
373 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
374 }
375 bool is_call_function_stub =
376 (maybe_call_function_stub->kind() == Code::STUB &&
377 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
378
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000379 // Step in through construct call requires no changes to the running code.
380 // Step in through getters/setters should already be prepared as well
381 // because caller of this function (Debug::PrepareStep) is expected to
382 // flood the top frame's function with one shot breakpoints.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000383 // Step in through CallFunction stub should also be prepared by caller of
384 // this function (Debug::PrepareStep) which should flood target function
385 // with breakpoints.
386 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
387 || is_call_function_stub);
388#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000389 }
390}
391
392
393// Check whether the break point is at a position which will exit the function.
394bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000395 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000396}
397
398
399bool BreakLocationIterator::HasBreakPoint() {
400 return debug_info_->HasBreakPoint(code_position());
401}
402
403
404// Check whether there is a debug break at the current position.
405bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000406 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000407 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000408 } else {
409 return Debug::IsDebugBreak(rinfo()->target_address());
410 }
411}
412
413
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000414void BreakLocationIterator::SetDebugBreakAtIC() {
415 // Patch the original code with the current address as the current address
416 // might have changed by the inline caching since the code was copied.
417 original_rinfo()->set_target_address(rinfo()->target_address());
418
419 RelocInfo::Mode mode = rmode();
420 if (RelocInfo::IsCodeTarget(mode)) {
421 Address target = rinfo()->target_address();
422 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
423
424 // Patch the code to invoke the builtin debug break function matching the
425 // calling convention used by the call site.
426 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
427 rinfo()->set_target_address(dbgbrk_code->entry());
428
429 // For stubs that refer back to an inlined version clear the cached map for
430 // the inlined case to always go through the IC. As long as the break point
431 // is set the patching performed by the runtime system will take place in
432 // the code copy and will therefore have no effect on the running code
433 // keeping it from using the inlined code.
ager@chromium.org5ec48922009-05-05 07:25:34 +0000434 if (code->is_keyed_load_stub()) KeyedLoadIC::ClearInlinedVersion(pc());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000435 if (code->is_keyed_store_stub()) KeyedStoreIC::ClearInlinedVersion(pc());
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000436 }
437}
438
439
440void BreakLocationIterator::ClearDebugBreakAtIC() {
441 // Patch the code to the original invoke.
442 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000443
444 RelocInfo::Mode mode = rmode();
445 if (RelocInfo::IsCodeTarget(mode)) {
446 Address target = original_rinfo()->target_address();
447 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
448
449 // Restore the inlined version of keyed stores to get back to the
450 // fast case. We need to patch back the keyed store because no
451 // patching happens when running normally. For keyed loads, the
452 // map check will get patched back when running normally after ICs
453 // have been cleared at GC.
454 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
455 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000456}
457
458
ager@chromium.orga1645e22009-09-09 19:27:10 +0000459bool BreakLocationIterator::IsDebuggerStatement() {
ager@chromium.org5c838252010-02-19 08:53:10 +0000460 return RelocInfo::DEBUG_BREAK == rmode();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000461}
462
463
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000464Object* BreakLocationIterator::BreakPointObjects() {
465 return debug_info_->GetBreakPointObjects(code_position());
466}
467
468
ager@chromium.org381abbb2009-02-25 13:23:22 +0000469// Clear out all the debug break code. This is ONLY supposed to be used when
470// shutting down the debugger as it will leave the break point information in
471// DebugInfo even though the code is patched back to the non break point state.
472void BreakLocationIterator::ClearAllDebugBreak() {
473 while (!Done()) {
474 ClearDebugBreak();
475 Next();
476 }
477}
478
479
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480bool BreakLocationIterator::RinfoDone() const {
481 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
482 return reloc_iterator_->done();
483}
484
485
486void BreakLocationIterator::RinfoNext() {
487 reloc_iterator_->next();
488 reloc_iterator_original_->next();
489#ifdef DEBUG
490 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
491 if (!reloc_iterator_->done()) {
492 ASSERT(rmode() == original_rmode());
493 }
494#endif
495}
496
497
498bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000499ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500DebugInfoListNode* Debug::debug_info_list_ = NULL;
501
502
503// Threading support.
504void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000505 thread_local_.break_count_ = 0;
506 thread_local_.break_id_ = 0;
507 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000508 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000509 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000510 thread_local_.step_count_ = 0;
511 thread_local_.last_fp_ = 0;
512 thread_local_.step_into_fp_ = 0;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000513 thread_local_.step_out_fp_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000515 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000516 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000517}
518
519
520JSCallerSavedBuffer Debug::registers_;
521Debug::ThreadLocal Debug::thread_local_;
522
523
524char* Debug::ArchiveDebug(char* storage) {
525 char* to = storage;
526 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
527 to += sizeof(ThreadLocal);
528 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
529 ThreadInit();
530 ASSERT(to <= storage + ArchiveSpacePerThread());
531 return storage + ArchiveSpacePerThread();
532}
533
534
535char* Debug::RestoreDebug(char* storage) {
536 char* from = storage;
537 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
538 from += sizeof(ThreadLocal);
539 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
540 ASSERT(from <= storage + ArchiveSpacePerThread());
541 return storage + ArchiveSpacePerThread();
542}
543
544
545int Debug::ArchiveSpacePerThread() {
546 return sizeof(ThreadLocal) + sizeof(registers_);
547}
548
549
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000550// Default break enabled.
551bool Debug::disable_break_ = false;
552
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000553// Default call debugger on uncaught exception.
554bool Debug::break_on_exception_ = false;
555bool Debug::break_on_uncaught_exception_ = true;
556
557Handle<Context> Debug::debug_context_ = Handle<Context>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000558Code* Debug::debug_break_return_ = NULL;
559
560
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000561void ScriptCache::Add(Handle<Script> script) {
562 // Create an entry in the hash map for the script.
563 int id = Smi::cast(script->id())->value();
564 HashMap::Entry* entry =
565 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
566 if (entry->value != NULL) {
567 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
568 return;
569 }
570
571 // Globalize the script object, make it weak and use the location of the
572 // global handle as the value in the hash map.
573 Handle<Script> script_ =
574 Handle<Script>::cast((GlobalHandles::Create(*script)));
575 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
576 this, ScriptCache::HandleWeakScript);
577 entry->value = script_.location();
578}
579
580
581Handle<FixedArray> ScriptCache::GetScripts() {
582 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
583 int count = 0;
584 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
585 ASSERT(entry->value != NULL);
586 if (entry->value != NULL) {
587 instances->set(count, *reinterpret_cast<Script**>(entry->value));
588 count++;
589 }
590 }
591 return instances;
592}
593
594
595void ScriptCache::ProcessCollectedScripts() {
596 for (int i = 0; i < collected_scripts_.length(); i++) {
597 Debugger::OnScriptCollected(collected_scripts_[i]);
598 }
599 collected_scripts_.Clear();
600}
601
602
603void ScriptCache::Clear() {
604 // Iterate the script cache to get rid of all the weak handles.
605 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
606 ASSERT(entry != NULL);
607 Object** location = reinterpret_cast<Object**>(entry->value);
608 ASSERT((*location)->IsScript());
609 GlobalHandles::ClearWeakness(location);
610 GlobalHandles::Destroy(location);
611 }
612 // Clear the content of the hash map.
613 HashMap::Clear();
614}
615
616
617void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
618 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
619 // Find the location of the global handle.
620 Script** location =
621 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
622 ASSERT((*location)->IsScript());
623
624 // Remove the entry from the cache.
625 int id = Smi::cast((*location)->id())->value();
626 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
627 script_cache->collected_scripts_.Add(id);
628
629 // Clear the weak handle.
630 obj.Dispose();
631 obj.Clear();
632}
633
634
635void Debug::Setup(bool create_heap_objects) {
636 ThreadInit();
637 if (create_heap_objects) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000638 // Get code to handle debug break on return.
639 debug_break_return_ =
640 Builtins::builtin(Builtins::Return_DebugBreak);
641 ASSERT(debug_break_return_->IsCode());
642 }
643}
644
645
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000646void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000647 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
648 RemoveDebugInfo(node->debug_info());
649#ifdef DEBUG
650 node = Debug::debug_info_list_;
651 while (node != NULL) {
652 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
653 node = node->next();
654 }
655#endif
656}
657
658
659DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
660 // Globalize the request debug info object and make it weak.
661 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
662 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
663 this, Debug::HandleWeakDebugInfo);
664}
665
666
667DebugInfoListNode::~DebugInfoListNode() {
668 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
669}
670
671
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000672bool Debug::CompileDebuggerScript(int index) {
673 HandleScope scope;
674
kasper.lund44510672008-07-25 07:37:58 +0000675 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000676 if (index == -1) {
677 return false;
678 }
kasper.lund44510672008-07-25 07:37:58 +0000679
680 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000681 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
682 Vector<const char> name = Natives::GetScriptName(index);
683 Handle<String> script_name = Factory::NewStringFromAscii(name);
684
685 // Compile the script.
686 bool allow_natives_syntax = FLAG_allow_natives_syntax;
687 FLAG_allow_natives_syntax = true;
688 Handle<JSFunction> boilerplate;
fschneider@chromium.org086aac62010-03-17 13:18:24 +0000689 boilerplate = Compiler::Compile(source_code,
690 script_name,
691 0,
692 0,
693 NULL,
694 NULL,
695 Handle<String>::null(),
696 NATIVES_CODE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000697 FLAG_allow_natives_syntax = allow_natives_syntax;
698
699 // Silently ignore stack overflows during compilation.
700 if (boilerplate.is_null()) {
701 ASSERT(Top::has_pending_exception());
702 Top::clear_pending_exception();
703 return false;
704 }
705
kasper.lund44510672008-07-25 07:37:58 +0000706 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000708 bool caught_exception = false;
709 Handle<JSFunction> function =
710 Factory::NewFunctionFromBoilerplate(boilerplate, context);
711 Handle<Object> result =
712 Execution::TryCall(function, Handle<Object>(context->global()),
713 0, NULL, &caught_exception);
714
715 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000716 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000717 Handle<Object> message = MessageHandler::MakeMessageObject(
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000718 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000719 Handle<String>());
720 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000721 return false;
722 }
723
kasper.lund44510672008-07-25 07:37:58 +0000724 // Mark this script as native and return successfully.
725 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000726 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000727 return true;
728}
729
730
731bool Debug::Load() {
732 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000733 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000734
kasper.lund44510672008-07-25 07:37:58 +0000735 // Bail out if we're already in the process of compiling the native
736 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000737 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
738 return false;
739 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000740
741 // Disable breakpoints and interrupts while compiling and running the
742 // debugger scripts including the context creation code.
743 DisableBreak disable(true);
744 PostponeInterruptsScope postpone;
745
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000746 // Create the debugger context.
747 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000748 Handle<Context> context =
749 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
750 v8::Handle<ObjectTemplate>(),
751 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000752
kasper.lund44510672008-07-25 07:37:58 +0000753 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000754 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000755 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000756
757 // Expose the builtins object in the debugger context.
758 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
759 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
760 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000761
762 // Compile the JavaScript for the debugger in the debugger context.
763 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000764 bool caught_exception =
765 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
766 !CompileDebuggerScript(Natives::GetIndex("debug"));
ager@chromium.orgce5e87b2010-03-10 10:24:18 +0000767
768 if (FLAG_enable_liveedit) {
769 caught_exception = caught_exception ||
770 !CompileDebuggerScript(Natives::GetIndex("liveedit"));
771 }
772
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000773 Debugger::set_compiling_natives(false);
774
mads.s.agercbaa0602008-08-14 13:41:48 +0000775 // Make sure we mark the debugger as not loading before we might
776 // return.
777 Debugger::set_loading_debugger(false);
778
kasper.lund44510672008-07-25 07:37:58 +0000779 // Check for caught exceptions.
780 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000781
782 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000783 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000784
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000785 return true;
786}
787
788
789void Debug::Unload() {
790 // Return debugger is not loaded.
791 if (!IsLoaded()) {
792 return;
793 }
794
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000795 // Clear the script cache.
796 DestroyScriptCache();
797
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000798 // Clear debugger context global handle.
799 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
800 debug_context_ = Handle<Context>();
801}
802
803
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000804// Set the flag indicating that preemption happened during debugging.
805void Debug::PreemptionWhileInDebugger() {
806 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000807 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000808}
809
810
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000811void Debug::Iterate(ObjectVisitor* v) {
vegorov@chromium.orgf8372902010-03-15 10:26:20 +0000812 v->VisitPointer(BitCast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000813}
814
815
816Object* Debug::Break(Arguments args) {
817 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000818 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000819
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000820 // Get the top-most JavaScript frame.
821 JavaScriptFrameIterator it;
822 JavaScriptFrame* frame = it.frame();
823
824 // Just continue if breaks are disabled or debugger cannot be loaded.
825 if (disable_break() || !Load()) {
826 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000827 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000828 }
829
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000830 // Enter the debugger.
831 EnterDebugger debugger;
832 if (debugger.FailedToEnter()) {
833 return Heap::undefined_value();
834 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000835
kasper.lund44510672008-07-25 07:37:58 +0000836 // Postpone interrupt during breakpoint processing.
837 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838
839 // Get the debug info (create it if it does not exist).
840 Handle<SharedFunctionInfo> shared =
841 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
842 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
843
844 // Find the break point where execution has stopped.
845 BreakLocationIterator break_location_iterator(debug_info,
846 ALL_BREAK_LOCATIONS);
847 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
848
849 // Check whether step next reached a new statement.
850 if (!StepNextContinue(&break_location_iterator, frame)) {
851 // Decrease steps left if performing multiple steps.
852 if (thread_local_.step_count_ > 0) {
853 thread_local_.step_count_--;
854 }
855 }
856
857 // If there is one or more real break points check whether any of these are
858 // triggered.
859 Handle<Object> break_points_hit(Heap::undefined_value());
860 if (break_location_iterator.HasBreakPoint()) {
861 Handle<Object> break_point_objects =
862 Handle<Object>(break_location_iterator.BreakPointObjects());
863 break_points_hit = CheckBreakPoints(break_point_objects);
864 }
865
ager@chromium.orga1645e22009-09-09 19:27:10 +0000866 // If step out is active skip everything until the frame where we need to step
867 // out to is reached, unless real breakpoint is hit.
868 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
869 break_points_hit->IsUndefined() ) {
870 // Step count should always be 0 for StepOut.
871 ASSERT(thread_local_.step_count_ == 0);
872 } else if (!break_points_hit->IsUndefined() ||
873 (thread_local_.last_step_action_ != StepNone &&
874 thread_local_.step_count_ == 0)) {
875 // Notify debugger if a real break point is triggered or if performing
876 // single stepping with no more steps to perform. Otherwise do another step.
877
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878 // Clear all current stepping setup.
879 ClearStepping();
880
881 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000882 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000883 } else if (thread_local_.last_step_action_ != StepNone) {
884 // Hold on to last step action as it is cleared by the call to
885 // ClearStepping.
886 StepAction step_action = thread_local_.last_step_action_;
887 int step_count = thread_local_.step_count_;
888
889 // Clear all current stepping setup.
890 ClearStepping();
891
892 // Set up for the remaining steps.
893 PrepareStep(step_action, step_count);
894 }
895
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000896 // Install jump to the call address which was overwritten.
897 SetAfterBreakTarget(frame);
898
mads.s.ager31e71382008-08-13 09:32:07 +0000899 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000900}
901
902
903// Check the break point objects for whether one or more are actually
904// triggered. This function returns a JSArray with the break point objects
905// which is triggered.
906Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
907 int break_points_hit_count = 0;
908 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
909
v8.team.kasperl727e9952008-09-02 14:56:44 +0000910 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000911 ASSERT(!break_point_objects->IsUndefined());
912 if (break_point_objects->IsFixedArray()) {
913 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
914 for (int i = 0; i < array->length(); i++) {
915 Handle<Object> o(array->get(i));
916 if (CheckBreakPoint(o)) {
917 break_points_hit->SetElement(break_points_hit_count++, *o);
918 }
919 }
920 } else {
921 if (CheckBreakPoint(break_point_objects)) {
922 break_points_hit->SetElement(break_points_hit_count++,
923 *break_point_objects);
924 }
925 }
926
927 // Return undefined if no break points where triggered.
928 if (break_points_hit_count == 0) {
929 return Factory::undefined_value();
930 }
931 return break_points_hit;
932}
933
934
935// Check whether a single break point object is triggered.
936bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000937 HandleScope scope;
938
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000939 // Ignore check if break point object is not a JSObject.
940 if (!break_point_object->IsJSObject()) return true;
941
942 // Get the function CheckBreakPoint (defined in debug.js).
943 Handle<JSFunction> check_break_point =
944 Handle<JSFunction>(JSFunction::cast(
945 debug_context()->global()->GetProperty(
946 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
947
948 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000949 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950
951 // Call HandleBreakPointx.
952 bool caught_exception = false;
953 const int argc = 2;
954 Object** argv[argc] = {
955 break_id.location(),
956 reinterpret_cast<Object**>(break_point_object.location())
957 };
958 Handle<Object> result = Execution::TryCall(check_break_point,
959 Top::builtins(), argc, argv,
960 &caught_exception);
961
962 // If exception or non boolean result handle as not triggered
963 if (caught_exception || !result->IsBoolean()) {
964 return false;
965 }
966
967 // Return whether the break point is triggered.
968 return *result == Heap::true_value();
969}
970
971
972// Check whether the function has debug information.
973bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
974 return !shared->debug_info()->IsUndefined();
975}
976
977
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000978// Return the debug info for this function. EnsureDebugInfo must be called
979// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000980Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000981 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000982 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
983}
984
985
986void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
987 int source_position,
988 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000989 HandleScope scope;
990
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000991 if (!EnsureDebugInfo(shared)) {
992 // Return if retrieving debug info failed.
993 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000994 }
995
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000996 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000997 // Source positions starts with zero.
998 ASSERT(source_position >= 0);
999
1000 // Find the break point and change it.
1001 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1002 it.FindBreakLocationFromPosition(source_position);
1003 it.SetBreakPoint(break_point_object);
1004
1005 // At least one active break point now.
1006 ASSERT(debug_info->GetBreakPointCount() > 0);
1007}
1008
1009
1010void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001011 HandleScope scope;
1012
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001013 DebugInfoListNode* node = debug_info_list_;
1014 while (node != NULL) {
1015 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1016 break_point_object);
1017 if (!result->IsUndefined()) {
1018 // Get information in the break point.
1019 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1020 Handle<DebugInfo> debug_info = node->debug_info();
1021 Handle<SharedFunctionInfo> shared(debug_info->shared());
1022 int source_position = break_point_info->statement_position()->value();
1023
1024 // Source positions starts with zero.
1025 ASSERT(source_position >= 0);
1026
1027 // Find the break point and clear it.
1028 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1029 it.FindBreakLocationFromPosition(source_position);
1030 it.ClearBreakPoint(break_point_object);
1031
1032 // If there are no more break points left remove the debug info for this
1033 // function.
1034 if (debug_info->GetBreakPointCount() == 0) {
1035 RemoveDebugInfo(debug_info);
1036 }
1037
1038 return;
1039 }
1040 node = node->next();
1041 }
1042}
1043
1044
ager@chromium.org381abbb2009-02-25 13:23:22 +00001045void Debug::ClearAllBreakPoints() {
1046 DebugInfoListNode* node = debug_info_list_;
1047 while (node != NULL) {
1048 // Remove all debug break code.
1049 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1050 it.ClearAllDebugBreak();
1051 node = node->next();
1052 }
1053
1054 // Remove all debug info.
1055 while (debug_info_list_ != NULL) {
1056 RemoveDebugInfo(debug_info_list_->debug_info());
1057 }
1058}
1059
1060
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001061void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001062 // Make sure the function has setup the debug info.
1063 if (!EnsureDebugInfo(shared)) {
1064 // Return if we failed to retrieve the debug info.
1065 return;
1066 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067
1068 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001069 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001070 while (!it.Done()) {
1071 it.SetOneShot();
1072 it.Next();
1073 }
1074}
1075
1076
1077void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001078 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001079 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001080 if (id == StackFrame::NO_ID) {
1081 // If there is no JavaScript stack don't do anything.
1082 return;
1083 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001084 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1085 JavaScriptFrame* frame = it.frame();
1086 if (frame->HasHandler()) {
1087 Handle<SharedFunctionInfo> shared =
1088 Handle<SharedFunctionInfo>(
1089 JSFunction::cast(frame->function())->shared());
1090 // Flood the function with the catch block with break points
1091 FloodWithOneShot(shared);
1092 return;
1093 }
1094 }
1095}
1096
1097
1098void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1099 if (type == BreakUncaughtException) {
1100 break_on_uncaught_exception_ = enable;
1101 } else {
1102 break_on_exception_ = enable;
1103 }
1104}
1105
1106
1107void Debug::PrepareStep(StepAction step_action, int step_count) {
1108 HandleScope scope;
1109 ASSERT(Debug::InDebugger());
1110
1111 // Remember this step action and count.
1112 thread_local_.last_step_action_ = step_action;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001113 if (step_action == StepOut) {
1114 // For step out target frame will be found on the stack so there is no need
1115 // to set step counter for it. It's expected to always be 0 for StepOut.
1116 thread_local_.step_count_ = 0;
1117 } else {
1118 thread_local_.step_count_ = step_count;
1119 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001120
1121 // Get the frame where the execution has stopped and skip the debug frame if
1122 // any. The debug frame will only be present if execution was stopped due to
1123 // hitting a break point. In other situations (e.g. unhandled exception) the
1124 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001125 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001126 if (id == StackFrame::NO_ID) {
1127 // If there is no JavaScript stack don't do anything.
1128 return;
1129 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001130 JavaScriptFrameIterator frames_it(id);
1131 JavaScriptFrame* frame = frames_it.frame();
1132
1133 // First of all ensure there is one-shot break points in the top handler
1134 // if any.
1135 FloodHandlerWithOneShot();
1136
1137 // If the function on the top frame is unresolved perform step out. This will
1138 // be the case when calling unknown functions and having the debugger stopped
1139 // in an unhandled exception.
1140 if (!frame->function()->IsJSFunction()) {
1141 // Step out: Find the calling JavaScript frame and flood it with
1142 // breakpoints.
1143 frames_it.Advance();
1144 // Fill the function to return to with one-shot break points.
1145 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1146 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1147 return;
1148 }
1149
1150 // Get the debug info (create it if it does not exist).
1151 Handle<SharedFunctionInfo> shared =
1152 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001153 if (!EnsureDebugInfo(shared)) {
1154 // Return if ensuring debug info failed.
1155 return;
1156 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001157 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1158
1159 // Find the break location where execution has stopped.
1160 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1161 it.FindBreakLocationFromAddress(frame->pc());
1162
1163 // Compute whether or not the target is a call target.
1164 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001165 bool is_load_or_store = false;
1166 bool is_inline_cache_stub = false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001167 Handle<Code> call_function_stub;
ager@chromium.org236ad962008-09-25 09:45:57 +00001168 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001169 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001170 Code* code = Code::GetCodeFromTargetAddress(target);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001171 if (code->is_call_stub()) {
1172 is_call_target = true;
1173 }
1174 if (code->is_inline_cache_stub()) {
1175 is_inline_cache_stub = true;
1176 is_load_or_store = !is_call_target;
1177 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001178
1179 // Check if target code is CallFunction stub.
1180 Code* maybe_call_function_stub = code;
1181 // If there is a breakpoint at this line look at the original code to
1182 // check if it is a CallFunction stub.
1183 if (it.IsDebugBreak()) {
1184 Address original_target = it.original_rinfo()->target_address();
1185 maybe_call_function_stub =
1186 Code::GetCodeFromTargetAddress(original_target);
1187 }
1188 if (maybe_call_function_stub->kind() == Code::STUB &&
1189 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1190 // Save reference to the code as we may need it to find out arguments
1191 // count for 'step in' later.
1192 call_function_stub = Handle<Code>(maybe_call_function_stub);
1193 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001194 }
1195
v8.team.kasperl727e9952008-09-02 14:56:44 +00001196 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001197 if (it.IsExit() || step_action == StepOut) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001198 if (step_action == StepOut) {
1199 // Skip step_count frames starting with the current one.
1200 while (step_count-- > 0 && !frames_it.done()) {
1201 frames_it.Advance();
1202 }
1203 } else {
1204 ASSERT(it.IsExit());
1205 frames_it.Advance();
1206 }
1207 // Skip builtin functions on the stack.
1208 while (!frames_it.done() &&
1209 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1210 frames_it.Advance();
1211 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001212 // Step out: If there is a JavaScript caller frame, we need to
1213 // flood it with breakpoints.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001214 if (!frames_it.done()) {
1215 // Fill the function to return to with one-shot break points.
1216 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1217 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001218 // Set target frame pointer.
1219 ActivateStepOut(frames_it.frame());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001220 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001221 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1222 !call_function_stub.is_null())
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001223 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001224 // Step next or step min.
1225
1226 // Fill the current function with one-shot break points.
1227 FloodWithOneShot(shared);
1228
1229 // Remember source position and frame to handle step next.
1230 thread_local_.last_statement_position_ =
1231 debug_info->code()->SourceStatementPosition(frame->pc());
1232 thread_local_.last_fp_ = frame->fp();
1233 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001234 // If it's CallFunction stub ensure target function is compiled and flood
1235 // it with one shot breakpoints.
1236 if (!call_function_stub.is_null()) {
1237 // Find out number of arguments from the stub minor key.
1238 // Reverse lookup required as the minor key cannot be retrieved
1239 // from the code object.
1240 Handle<Object> obj(
1241 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1242 ASSERT(*obj != Heap::undefined_value());
1243 ASSERT(obj->IsSmi());
1244 // Get the STUB key and extract major and minor key.
1245 uint32_t key = Smi::cast(*obj)->value();
1246 // Argc in the stub is the number of arguments passed - not the
1247 // expected arguments of the called function.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001248 int call_function_arg_count =
1249 CallFunctionStub::ExtractArgcFromMinorKey(
1250 CodeStub::MinorKeyFromKey(key));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001251 ASSERT(call_function_stub->major_key() ==
1252 CodeStub::MajorKeyFromKey(key));
1253
1254 // Find target function on the expression stack.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001255 // Expression stack looks like this (top to bottom):
ager@chromium.orga1645e22009-09-09 19:27:10 +00001256 // argN
1257 // ...
1258 // arg0
1259 // Receiver
1260 // Function to call
1261 int expressions_count = frame->ComputeExpressionsCount();
1262 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1263 Object* fun = frame->GetExpression(
1264 expressions_count - 2 - call_function_arg_count);
1265 if (fun->IsJSFunction()) {
1266 Handle<JSFunction> js_function(JSFunction::cast(fun));
1267 // Don't step into builtins.
1268 if (!js_function->IsBuiltin()) {
1269 // It will also compile target function if it's not compiled yet.
1270 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1271 }
1272 }
1273 }
1274
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001275 // Fill the current function with one-shot break points even for step in on
1276 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001277 // which step in will not stop. It also prepares for stepping in
1278 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001279 FloodWithOneShot(shared);
1280
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001281 if (is_load_or_store) {
1282 // Remember source position and frame to handle step in getter/setter. If
1283 // there is a custom getter/setter it will be handled in
1284 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1285 // propagated on the next Debug::Break.
1286 thread_local_.last_statement_position_ =
1287 debug_info->code()->SourceStatementPosition(frame->pc());
1288 thread_local_.last_fp_ = frame->fp();
1289 }
1290
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001291 // Step in or Step in min
1292 it.PrepareStepIn();
1293 ActivateStepIn(frame);
1294 }
1295}
1296
1297
1298// Check whether the current debug break should be reported to the debugger. It
1299// is used to have step next and step in only report break back to the debugger
1300// if on a different frame or in a different statement. In some situations
1301// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001302// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001303// steps before reporting break back to the debugger.
1304bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1305 JavaScriptFrame* frame) {
1306 // If the step last action was step next or step in make sure that a new
1307 // statement is hit.
1308 if (thread_local_.last_step_action_ == StepNext ||
1309 thread_local_.last_step_action_ == StepIn) {
1310 // Never continue if returning from function.
1311 if (break_location_iterator->IsExit()) return false;
1312
1313 // Continue if we are still on the same frame and in the same statement.
1314 int current_statement_position =
1315 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1316 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001317 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001318 }
1319
1320 // No step next action - don't continue.
1321 return false;
1322}
1323
1324
1325// Check whether the code object at the specified address is a debug break code
1326// object.
1327bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001328 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001329 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001330}
1331
1332
1333// Check whether a code stub with the specified major key is a possible break
1334// point location when looking for source break locations.
1335bool Debug::IsSourceBreakStub(Code* code) {
1336 CodeStub::Major major_key = code->major_key();
1337 return major_key == CodeStub::CallFunction;
1338}
1339
1340
1341// Check whether a code stub with the specified major key is a possible break
1342// location.
1343bool Debug::IsBreakStub(Code* code) {
1344 CodeStub::Major major_key = code->major_key();
1345 return major_key == CodeStub::CallFunction ||
1346 major_key == CodeStub::StackCheck;
1347}
1348
1349
1350// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001351Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001352 // Find the builtin debug break function matching the calling convention
1353 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001354 if (code->is_inline_cache_stub()) {
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001355 switch (code->kind()) {
1356 case Code::CALL_IC:
1357 return ComputeCallDebugBreak(code->arguments_count());
1358
1359 case Code::LOAD_IC:
1360 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1361
1362 case Code::STORE_IC:
1363 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1364
1365 case Code::KEYED_LOAD_IC:
1366 return Handle<Code>(
1367 Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1368
1369 case Code::KEYED_STORE_IC:
1370 return Handle<Code>(
1371 Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1372
1373 default:
1374 UNREACHABLE();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001375 }
1376 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001377 if (RelocInfo::IsConstructCall(mode)) {
1378 Handle<Code> result =
1379 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1380 return result;
1381 }
1382 if (code->kind() == Code::STUB) {
1383 ASSERT(code->major_key() == CodeStub::CallFunction ||
1384 code->major_key() == CodeStub::StackCheck);
1385 Handle<Code> result =
1386 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1387 return result;
1388 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001389
1390 UNREACHABLE();
1391 return Handle<Code>::null();
1392}
1393
1394
1395// Simple function for returning the source positions for active break points.
1396Handle<Object> Debug::GetSourceBreakLocations(
1397 Handle<SharedFunctionInfo> shared) {
1398 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1399 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1400 if (debug_info->GetBreakPointCount() == 0) {
1401 return Handle<Object>(Heap::undefined_value());
1402 }
1403 Handle<FixedArray> locations =
1404 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1405 int count = 0;
1406 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1407 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1408 BreakPointInfo* break_point_info =
1409 BreakPointInfo::cast(debug_info->break_points()->get(i));
1410 if (break_point_info->GetBreakPointCount() > 0) {
1411 locations->set(count++, break_point_info->statement_position());
1412 }
1413 }
1414 }
1415 return locations;
1416}
1417
1418
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001419void Debug::NewBreak(StackFrame::Id break_frame_id) {
1420 thread_local_.break_frame_id_ = break_frame_id;
1421 thread_local_.break_id_ = ++thread_local_.break_count_;
1422}
1423
1424
1425void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1426 thread_local_.break_frame_id_ = break_frame_id;
1427 thread_local_.break_id_ = break_id;
1428}
1429
1430
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001431// Handle stepping into a function.
1432void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001433 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001434 Address fp,
1435 bool is_constructor) {
1436 // If the frame pointer is not supplied by the caller find it.
1437 if (fp == 0) {
1438 StackFrameIterator it;
1439 it.Advance();
1440 // For constructor functions skip another frame.
1441 if (is_constructor) {
1442 ASSERT(it.frame()->is_construct());
1443 it.Advance();
1444 }
1445 fp = it.frame()->fp();
1446 }
1447
1448 // Flood the function with one-shot break points if it is called from where
1449 // step into was requested.
1450 if (fp == Debug::step_in_fp()) {
1451 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001452 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001453 if (function->shared()->code() ==
1454 Builtins::builtin(Builtins::FunctionApply) ||
1455 function->shared()->code() ==
1456 Builtins::builtin(Builtins::FunctionCall)) {
1457 // Handle function.apply and function.call separately to flood the
1458 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001459 // Builtins::FunctionCall. The receiver of call/apply is the target
1460 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001461 if (!holder.is_null() && holder->IsJSFunction() &&
1462 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001463 Handle<SharedFunctionInfo> shared_info(
1464 JSFunction::cast(*holder)->shared());
1465 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001466 }
1467 } else {
1468 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1469 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001470 }
1471 }
1472}
1473
1474
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001475void Debug::ClearStepping() {
1476 // Clear the various stepping setup.
1477 ClearOneShot();
1478 ClearStepIn();
ager@chromium.orga1645e22009-09-09 19:27:10 +00001479 ClearStepOut();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001480 ClearStepNext();
1481
1482 // Clear multiple step counter.
1483 thread_local_.step_count_ = 0;
1484}
1485
1486// Clears all the one-shot break points that are currently set. Normally this
1487// function is called each time a break point is hit as one shot break points
1488// are used to support stepping.
1489void Debug::ClearOneShot() {
1490 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001491 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001492 // removed from the list.
1493
1494 DebugInfoListNode* node = debug_info_list_;
1495 while (node != NULL) {
1496 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1497 while (!it.Done()) {
1498 it.ClearOneShot();
1499 it.Next();
1500 }
1501 node = node->next();
1502 }
1503}
1504
1505
1506void Debug::ActivateStepIn(StackFrame* frame) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001507 ASSERT(!StepOutActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001508 thread_local_.step_into_fp_ = frame->fp();
1509}
1510
1511
1512void Debug::ClearStepIn() {
1513 thread_local_.step_into_fp_ = 0;
1514}
1515
1516
ager@chromium.orga1645e22009-09-09 19:27:10 +00001517void Debug::ActivateStepOut(StackFrame* frame) {
1518 ASSERT(!StepInActive());
1519 thread_local_.step_out_fp_ = frame->fp();
1520}
1521
1522
1523void Debug::ClearStepOut() {
1524 thread_local_.step_out_fp_ = 0;
1525}
1526
1527
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001528void Debug::ClearStepNext() {
1529 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001530 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001531 thread_local_.last_fp_ = 0;
1532}
1533
1534
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001535// Ensures the debug information is present for shared.
1536bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1537 // Return if we already have the debug info for shared.
1538 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001539
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001540 // Ensure shared in compiled. Return false if this failed.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001541 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001542
1543 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001544 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001545
1546 // Add debug info to the list.
1547 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1548 node->set_next(debug_info_list_);
1549 debug_info_list_ = node;
1550
1551 // Now there is at least one break point.
1552 has_break_points_ = true;
1553
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001554 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001555}
1556
1557
1558void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1559 ASSERT(debug_info_list_ != NULL);
1560 // Run through the debug info objects to find this one and remove it.
1561 DebugInfoListNode* prev = NULL;
1562 DebugInfoListNode* current = debug_info_list_;
1563 while (current != NULL) {
1564 if (*current->debug_info() == *debug_info) {
1565 // Unlink from list. If prev is NULL we are looking at the first element.
1566 if (prev == NULL) {
1567 debug_info_list_ = current->next();
1568 } else {
1569 prev->set_next(current->next());
1570 }
1571 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1572 delete current;
1573
1574 // If there are no more debug info objects there are not more break
1575 // points.
1576 has_break_points_ = debug_info_list_ != NULL;
1577
1578 return;
1579 }
1580 // Move to next in list.
1581 prev = current;
1582 current = current->next();
1583 }
1584 UNREACHABLE();
1585}
1586
1587
1588void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001589 HandleScope scope;
1590
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001591 // Get the executing function in which the debug break occurred.
1592 Handle<SharedFunctionInfo> shared =
1593 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001594 if (!EnsureDebugInfo(shared)) {
1595 // Return if we failed to retrieve the debug info.
1596 return;
1597 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001598 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1599 Handle<Code> code(debug_info->code());
1600 Handle<Code> original_code(debug_info->original_code());
1601#ifdef DEBUG
1602 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001603 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001604 ASSERT(frame_code.is_identical_to(code));
1605#endif
1606
1607 // Find the call address in the running code. This address holds the call to
1608 // either a DebugBreakXXX or to the debug break return entry code if the
1609 // break point is still active after processing the break point.
ager@chromium.org4af710e2009-09-15 12:20:11 +00001610 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001611
1612 // Check if the location is at JS exit.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001613 bool at_js_return = false;
1614 bool break_at_js_return_active = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001615 RelocIterator it(debug_info->code());
1616 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001617 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001618 at_js_return = (it.rinfo()->pc() ==
1619 addr - Assembler::kPatchReturnSequenceAddressOffset);
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001620 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621 }
1622 it.next();
1623 }
1624
1625 // Handle the jump to continue execution after break point depending on the
1626 // break location.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001627 if (at_js_return) {
1628 // If the break point as return is still active jump to the corresponding
1629 // place in the original code. If not the break point was removed during
1630 // break point processing.
1631 if (break_at_js_return_active) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001632 addr += original_code->instruction_start() - code->instruction_start();
1633 }
1634
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001635 // Move back to where the call instruction sequence started.
1636 thread_local_.after_break_target_ =
1637 addr - Assembler::kPatchReturnSequenceAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001638 } else {
1639 // Check if there still is a debug break call at the target address. If the
1640 // break point has been removed it will have disappeared. If it have
1641 // disappeared don't try to look in the original code as the running code
1642 // will have the right address. This takes care of the case where the last
1643 // break point is removed from the function and therefore no "original code"
1644 // is available. If the debug break call is still there find the address in
1645 // the original code.
1646 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1647 // If the break point is still there find the call address which was
1648 // overwritten in the original code by the call to DebugBreakXXX.
1649
1650 // Find the corresponding address in the original code.
1651 addr += original_code->instruction_start() - code->instruction_start();
1652 }
1653
1654 // Install jump to the call address in the original code. This will be the
1655 // call which was overwritten by the call to DebugBreakXXX.
1656 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1657 }
1658}
1659
1660
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001661bool Debug::IsDebugGlobal(GlobalObject* global) {
1662 return IsLoaded() && global == Debug::debug_context()->global();
1663}
1664
1665
ager@chromium.org32912102009-01-16 10:38:43 +00001666void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001667 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001668 ASSERT(Top::context() == *Debug::debug_context());
1669
1670 // Clear the mirror cache.
1671 Handle<String> function_name =
1672 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1673 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1674 ASSERT(fun->IsJSFunction());
1675 bool caught_exception;
1676 Handle<Object> js_object = Execution::TryCall(
1677 Handle<JSFunction>::cast(fun),
1678 Handle<JSObject>(Debug::debug_context()->global()),
1679 0, NULL, &caught_exception);
1680}
1681
1682
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001683void Debug::CreateScriptCache() {
1684 HandleScope scope;
1685
1686 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1687 // rid of all the cached script wrappers and the second gets rid of the
1688 // scripts which is no longer referenced.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001689 Heap::CollectAllGarbage(false);
1690 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001691
1692 ASSERT(script_cache_ == NULL);
1693 script_cache_ = new ScriptCache();
1694
1695 // Scan heap for Script objects.
1696 int count = 0;
1697 HeapIterator iterator;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001698 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +00001699 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001700 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1701 count++;
1702 }
1703 }
1704}
1705
1706
1707void Debug::DestroyScriptCache() {
1708 // Get rid of the script cache if it was created.
1709 if (script_cache_ != NULL) {
1710 delete script_cache_;
1711 script_cache_ = NULL;
1712 }
1713}
1714
1715
1716void Debug::AddScriptToScriptCache(Handle<Script> script) {
1717 if (script_cache_ != NULL) {
1718 script_cache_->Add(script);
1719 }
1720}
1721
1722
1723Handle<FixedArray> Debug::GetLoadedScripts() {
1724 // Create and fill the script cache when the loaded scripts is requested for
1725 // the first time.
1726 if (script_cache_ == NULL) {
1727 CreateScriptCache();
1728 }
1729
1730 // If the script cache is not active just return an empty array.
1731 ASSERT(script_cache_ != NULL);
1732 if (script_cache_ == NULL) {
1733 Factory::NewFixedArray(0);
1734 }
1735
1736 // Perform GC to get unreferenced scripts evicted from the cache before
1737 // returning the content.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001738 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001739
1740 // Get the scripts from the cache.
1741 return script_cache_->GetScripts();
1742}
1743
1744
1745void Debug::AfterGarbageCollection() {
1746 // Generate events for collected scripts.
1747 if (script_cache_ != NULL) {
1748 script_cache_->ProcessCollectedScripts();
1749 }
1750}
1751
1752
ager@chromium.org71daaf62009-04-01 07:22:49 +00001753Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001754Handle<Object> Debugger::event_listener_ = Handle<Object>();
1755Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001756bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001757bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001758bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001759v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001760bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001761v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001762Mutex* Debugger::dispatch_handler_access_ = OS::CreateMutex();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001763v8::Debug::DebugMessageDispatchHandler
1764 Debugger::debug_message_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001765MessageDispatchHelperThread* Debugger::message_dispatch_helper_thread_ = NULL;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001766int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001767DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001768LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001769Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001770
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001771
1772Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1773 int argc, Object*** argv,
1774 bool* caught_exception) {
1775 ASSERT(Top::context() == *Debug::debug_context());
1776
1777 // Create the execution state object.
1778 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1779 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1780 ASSERT(constructor->IsJSFunction());
1781 if (!constructor->IsJSFunction()) {
1782 *caught_exception = true;
1783 return Factory::undefined_value();
1784 }
1785 Handle<Object> js_object = Execution::TryCall(
1786 Handle<JSFunction>::cast(constructor),
1787 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1788 caught_exception);
1789 return js_object;
1790}
1791
1792
1793Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1794 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001795 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001796 const int argc = 1;
1797 Object** argv[argc] = { break_id.location() };
1798 return MakeJSObject(CStrVector("MakeExecutionState"),
1799 argc, argv, caught_exception);
1800}
1801
1802
1803Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1804 Handle<Object> break_points_hit,
1805 bool* caught_exception) {
1806 // Create the new break event object.
1807 const int argc = 2;
1808 Object** argv[argc] = { exec_state.location(),
1809 break_points_hit.location() };
1810 return MakeJSObject(CStrVector("MakeBreakEvent"),
1811 argc,
1812 argv,
1813 caught_exception);
1814}
1815
1816
1817Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1818 Handle<Object> exception,
1819 bool uncaught,
1820 bool* caught_exception) {
1821 // Create the new exception event object.
1822 const int argc = 3;
1823 Object** argv[argc] = { exec_state.location(),
1824 exception.location(),
1825 uncaught ? Factory::true_value().location() :
1826 Factory::false_value().location()};
1827 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1828 argc, argv, caught_exception);
1829}
1830
1831
1832Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1833 bool* caught_exception) {
1834 // Create the new function event object.
1835 const int argc = 1;
1836 Object** argv[argc] = { function.location() };
1837 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1838 argc, argv, caught_exception);
1839}
1840
1841
1842Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001843 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001844 bool* caught_exception) {
1845 // Create the compile event object.
1846 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001847 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001848 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001849 Object** argv[argc] = { exec_state.location(),
1850 script_wrapper.location(),
1851 before ? Factory::true_value().location() :
1852 Factory::false_value().location() };
1853
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001854 return MakeJSObject(CStrVector("MakeCompileEvent"),
1855 argc,
1856 argv,
1857 caught_exception);
1858}
1859
1860
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001861Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1862 bool* caught_exception) {
1863 // Create the script collected event object.
1864 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1865 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1866 const int argc = 2;
1867 Object** argv[argc] = { exec_state.location(), id_object.location() };
1868
1869 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1870 argc,
1871 argv,
1872 caught_exception);
1873}
1874
1875
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001876void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1877 HandleScope scope;
1878
1879 // Bail out based on state or if there is no listener for this event
1880 if (Debug::InDebugger()) return;
1881 if (!Debugger::EventActive(v8::Exception)) return;
1882
1883 // Bail out if exception breaks are not active
1884 if (uncaught) {
1885 // Uncaught exceptions are reported by either flags.
1886 if (!(Debug::break_on_uncaught_exception() ||
1887 Debug::break_on_exception())) return;
1888 } else {
1889 // Caught exceptions are reported is activated.
1890 if (!Debug::break_on_exception()) return;
1891 }
1892
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001893 // Enter the debugger.
1894 EnterDebugger debugger;
1895 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001896
1897 // Clear all current stepping setup.
1898 Debug::ClearStepping();
1899 // Create the event data object.
1900 bool caught_exception = false;
1901 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1902 Handle<Object> event_data;
1903 if (!caught_exception) {
1904 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1905 &caught_exception);
1906 }
1907 // Bail out and don't call debugger if exception.
1908 if (caught_exception) {
1909 return;
1910 }
1911
ager@chromium.org5ec48922009-05-05 07:25:34 +00001912 // Process debug event.
1913 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001914 // Return to continue execution from where the exception was thrown.
1915}
1916
1917
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001918void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1919 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001920 HandleScope scope;
1921
kasper.lund212ac232008-07-16 07:07:30 +00001922 // Debugger has already been entered by caller.
1923 ASSERT(Top::context() == *Debug::debug_context());
1924
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001925 // Bail out if there is no listener for this event
1926 if (!Debugger::EventActive(v8::Break)) return;
1927
1928 // Debugger must be entered in advance.
1929 ASSERT(Top::context() == *Debug::debug_context());
1930
1931 // Create the event data object.
1932 bool caught_exception = false;
1933 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1934 Handle<Object> event_data;
1935 if (!caught_exception) {
1936 event_data = MakeBreakEvent(exec_state, break_points_hit,
1937 &caught_exception);
1938 }
1939 // Bail out and don't call debugger if exception.
1940 if (caught_exception) {
1941 return;
1942 }
1943
ager@chromium.org5ec48922009-05-05 07:25:34 +00001944 // Process debug event.
1945 ProcessDebugEvent(v8::Break,
1946 Handle<JSObject>::cast(event_data),
1947 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001948}
1949
1950
1951void Debugger::OnBeforeCompile(Handle<Script> script) {
1952 HandleScope scope;
1953
1954 // Bail out based on state or if there is no listener for this event
1955 if (Debug::InDebugger()) return;
1956 if (compiling_natives()) return;
1957 if (!EventActive(v8::BeforeCompile)) return;
1958
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001959 // Enter the debugger.
1960 EnterDebugger debugger;
1961 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001962
1963 // Create the event data object.
1964 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001965 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001966 // Bail out and don't call debugger if exception.
1967 if (caught_exception) {
1968 return;
1969 }
1970
ager@chromium.org5ec48922009-05-05 07:25:34 +00001971 // Process debug event.
1972 ProcessDebugEvent(v8::BeforeCompile,
1973 Handle<JSObject>::cast(event_data),
1974 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001975}
1976
1977
1978// Handle debugger actions when a new script is compiled.
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00001979void Debugger::OnAfterCompile(Handle<Script> script,
1980 AfterCompileFlags after_compile_flags) {
kasper.lund212ac232008-07-16 07:07:30 +00001981 HandleScope scope;
1982
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001983 // Add the newly compiled script to the script cache.
1984 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001985
1986 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001987 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001988
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001989 // No compile events while compiling natives.
1990 if (compiling_natives()) return;
1991
iposva@chromium.org245aa852009-02-10 00:49:54 +00001992 // Store whether in debugger before entering debugger.
1993 bool in_debugger = Debug::InDebugger();
1994
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001995 // Enter the debugger.
1996 EnterDebugger debugger;
1997 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001998
1999 // If debugging there might be script break points registered for this
2000 // script. Make sure that these break points are set.
2001
2002 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
2003 Handle<Object> update_script_break_points =
2004 Handle<Object>(Debug::debug_context()->global()->GetProperty(
2005 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
2006 if (!update_script_break_points->IsJSFunction()) {
2007 return;
2008 }
2009 ASSERT(update_script_break_points->IsJSFunction());
2010
2011 // Wrap the script object in a proper JS object before passing it
2012 // to JavaScript.
2013 Handle<JSValue> wrapper = GetScriptWrapper(script);
2014
2015 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00002016 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002017 const int argc = 1;
2018 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2019 Handle<Object> result = Execution::TryCall(
2020 Handle<JSFunction>::cast(update_script_break_points),
2021 Top::builtins(), argc, argv,
2022 &caught_exception);
2023 if (caught_exception) {
2024 return;
2025 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002026 // Bail out based on state or if there is no listener for this event
ager@chromium.orgce5e87b2010-03-10 10:24:18 +00002027 if (in_debugger && (after_compile_flags & SEND_WHEN_DEBUGGING) == 0) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002028 if (!Debugger::EventActive(v8::AfterCompile)) return;
2029
2030 // Create the compile state object.
2031 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002032 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002033 &caught_exception);
2034 // Bail out and don't call debugger if exception.
2035 if (caught_exception) {
2036 return;
2037 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00002038 // Process debug event.
2039 ProcessDebugEvent(v8::AfterCompile,
2040 Handle<JSObject>::cast(event_data),
2041 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002042}
2043
2044
2045void Debugger::OnNewFunction(Handle<JSFunction> function) {
2046 return;
2047 HandleScope scope;
2048
2049 // Bail out based on state or if there is no listener for this event
2050 if (Debug::InDebugger()) return;
2051 if (compiling_natives()) return;
2052 if (!Debugger::EventActive(v8::NewFunction)) return;
2053
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002054 // Enter the debugger.
2055 EnterDebugger debugger;
2056 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002057
2058 // Create the event object.
2059 bool caught_exception = false;
2060 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
2061 // Bail out and don't call debugger if exception.
2062 if (caught_exception) {
2063 return;
2064 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002065 // Process debug event.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002066 ProcessDebugEvent(v8::NewFunction, Handle<JSObject>::cast(event_data), true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002067}
2068
2069
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002070void Debugger::OnScriptCollected(int id) {
2071 HandleScope scope;
2072
2073 // No more to do if not debugging.
2074 if (!IsDebuggerActive()) return;
2075 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2076
2077 // Enter the debugger.
2078 EnterDebugger debugger;
2079 if (debugger.FailedToEnter()) return;
2080
2081 // Create the script collected state object.
2082 bool caught_exception = false;
2083 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2084 &caught_exception);
2085 // Bail out and don't call debugger if exception.
2086 if (caught_exception) {
2087 return;
2088 }
2089
2090 // Process debug event.
2091 ProcessDebugEvent(v8::ScriptCollected,
2092 Handle<JSObject>::cast(event_data),
2093 true);
2094}
2095
2096
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002097void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002098 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002099 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002100 HandleScope scope;
2101
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002102 // Clear any pending debug break if this is a real break.
2103 if (!auto_continue) {
2104 Debug::clear_interrupt_pending(DEBUGBREAK);
2105 }
2106
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002107 // Create the execution state.
2108 bool caught_exception = false;
2109 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2110 if (caught_exception) {
2111 return;
2112 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002113 // First notify the message handler if any.
2114 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002115 NotifyMessageHandler(event,
2116 Handle<JSObject>::cast(exec_state),
2117 event_data,
2118 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002119 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002120 // Notify registered debug event listener. This can be either a C or a
2121 // JavaScript function.
2122 if (!event_listener_.is_null()) {
2123 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002124 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002125 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002126 v8::Debug::EventCallback callback =
2127 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002128 callback(event,
2129 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002130 v8::Utils::ToLocal(event_data),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002131 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002132 } else {
2133 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002134 ASSERT(event_listener_->IsJSFunction());
2135 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002136
2137 // Invoke the JavaScript debug event listener.
2138 const int argc = 4;
2139 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2140 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002141 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002142 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002143 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2144 argc, argv, &caught_exception);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002145 // Silently ignore exceptions from debug event listeners.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002146 }
2147 }
2148}
2149
2150
ager@chromium.org71daaf62009-04-01 07:22:49 +00002151void Debugger::UnloadDebugger() {
2152 // Make sure that there are no breakpoints left.
2153 Debug::ClearAllBreakPoints();
2154
2155 // Unload the debugger if feasible.
2156 if (!never_unload_debugger_) {
2157 Debug::Unload();
2158 }
2159
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002160 // Clear the flag indicating that the debugger should be unloaded.
2161 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002162}
2163
2164
ager@chromium.org41826e72009-03-30 13:30:57 +00002165void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002166 Handle<JSObject> exec_state,
2167 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002168 bool auto_continue) {
2169 HandleScope scope;
2170
2171 if (!Debug::Load()) return;
2172
2173 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002174 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002175 switch (event) {
2176 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002177 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002178 break;
2179 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002180 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002181 break;
2182 case v8::BeforeCompile:
2183 break;
2184 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002185 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002186 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002187 case v8::ScriptCollected:
2188 sendEventMessage = true;
2189 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002190 case v8::NewFunction:
2191 break;
2192 default:
2193 UNREACHABLE();
2194 }
2195
ager@chromium.org5ec48922009-05-05 07:25:34 +00002196 // The debug command interrupt flag might have been set when the command was
2197 // added. It should be enough to clear the flag only once while we are in the
2198 // debugger.
2199 ASSERT(Debug::InDebugger());
2200 StackGuard::Continue(DEBUGCOMMAND);
2201
2202 // Notify the debugger that a debug event has occurred unless auto continue is
2203 // active in which case no event is send.
2204 if (sendEventMessage) {
2205 MessageImpl message = MessageImpl::NewEvent(
2206 event,
2207 auto_continue,
2208 Handle<JSObject>::cast(exec_state),
2209 Handle<JSObject>::cast(event_data));
2210 InvokeMessageHandler(message);
2211 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002212
2213 // If auto continue don't make the event cause a break, but process messages
2214 // in the queue if any. For script collected events don't even process
2215 // messages in the queue as the execution state might not be what is expected
2216 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002217 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002218 return;
2219 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002220
ager@chromium.org41826e72009-03-30 13:30:57 +00002221 v8::TryCatch try_catch;
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002222
2223 // DebugCommandProcessor goes here.
2224 v8::Local<v8::Object> cmd_processor;
2225 {
2226 v8::Local<v8::Object> api_exec_state =
2227 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2228 v8::Local<v8::String> fun_name =
2229 v8::String::New("debugCommandProcessor");
2230 v8::Local<v8::Function> fun =
2231 v8::Function::Cast(*api_exec_state->Get(fun_name));
2232
2233 v8::Handle<v8::Boolean> running =
2234 auto_continue ? v8::True() : v8::False();
2235 static const int kArgc = 1;
2236 v8::Handle<Value> argv[kArgc] = { running };
2237 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2238 if (try_catch.HasCaught()) {
2239 PrintLn(try_catch.Exception());
2240 return;
2241 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002242 }
2243
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002244 bool running = auto_continue;
2245
ager@chromium.org41826e72009-03-30 13:30:57 +00002246 // Process requests from the debugger.
2247 while (true) {
2248 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002249 if (Debugger::host_dispatch_handler_) {
2250 // In case there is a host dispatch - do periodic dispatches.
2251 if (!command_received_->Wait(host_dispatch_micros_)) {
2252 // Timout expired, do the dispatch.
2253 Debugger::host_dispatch_handler_();
2254 continue;
2255 }
2256 } else {
2257 // In case there is no host dispatch - just wait.
2258 command_received_->Wait();
2259 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002260
ager@chromium.org41826e72009-03-30 13:30:57 +00002261 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002262 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002263 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002264 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002265 // Delete command text and user data.
2266 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002267 return;
2268 }
2269
ager@chromium.org41826e72009-03-30 13:30:57 +00002270 // Invoke JavaScript to process the debug request.
2271 v8::Local<v8::String> fun_name;
2272 v8::Local<v8::Function> fun;
2273 v8::Local<v8::Value> request;
2274 v8::TryCatch try_catch;
2275 fun_name = v8::String::New("processDebugRequest");
2276 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002277
2278 request = v8::String::New(command.text().start(),
2279 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002280 static const int kArgc = 1;
2281 v8::Handle<Value> argv[kArgc] = { request };
2282 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2283
2284 // Get the response.
2285 v8::Local<v8::String> response;
ager@chromium.org41826e72009-03-30 13:30:57 +00002286 if (!try_catch.HasCaught()) {
2287 // Get response string.
2288 if (!response_val->IsUndefined()) {
2289 response = v8::String::Cast(*response_val);
2290 } else {
2291 response = v8::String::New("");
2292 }
2293
2294 // Log the JSON request/response.
2295 if (FLAG_trace_debug_json) {
2296 PrintLn(request);
2297 PrintLn(response);
2298 }
2299
2300 // Get the running state.
2301 fun_name = v8::String::New("isRunning");
2302 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2303 static const int kArgc = 1;
2304 v8::Handle<Value> argv[kArgc] = { response };
2305 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2306 if (!try_catch.HasCaught()) {
2307 running = running_val->ToBoolean()->Value();
2308 }
2309 } else {
2310 // In case of failure the result text is the exception text.
2311 response = try_catch.Exception()->ToString();
2312 }
2313
ager@chromium.org41826e72009-03-30 13:30:57 +00002314 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002315 MessageImpl message = MessageImpl::NewResponse(
2316 event,
2317 running,
2318 Handle<JSObject>::cast(exec_state),
2319 Handle<JSObject>::cast(event_data),
2320 Handle<String>(Utils::OpenHandle(*response)),
2321 command.client_data());
2322 InvokeMessageHandler(message);
2323 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002324
2325 // Return from debug event processing if either the VM is put into the
2326 // runnning state (through a continue command) or auto continue is active
2327 // and there are no more commands queued.
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002328 if (running && !HasCommands()) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002329 return;
2330 }
2331 }
2332}
2333
2334
iposva@chromium.org245aa852009-02-10 00:49:54 +00002335void Debugger::SetEventListener(Handle<Object> callback,
2336 Handle<Object> data) {
2337 HandleScope scope;
2338
2339 // Clear the global handles for the event listener and the event listener data
2340 // object.
2341 if (!event_listener_.is_null()) {
2342 GlobalHandles::Destroy(
2343 reinterpret_cast<Object**>(event_listener_.location()));
2344 event_listener_ = Handle<Object>();
2345 }
2346 if (!event_listener_data_.is_null()) {
2347 GlobalHandles::Destroy(
2348 reinterpret_cast<Object**>(event_listener_data_.location()));
2349 event_listener_data_ = Handle<Object>();
2350 }
2351
2352 // If there is a new debug event listener register it together with its data
2353 // object.
2354 if (!callback->IsUndefined() && !callback->IsNull()) {
2355 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2356 if (data.is_null()) {
2357 data = Factory::undefined_value();
2358 }
2359 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2360 }
2361
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002362 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002363}
2364
2365
ager@chromium.org5ec48922009-05-05 07:25:34 +00002366void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002367 ScopedLock with(debugger_access_);
2368
ager@chromium.org381abbb2009-02-25 13:23:22 +00002369 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002370 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002371 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002372 // Send an empty command to the debugger if in a break to make JavaScript
2373 // run again if the debugger is closed.
2374 if (Debug::InDebugger()) {
2375 ProcessCommand(Vector<const uint16_t>::empty());
2376 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002377 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002378}
2379
2380
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002381void Debugger::ListenersChanged() {
2382 if (IsDebuggerActive()) {
2383 // Disable the compilation cache when the debugger is active.
2384 CompilationCache::Disable();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002385 debugger_unload_pending_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002386 } else {
2387 CompilationCache::Enable();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002388 // Unload the debugger if event listener and message handler cleared.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002389 // Schedule this for later, because we may be in non-V8 thread.
2390 debugger_unload_pending_ = true;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002391 }
2392}
2393
2394
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002395void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2396 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002397 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002398 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002399}
2400
2401
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002402void Debugger::SetDebugMessageDispatchHandler(
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002403 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2404 ScopedLock with(dispatch_handler_access_);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002405 debug_message_dispatch_handler_ = handler;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002406
2407 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2408 message_dispatch_helper_thread_ = new MessageDispatchHelperThread;
2409 message_dispatch_helper_thread_->Start();
2410 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002411}
2412
2413
ager@chromium.org41826e72009-03-30 13:30:57 +00002414// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002415// public API.
2416void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002417 ScopedLock with(debugger_access_);
2418
ager@chromium.org381abbb2009-02-25 13:23:22 +00002419 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002420 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002421 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002422}
2423
2424
2425// Puts a command coming from the public API on the queue. Creates
2426// a copy of the command string managed by the debugger. Up to this
2427// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002428// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002429void Debugger::ProcessCommand(Vector<const uint16_t> command,
2430 v8::Debug::ClientData* client_data) {
2431 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002432 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002433 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002434 command.length()),
2435 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002436 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002437 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002438 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002439
2440 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002441 if (!Debug::InDebugger()) {
2442 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002443 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002444
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002445 MessageDispatchHelperThread* dispatch_thread;
2446 {
2447 ScopedLock with(dispatch_handler_access_);
2448 dispatch_thread = message_dispatch_helper_thread_;
2449 }
2450
2451 if (dispatch_thread == NULL) {
2452 CallMessageDispatchHandler();
2453 } else {
2454 dispatch_thread->Schedule();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002455 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002456}
2457
2458
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002459bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002460 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002461}
2462
2463
ager@chromium.org71daaf62009-04-01 07:22:49 +00002464bool Debugger::IsDebuggerActive() {
2465 ScopedLock with(debugger_access_);
2466
2467 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002468}
2469
2470
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002471Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2472 Handle<Object> data,
2473 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002474 // When calling functions in the debugger prevent it from beeing unloaded.
2475 Debugger::never_unload_debugger_ = true;
2476
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002477 // Enter the debugger.
2478 EnterDebugger debugger;
2479 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2480 return Factory::undefined_value();
2481 }
2482
2483 // Create the execution state.
2484 bool caught_exception = false;
2485 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2486 if (caught_exception) {
2487 return Factory::undefined_value();
2488 }
2489
2490 static const int kArgc = 2;
2491 Object** argv[kArgc] = { exec_state.location(), data.location() };
2492 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2493 kArgc, argv, pending_exception);
2494 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