blob: 3c2bfa80c6e8e2b792ced29f25db7935472fec38 [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"
kasperl@chromium.org71affb52009-05-26 05:44:31 +000034#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000035#include "compiler.h"
36#include "debug.h"
37#include "execution.h"
38#include "global-handles.h"
ager@chromium.org65dad4b2009-04-23 08:48:43 +000039#include "ic.h"
40#include "ic-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000041#include "natives.h"
42#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000043#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044
ager@chromium.org5ec48922009-05-05 07:25:34 +000045#include "../include/v8-debug.h"
46
kasperl@chromium.org71affb52009-05-26 05:44:31 +000047namespace v8 {
48namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000049
ager@chromium.org65dad4b2009-04-23 08:48:43 +000050#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000051static void PrintLn(v8::Local<v8::Value> value) {
52 v8::Local<v8::String> s = value->ToString();
53 char* data = NewArray<char>(s->Length() + 1);
54 if (data == NULL) {
55 V8::FatalProcessOutOfMemory("PrintLn");
56 return;
57 }
58 s->WriteAscii(data);
59 PrintF("%s\n", data);
60 DeleteArray(data);
61}
62
63
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000064static Handle<Code> ComputeCallDebugBreak(int argc) {
65 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
66}
67
68
69static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
70 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
71}
72
73
74BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
75 BreakLocatorType type) {
76 debug_info_ = debug_info;
77 type_ = type;
ager@chromium.orga1645e22009-09-09 19:27:10 +000078 // Get the stub early to avoid possible GC during iterations. We may need
79 // this stub to detect debugger calls generated from debugger statements.
80 debug_break_stub_ = RuntimeStub(Runtime::kDebugBreak, 0).GetCode();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000081 reloc_iterator_ = NULL;
82 reloc_iterator_original_ = NULL;
83 Reset(); // Initialize the rest of the member variables.
84}
85
86
87BreakLocationIterator::~BreakLocationIterator() {
88 ASSERT(reloc_iterator_ != NULL);
89 ASSERT(reloc_iterator_original_ != NULL);
90 delete reloc_iterator_;
91 delete reloc_iterator_original_;
92}
93
94
95void BreakLocationIterator::Next() {
96 AssertNoAllocation nogc;
97 ASSERT(!RinfoDone());
98
99 // Iterate through reloc info for code and original code stopping at each
100 // breakable code target.
101 bool first = break_point_ == -1;
102 while (!RinfoDone()) {
103 if (!first) RinfoNext();
104 first = false;
105 if (RinfoDone()) return;
106
ager@chromium.org236ad962008-09-25 09:45:57 +0000107 // Whenever a statement position or (plain) position is passed update the
108 // current value of these.
109 if (RelocInfo::IsPosition(rmode())) {
110 if (RelocInfo::IsStatementPosition(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000111 statement_position_ =
112 rinfo()->data() - debug_info_->shared()->start_position();
113 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000114 // Always update the position as we don't want that to be before the
115 // statement position.
116 position_ = 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.org236ad962008-09-25 09:45:57 +0000127 if (code->is_inline_cache_stub() || RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000128 break_point_++;
129 return;
130 }
131 if (code->kind() == Code::STUB) {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000132 if (IsDebuggerStatement()) {
133 break_point_++;
134 return;
135 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000136 if (type_ == ALL_BREAK_LOCATIONS) {
137 if (Debug::IsBreakStub(code)) {
138 break_point_++;
139 return;
140 }
141 } else {
142 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
143 if (Debug::IsSourceBreakStub(code)) {
144 break_point_++;
145 return;
146 }
147 }
148 }
149 }
150
151 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000152 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000153 // Set the positions to the end of the function.
154 if (debug_info_->shared()->HasSourceCode()) {
155 position_ = debug_info_->shared()->end_position() -
156 debug_info_->shared()->start_position();
157 } else {
158 position_ = 0;
159 }
160 statement_position_ = position_;
161 break_point_++;
162 return;
163 }
164 }
165}
166
167
168void BreakLocationIterator::Next(int count) {
169 while (count > 0) {
170 Next();
171 count--;
172 }
173}
174
175
176// Find the break point closest to the supplied address.
177void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
178 // Run through all break points to locate the one closest to the address.
179 int closest_break_point = 0;
180 int distance = kMaxInt;
181 while (!Done()) {
182 // Check if this break point is closer that what was previously found.
183 if (this->pc() < pc && pc - this->pc() < distance) {
184 closest_break_point = break_point();
185 distance = pc - this->pc();
186 // Check whether we can't get any closer.
187 if (distance == 0) break;
188 }
189 Next();
190 }
191
192 // Move to the break point found.
193 Reset();
194 Next(closest_break_point);
195}
196
197
198// Find the break point closest to the supplied source position.
199void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
200 // Run through all break points to locate the one closest to the source
201 // position.
202 int closest_break_point = 0;
203 int distance = kMaxInt;
204 while (!Done()) {
205 // Check if this break point is closer that what was previously found.
206 if (position <= statement_position() &&
207 statement_position() - position < distance) {
208 closest_break_point = break_point();
209 distance = statement_position() - position;
210 // Check whether we can't get any closer.
211 if (distance == 0) break;
212 }
213 Next();
214 }
215
216 // Move to the break point found.
217 Reset();
218 Next(closest_break_point);
219}
220
221
222void BreakLocationIterator::Reset() {
223 // Create relocation iterators for the two code objects.
224 if (reloc_iterator_ != NULL) delete reloc_iterator_;
225 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
226 reloc_iterator_ = new RelocIterator(debug_info_->code());
227 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
228
229 // Position at the first break point.
230 break_point_ = -1;
231 position_ = 1;
232 statement_position_ = 1;
233 Next();
234}
235
236
237bool BreakLocationIterator::Done() const {
238 return RinfoDone();
239}
240
241
242void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
243 // If there is not already a real break point here patch code with debug
244 // break.
245 if (!HasBreakPoint()) {
246 SetDebugBreak();
247 }
ager@chromium.orga1645e22009-09-09 19:27:10 +0000248 ASSERT(IsDebugBreak() || IsDebuggerStatement());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000249 // Set the break point information.
250 DebugInfo::SetBreakPoint(debug_info_, code_position(),
251 position(), statement_position(),
252 break_point_object);
253}
254
255
256void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
257 // Clear the break point information.
258 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
259 // If there are no more break points here remove the debug break.
260 if (!HasBreakPoint()) {
261 ClearDebugBreak();
262 ASSERT(!IsDebugBreak());
263 }
264}
265
266
267void BreakLocationIterator::SetOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000268 // Debugger statement always calls debugger. No need to modify it.
269 if (IsDebuggerStatement()) {
270 return;
271 }
272
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000273 // If there is a real break point here no more to do.
274 if (HasBreakPoint()) {
275 ASSERT(IsDebugBreak());
276 return;
277 }
278
279 // Patch code with debug break.
280 SetDebugBreak();
281}
282
283
284void BreakLocationIterator::ClearOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000285 // Debugger statement always calls debugger. No need to modify it.
286 if (IsDebuggerStatement()) {
287 return;
288 }
289
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290 // If there is a real break point here no more to do.
291 if (HasBreakPoint()) {
292 ASSERT(IsDebugBreak());
293 return;
294 }
295
296 // Patch code removing debug break.
297 ClearDebugBreak();
298 ASSERT(!IsDebugBreak());
299}
300
301
302void BreakLocationIterator::SetDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000303 // Debugger statement always calls debugger. No need to modify it.
304 if (IsDebuggerStatement()) {
305 return;
306 }
307
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000308 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000309 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000310 // function twice might happen when stepping in a function with an exception
311 // handler as the handler and the function is the same.
312 if (IsDebugBreak()) {
313 return;
314 }
315
ager@chromium.org236ad962008-09-25 09:45:57 +0000316 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000317 // Patch the frame exit code with a break point.
318 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000319 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000320 // Patch the IC call.
321 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000322 }
323 ASSERT(IsDebugBreak());
324}
325
326
327void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000328 // Debugger statement always calls debugger. No need to modify it.
329 if (IsDebuggerStatement()) {
330 return;
331 }
332
ager@chromium.org236ad962008-09-25 09:45:57 +0000333 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000334 // Restore the frame exit code.
335 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000337 // Patch the IC call.
338 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000339 }
340 ASSERT(!IsDebugBreak());
341}
342
343
344void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000345 HandleScope scope;
346
ager@chromium.orga1645e22009-09-09 19:27:10 +0000347 // Step in can only be prepared if currently positioned on an IC call,
348 // construct call or CallFunction stub call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000349 Address target = rinfo()->target_address();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000350 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000351 if (code->is_call_stub()) {
352 // Step in through IC call is handled by the runtime system. Therefore make
353 // sure that the any current IC is cleared and the runtime system is
354 // called. If the executing code has a debug break at the location change
355 // the call in the original code as it is the code there that will be
356 // executed in place of the debug break call.
357 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
358 if (IsDebugBreak()) {
359 original_rinfo()->set_target_address(stub->entry());
360 } else {
361 rinfo()->set_target_address(stub->entry());
362 }
363 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000364#ifdef DEBUG
365 // All the following stuff is needed only for assertion checks so the code
366 // is wrapped in ifdef.
367 Handle<Code> maybe_call_function_stub = code;
368 if (IsDebugBreak()) {
369 Address original_target = original_rinfo()->target_address();
370 maybe_call_function_stub =
371 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
372 }
373 bool is_call_function_stub =
374 (maybe_call_function_stub->kind() == Code::STUB &&
375 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
376
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000377 // Step in through construct call requires no changes to the running code.
378 // Step in through getters/setters should already be prepared as well
379 // because caller of this function (Debug::PrepareStep) is expected to
380 // flood the top frame's function with one shot breakpoints.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000381 // Step in through CallFunction stub should also be prepared by caller of
382 // this function (Debug::PrepareStep) which should flood target function
383 // with breakpoints.
384 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
385 || is_call_function_stub);
386#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000387 }
388}
389
390
391// Check whether the break point is at a position which will exit the function.
392bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000393 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000394}
395
396
397bool BreakLocationIterator::HasBreakPoint() {
398 return debug_info_->HasBreakPoint(code_position());
399}
400
401
402// Check whether there is a debug break at the current position.
403bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000404 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000405 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000406 } else {
407 return Debug::IsDebugBreak(rinfo()->target_address());
408 }
409}
410
411
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000412void BreakLocationIterator::SetDebugBreakAtIC() {
413 // Patch the original code with the current address as the current address
414 // might have changed by the inline caching since the code was copied.
415 original_rinfo()->set_target_address(rinfo()->target_address());
416
417 RelocInfo::Mode mode = rmode();
418 if (RelocInfo::IsCodeTarget(mode)) {
419 Address target = rinfo()->target_address();
420 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
421
422 // Patch the code to invoke the builtin debug break function matching the
423 // calling convention used by the call site.
424 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
425 rinfo()->set_target_address(dbgbrk_code->entry());
426
427 // For stubs that refer back to an inlined version clear the cached map for
428 // the inlined case to always go through the IC. As long as the break point
429 // is set the patching performed by the runtime system will take place in
430 // the code copy and will therefore have no effect on the running code
431 // keeping it from using the inlined code.
ager@chromium.org5ec48922009-05-05 07:25:34 +0000432 if (code->is_keyed_load_stub()) KeyedLoadIC::ClearInlinedVersion(pc());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000433 if (code->is_keyed_store_stub()) KeyedStoreIC::ClearInlinedVersion(pc());
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000434 }
435}
436
437
438void BreakLocationIterator::ClearDebugBreakAtIC() {
439 // Patch the code to the original invoke.
440 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000441
442 RelocInfo::Mode mode = rmode();
443 if (RelocInfo::IsCodeTarget(mode)) {
444 Address target = original_rinfo()->target_address();
445 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
446
447 // Restore the inlined version of keyed stores to get back to the
448 // fast case. We need to patch back the keyed store because no
449 // patching happens when running normally. For keyed loads, the
450 // map check will get patched back when running normally after ICs
451 // have been cleared at GC.
452 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
453 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000454}
455
456
ager@chromium.orga1645e22009-09-09 19:27:10 +0000457bool BreakLocationIterator::IsDebuggerStatement() {
458 if (RelocInfo::IsCodeTarget(rmode())) {
459 Address target = original_rinfo()->target_address();
460 Code* code = Code::GetCodeFromTargetAddress(target);
461 if (code->kind() == Code::STUB) {
462 CodeStub::Major major_key = code->major_key();
463 if (major_key == CodeStub::Runtime) {
464 return (*debug_break_stub_ == code);
465 }
466 }
467 }
468 return false;
469}
470
471
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000472Object* BreakLocationIterator::BreakPointObjects() {
473 return debug_info_->GetBreakPointObjects(code_position());
474}
475
476
ager@chromium.org381abbb2009-02-25 13:23:22 +0000477// Clear out all the debug break code. This is ONLY supposed to be used when
478// shutting down the debugger as it will leave the break point information in
479// DebugInfo even though the code is patched back to the non break point state.
480void BreakLocationIterator::ClearAllDebugBreak() {
481 while (!Done()) {
482 ClearDebugBreak();
483 Next();
484 }
485}
486
487
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000488bool BreakLocationIterator::RinfoDone() const {
489 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
490 return reloc_iterator_->done();
491}
492
493
494void BreakLocationIterator::RinfoNext() {
495 reloc_iterator_->next();
496 reloc_iterator_original_->next();
497#ifdef DEBUG
498 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
499 if (!reloc_iterator_->done()) {
500 ASSERT(rmode() == original_rmode());
501 }
502#endif
503}
504
505
506bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000507ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000508DebugInfoListNode* Debug::debug_info_list_ = NULL;
509
510
511// Threading support.
512void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000513 thread_local_.break_count_ = 0;
514 thread_local_.break_id_ = 0;
515 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000516 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000517 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000518 thread_local_.step_count_ = 0;
519 thread_local_.last_fp_ = 0;
520 thread_local_.step_into_fp_ = 0;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000521 thread_local_.step_out_fp_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000522 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000523 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000524 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000525}
526
527
528JSCallerSavedBuffer Debug::registers_;
529Debug::ThreadLocal Debug::thread_local_;
530
531
532char* Debug::ArchiveDebug(char* storage) {
533 char* to = storage;
534 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
535 to += sizeof(ThreadLocal);
536 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
537 ThreadInit();
538 ASSERT(to <= storage + ArchiveSpacePerThread());
539 return storage + ArchiveSpacePerThread();
540}
541
542
543char* Debug::RestoreDebug(char* storage) {
544 char* from = storage;
545 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
546 from += sizeof(ThreadLocal);
547 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
548 ASSERT(from <= storage + ArchiveSpacePerThread());
549 return storage + ArchiveSpacePerThread();
550}
551
552
553int Debug::ArchiveSpacePerThread() {
554 return sizeof(ThreadLocal) + sizeof(registers_);
555}
556
557
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000558// Default break enabled.
559bool Debug::disable_break_ = false;
560
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000561// Default call debugger on uncaught exception.
562bool Debug::break_on_exception_ = false;
563bool Debug::break_on_uncaught_exception_ = true;
564
565Handle<Context> Debug::debug_context_ = Handle<Context>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000566Code* Debug::debug_break_return_ = NULL;
567
568
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000569void ScriptCache::Add(Handle<Script> script) {
570 // Create an entry in the hash map for the script.
571 int id = Smi::cast(script->id())->value();
572 HashMap::Entry* entry =
573 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
574 if (entry->value != NULL) {
575 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
576 return;
577 }
578
579 // Globalize the script object, make it weak and use the location of the
580 // global handle as the value in the hash map.
581 Handle<Script> script_ =
582 Handle<Script>::cast((GlobalHandles::Create(*script)));
583 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
584 this, ScriptCache::HandleWeakScript);
585 entry->value = script_.location();
586}
587
588
589Handle<FixedArray> ScriptCache::GetScripts() {
590 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
591 int count = 0;
592 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
593 ASSERT(entry->value != NULL);
594 if (entry->value != NULL) {
595 instances->set(count, *reinterpret_cast<Script**>(entry->value));
596 count++;
597 }
598 }
599 return instances;
600}
601
602
603void ScriptCache::ProcessCollectedScripts() {
604 for (int i = 0; i < collected_scripts_.length(); i++) {
605 Debugger::OnScriptCollected(collected_scripts_[i]);
606 }
607 collected_scripts_.Clear();
608}
609
610
611void ScriptCache::Clear() {
612 // Iterate the script cache to get rid of all the weak handles.
613 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
614 ASSERT(entry != NULL);
615 Object** location = reinterpret_cast<Object**>(entry->value);
616 ASSERT((*location)->IsScript());
617 GlobalHandles::ClearWeakness(location);
618 GlobalHandles::Destroy(location);
619 }
620 // Clear the content of the hash map.
621 HashMap::Clear();
622}
623
624
625void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
626 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
627 // Find the location of the global handle.
628 Script** location =
629 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
630 ASSERT((*location)->IsScript());
631
632 // Remove the entry from the cache.
633 int id = Smi::cast((*location)->id())->value();
634 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
635 script_cache->collected_scripts_.Add(id);
636
637 // Clear the weak handle.
638 obj.Dispose();
639 obj.Clear();
640}
641
642
643void Debug::Setup(bool create_heap_objects) {
644 ThreadInit();
645 if (create_heap_objects) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000646 // Get code to handle debug break on return.
647 debug_break_return_ =
648 Builtins::builtin(Builtins::Return_DebugBreak);
649 ASSERT(debug_break_return_->IsCode());
650 }
651}
652
653
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000654void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000655 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
656 RemoveDebugInfo(node->debug_info());
657#ifdef DEBUG
658 node = Debug::debug_info_list_;
659 while (node != NULL) {
660 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
661 node = node->next();
662 }
663#endif
664}
665
666
667DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
668 // Globalize the request debug info object and make it weak.
669 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
670 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
671 this, Debug::HandleWeakDebugInfo);
672}
673
674
675DebugInfoListNode::~DebugInfoListNode() {
676 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
677}
678
679
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000680bool Debug::CompileDebuggerScript(int index) {
681 HandleScope scope;
682
kasper.lund44510672008-07-25 07:37:58 +0000683 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000684 if (index == -1) {
685 return false;
686 }
kasper.lund44510672008-07-25 07:37:58 +0000687
688 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000689 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
690 Vector<const char> name = Natives::GetScriptName(index);
691 Handle<String> script_name = Factory::NewStringFromAscii(name);
692
693 // Compile the script.
694 bool allow_natives_syntax = FLAG_allow_natives_syntax;
695 FLAG_allow_natives_syntax = true;
696 Handle<JSFunction> boilerplate;
697 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL);
698 FLAG_allow_natives_syntax = allow_natives_syntax;
699
700 // Silently ignore stack overflows during compilation.
701 if (boilerplate.is_null()) {
702 ASSERT(Top::has_pending_exception());
703 Top::clear_pending_exception();
704 return false;
705 }
706
kasper.lund44510672008-07-25 07:37:58 +0000707 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000708 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000709 bool caught_exception = false;
710 Handle<JSFunction> function =
711 Factory::NewFunctionFromBoilerplate(boilerplate, context);
712 Handle<Object> result =
713 Execution::TryCall(function, Handle<Object>(context->global()),
714 0, NULL, &caught_exception);
715
716 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000717 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000718 Handle<Object> message = MessageHandler::MakeMessageObject(
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000719 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000720 Handle<String>());
721 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000722 return false;
723 }
724
kasper.lund44510672008-07-25 07:37:58 +0000725 // Mark this script as native and return successfully.
726 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000727 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000728 return true;
729}
730
731
732bool Debug::Load() {
733 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000734 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000735
kasper.lund44510672008-07-25 07:37:58 +0000736 // Bail out if we're already in the process of compiling the native
737 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000738 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
739 return false;
740 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000741
742 // Disable breakpoints and interrupts while compiling and running the
743 // debugger scripts including the context creation code.
744 DisableBreak disable(true);
745 PostponeInterruptsScope postpone;
746
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000747 // Create the debugger context.
748 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000749 Handle<Context> context =
750 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
751 v8::Handle<ObjectTemplate>(),
752 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000753
kasper.lund44510672008-07-25 07:37:58 +0000754 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000755 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000756 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000757
758 // Expose the builtins object in the debugger context.
759 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
760 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
761 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000762
763 // Compile the JavaScript for the debugger in the debugger context.
764 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000765 bool caught_exception =
766 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
767 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000768 Debugger::set_compiling_natives(false);
769
mads.s.agercbaa0602008-08-14 13:41:48 +0000770 // Make sure we mark the debugger as not loading before we might
771 // return.
772 Debugger::set_loading_debugger(false);
773
kasper.lund44510672008-07-25 07:37:58 +0000774 // Check for caught exceptions.
775 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000776
777 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000778 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000779
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000780 return true;
781}
782
783
784void Debug::Unload() {
785 // Return debugger is not loaded.
786 if (!IsLoaded()) {
787 return;
788 }
789
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000790 // Clear the script cache.
791 DestroyScriptCache();
792
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000793 // Clear debugger context global handle.
794 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
795 debug_context_ = Handle<Context>();
796}
797
798
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000799// Set the flag indicating that preemption happened during debugging.
800void Debug::PreemptionWhileInDebugger() {
801 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000802 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000803}
804
805
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000806void Debug::Iterate(ObjectVisitor* v) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000807 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000808}
809
810
811Object* Debug::Break(Arguments args) {
812 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000813 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000814
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000815 // Get the top-most JavaScript frame.
816 JavaScriptFrameIterator it;
817 JavaScriptFrame* frame = it.frame();
818
819 // Just continue if breaks are disabled or debugger cannot be loaded.
820 if (disable_break() || !Load()) {
821 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000822 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000823 }
824
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000825 // Enter the debugger.
826 EnterDebugger debugger;
827 if (debugger.FailedToEnter()) {
828 return Heap::undefined_value();
829 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000830
kasper.lund44510672008-07-25 07:37:58 +0000831 // Postpone interrupt during breakpoint processing.
832 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000833
834 // Get the debug info (create it if it does not exist).
835 Handle<SharedFunctionInfo> shared =
836 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
837 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
838
839 // Find the break point where execution has stopped.
840 BreakLocationIterator break_location_iterator(debug_info,
841 ALL_BREAK_LOCATIONS);
842 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
843
844 // Check whether step next reached a new statement.
845 if (!StepNextContinue(&break_location_iterator, frame)) {
846 // Decrease steps left if performing multiple steps.
847 if (thread_local_.step_count_ > 0) {
848 thread_local_.step_count_--;
849 }
850 }
851
852 // If there is one or more real break points check whether any of these are
853 // triggered.
854 Handle<Object> break_points_hit(Heap::undefined_value());
855 if (break_location_iterator.HasBreakPoint()) {
856 Handle<Object> break_point_objects =
857 Handle<Object>(break_location_iterator.BreakPointObjects());
858 break_points_hit = CheckBreakPoints(break_point_objects);
859 }
860
ager@chromium.orga1645e22009-09-09 19:27:10 +0000861 // If step out is active skip everything until the frame where we need to step
862 // out to is reached, unless real breakpoint is hit.
863 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
864 break_points_hit->IsUndefined() ) {
865 // Step count should always be 0 for StepOut.
866 ASSERT(thread_local_.step_count_ == 0);
867 } else if (!break_points_hit->IsUndefined() ||
868 (thread_local_.last_step_action_ != StepNone &&
869 thread_local_.step_count_ == 0)) {
870 // Notify debugger if a real break point is triggered or if performing
871 // single stepping with no more steps to perform. Otherwise do another step.
872
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000873 // Clear all current stepping setup.
874 ClearStepping();
875
876 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000877 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000878 } else if (thread_local_.last_step_action_ != StepNone) {
879 // Hold on to last step action as it is cleared by the call to
880 // ClearStepping.
881 StepAction step_action = thread_local_.last_step_action_;
882 int step_count = thread_local_.step_count_;
883
884 // Clear all current stepping setup.
885 ClearStepping();
886
887 // Set up for the remaining steps.
888 PrepareStep(step_action, step_count);
889 }
890
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000891 // Install jump to the call address which was overwritten.
892 SetAfterBreakTarget(frame);
893
mads.s.ager31e71382008-08-13 09:32:07 +0000894 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000895}
896
897
898// Check the break point objects for whether one or more are actually
899// triggered. This function returns a JSArray with the break point objects
900// which is triggered.
901Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
902 int break_points_hit_count = 0;
903 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
904
v8.team.kasperl727e9952008-09-02 14:56:44 +0000905 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000906 ASSERT(!break_point_objects->IsUndefined());
907 if (break_point_objects->IsFixedArray()) {
908 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
909 for (int i = 0; i < array->length(); i++) {
910 Handle<Object> o(array->get(i));
911 if (CheckBreakPoint(o)) {
912 break_points_hit->SetElement(break_points_hit_count++, *o);
913 }
914 }
915 } else {
916 if (CheckBreakPoint(break_point_objects)) {
917 break_points_hit->SetElement(break_points_hit_count++,
918 *break_point_objects);
919 }
920 }
921
922 // Return undefined if no break points where triggered.
923 if (break_points_hit_count == 0) {
924 return Factory::undefined_value();
925 }
926 return break_points_hit;
927}
928
929
930// Check whether a single break point object is triggered.
931bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000932 HandleScope scope;
933
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000934 // Ignore check if break point object is not a JSObject.
935 if (!break_point_object->IsJSObject()) return true;
936
937 // Get the function CheckBreakPoint (defined in debug.js).
938 Handle<JSFunction> check_break_point =
939 Handle<JSFunction>(JSFunction::cast(
940 debug_context()->global()->GetProperty(
941 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
942
943 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000944 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000945
946 // Call HandleBreakPointx.
947 bool caught_exception = false;
948 const int argc = 2;
949 Object** argv[argc] = {
950 break_id.location(),
951 reinterpret_cast<Object**>(break_point_object.location())
952 };
953 Handle<Object> result = Execution::TryCall(check_break_point,
954 Top::builtins(), argc, argv,
955 &caught_exception);
956
957 // If exception or non boolean result handle as not triggered
958 if (caught_exception || !result->IsBoolean()) {
959 return false;
960 }
961
962 // Return whether the break point is triggered.
963 return *result == Heap::true_value();
964}
965
966
967// Check whether the function has debug information.
968bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
969 return !shared->debug_info()->IsUndefined();
970}
971
972
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000973// Return the debug info for this function. EnsureDebugInfo must be called
974// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000975Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000976 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000977 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
978}
979
980
981void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
982 int source_position,
983 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000984 HandleScope scope;
985
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000986 if (!EnsureDebugInfo(shared)) {
987 // Return if retrieving debug info failed.
988 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000989 }
990
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000991 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000992 // Source positions starts with zero.
993 ASSERT(source_position >= 0);
994
995 // Find the break point and change it.
996 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
997 it.FindBreakLocationFromPosition(source_position);
998 it.SetBreakPoint(break_point_object);
999
1000 // At least one active break point now.
1001 ASSERT(debug_info->GetBreakPointCount() > 0);
1002}
1003
1004
1005void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001006 HandleScope scope;
1007
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001008 DebugInfoListNode* node = debug_info_list_;
1009 while (node != NULL) {
1010 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1011 break_point_object);
1012 if (!result->IsUndefined()) {
1013 // Get information in the break point.
1014 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1015 Handle<DebugInfo> debug_info = node->debug_info();
1016 Handle<SharedFunctionInfo> shared(debug_info->shared());
1017 int source_position = break_point_info->statement_position()->value();
1018
1019 // Source positions starts with zero.
1020 ASSERT(source_position >= 0);
1021
1022 // Find the break point and clear it.
1023 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1024 it.FindBreakLocationFromPosition(source_position);
1025 it.ClearBreakPoint(break_point_object);
1026
1027 // If there are no more break points left remove the debug info for this
1028 // function.
1029 if (debug_info->GetBreakPointCount() == 0) {
1030 RemoveDebugInfo(debug_info);
1031 }
1032
1033 return;
1034 }
1035 node = node->next();
1036 }
1037}
1038
1039
ager@chromium.org381abbb2009-02-25 13:23:22 +00001040void Debug::ClearAllBreakPoints() {
1041 DebugInfoListNode* node = debug_info_list_;
1042 while (node != NULL) {
1043 // Remove all debug break code.
1044 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1045 it.ClearAllDebugBreak();
1046 node = node->next();
1047 }
1048
1049 // Remove all debug info.
1050 while (debug_info_list_ != NULL) {
1051 RemoveDebugInfo(debug_info_list_->debug_info());
1052 }
1053}
1054
1055
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001056void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001057 // Make sure the function has setup the debug info.
1058 if (!EnsureDebugInfo(shared)) {
1059 // Return if we failed to retrieve the debug info.
1060 return;
1061 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001062
1063 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001064 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001065 while (!it.Done()) {
1066 it.SetOneShot();
1067 it.Next();
1068 }
1069}
1070
1071
1072void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001073 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001074 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001075 if (id == StackFrame::NO_ID) {
1076 // If there is no JavaScript stack don't do anything.
1077 return;
1078 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001079 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1080 JavaScriptFrame* frame = it.frame();
1081 if (frame->HasHandler()) {
1082 Handle<SharedFunctionInfo> shared =
1083 Handle<SharedFunctionInfo>(
1084 JSFunction::cast(frame->function())->shared());
1085 // Flood the function with the catch block with break points
1086 FloodWithOneShot(shared);
1087 return;
1088 }
1089 }
1090}
1091
1092
1093void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1094 if (type == BreakUncaughtException) {
1095 break_on_uncaught_exception_ = enable;
1096 } else {
1097 break_on_exception_ = enable;
1098 }
1099}
1100
1101
1102void Debug::PrepareStep(StepAction step_action, int step_count) {
1103 HandleScope scope;
1104 ASSERT(Debug::InDebugger());
1105
1106 // Remember this step action and count.
1107 thread_local_.last_step_action_ = step_action;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001108 if (step_action == StepOut) {
1109 // For step out target frame will be found on the stack so there is no need
1110 // to set step counter for it. It's expected to always be 0 for StepOut.
1111 thread_local_.step_count_ = 0;
1112 } else {
1113 thread_local_.step_count_ = step_count;
1114 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001115
1116 // Get the frame where the execution has stopped and skip the debug frame if
1117 // any. The debug frame will only be present if execution was stopped due to
1118 // hitting a break point. In other situations (e.g. unhandled exception) the
1119 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001120 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001121 if (id == StackFrame::NO_ID) {
1122 // If there is no JavaScript stack don't do anything.
1123 return;
1124 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001125 JavaScriptFrameIterator frames_it(id);
1126 JavaScriptFrame* frame = frames_it.frame();
1127
1128 // First of all ensure there is one-shot break points in the top handler
1129 // if any.
1130 FloodHandlerWithOneShot();
1131
1132 // If the function on the top frame is unresolved perform step out. This will
1133 // be the case when calling unknown functions and having the debugger stopped
1134 // in an unhandled exception.
1135 if (!frame->function()->IsJSFunction()) {
1136 // Step out: Find the calling JavaScript frame and flood it with
1137 // breakpoints.
1138 frames_it.Advance();
1139 // Fill the function to return to with one-shot break points.
1140 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1141 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1142 return;
1143 }
1144
1145 // Get the debug info (create it if it does not exist).
1146 Handle<SharedFunctionInfo> shared =
1147 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001148 if (!EnsureDebugInfo(shared)) {
1149 // Return if ensuring debug info failed.
1150 return;
1151 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001152 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1153
1154 // Find the break location where execution has stopped.
1155 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1156 it.FindBreakLocationFromAddress(frame->pc());
1157
1158 // Compute whether or not the target is a call target.
1159 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001160 bool is_load_or_store = false;
1161 bool is_inline_cache_stub = false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001162 Handle<Code> call_function_stub;
ager@chromium.org236ad962008-09-25 09:45:57 +00001163 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001164 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001165 Code* code = Code::GetCodeFromTargetAddress(target);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001166 if (code->is_call_stub()) {
1167 is_call_target = true;
1168 }
1169 if (code->is_inline_cache_stub()) {
1170 is_inline_cache_stub = true;
1171 is_load_or_store = !is_call_target;
1172 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001173
1174 // Check if target code is CallFunction stub.
1175 Code* maybe_call_function_stub = code;
1176 // If there is a breakpoint at this line look at the original code to
1177 // check if it is a CallFunction stub.
1178 if (it.IsDebugBreak()) {
1179 Address original_target = it.original_rinfo()->target_address();
1180 maybe_call_function_stub =
1181 Code::GetCodeFromTargetAddress(original_target);
1182 }
1183 if (maybe_call_function_stub->kind() == Code::STUB &&
1184 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1185 // Save reference to the code as we may need it to find out arguments
1186 // count for 'step in' later.
1187 call_function_stub = Handle<Code>(maybe_call_function_stub);
1188 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001189 }
1190
v8.team.kasperl727e9952008-09-02 14:56:44 +00001191 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001192 if (it.IsExit() || step_action == StepOut) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001193 if (step_action == StepOut) {
1194 // Skip step_count frames starting with the current one.
1195 while (step_count-- > 0 && !frames_it.done()) {
1196 frames_it.Advance();
1197 }
1198 } else {
1199 ASSERT(it.IsExit());
1200 frames_it.Advance();
1201 }
1202 // Skip builtin functions on the stack.
1203 while (!frames_it.done() &&
1204 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1205 frames_it.Advance();
1206 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001207 // Step out: If there is a JavaScript caller frame, we need to
1208 // flood it with breakpoints.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001209 if (!frames_it.done()) {
1210 // Fill the function to return to with one-shot break points.
1211 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1212 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001213 // Set target frame pointer.
1214 ActivateStepOut(frames_it.frame());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001215 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001216 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1217 !call_function_stub.is_null())
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001218 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001219 // Step next or step min.
1220
1221 // Fill the current function with one-shot break points.
1222 FloodWithOneShot(shared);
1223
1224 // Remember source position and frame to handle step next.
1225 thread_local_.last_statement_position_ =
1226 debug_info->code()->SourceStatementPosition(frame->pc());
1227 thread_local_.last_fp_ = frame->fp();
1228 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001229 // If it's CallFunction stub ensure target function is compiled and flood
1230 // it with one shot breakpoints.
1231 if (!call_function_stub.is_null()) {
1232 // Find out number of arguments from the stub minor key.
1233 // Reverse lookup required as the minor key cannot be retrieved
1234 // from the code object.
1235 Handle<Object> obj(
1236 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1237 ASSERT(*obj != Heap::undefined_value());
1238 ASSERT(obj->IsSmi());
1239 // Get the STUB key and extract major and minor key.
1240 uint32_t key = Smi::cast(*obj)->value();
1241 // Argc in the stub is the number of arguments passed - not the
1242 // expected arguments of the called function.
1243 int call_function_arg_count = CodeStub::MinorKeyFromKey(key);
1244 ASSERT(call_function_stub->major_key() ==
1245 CodeStub::MajorKeyFromKey(key));
1246
1247 // Find target function on the expression stack.
1248 // Expression stack lools like this (top to bottom):
1249 // argN
1250 // ...
1251 // arg0
1252 // Receiver
1253 // Function to call
1254 int expressions_count = frame->ComputeExpressionsCount();
1255 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1256 Object* fun = frame->GetExpression(
1257 expressions_count - 2 - call_function_arg_count);
1258 if (fun->IsJSFunction()) {
1259 Handle<JSFunction> js_function(JSFunction::cast(fun));
1260 // Don't step into builtins.
1261 if (!js_function->IsBuiltin()) {
1262 // It will also compile target function if it's not compiled yet.
1263 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1264 }
1265 }
1266 }
1267
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001268 // Fill the current function with one-shot break points even for step in on
1269 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001270 // which step in will not stop. It also prepares for stepping in
1271 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001272 FloodWithOneShot(shared);
1273
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001274 if (is_load_or_store) {
1275 // Remember source position and frame to handle step in getter/setter. If
1276 // there is a custom getter/setter it will be handled in
1277 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1278 // propagated on the next Debug::Break.
1279 thread_local_.last_statement_position_ =
1280 debug_info->code()->SourceStatementPosition(frame->pc());
1281 thread_local_.last_fp_ = frame->fp();
1282 }
1283
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001284 // Step in or Step in min
1285 it.PrepareStepIn();
1286 ActivateStepIn(frame);
1287 }
1288}
1289
1290
1291// Check whether the current debug break should be reported to the debugger. It
1292// is used to have step next and step in only report break back to the debugger
1293// if on a different frame or in a different statement. In some situations
1294// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001295// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001296// steps before reporting break back to the debugger.
1297bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1298 JavaScriptFrame* frame) {
1299 // If the step last action was step next or step in make sure that a new
1300 // statement is hit.
1301 if (thread_local_.last_step_action_ == StepNext ||
1302 thread_local_.last_step_action_ == StepIn) {
1303 // Never continue if returning from function.
1304 if (break_location_iterator->IsExit()) return false;
1305
1306 // Continue if we are still on the same frame and in the same statement.
1307 int current_statement_position =
1308 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1309 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001310 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001311 }
1312
1313 // No step next action - don't continue.
1314 return false;
1315}
1316
1317
1318// Check whether the code object at the specified address is a debug break code
1319// object.
1320bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001321 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001322 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001323}
1324
1325
1326// Check whether a code stub with the specified major key is a possible break
1327// point location when looking for source break locations.
1328bool Debug::IsSourceBreakStub(Code* code) {
1329 CodeStub::Major major_key = code->major_key();
1330 return major_key == CodeStub::CallFunction;
1331}
1332
1333
1334// Check whether a code stub with the specified major key is a possible break
1335// location.
1336bool Debug::IsBreakStub(Code* code) {
1337 CodeStub::Major major_key = code->major_key();
1338 return major_key == CodeStub::CallFunction ||
1339 major_key == CodeStub::StackCheck;
1340}
1341
1342
1343// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001344Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001345 // Find the builtin debug break function matching the calling convention
1346 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001347 if (code->is_inline_cache_stub()) {
1348 if (code->is_call_stub()) {
1349 return ComputeCallDebugBreak(code->arguments_count());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001350 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001351 if (code->is_load_stub()) {
1352 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1353 }
1354 if (code->is_store_stub()) {
1355 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1356 }
1357 if (code->is_keyed_load_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001358 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001359 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001360 return result;
1361 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001362 if (code->is_keyed_store_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001363 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001364 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001365 return result;
1366 }
1367 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001368 if (RelocInfo::IsConstructCall(mode)) {
1369 Handle<Code> result =
1370 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1371 return result;
1372 }
1373 if (code->kind() == Code::STUB) {
1374 ASSERT(code->major_key() == CodeStub::CallFunction ||
1375 code->major_key() == CodeStub::StackCheck);
1376 Handle<Code> result =
1377 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1378 return result;
1379 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001380
1381 UNREACHABLE();
1382 return Handle<Code>::null();
1383}
1384
1385
1386// Simple function for returning the source positions for active break points.
1387Handle<Object> Debug::GetSourceBreakLocations(
1388 Handle<SharedFunctionInfo> shared) {
1389 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1390 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1391 if (debug_info->GetBreakPointCount() == 0) {
1392 return Handle<Object>(Heap::undefined_value());
1393 }
1394 Handle<FixedArray> locations =
1395 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1396 int count = 0;
1397 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1398 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1399 BreakPointInfo* break_point_info =
1400 BreakPointInfo::cast(debug_info->break_points()->get(i));
1401 if (break_point_info->GetBreakPointCount() > 0) {
1402 locations->set(count++, break_point_info->statement_position());
1403 }
1404 }
1405 }
1406 return locations;
1407}
1408
1409
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001410void Debug::NewBreak(StackFrame::Id break_frame_id) {
1411 thread_local_.break_frame_id_ = break_frame_id;
1412 thread_local_.break_id_ = ++thread_local_.break_count_;
1413}
1414
1415
1416void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1417 thread_local_.break_frame_id_ = break_frame_id;
1418 thread_local_.break_id_ = break_id;
1419}
1420
1421
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001422// Handle stepping into a function.
1423void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001424 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001425 Address fp,
1426 bool is_constructor) {
1427 // If the frame pointer is not supplied by the caller find it.
1428 if (fp == 0) {
1429 StackFrameIterator it;
1430 it.Advance();
1431 // For constructor functions skip another frame.
1432 if (is_constructor) {
1433 ASSERT(it.frame()->is_construct());
1434 it.Advance();
1435 }
1436 fp = it.frame()->fp();
1437 }
1438
1439 // Flood the function with one-shot break points if it is called from where
1440 // step into was requested.
1441 if (fp == Debug::step_in_fp()) {
1442 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001443 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001444 if (function->shared()->code() ==
1445 Builtins::builtin(Builtins::FunctionApply) ||
1446 function->shared()->code() ==
1447 Builtins::builtin(Builtins::FunctionCall)) {
1448 // Handle function.apply and function.call separately to flood the
1449 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001450 // Builtins::FunctionCall. The receiver of call/apply is the target
1451 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001452 if (!holder.is_null() && holder->IsJSFunction() &&
1453 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001454 Handle<SharedFunctionInfo> shared_info(
1455 JSFunction::cast(*holder)->shared());
1456 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001457 }
1458 } else {
1459 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1460 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001461 }
1462 }
1463}
1464
1465
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001466void Debug::ClearStepping() {
1467 // Clear the various stepping setup.
1468 ClearOneShot();
1469 ClearStepIn();
ager@chromium.orga1645e22009-09-09 19:27:10 +00001470 ClearStepOut();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001471 ClearStepNext();
1472
1473 // Clear multiple step counter.
1474 thread_local_.step_count_ = 0;
1475}
1476
1477// Clears all the one-shot break points that are currently set. Normally this
1478// function is called each time a break point is hit as one shot break points
1479// are used to support stepping.
1480void Debug::ClearOneShot() {
1481 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001482 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001483 // removed from the list.
1484
1485 DebugInfoListNode* node = debug_info_list_;
1486 while (node != NULL) {
1487 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1488 while (!it.Done()) {
1489 it.ClearOneShot();
1490 it.Next();
1491 }
1492 node = node->next();
1493 }
1494}
1495
1496
1497void Debug::ActivateStepIn(StackFrame* frame) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001498 ASSERT(!StepOutActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001499 thread_local_.step_into_fp_ = frame->fp();
1500}
1501
1502
1503void Debug::ClearStepIn() {
1504 thread_local_.step_into_fp_ = 0;
1505}
1506
1507
ager@chromium.orga1645e22009-09-09 19:27:10 +00001508void Debug::ActivateStepOut(StackFrame* frame) {
1509 ASSERT(!StepInActive());
1510 thread_local_.step_out_fp_ = frame->fp();
1511}
1512
1513
1514void Debug::ClearStepOut() {
1515 thread_local_.step_out_fp_ = 0;
1516}
1517
1518
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001519void Debug::ClearStepNext() {
1520 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001521 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001522 thread_local_.last_fp_ = 0;
1523}
1524
1525
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001526bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1527 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001528 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001529}
1530
1531
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001532// Ensures the debug information is present for shared.
1533bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1534 // Return if we already have the debug info for shared.
1535 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001536
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001537 // Ensure shared in compiled. Return false if this failed.
1538 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001539
1540 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001541 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001542
1543 // Add debug info to the list.
1544 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1545 node->set_next(debug_info_list_);
1546 debug_info_list_ = node;
1547
1548 // Now there is at least one break point.
1549 has_break_points_ = true;
1550
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001551 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001552}
1553
1554
1555void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1556 ASSERT(debug_info_list_ != NULL);
1557 // Run through the debug info objects to find this one and remove it.
1558 DebugInfoListNode* prev = NULL;
1559 DebugInfoListNode* current = debug_info_list_;
1560 while (current != NULL) {
1561 if (*current->debug_info() == *debug_info) {
1562 // Unlink from list. If prev is NULL we are looking at the first element.
1563 if (prev == NULL) {
1564 debug_info_list_ = current->next();
1565 } else {
1566 prev->set_next(current->next());
1567 }
1568 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1569 delete current;
1570
1571 // If there are no more debug info objects there are not more break
1572 // points.
1573 has_break_points_ = debug_info_list_ != NULL;
1574
1575 return;
1576 }
1577 // Move to next in list.
1578 prev = current;
1579 current = current->next();
1580 }
1581 UNREACHABLE();
1582}
1583
1584
1585void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001586 HandleScope scope;
1587
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001588 // Get the executing function in which the debug break occurred.
1589 Handle<SharedFunctionInfo> shared =
1590 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001591 if (!EnsureDebugInfo(shared)) {
1592 // Return if we failed to retrieve the debug info.
1593 return;
1594 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001595 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1596 Handle<Code> code(debug_info->code());
1597 Handle<Code> original_code(debug_info->original_code());
1598#ifdef DEBUG
1599 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001600 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001601 ASSERT(frame_code.is_identical_to(code));
1602#endif
1603
1604 // Find the call address in the running code. This address holds the call to
1605 // either a DebugBreakXXX or to the debug break return entry code if the
1606 // break point is still active after processing the break point.
ager@chromium.org4af710e2009-09-15 12:20:11 +00001607 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608
1609 // Check if the location is at JS exit.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001610 bool at_js_return = false;
1611 bool break_at_js_return_active = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001612 RelocIterator it(debug_info->code());
1613 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001614 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001615 at_js_return = (it.rinfo()->pc() ==
1616 addr - Assembler::kPatchReturnSequenceAddressOffset);
1617 break_at_js_return_active = it.rinfo()->IsCallInstruction();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001618 }
1619 it.next();
1620 }
1621
1622 // Handle the jump to continue execution after break point depending on the
1623 // break location.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001624 if (at_js_return) {
1625 // If the break point as return is still active jump to the corresponding
1626 // place in the original code. If not the break point was removed during
1627 // break point processing.
1628 if (break_at_js_return_active) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001629 addr += original_code->instruction_start() - code->instruction_start();
1630 }
1631
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001632 // Move back to where the call instruction sequence started.
1633 thread_local_.after_break_target_ =
1634 addr - Assembler::kPatchReturnSequenceAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001635 } else {
1636 // Check if there still is a debug break call at the target address. If the
1637 // break point has been removed it will have disappeared. If it have
1638 // disappeared don't try to look in the original code as the running code
1639 // will have the right address. This takes care of the case where the last
1640 // break point is removed from the function and therefore no "original code"
1641 // is available. If the debug break call is still there find the address in
1642 // the original code.
1643 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1644 // If the break point is still there find the call address which was
1645 // overwritten in the original code by the call to DebugBreakXXX.
1646
1647 // Find the corresponding address in the original code.
1648 addr += original_code->instruction_start() - code->instruction_start();
1649 }
1650
1651 // Install jump to the call address in the original code. This will be the
1652 // call which was overwritten by the call to DebugBreakXXX.
1653 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1654 }
1655}
1656
1657
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001658bool Debug::IsDebugGlobal(GlobalObject* global) {
1659 return IsLoaded() && global == Debug::debug_context()->global();
1660}
1661
1662
ager@chromium.org32912102009-01-16 10:38:43 +00001663void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001664 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001665 ASSERT(Top::context() == *Debug::debug_context());
1666
1667 // Clear the mirror cache.
1668 Handle<String> function_name =
1669 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1670 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1671 ASSERT(fun->IsJSFunction());
1672 bool caught_exception;
1673 Handle<Object> js_object = Execution::TryCall(
1674 Handle<JSFunction>::cast(fun),
1675 Handle<JSObject>(Debug::debug_context()->global()),
1676 0, NULL, &caught_exception);
1677}
1678
1679
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001680// If an object given is an external string, check that the underlying
1681// resource is accessible. For other kinds of objects, always return true.
1682static bool IsExternalStringValid(Object* str) {
1683 if (!str->IsString() || !StringShape(String::cast(str)).IsExternal()) {
1684 return true;
1685 }
1686 if (String::cast(str)->IsAsciiRepresentation()) {
1687 return ExternalAsciiString::cast(str)->resource() != NULL;
1688 } else if (String::cast(str)->IsTwoByteRepresentation()) {
1689 return ExternalTwoByteString::cast(str)->resource() != NULL;
1690 } else {
1691 return true;
1692 }
1693}
1694
1695
1696void Debug::CreateScriptCache() {
1697 HandleScope scope;
1698
1699 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1700 // rid of all the cached script wrappers and the second gets rid of the
1701 // scripts which is no longer referenced.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001702 Heap::CollectAllGarbage(false);
1703 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001704
1705 ASSERT(script_cache_ == NULL);
1706 script_cache_ = new ScriptCache();
1707
1708 // Scan heap for Script objects.
1709 int count = 0;
1710 HeapIterator iterator;
1711 while (iterator.has_next()) {
1712 HeapObject* obj = iterator.next();
1713 ASSERT(obj != NULL);
1714 if (obj->IsScript() && IsExternalStringValid(Script::cast(obj)->source())) {
1715 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1716 count++;
1717 }
1718 }
1719}
1720
1721
1722void Debug::DestroyScriptCache() {
1723 // Get rid of the script cache if it was created.
1724 if (script_cache_ != NULL) {
1725 delete script_cache_;
1726 script_cache_ = NULL;
1727 }
1728}
1729
1730
1731void Debug::AddScriptToScriptCache(Handle<Script> script) {
1732 if (script_cache_ != NULL) {
1733 script_cache_->Add(script);
1734 }
1735}
1736
1737
1738Handle<FixedArray> Debug::GetLoadedScripts() {
1739 // Create and fill the script cache when the loaded scripts is requested for
1740 // the first time.
1741 if (script_cache_ == NULL) {
1742 CreateScriptCache();
1743 }
1744
1745 // If the script cache is not active just return an empty array.
1746 ASSERT(script_cache_ != NULL);
1747 if (script_cache_ == NULL) {
1748 Factory::NewFixedArray(0);
1749 }
1750
1751 // Perform GC to get unreferenced scripts evicted from the cache before
1752 // returning the content.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001753 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001754
1755 // Get the scripts from the cache.
1756 return script_cache_->GetScripts();
1757}
1758
1759
1760void Debug::AfterGarbageCollection() {
1761 // Generate events for collected scripts.
1762 if (script_cache_ != NULL) {
1763 script_cache_->ProcessCollectedScripts();
1764 }
1765}
1766
1767
ager@chromium.org71daaf62009-04-01 07:22:49 +00001768Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001769Handle<Object> Debugger::event_listener_ = Handle<Object>();
1770Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001771bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001772bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001773bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001774v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001775bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001776v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
1777int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001778DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001779LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001780Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001781
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782
1783Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1784 int argc, Object*** argv,
1785 bool* caught_exception) {
1786 ASSERT(Top::context() == *Debug::debug_context());
1787
1788 // Create the execution state object.
1789 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1790 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1791 ASSERT(constructor->IsJSFunction());
1792 if (!constructor->IsJSFunction()) {
1793 *caught_exception = true;
1794 return Factory::undefined_value();
1795 }
1796 Handle<Object> js_object = Execution::TryCall(
1797 Handle<JSFunction>::cast(constructor),
1798 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1799 caught_exception);
1800 return js_object;
1801}
1802
1803
1804Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1805 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001806 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001807 const int argc = 1;
1808 Object** argv[argc] = { break_id.location() };
1809 return MakeJSObject(CStrVector("MakeExecutionState"),
1810 argc, argv, caught_exception);
1811}
1812
1813
1814Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1815 Handle<Object> break_points_hit,
1816 bool* caught_exception) {
1817 // Create the new break event object.
1818 const int argc = 2;
1819 Object** argv[argc] = { exec_state.location(),
1820 break_points_hit.location() };
1821 return MakeJSObject(CStrVector("MakeBreakEvent"),
1822 argc,
1823 argv,
1824 caught_exception);
1825}
1826
1827
1828Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1829 Handle<Object> exception,
1830 bool uncaught,
1831 bool* caught_exception) {
1832 // Create the new exception event object.
1833 const int argc = 3;
1834 Object** argv[argc] = { exec_state.location(),
1835 exception.location(),
1836 uncaught ? Factory::true_value().location() :
1837 Factory::false_value().location()};
1838 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1839 argc, argv, caught_exception);
1840}
1841
1842
1843Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1844 bool* caught_exception) {
1845 // Create the new function event object.
1846 const int argc = 1;
1847 Object** argv[argc] = { function.location() };
1848 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1849 argc, argv, caught_exception);
1850}
1851
1852
1853Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001854 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001855 bool* caught_exception) {
1856 // Create the compile event object.
1857 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001858 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001860 Object** argv[argc] = { exec_state.location(),
1861 script_wrapper.location(),
1862 before ? Factory::true_value().location() :
1863 Factory::false_value().location() };
1864
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001865 return MakeJSObject(CStrVector("MakeCompileEvent"),
1866 argc,
1867 argv,
1868 caught_exception);
1869}
1870
1871
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001872Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1873 bool* caught_exception) {
1874 // Create the script collected event object.
1875 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1876 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1877 const int argc = 2;
1878 Object** argv[argc] = { exec_state.location(), id_object.location() };
1879
1880 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1881 argc,
1882 argv,
1883 caught_exception);
1884}
1885
1886
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001887void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1888 HandleScope scope;
1889
1890 // Bail out based on state or if there is no listener for this event
1891 if (Debug::InDebugger()) return;
1892 if (!Debugger::EventActive(v8::Exception)) return;
1893
1894 // Bail out if exception breaks are not active
1895 if (uncaught) {
1896 // Uncaught exceptions are reported by either flags.
1897 if (!(Debug::break_on_uncaught_exception() ||
1898 Debug::break_on_exception())) return;
1899 } else {
1900 // Caught exceptions are reported is activated.
1901 if (!Debug::break_on_exception()) return;
1902 }
1903
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001904 // Enter the debugger.
1905 EnterDebugger debugger;
1906 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001907
1908 // Clear all current stepping setup.
1909 Debug::ClearStepping();
1910 // Create the event data object.
1911 bool caught_exception = false;
1912 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1913 Handle<Object> event_data;
1914 if (!caught_exception) {
1915 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1916 &caught_exception);
1917 }
1918 // Bail out and don't call debugger if exception.
1919 if (caught_exception) {
1920 return;
1921 }
1922
ager@chromium.org5ec48922009-05-05 07:25:34 +00001923 // Process debug event.
1924 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001925 // Return to continue execution from where the exception was thrown.
1926}
1927
1928
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001929void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1930 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001931 HandleScope scope;
1932
kasper.lund212ac232008-07-16 07:07:30 +00001933 // Debugger has already been entered by caller.
1934 ASSERT(Top::context() == *Debug::debug_context());
1935
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001936 // Bail out if there is no listener for this event
1937 if (!Debugger::EventActive(v8::Break)) return;
1938
1939 // Debugger must be entered in advance.
1940 ASSERT(Top::context() == *Debug::debug_context());
1941
1942 // Create the event data object.
1943 bool caught_exception = false;
1944 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1945 Handle<Object> event_data;
1946 if (!caught_exception) {
1947 event_data = MakeBreakEvent(exec_state, break_points_hit,
1948 &caught_exception);
1949 }
1950 // Bail out and don't call debugger if exception.
1951 if (caught_exception) {
1952 return;
1953 }
1954
ager@chromium.org5ec48922009-05-05 07:25:34 +00001955 // Process debug event.
1956 ProcessDebugEvent(v8::Break,
1957 Handle<JSObject>::cast(event_data),
1958 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001959}
1960
1961
1962void Debugger::OnBeforeCompile(Handle<Script> script) {
1963 HandleScope scope;
1964
1965 // Bail out based on state or if there is no listener for this event
1966 if (Debug::InDebugger()) return;
1967 if (compiling_natives()) return;
1968 if (!EventActive(v8::BeforeCompile)) return;
1969
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001970 // Enter the debugger.
1971 EnterDebugger debugger;
1972 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001973
1974 // Create the event data object.
1975 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001976 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001977 // Bail out and don't call debugger if exception.
1978 if (caught_exception) {
1979 return;
1980 }
1981
ager@chromium.org5ec48922009-05-05 07:25:34 +00001982 // Process debug event.
1983 ProcessDebugEvent(v8::BeforeCompile,
1984 Handle<JSObject>::cast(event_data),
1985 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001986}
1987
1988
1989// Handle debugger actions when a new script is compiled.
1990void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001991 HandleScope scope;
1992
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001993 // Add the newly compiled script to the script cache.
1994 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001995
1996 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001997 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001998
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001999 // No compile events while compiling natives.
2000 if (compiling_natives()) return;
2001
iposva@chromium.org245aa852009-02-10 00:49:54 +00002002 // Store whether in debugger before entering debugger.
2003 bool in_debugger = Debug::InDebugger();
2004
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002005 // Enter the debugger.
2006 EnterDebugger debugger;
2007 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002008
2009 // If debugging there might be script break points registered for this
2010 // script. Make sure that these break points are set.
2011
2012 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
2013 Handle<Object> update_script_break_points =
2014 Handle<Object>(Debug::debug_context()->global()->GetProperty(
2015 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
2016 if (!update_script_break_points->IsJSFunction()) {
2017 return;
2018 }
2019 ASSERT(update_script_break_points->IsJSFunction());
2020
2021 // Wrap the script object in a proper JS object before passing it
2022 // to JavaScript.
2023 Handle<JSValue> wrapper = GetScriptWrapper(script);
2024
2025 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00002026 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002027 const int argc = 1;
2028 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2029 Handle<Object> result = Execution::TryCall(
2030 Handle<JSFunction>::cast(update_script_break_points),
2031 Top::builtins(), argc, argv,
2032 &caught_exception);
2033 if (caught_exception) {
2034 return;
2035 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002036 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00002037 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002038 if (!Debugger::EventActive(v8::AfterCompile)) return;
2039
2040 // Create the compile state object.
2041 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002042 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002043 &caught_exception);
2044 // Bail out and don't call debugger if exception.
2045 if (caught_exception) {
2046 return;
2047 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00002048 // Process debug event.
2049 ProcessDebugEvent(v8::AfterCompile,
2050 Handle<JSObject>::cast(event_data),
2051 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002052}
2053
2054
2055void Debugger::OnNewFunction(Handle<JSFunction> function) {
2056 return;
2057 HandleScope scope;
2058
2059 // Bail out based on state or if there is no listener for this event
2060 if (Debug::InDebugger()) return;
2061 if (compiling_natives()) return;
2062 if (!Debugger::EventActive(v8::NewFunction)) return;
2063
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002064 // Enter the debugger.
2065 EnterDebugger debugger;
2066 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002067
2068 // Create the event object.
2069 bool caught_exception = false;
2070 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
2071 // Bail out and don't call debugger if exception.
2072 if (caught_exception) {
2073 return;
2074 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002075 // Process debug event.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002076 ProcessDebugEvent(v8::NewFunction, Handle<JSObject>::cast(event_data), true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002077}
2078
2079
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002080void Debugger::OnScriptCollected(int id) {
2081 HandleScope scope;
2082
2083 // No more to do if not debugging.
2084 if (!IsDebuggerActive()) return;
2085 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2086
2087 // Enter the debugger.
2088 EnterDebugger debugger;
2089 if (debugger.FailedToEnter()) return;
2090
2091 // Create the script collected state object.
2092 bool caught_exception = false;
2093 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2094 &caught_exception);
2095 // Bail out and don't call debugger if exception.
2096 if (caught_exception) {
2097 return;
2098 }
2099
2100 // Process debug event.
2101 ProcessDebugEvent(v8::ScriptCollected,
2102 Handle<JSObject>::cast(event_data),
2103 true);
2104}
2105
2106
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002107void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002108 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002109 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002110 HandleScope scope;
2111
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002112 // Clear any pending debug break if this is a real break.
2113 if (!auto_continue) {
2114 Debug::clear_interrupt_pending(DEBUGBREAK);
2115 }
2116
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002117 // Create the execution state.
2118 bool caught_exception = false;
2119 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2120 if (caught_exception) {
2121 return;
2122 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002123 // First notify the message handler if any.
2124 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002125 NotifyMessageHandler(event,
2126 Handle<JSObject>::cast(exec_state),
2127 event_data,
2128 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002129 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002130 // Notify registered debug event listener. This can be either a C or a
2131 // JavaScript function.
2132 if (!event_listener_.is_null()) {
2133 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002134 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002135 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002136 v8::Debug::EventCallback callback =
2137 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002138 callback(event,
2139 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002140 v8::Utils::ToLocal(event_data),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002141 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002142 } else {
2143 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002144 ASSERT(event_listener_->IsJSFunction());
2145 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002146
2147 // Invoke the JavaScript debug event listener.
2148 const int argc = 4;
2149 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2150 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002151 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002152 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002153 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2154 argc, argv, &caught_exception);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002155 // Silently ignore exceptions from debug event listeners.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002156 }
2157 }
2158}
2159
2160
ager@chromium.org71daaf62009-04-01 07:22:49 +00002161void Debugger::UnloadDebugger() {
2162 // Make sure that there are no breakpoints left.
2163 Debug::ClearAllBreakPoints();
2164
2165 // Unload the debugger if feasible.
2166 if (!never_unload_debugger_) {
2167 Debug::Unload();
2168 }
2169
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002170 // Clear the flag indicating that the debugger should be unloaded.
2171 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002172}
2173
2174
ager@chromium.org41826e72009-03-30 13:30:57 +00002175void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002176 Handle<JSObject> exec_state,
2177 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002178 bool auto_continue) {
2179 HandleScope scope;
2180
2181 if (!Debug::Load()) return;
2182
2183 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002184 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002185 switch (event) {
2186 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002187 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002188 break;
2189 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002190 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002191 break;
2192 case v8::BeforeCompile:
2193 break;
2194 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002195 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002196 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002197 case v8::ScriptCollected:
2198 sendEventMessage = true;
2199 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002200 case v8::NewFunction:
2201 break;
2202 default:
2203 UNREACHABLE();
2204 }
2205
ager@chromium.org5ec48922009-05-05 07:25:34 +00002206 // The debug command interrupt flag might have been set when the command was
2207 // added. It should be enough to clear the flag only once while we are in the
2208 // debugger.
2209 ASSERT(Debug::InDebugger());
2210 StackGuard::Continue(DEBUGCOMMAND);
2211
2212 // Notify the debugger that a debug event has occurred unless auto continue is
2213 // active in which case no event is send.
2214 if (sendEventMessage) {
2215 MessageImpl message = MessageImpl::NewEvent(
2216 event,
2217 auto_continue,
2218 Handle<JSObject>::cast(exec_state),
2219 Handle<JSObject>::cast(event_data));
2220 InvokeMessageHandler(message);
2221 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002222
2223 // If auto continue don't make the event cause a break, but process messages
2224 // in the queue if any. For script collected events don't even process
2225 // messages in the queue as the execution state might not be what is expected
2226 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002227 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002228 return;
2229 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002230
2231 // Get the DebugCommandProcessor.
2232 v8::Local<v8::Object> api_exec_state =
2233 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2234 v8::Local<v8::String> fun_name =
2235 v8::String::New("debugCommandProcessor");
2236 v8::Local<v8::Function> fun =
2237 v8::Function::Cast(*api_exec_state->Get(fun_name));
2238 v8::TryCatch try_catch;
2239 v8::Local<v8::Object> cmd_processor =
2240 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
2241 if (try_catch.HasCaught()) {
2242 PrintLn(try_catch.Exception());
2243 return;
2244 }
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;
2286 bool running = false;
2287 if (!try_catch.HasCaught()) {
2288 // Get response string.
2289 if (!response_val->IsUndefined()) {
2290 response = v8::String::Cast(*response_val);
2291 } else {
2292 response = v8::String::New("");
2293 }
2294
2295 // Log the JSON request/response.
2296 if (FLAG_trace_debug_json) {
2297 PrintLn(request);
2298 PrintLn(response);
2299 }
2300
2301 // Get the running state.
2302 fun_name = v8::String::New("isRunning");
2303 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2304 static const int kArgc = 1;
2305 v8::Handle<Value> argv[kArgc] = { response };
2306 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2307 if (!try_catch.HasCaught()) {
2308 running = running_val->ToBoolean()->Value();
2309 }
2310 } else {
2311 // In case of failure the result text is the exception text.
2312 response = try_catch.Exception()->ToString();
2313 }
2314
ager@chromium.org41826e72009-03-30 13:30:57 +00002315 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002316 MessageImpl message = MessageImpl::NewResponse(
2317 event,
2318 running,
2319 Handle<JSObject>::cast(exec_state),
2320 Handle<JSObject>::cast(event_data),
2321 Handle<String>(Utils::OpenHandle(*response)),
2322 command.client_data());
2323 InvokeMessageHandler(message);
2324 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002325
2326 // Return from debug event processing if either the VM is put into the
2327 // runnning state (through a continue command) or auto continue is active
2328 // and there are no more commands queued.
2329 if (running || (auto_continue && !HasCommands())) {
2330 return;
2331 }
2332 }
2333}
2334
2335
iposva@chromium.org245aa852009-02-10 00:49:54 +00002336void Debugger::SetEventListener(Handle<Object> callback,
2337 Handle<Object> data) {
2338 HandleScope scope;
2339
2340 // Clear the global handles for the event listener and the event listener data
2341 // object.
2342 if (!event_listener_.is_null()) {
2343 GlobalHandles::Destroy(
2344 reinterpret_cast<Object**>(event_listener_.location()));
2345 event_listener_ = Handle<Object>();
2346 }
2347 if (!event_listener_data_.is_null()) {
2348 GlobalHandles::Destroy(
2349 reinterpret_cast<Object**>(event_listener_data_.location()));
2350 event_listener_data_ = Handle<Object>();
2351 }
2352
2353 // If there is a new debug event listener register it together with its data
2354 // object.
2355 if (!callback->IsUndefined() && !callback->IsNull()) {
2356 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2357 if (data.is_null()) {
2358 data = Factory::undefined_value();
2359 }
2360 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2361 }
2362
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002363 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002364}
2365
2366
ager@chromium.org5ec48922009-05-05 07:25:34 +00002367void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002368 ScopedLock with(debugger_access_);
2369
ager@chromium.org381abbb2009-02-25 13:23:22 +00002370 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002371 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002372 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002373 // Send an empty command to the debugger if in a break to make JavaScript
2374 // run again if the debugger is closed.
2375 if (Debug::InDebugger()) {
2376 ProcessCommand(Vector<const uint16_t>::empty());
2377 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002378 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002379}
2380
2381
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002382void Debugger::ListenersChanged() {
2383 if (IsDebuggerActive()) {
2384 // Disable the compilation cache when the debugger is active.
2385 CompilationCache::Disable();
2386 } else {
2387 CompilationCache::Enable();
2388
2389 // Unload the debugger if event listener and message handler cleared.
2390 if (Debug::InDebugger()) {
2391 // If we are in debugger set the flag to unload the debugger when last
2392 // EnterDebugger on the current stack is destroyed.
2393 debugger_unload_pending_ = true;
2394 } else {
2395 UnloadDebugger();
2396 }
2397 }
2398}
2399
2400
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002401void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2402 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002403 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002404 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002405}
2406
2407
ager@chromium.org41826e72009-03-30 13:30:57 +00002408// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002409// public API.
2410void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002411 ScopedLock with(debugger_access_);
2412
ager@chromium.org381abbb2009-02-25 13:23:22 +00002413 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002414 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002415 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002416}
2417
2418
2419// Puts a command coming from the public API on the queue. Creates
2420// a copy of the command string managed by the debugger. Up to this
2421// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002422// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002423void Debugger::ProcessCommand(Vector<const uint16_t> command,
2424 v8::Debug::ClientData* client_data) {
2425 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002426 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002427 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002428 command.length()),
2429 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002430 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002431 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002432 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002433
2434 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002435 if (!Debug::InDebugger()) {
2436 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002437 }
2438}
2439
2440
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002441bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002442 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002443}
2444
2445
ager@chromium.org71daaf62009-04-01 07:22:49 +00002446bool Debugger::IsDebuggerActive() {
2447 ScopedLock with(debugger_access_);
2448
2449 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002450}
2451
2452
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002453Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2454 Handle<Object> data,
2455 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002456 // When calling functions in the debugger prevent it from beeing unloaded.
2457 Debugger::never_unload_debugger_ = true;
2458
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002459 // Enter the debugger.
2460 EnterDebugger debugger;
2461 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2462 return Factory::undefined_value();
2463 }
2464
2465 // Create the execution state.
2466 bool caught_exception = false;
2467 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2468 if (caught_exception) {
2469 return Factory::undefined_value();
2470 }
2471
2472 static const int kArgc = 2;
2473 Object** argv[kArgc] = { exec_state.location(), data.location() };
2474 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2475 kArgc, argv, pending_exception);
2476 return result;
2477}
2478
2479
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002480bool Debugger::StartAgent(const char* name, int port) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002481 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002482 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002483 agent_->Start();
2484 return true;
2485 }
2486
2487 return false;
2488}
2489
2490
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002491void Debugger::StopAgent() {
2492 if (agent_ != NULL) {
2493 agent_->Shutdown();
2494 agent_->Join();
2495 delete agent_;
2496 agent_ = NULL;
2497 }
2498}
2499
2500
ager@chromium.org5ec48922009-05-05 07:25:34 +00002501MessageImpl MessageImpl::NewEvent(DebugEvent event,
2502 bool running,
2503 Handle<JSObject> exec_state,
2504 Handle<JSObject> event_data) {
2505 MessageImpl message(true, event, running,
2506 exec_state, event_data, Handle<String>(), NULL);
2507 return message;
2508}
2509
2510
2511MessageImpl MessageImpl::NewResponse(DebugEvent event,
2512 bool running,
2513 Handle<JSObject> exec_state,
2514 Handle<JSObject> event_data,
2515 Handle<String> response_json,
2516 v8::Debug::ClientData* client_data) {
2517 MessageImpl message(false, event, running,
2518 exec_state, event_data, response_json, client_data);
2519 return message;
2520}
2521
2522
2523MessageImpl::MessageImpl(bool is_event,
2524 DebugEvent event,
2525 bool running,
2526 Handle<JSObject> exec_state,
2527 Handle<JSObject> event_data,
2528 Handle<String> response_json,
2529 v8::Debug::ClientData* client_data)
2530 : is_event_(is_event),
2531 event_(event),
2532 running_(running),
2533 exec_state_(exec_state),
2534 event_data_(event_data),
2535 response_json_(response_json),
2536 client_data_(client_data) {}
2537
2538
2539bool MessageImpl::IsEvent() const {
2540 return is_event_;
2541}
2542
2543
2544bool MessageImpl::IsResponse() const {
2545 return !is_event_;
2546}
2547
2548
2549DebugEvent MessageImpl::GetEvent() const {
2550 return event_;
2551}
2552
2553
2554bool MessageImpl::WillStartRunning() const {
2555 return running_;
2556}
2557
2558
2559v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2560 return v8::Utils::ToLocal(exec_state_);
2561}
2562
2563
2564v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2565 return v8::Utils::ToLocal(event_data_);
2566}
2567
2568
2569v8::Handle<v8::String> MessageImpl::GetJSON() const {
2570 v8::HandleScope scope;
2571
2572 if (IsEvent()) {
2573 // Call toJSONProtocol on the debug event object.
2574 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2575 if (!fun->IsJSFunction()) {
2576 return v8::Handle<v8::String>();
2577 }
2578 bool caught_exception;
2579 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2580 event_data_,
2581 0, NULL, &caught_exception);
2582 if (caught_exception || !json->IsString()) {
2583 return v8::Handle<v8::String>();
2584 }
2585 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2586 } else {
2587 return v8::Utils::ToLocal(response_json_);
2588 }
2589}
2590
2591
2592v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002593 Handle<Context> context = Debug::debugger_entry()->GetContext();
2594 // Top::context() may have been NULL when "script collected" event occured.
2595 if (*context == NULL) {
2596 ASSERT(event_ == v8::ScriptCollected);
2597 return v8::Local<v8::Context>();
2598 }
2599 Handle<Context> global_context(context->global_context());
2600 return v8::Utils::ToLocal(global_context);
ager@chromium.org5ec48922009-05-05 07:25:34 +00002601}
2602
2603
2604v8::Debug::ClientData* MessageImpl::GetClientData() const {
2605 return client_data_;
2606}
2607
2608
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002609CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2610 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002611}
2612
2613
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002614CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2615 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002616 : text_(text),
2617 client_data_(data) {
2618}
2619
2620
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002621CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002622}
2623
2624
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002625void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002626 text_.Dispose();
2627 delete client_data_;
2628 client_data_ = NULL;
2629}
2630
2631
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002632CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2633 v8::Debug::ClientData* data) {
2634 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002635}
2636
2637
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002638CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2639 size_(size) {
2640 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002641}
2642
2643
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002644CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002645 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002646 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002647 m.Dispose();
2648 }
kasper.lund7276f142008-07-30 08:49:36 +00002649 DeleteArray(messages_);
2650}
2651
2652
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002653CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002654 ASSERT(!IsEmpty());
2655 int result = start_;
2656 start_ = (start_ + 1) % size_;
2657 return messages_[result];
2658}
2659
2660
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002661void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002662 if ((end_ + 1) % size_ == start_) {
2663 Expand();
2664 }
2665 messages_[end_] = message;
2666 end_ = (end_ + 1) % size_;
2667}
2668
2669
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002670void CommandMessageQueue::Expand() {
2671 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002672 while (!IsEmpty()) {
2673 new_queue.Put(Get());
2674 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002675 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002676 *this = new_queue;
2677 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002678 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2679 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002680 // Automatic destructor called on new_queue, freeing array_to_free.
2681}
2682
2683
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002684LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2685 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002686 lock_ = OS::CreateMutex();
2687}
2688
2689
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002690LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002691 delete lock_;
2692}
2693
2694
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002695bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002696 ScopedLock sl(lock_);
2697 return queue_.IsEmpty();
2698}
2699
2700
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002701CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002702 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002703 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002704 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002705 return result;
2706}
2707
2708
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002709void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002710 ScopedLock sl(lock_);
2711 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002712 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002713}
2714
2715
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002716void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002717 ScopedLock sl(lock_);
2718 queue_.Clear();
2719}
2720
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002721#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002722
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002723} } // namespace v8::internal