blob: 8c4f51d95a2824c6c92abb2f505e0a76968e9e4c [file] [log] [blame]
ager@chromium.org9258b6b2008-09-11 09:11:10 +00001// Copyright 2006-2008 the V8 project authors. All rights reserved.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "api.h"
31#include "arguments.h"
32#include "bootstrapper.h"
33#include "code-stubs.h"
ager@chromium.org5c838252010-02-19 08:53:10 +000034#include "codegen.h"
kasperl@chromium.org71affb52009-05-26 05:44:31 +000035#include "compilation-cache.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000036#include "compiler.h"
37#include "debug.h"
38#include "execution.h"
39#include "global-handles.h"
ager@chromium.org65dad4b2009-04-23 08:48:43 +000040#include "ic.h"
41#include "ic-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000042#include "natives.h"
43#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000044#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000045
ager@chromium.org5ec48922009-05-05 07:25:34 +000046#include "../include/v8-debug.h"
47
kasperl@chromium.org71affb52009-05-26 05:44:31 +000048namespace v8 {
49namespace internal {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000050
ager@chromium.org65dad4b2009-04-23 08:48:43 +000051#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000052static void PrintLn(v8::Local<v8::Value> value) {
53 v8::Local<v8::String> s = value->ToString();
54 char* data = NewArray<char>(s->Length() + 1);
55 if (data == NULL) {
56 V8::FatalProcessOutOfMemory("PrintLn");
57 return;
58 }
59 s->WriteAscii(data);
60 PrintF("%s\n", data);
61 DeleteArray(data);
62}
63
64
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000065static Handle<Code> ComputeCallDebugBreak(int argc) {
66 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
67}
68
69
70static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
71 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
72}
73
74
75BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
76 BreakLocatorType type) {
77 debug_info_ = debug_info;
78 type_ = type;
79 reloc_iterator_ = NULL;
80 reloc_iterator_original_ = NULL;
81 Reset(); // Initialize the rest of the member variables.
82}
83
84
85BreakLocationIterator::~BreakLocationIterator() {
86 ASSERT(reloc_iterator_ != NULL);
87 ASSERT(reloc_iterator_original_ != NULL);
88 delete reloc_iterator_;
89 delete reloc_iterator_original_;
90}
91
92
93void BreakLocationIterator::Next() {
94 AssertNoAllocation nogc;
95 ASSERT(!RinfoDone());
96
97 // Iterate through reloc info for code and original code stopping at each
98 // breakable code target.
99 bool first = break_point_ == -1;
100 while (!RinfoDone()) {
101 if (!first) RinfoNext();
102 first = false;
103 if (RinfoDone()) return;
104
ager@chromium.org236ad962008-09-25 09:45:57 +0000105 // Whenever a statement position or (plain) position is passed update the
106 // current value of these.
107 if (RelocInfo::IsPosition(rmode())) {
108 if (RelocInfo::IsStatementPosition(rmode())) {
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000109 statement_position_ = static_cast<int>(
110 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000111 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000112 // Always update the position as we don't want that to be before the
113 // statement position.
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000114 position_ = static_cast<int>(
115 rinfo()->data() - debug_info_->shared()->start_position());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000116 ASSERT(position_ >= 0);
117 ASSERT(statement_position_ >= 0);
118 }
119
120 // Check for breakable code target. Look in the original code as setting
121 // break points can cause the code targets in the running (debugged) code to
122 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000123 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000124 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000125 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.org236ad962008-09-25 09:45:57 +0000126 if (code->is_inline_cache_stub() || RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000127 break_point_++;
128 return;
129 }
130 if (code->kind() == Code::STUB) {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000131 if (IsDebuggerStatement()) {
132 break_point_++;
133 return;
134 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000135 if (type_ == ALL_BREAK_LOCATIONS) {
136 if (Debug::IsBreakStub(code)) {
137 break_point_++;
138 return;
139 }
140 } else {
141 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
142 if (Debug::IsSourceBreakStub(code)) {
143 break_point_++;
144 return;
145 }
146 }
147 }
148 }
149
150 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000151 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000152 // Set the positions to the end of the function.
153 if (debug_info_->shared()->HasSourceCode()) {
154 position_ = debug_info_->shared()->end_position() -
155 debug_info_->shared()->start_position();
156 } else {
157 position_ = 0;
158 }
159 statement_position_ = position_;
160 break_point_++;
161 return;
162 }
163 }
164}
165
166
167void BreakLocationIterator::Next(int count) {
168 while (count > 0) {
169 Next();
170 count--;
171 }
172}
173
174
175// Find the break point closest to the supplied address.
176void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
177 // Run through all break points to locate the one closest to the address.
178 int closest_break_point = 0;
179 int distance = kMaxInt;
180 while (!Done()) {
181 // Check if this break point is closer that what was previously found.
182 if (this->pc() < pc && pc - this->pc() < distance) {
183 closest_break_point = break_point();
ager@chromium.orgc4c92722009-11-18 14:12:51 +0000184 distance = static_cast<int>(pc - this->pc());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000185 // Check whether we can't get any closer.
186 if (distance == 0) break;
187 }
188 Next();
189 }
190
191 // Move to the break point found.
192 Reset();
193 Next(closest_break_point);
194}
195
196
197// Find the break point closest to the supplied source position.
198void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
199 // Run through all break points to locate the one closest to the source
200 // position.
201 int closest_break_point = 0;
202 int distance = kMaxInt;
203 while (!Done()) {
204 // Check if this break point is closer that what was previously found.
205 if (position <= statement_position() &&
206 statement_position() - position < distance) {
207 closest_break_point = break_point();
208 distance = statement_position() - position;
209 // Check whether we can't get any closer.
210 if (distance == 0) break;
211 }
212 Next();
213 }
214
215 // Move to the break point found.
216 Reset();
217 Next(closest_break_point);
218}
219
220
221void BreakLocationIterator::Reset() {
222 // Create relocation iterators for the two code objects.
223 if (reloc_iterator_ != NULL) delete reloc_iterator_;
224 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
225 reloc_iterator_ = new RelocIterator(debug_info_->code());
226 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
227
228 // Position at the first break point.
229 break_point_ = -1;
230 position_ = 1;
231 statement_position_ = 1;
232 Next();
233}
234
235
236bool BreakLocationIterator::Done() const {
237 return RinfoDone();
238}
239
240
241void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
242 // If there is not already a real break point here patch code with debug
243 // break.
244 if (!HasBreakPoint()) {
245 SetDebugBreak();
246 }
ager@chromium.orga1645e22009-09-09 19:27:10 +0000247 ASSERT(IsDebugBreak() || IsDebuggerStatement());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000248 // Set the break point information.
249 DebugInfo::SetBreakPoint(debug_info_, code_position(),
250 position(), statement_position(),
251 break_point_object);
252}
253
254
255void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
256 // Clear the break point information.
257 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
258 // If there are no more break points here remove the debug break.
259 if (!HasBreakPoint()) {
260 ClearDebugBreak();
261 ASSERT(!IsDebugBreak());
262 }
263}
264
265
266void BreakLocationIterator::SetOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000267 // Debugger statement always calls debugger. No need to modify it.
268 if (IsDebuggerStatement()) {
269 return;
270 }
271
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000272 // If there is a real break point here no more to do.
273 if (HasBreakPoint()) {
274 ASSERT(IsDebugBreak());
275 return;
276 }
277
278 // Patch code with debug break.
279 SetDebugBreak();
280}
281
282
283void BreakLocationIterator::ClearOneShot() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000284 // Debugger statement always calls debugger. No need to modify it.
285 if (IsDebuggerStatement()) {
286 return;
287 }
288
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000289 // If there is a real break point here no more to do.
290 if (HasBreakPoint()) {
291 ASSERT(IsDebugBreak());
292 return;
293 }
294
295 // Patch code removing debug break.
296 ClearDebugBreak();
297 ASSERT(!IsDebugBreak());
298}
299
300
301void BreakLocationIterator::SetDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000302 // Debugger statement always calls debugger. No need to modify it.
303 if (IsDebuggerStatement()) {
304 return;
305 }
306
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000307 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000308 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000309 // function twice might happen when stepping in a function with an exception
310 // handler as the handler and the function is the same.
311 if (IsDebugBreak()) {
312 return;
313 }
314
ager@chromium.org236ad962008-09-25 09:45:57 +0000315 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000316 // Patch the frame exit code with a break point.
317 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000318 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000319 // Patch the IC call.
320 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000321 }
322 ASSERT(IsDebugBreak());
323}
324
325
326void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000327 // Debugger statement always calls debugger. No need to modify it.
328 if (IsDebuggerStatement()) {
329 return;
330 }
331
ager@chromium.org236ad962008-09-25 09:45:57 +0000332 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000333 // Restore the frame exit code.
334 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000336 // Patch the IC call.
337 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000338 }
339 ASSERT(!IsDebugBreak());
340}
341
342
343void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000344 HandleScope scope;
345
ager@chromium.orga1645e22009-09-09 19:27:10 +0000346 // Step in can only be prepared if currently positioned on an IC call,
347 // construct call or CallFunction stub call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000348 Address target = rinfo()->target_address();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000349 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000350 if (code->is_call_stub()) {
351 // Step in through IC call is handled by the runtime system. Therefore make
352 // sure that the any current IC is cleared and the runtime system is
353 // called. If the executing code has a debug break at the location change
354 // the call in the original code as it is the code there that will be
355 // executed in place of the debug break call.
356 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
357 if (IsDebugBreak()) {
358 original_rinfo()->set_target_address(stub->entry());
359 } else {
360 rinfo()->set_target_address(stub->entry());
361 }
362 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +0000363#ifdef DEBUG
364 // All the following stuff is needed only for assertion checks so the code
365 // is wrapped in ifdef.
366 Handle<Code> maybe_call_function_stub = code;
367 if (IsDebugBreak()) {
368 Address original_target = original_rinfo()->target_address();
369 maybe_call_function_stub =
370 Handle<Code>(Code::GetCodeFromTargetAddress(original_target));
371 }
372 bool is_call_function_stub =
373 (maybe_call_function_stub->kind() == Code::STUB &&
374 maybe_call_function_stub->major_key() == CodeStub::CallFunction);
375
kasperl@chromium.orge959c182009-07-27 08:59:04 +0000376 // Step in through construct call requires no changes to the running code.
377 // Step in through getters/setters should already be prepared as well
378 // because caller of this function (Debug::PrepareStep) is expected to
379 // flood the top frame's function with one shot breakpoints.
ager@chromium.orga1645e22009-09-09 19:27:10 +0000380 // Step in through CallFunction stub should also be prepared by caller of
381 // this function (Debug::PrepareStep) which should flood target function
382 // with breakpoints.
383 ASSERT(RelocInfo::IsConstructCall(rmode()) || code->is_inline_cache_stub()
384 || is_call_function_stub);
385#endif
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000386 }
387}
388
389
390// Check whether the break point is at a position which will exit the function.
391bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000392 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393}
394
395
396bool BreakLocationIterator::HasBreakPoint() {
397 return debug_info_->HasBreakPoint(code_position());
398}
399
400
401// Check whether there is a debug break at the current position.
402bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000403 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000404 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000405 } else {
406 return Debug::IsDebugBreak(rinfo()->target_address());
407 }
408}
409
410
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000411void BreakLocationIterator::SetDebugBreakAtIC() {
412 // Patch the original code with the current address as the current address
413 // might have changed by the inline caching since the code was copied.
414 original_rinfo()->set_target_address(rinfo()->target_address());
415
416 RelocInfo::Mode mode = rmode();
417 if (RelocInfo::IsCodeTarget(mode)) {
418 Address target = rinfo()->target_address();
419 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
420
421 // Patch the code to invoke the builtin debug break function matching the
422 // calling convention used by the call site.
423 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
424 rinfo()->set_target_address(dbgbrk_code->entry());
425
426 // For stubs that refer back to an inlined version clear the cached map for
427 // the inlined case to always go through the IC. As long as the break point
428 // is set the patching performed by the runtime system will take place in
429 // the code copy and will therefore have no effect on the running code
430 // keeping it from using the inlined code.
ager@chromium.org5ec48922009-05-05 07:25:34 +0000431 if (code->is_keyed_load_stub()) KeyedLoadIC::ClearInlinedVersion(pc());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000432 if (code->is_keyed_store_stub()) KeyedStoreIC::ClearInlinedVersion(pc());
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000433 }
434}
435
436
437void BreakLocationIterator::ClearDebugBreakAtIC() {
438 // Patch the code to the original invoke.
439 rinfo()->set_target_address(original_rinfo()->target_address());
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000440
441 RelocInfo::Mode mode = rmode();
442 if (RelocInfo::IsCodeTarget(mode)) {
443 Address target = original_rinfo()->target_address();
444 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
445
446 // Restore the inlined version of keyed stores to get back to the
447 // fast case. We need to patch back the keyed store because no
448 // patching happens when running normally. For keyed loads, the
449 // map check will get patched back when running normally after ICs
450 // have been cleared at GC.
451 if (code->is_keyed_store_stub()) KeyedStoreIC::RestoreInlinedVersion(pc());
452 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000453}
454
455
ager@chromium.orga1645e22009-09-09 19:27:10 +0000456bool BreakLocationIterator::IsDebuggerStatement() {
ager@chromium.org5c838252010-02-19 08:53:10 +0000457 return RelocInfo::DEBUG_BREAK == rmode();
ager@chromium.orga1645e22009-09-09 19:27:10 +0000458}
459
460
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000461Object* BreakLocationIterator::BreakPointObjects() {
462 return debug_info_->GetBreakPointObjects(code_position());
463}
464
465
ager@chromium.org381abbb2009-02-25 13:23:22 +0000466// Clear out all the debug break code. This is ONLY supposed to be used when
467// shutting down the debugger as it will leave the break point information in
468// DebugInfo even though the code is patched back to the non break point state.
469void BreakLocationIterator::ClearAllDebugBreak() {
470 while (!Done()) {
471 ClearDebugBreak();
472 Next();
473 }
474}
475
476
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000477bool BreakLocationIterator::RinfoDone() const {
478 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
479 return reloc_iterator_->done();
480}
481
482
483void BreakLocationIterator::RinfoNext() {
484 reloc_iterator_->next();
485 reloc_iterator_original_->next();
486#ifdef DEBUG
487 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
488 if (!reloc_iterator_->done()) {
489 ASSERT(rmode() == original_rmode());
490 }
491#endif
492}
493
494
495bool Debug::has_break_points_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000496ScriptCache* Debug::script_cache_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000497DebugInfoListNode* Debug::debug_info_list_ = NULL;
498
499
500// Threading support.
501void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000502 thread_local_.break_count_ = 0;
503 thread_local_.break_id_ = 0;
504 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000505 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000506 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000507 thread_local_.step_count_ = 0;
508 thread_local_.last_fp_ = 0;
509 thread_local_.step_into_fp_ = 0;
ager@chromium.orga1645e22009-09-09 19:27:10 +0000510 thread_local_.step_out_fp_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000511 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000512 thread_local_.debugger_entry_ = NULL;
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000513 thread_local_.pending_interrupts_ = 0;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000514}
515
516
517JSCallerSavedBuffer Debug::registers_;
518Debug::ThreadLocal Debug::thread_local_;
519
520
521char* Debug::ArchiveDebug(char* storage) {
522 char* to = storage;
523 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
524 to += sizeof(ThreadLocal);
525 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
526 ThreadInit();
527 ASSERT(to <= storage + ArchiveSpacePerThread());
528 return storage + ArchiveSpacePerThread();
529}
530
531
532char* Debug::RestoreDebug(char* storage) {
533 char* from = storage;
534 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
535 from += sizeof(ThreadLocal);
536 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
537 ASSERT(from <= storage + ArchiveSpacePerThread());
538 return storage + ArchiveSpacePerThread();
539}
540
541
542int Debug::ArchiveSpacePerThread() {
543 return sizeof(ThreadLocal) + sizeof(registers_);
544}
545
546
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000547// Default break enabled.
548bool Debug::disable_break_ = false;
549
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000550// Default call debugger on uncaught exception.
551bool Debug::break_on_exception_ = false;
552bool Debug::break_on_uncaught_exception_ = true;
553
554Handle<Context> Debug::debug_context_ = Handle<Context>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000555Code* Debug::debug_break_return_ = NULL;
556
557
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000558void ScriptCache::Add(Handle<Script> script) {
559 // Create an entry in the hash map for the script.
560 int id = Smi::cast(script->id())->value();
561 HashMap::Entry* entry =
562 HashMap::Lookup(reinterpret_cast<void*>(id), Hash(id), true);
563 if (entry->value != NULL) {
564 ASSERT(*script == *reinterpret_cast<Script**>(entry->value));
565 return;
566 }
567
568 // Globalize the script object, make it weak and use the location of the
569 // global handle as the value in the hash map.
570 Handle<Script> script_ =
571 Handle<Script>::cast((GlobalHandles::Create(*script)));
572 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(script_.location()),
573 this, ScriptCache::HandleWeakScript);
574 entry->value = script_.location();
575}
576
577
578Handle<FixedArray> ScriptCache::GetScripts() {
579 Handle<FixedArray> instances = Factory::NewFixedArray(occupancy());
580 int count = 0;
581 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
582 ASSERT(entry->value != NULL);
583 if (entry->value != NULL) {
584 instances->set(count, *reinterpret_cast<Script**>(entry->value));
585 count++;
586 }
587 }
588 return instances;
589}
590
591
592void ScriptCache::ProcessCollectedScripts() {
593 for (int i = 0; i < collected_scripts_.length(); i++) {
594 Debugger::OnScriptCollected(collected_scripts_[i]);
595 }
596 collected_scripts_.Clear();
597}
598
599
600void ScriptCache::Clear() {
601 // Iterate the script cache to get rid of all the weak handles.
602 for (HashMap::Entry* entry = Start(); entry != NULL; entry = Next(entry)) {
603 ASSERT(entry != NULL);
604 Object** location = reinterpret_cast<Object**>(entry->value);
605 ASSERT((*location)->IsScript());
606 GlobalHandles::ClearWeakness(location);
607 GlobalHandles::Destroy(location);
608 }
609 // Clear the content of the hash map.
610 HashMap::Clear();
611}
612
613
614void ScriptCache::HandleWeakScript(v8::Persistent<v8::Value> obj, void* data) {
615 ScriptCache* script_cache = reinterpret_cast<ScriptCache*>(data);
616 // Find the location of the global handle.
617 Script** location =
618 reinterpret_cast<Script**>(Utils::OpenHandle(*obj).location());
619 ASSERT((*location)->IsScript());
620
621 // Remove the entry from the cache.
622 int id = Smi::cast((*location)->id())->value();
623 script_cache->Remove(reinterpret_cast<void*>(id), Hash(id));
624 script_cache->collected_scripts_.Add(id);
625
626 // Clear the weak handle.
627 obj.Dispose();
628 obj.Clear();
629}
630
631
632void Debug::Setup(bool create_heap_objects) {
633 ThreadInit();
634 if (create_heap_objects) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000635 // Get code to handle debug break on return.
636 debug_break_return_ =
637 Builtins::builtin(Builtins::Return_DebugBreak);
638 ASSERT(debug_break_return_->IsCode());
639 }
640}
641
642
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000643void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000644 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
645 RemoveDebugInfo(node->debug_info());
646#ifdef DEBUG
647 node = Debug::debug_info_list_;
648 while (node != NULL) {
649 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
650 node = node->next();
651 }
652#endif
653}
654
655
656DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
657 // Globalize the request debug info object and make it weak.
658 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
659 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
660 this, Debug::HandleWeakDebugInfo);
661}
662
663
664DebugInfoListNode::~DebugInfoListNode() {
665 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
666}
667
668
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000669bool Debug::CompileDebuggerScript(int index) {
670 HandleScope scope;
671
kasper.lund44510672008-07-25 07:37:58 +0000672 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000673 if (index == -1) {
674 return false;
675 }
kasper.lund44510672008-07-25 07:37:58 +0000676
677 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
679 Vector<const char> name = Natives::GetScriptName(index);
680 Handle<String> script_name = Factory::NewStringFromAscii(name);
681
682 // Compile the script.
683 bool allow_natives_syntax = FLAG_allow_natives_syntax;
684 FLAG_allow_natives_syntax = true;
685 Handle<JSFunction> boilerplate;
ager@chromium.org5c838252010-02-19 08:53:10 +0000686 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL,
687 Handle<String>::null());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000688 FLAG_allow_natives_syntax = allow_natives_syntax;
689
690 // Silently ignore stack overflows during compilation.
691 if (boilerplate.is_null()) {
692 ASSERT(Top::has_pending_exception());
693 Top::clear_pending_exception();
694 return false;
695 }
696
kasper.lund44510672008-07-25 07:37:58 +0000697 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000698 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000699 bool caught_exception = false;
700 Handle<JSFunction> function =
701 Factory::NewFunctionFromBoilerplate(boilerplate, context);
702 Handle<Object> result =
703 Execution::TryCall(function, Handle<Object>(context->global()),
704 0, NULL, &caught_exception);
705
706 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000708 Handle<Object> message = MessageHandler::MakeMessageObject(
ager@chromium.org18ad94b2009-09-02 08:22:29 +0000709 "error_loading_debugger", NULL, Vector<Handle<Object> >::empty(),
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000710 Handle<String>());
711 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000712 return false;
713 }
714
kasper.lund44510672008-07-25 07:37:58 +0000715 // Mark this script as native and return successfully.
716 Handle<Script> script(Script::cast(function->shared()->script()));
ager@chromium.orge2902be2009-06-08 12:21:35 +0000717 script->set_type(Smi::FromInt(Script::TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000718 return true;
719}
720
721
722bool Debug::Load() {
723 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000724 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000725
kasper.lund44510672008-07-25 07:37:58 +0000726 // Bail out if we're already in the process of compiling the native
727 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000728 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
729 return false;
730 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000731
732 // Disable breakpoints and interrupts while compiling and running the
733 // debugger scripts including the context creation code.
734 DisableBreak disable(true);
735 PostponeInterruptsScope postpone;
736
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000737 // Create the debugger context.
738 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000739 Handle<Context> context =
740 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
741 v8::Handle<ObjectTemplate>(),
742 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000743
kasper.lund44510672008-07-25 07:37:58 +0000744 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000745 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000746 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000747
748 // Expose the builtins object in the debugger context.
749 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
750 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
751 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000752
753 // Compile the JavaScript for the debugger in the debugger context.
754 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000755 bool caught_exception =
756 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
757 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000758 Debugger::set_compiling_natives(false);
759
mads.s.agercbaa0602008-08-14 13:41:48 +0000760 // Make sure we mark the debugger as not loading before we might
761 // return.
762 Debugger::set_loading_debugger(false);
763
kasper.lund44510672008-07-25 07:37:58 +0000764 // Check for caught exceptions.
765 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000766
767 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000768 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000769
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000770 return true;
771}
772
773
774void Debug::Unload() {
775 // Return debugger is not loaded.
776 if (!IsLoaded()) {
777 return;
778 }
779
kasperl@chromium.org71affb52009-05-26 05:44:31 +0000780 // Clear the script cache.
781 DestroyScriptCache();
782
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000783 // Clear debugger context global handle.
784 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
785 debug_context_ = Handle<Context>();
786}
787
788
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000789// Set the flag indicating that preemption happened during debugging.
790void Debug::PreemptionWhileInDebugger() {
791 ASSERT(InDebugger());
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000792 Debug::set_interrupts_pending(PREEMPT);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000793}
794
795
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000796void Debug::Iterate(ObjectVisitor* v) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000797 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000798}
799
800
801Object* Debug::Break(Arguments args) {
802 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000803 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000804
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000805 // Get the top-most JavaScript frame.
806 JavaScriptFrameIterator it;
807 JavaScriptFrame* frame = it.frame();
808
809 // Just continue if breaks are disabled or debugger cannot be loaded.
810 if (disable_break() || !Load()) {
811 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000812 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000813 }
814
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000815 // Enter the debugger.
816 EnterDebugger debugger;
817 if (debugger.FailedToEnter()) {
818 return Heap::undefined_value();
819 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000820
kasper.lund44510672008-07-25 07:37:58 +0000821 // Postpone interrupt during breakpoint processing.
822 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000823
824 // Get the debug info (create it if it does not exist).
825 Handle<SharedFunctionInfo> shared =
826 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
827 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
828
829 // Find the break point where execution has stopped.
830 BreakLocationIterator break_location_iterator(debug_info,
831 ALL_BREAK_LOCATIONS);
832 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
833
834 // Check whether step next reached a new statement.
835 if (!StepNextContinue(&break_location_iterator, frame)) {
836 // Decrease steps left if performing multiple steps.
837 if (thread_local_.step_count_ > 0) {
838 thread_local_.step_count_--;
839 }
840 }
841
842 // If there is one or more real break points check whether any of these are
843 // triggered.
844 Handle<Object> break_points_hit(Heap::undefined_value());
845 if (break_location_iterator.HasBreakPoint()) {
846 Handle<Object> break_point_objects =
847 Handle<Object>(break_location_iterator.BreakPointObjects());
848 break_points_hit = CheckBreakPoints(break_point_objects);
849 }
850
ager@chromium.orga1645e22009-09-09 19:27:10 +0000851 // If step out is active skip everything until the frame where we need to step
852 // out to is reached, unless real breakpoint is hit.
853 if (Debug::StepOutActive() && frame->fp() != Debug::step_out_fp() &&
854 break_points_hit->IsUndefined() ) {
855 // Step count should always be 0 for StepOut.
856 ASSERT(thread_local_.step_count_ == 0);
857 } else if (!break_points_hit->IsUndefined() ||
858 (thread_local_.last_step_action_ != StepNone &&
859 thread_local_.step_count_ == 0)) {
860 // Notify debugger if a real break point is triggered or if performing
861 // single stepping with no more steps to perform. Otherwise do another step.
862
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000863 // Clear all current stepping setup.
864 ClearStepping();
865
866 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000867 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000868 } else if (thread_local_.last_step_action_ != StepNone) {
869 // Hold on to last step action as it is cleared by the call to
870 // ClearStepping.
871 StepAction step_action = thread_local_.last_step_action_;
872 int step_count = thread_local_.step_count_;
873
874 // Clear all current stepping setup.
875 ClearStepping();
876
877 // Set up for the remaining steps.
878 PrepareStep(step_action, step_count);
879 }
880
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000881 // Install jump to the call address which was overwritten.
882 SetAfterBreakTarget(frame);
883
mads.s.ager31e71382008-08-13 09:32:07 +0000884 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000885}
886
887
888// Check the break point objects for whether one or more are actually
889// triggered. This function returns a JSArray with the break point objects
890// which is triggered.
891Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
892 int break_points_hit_count = 0;
893 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
894
v8.team.kasperl727e9952008-09-02 14:56:44 +0000895 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000896 ASSERT(!break_point_objects->IsUndefined());
897 if (break_point_objects->IsFixedArray()) {
898 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
899 for (int i = 0; i < array->length(); i++) {
900 Handle<Object> o(array->get(i));
901 if (CheckBreakPoint(o)) {
902 break_points_hit->SetElement(break_points_hit_count++, *o);
903 }
904 }
905 } else {
906 if (CheckBreakPoint(break_point_objects)) {
907 break_points_hit->SetElement(break_points_hit_count++,
908 *break_point_objects);
909 }
910 }
911
912 // Return undefined if no break points where triggered.
913 if (break_points_hit_count == 0) {
914 return Factory::undefined_value();
915 }
916 return break_points_hit;
917}
918
919
920// Check whether a single break point object is triggered.
921bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000922 HandleScope scope;
923
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000924 // Ignore check if break point object is not a JSObject.
925 if (!break_point_object->IsJSObject()) return true;
926
927 // Get the function CheckBreakPoint (defined in debug.js).
928 Handle<JSFunction> check_break_point =
929 Handle<JSFunction>(JSFunction::cast(
930 debug_context()->global()->GetProperty(
931 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
932
933 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000934 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000935
936 // Call HandleBreakPointx.
937 bool caught_exception = false;
938 const int argc = 2;
939 Object** argv[argc] = {
940 break_id.location(),
941 reinterpret_cast<Object**>(break_point_object.location())
942 };
943 Handle<Object> result = Execution::TryCall(check_break_point,
944 Top::builtins(), argc, argv,
945 &caught_exception);
946
947 // If exception or non boolean result handle as not triggered
948 if (caught_exception || !result->IsBoolean()) {
949 return false;
950 }
951
952 // Return whether the break point is triggered.
953 return *result == Heap::true_value();
954}
955
956
957// Check whether the function has debug information.
958bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
959 return !shared->debug_info()->IsUndefined();
960}
961
962
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000963// Return the debug info for this function. EnsureDebugInfo must be called
964// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000965Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000966 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000967 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
968}
969
970
971void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
972 int source_position,
973 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000974 HandleScope scope;
975
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000976 if (!EnsureDebugInfo(shared)) {
977 // Return if retrieving debug info failed.
978 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000979 }
980
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000981 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000982 // Source positions starts with zero.
983 ASSERT(source_position >= 0);
984
985 // Find the break point and change it.
986 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
987 it.FindBreakLocationFromPosition(source_position);
988 it.SetBreakPoint(break_point_object);
989
990 // At least one active break point now.
991 ASSERT(debug_info->GetBreakPointCount() > 0);
992}
993
994
995void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000996 HandleScope scope;
997
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000998 DebugInfoListNode* node = debug_info_list_;
999 while (node != NULL) {
1000 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
1001 break_point_object);
1002 if (!result->IsUndefined()) {
1003 // Get information in the break point.
1004 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
1005 Handle<DebugInfo> debug_info = node->debug_info();
1006 Handle<SharedFunctionInfo> shared(debug_info->shared());
1007 int source_position = break_point_info->statement_position()->value();
1008
1009 // Source positions starts with zero.
1010 ASSERT(source_position >= 0);
1011
1012 // Find the break point and clear it.
1013 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
1014 it.FindBreakLocationFromPosition(source_position);
1015 it.ClearBreakPoint(break_point_object);
1016
1017 // If there are no more break points left remove the debug info for this
1018 // function.
1019 if (debug_info->GetBreakPointCount() == 0) {
1020 RemoveDebugInfo(debug_info);
1021 }
1022
1023 return;
1024 }
1025 node = node->next();
1026 }
1027}
1028
1029
ager@chromium.org381abbb2009-02-25 13:23:22 +00001030void Debug::ClearAllBreakPoints() {
1031 DebugInfoListNode* node = debug_info_list_;
1032 while (node != NULL) {
1033 // Remove all debug break code.
1034 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1035 it.ClearAllDebugBreak();
1036 node = node->next();
1037 }
1038
1039 // Remove all debug info.
1040 while (debug_info_list_ != NULL) {
1041 RemoveDebugInfo(debug_info_list_->debug_info());
1042 }
1043}
1044
1045
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001046void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001047 // Make sure the function has setup the debug info.
1048 if (!EnsureDebugInfo(shared)) {
1049 // Return if we failed to retrieve the debug info.
1050 return;
1051 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001052
1053 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001054 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001055 while (!it.Done()) {
1056 it.SetOneShot();
1057 it.Next();
1058 }
1059}
1060
1061
1062void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001063 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001064 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001065 if (id == StackFrame::NO_ID) {
1066 // If there is no JavaScript stack don't do anything.
1067 return;
1068 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001069 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
1070 JavaScriptFrame* frame = it.frame();
1071 if (frame->HasHandler()) {
1072 Handle<SharedFunctionInfo> shared =
1073 Handle<SharedFunctionInfo>(
1074 JSFunction::cast(frame->function())->shared());
1075 // Flood the function with the catch block with break points
1076 FloodWithOneShot(shared);
1077 return;
1078 }
1079 }
1080}
1081
1082
1083void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
1084 if (type == BreakUncaughtException) {
1085 break_on_uncaught_exception_ = enable;
1086 } else {
1087 break_on_exception_ = enable;
1088 }
1089}
1090
1091
1092void Debug::PrepareStep(StepAction step_action, int step_count) {
1093 HandleScope scope;
1094 ASSERT(Debug::InDebugger());
1095
1096 // Remember this step action and count.
1097 thread_local_.last_step_action_ = step_action;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001098 if (step_action == StepOut) {
1099 // For step out target frame will be found on the stack so there is no need
1100 // to set step counter for it. It's expected to always be 0 for StepOut.
1101 thread_local_.step_count_ = 0;
1102 } else {
1103 thread_local_.step_count_ = step_count;
1104 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001105
1106 // Get the frame where the execution has stopped and skip the debug frame if
1107 // any. The debug frame will only be present if execution was stopped due to
1108 // hitting a break point. In other situations (e.g. unhandled exception) the
1109 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001110 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001111 if (id == StackFrame::NO_ID) {
1112 // If there is no JavaScript stack don't do anything.
1113 return;
1114 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001115 JavaScriptFrameIterator frames_it(id);
1116 JavaScriptFrame* frame = frames_it.frame();
1117
1118 // First of all ensure there is one-shot break points in the top handler
1119 // if any.
1120 FloodHandlerWithOneShot();
1121
1122 // If the function on the top frame is unresolved perform step out. This will
1123 // be the case when calling unknown functions and having the debugger stopped
1124 // in an unhandled exception.
1125 if (!frame->function()->IsJSFunction()) {
1126 // Step out: Find the calling JavaScript frame and flood it with
1127 // breakpoints.
1128 frames_it.Advance();
1129 // Fill the function to return to with one-shot break points.
1130 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1131 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1132 return;
1133 }
1134
1135 // Get the debug info (create it if it does not exist).
1136 Handle<SharedFunctionInfo> shared =
1137 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001138 if (!EnsureDebugInfo(shared)) {
1139 // Return if ensuring debug info failed.
1140 return;
1141 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001142 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1143
1144 // Find the break location where execution has stopped.
1145 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
1146 it.FindBreakLocationFromAddress(frame->pc());
1147
1148 // Compute whether or not the target is a call target.
1149 bool is_call_target = false;
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001150 bool is_load_or_store = false;
1151 bool is_inline_cache_stub = false;
ager@chromium.orga1645e22009-09-09 19:27:10 +00001152 Handle<Code> call_function_stub;
ager@chromium.org236ad962008-09-25 09:45:57 +00001153 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001154 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001155 Code* code = Code::GetCodeFromTargetAddress(target);
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001156 if (code->is_call_stub()) {
1157 is_call_target = true;
1158 }
1159 if (code->is_inline_cache_stub()) {
1160 is_inline_cache_stub = true;
1161 is_load_or_store = !is_call_target;
1162 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001163
1164 // Check if target code is CallFunction stub.
1165 Code* maybe_call_function_stub = code;
1166 // If there is a breakpoint at this line look at the original code to
1167 // check if it is a CallFunction stub.
1168 if (it.IsDebugBreak()) {
1169 Address original_target = it.original_rinfo()->target_address();
1170 maybe_call_function_stub =
1171 Code::GetCodeFromTargetAddress(original_target);
1172 }
1173 if (maybe_call_function_stub->kind() == Code::STUB &&
1174 maybe_call_function_stub->major_key() == CodeStub::CallFunction) {
1175 // Save reference to the code as we may need it to find out arguments
1176 // count for 'step in' later.
1177 call_function_stub = Handle<Code>(maybe_call_function_stub);
1178 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001179 }
1180
v8.team.kasperl727e9952008-09-02 14:56:44 +00001181 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001182 if (it.IsExit() || step_action == StepOut) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001183 if (step_action == StepOut) {
1184 // Skip step_count frames starting with the current one.
1185 while (step_count-- > 0 && !frames_it.done()) {
1186 frames_it.Advance();
1187 }
1188 } else {
1189 ASSERT(it.IsExit());
1190 frames_it.Advance();
1191 }
1192 // Skip builtin functions on the stack.
1193 while (!frames_it.done() &&
1194 JSFunction::cast(frames_it.frame()->function())->IsBuiltin()) {
1195 frames_it.Advance();
1196 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001197 // Step out: If there is a JavaScript caller frame, we need to
1198 // flood it with breakpoints.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001199 if (!frames_it.done()) {
1200 // Fill the function to return to with one-shot break points.
1201 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1202 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001203 // Set target frame pointer.
1204 ActivateStepOut(frames_it.frame());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001205 }
ager@chromium.orga1645e22009-09-09 19:27:10 +00001206 } else if (!(is_inline_cache_stub || RelocInfo::IsConstructCall(it.rmode()) ||
1207 !call_function_stub.is_null())
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001208 || step_action == StepNext || step_action == StepMin) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001209 // Step next or step min.
1210
1211 // Fill the current function with one-shot break points.
1212 FloodWithOneShot(shared);
1213
1214 // Remember source position and frame to handle step next.
1215 thread_local_.last_statement_position_ =
1216 debug_info->code()->SourceStatementPosition(frame->pc());
1217 thread_local_.last_fp_ = frame->fp();
1218 } else {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001219 // If it's CallFunction stub ensure target function is compiled and flood
1220 // it with one shot breakpoints.
1221 if (!call_function_stub.is_null()) {
1222 // Find out number of arguments from the stub minor key.
1223 // Reverse lookup required as the minor key cannot be retrieved
1224 // from the code object.
1225 Handle<Object> obj(
1226 Heap::code_stubs()->SlowReverseLookup(*call_function_stub));
1227 ASSERT(*obj != Heap::undefined_value());
1228 ASSERT(obj->IsSmi());
1229 // Get the STUB key and extract major and minor key.
1230 uint32_t key = Smi::cast(*obj)->value();
1231 // Argc in the stub is the number of arguments passed - not the
1232 // expected arguments of the called function.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001233 int call_function_arg_count =
1234 CallFunctionStub::ExtractArgcFromMinorKey(
1235 CodeStub::MinorKeyFromKey(key));
ager@chromium.orga1645e22009-09-09 19:27:10 +00001236 ASSERT(call_function_stub->major_key() ==
1237 CodeStub::MajorKeyFromKey(key));
1238
1239 // Find target function on the expression stack.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001240 // Expression stack looks like this (top to bottom):
ager@chromium.orga1645e22009-09-09 19:27:10 +00001241 // argN
1242 // ...
1243 // arg0
1244 // Receiver
1245 // Function to call
1246 int expressions_count = frame->ComputeExpressionsCount();
1247 ASSERT(expressions_count - 2 - call_function_arg_count >= 0);
1248 Object* fun = frame->GetExpression(
1249 expressions_count - 2 - call_function_arg_count);
1250 if (fun->IsJSFunction()) {
1251 Handle<JSFunction> js_function(JSFunction::cast(fun));
1252 // Don't step into builtins.
1253 if (!js_function->IsBuiltin()) {
1254 // It will also compile target function if it's not compiled yet.
1255 FloodWithOneShot(Handle<SharedFunctionInfo>(js_function->shared()));
1256 }
1257 }
1258 }
1259
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001260 // Fill the current function with one-shot break points even for step in on
1261 // a call target as the function called might be a native function for
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001262 // which step in will not stop. It also prepares for stepping in
1263 // getters/setters.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001264 FloodWithOneShot(shared);
1265
kasperl@chromium.orge959c182009-07-27 08:59:04 +00001266 if (is_load_or_store) {
1267 // Remember source position and frame to handle step in getter/setter. If
1268 // there is a custom getter/setter it will be handled in
1269 // Object::Get/SetPropertyWithCallback, otherwise the step action will be
1270 // propagated on the next Debug::Break.
1271 thread_local_.last_statement_position_ =
1272 debug_info->code()->SourceStatementPosition(frame->pc());
1273 thread_local_.last_fp_ = frame->fp();
1274 }
1275
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001276 // Step in or Step in min
1277 it.PrepareStepIn();
1278 ActivateStepIn(frame);
1279 }
1280}
1281
1282
1283// Check whether the current debug break should be reported to the debugger. It
1284// is used to have step next and step in only report break back to the debugger
1285// if on a different frame or in a different statement. In some situations
1286// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001287// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001288// steps before reporting break back to the debugger.
1289bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1290 JavaScriptFrame* frame) {
1291 // If the step last action was step next or step in make sure that a new
1292 // statement is hit.
1293 if (thread_local_.last_step_action_ == StepNext ||
1294 thread_local_.last_step_action_ == StepIn) {
1295 // Never continue if returning from function.
1296 if (break_location_iterator->IsExit()) return false;
1297
1298 // Continue if we are still on the same frame and in the same statement.
1299 int current_statement_position =
1300 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1301 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001302 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001303 }
1304
1305 // No step next action - don't continue.
1306 return false;
1307}
1308
1309
1310// Check whether the code object at the specified address is a debug break code
1311// object.
1312bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001313 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001314 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001315}
1316
1317
1318// Check whether a code stub with the specified major key is a possible break
1319// point location when looking for source break locations.
1320bool Debug::IsSourceBreakStub(Code* code) {
1321 CodeStub::Major major_key = code->major_key();
1322 return major_key == CodeStub::CallFunction;
1323}
1324
1325
1326// Check whether a code stub with the specified major key is a possible break
1327// location.
1328bool Debug::IsBreakStub(Code* code) {
1329 CodeStub::Major major_key = code->major_key();
1330 return major_key == CodeStub::CallFunction ||
1331 major_key == CodeStub::StackCheck;
1332}
1333
1334
1335// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001336Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001337 // Find the builtin debug break function matching the calling convention
1338 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001339 if (code->is_inline_cache_stub()) {
1340 if (code->is_call_stub()) {
1341 return ComputeCallDebugBreak(code->arguments_count());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001342 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001343 if (code->is_load_stub()) {
1344 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1345 }
1346 if (code->is_store_stub()) {
1347 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1348 }
1349 if (code->is_keyed_load_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001350 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001351 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001352 return result;
1353 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001354 if (code->is_keyed_store_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001355 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001356 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001357 return result;
1358 }
1359 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001360 if (RelocInfo::IsConstructCall(mode)) {
1361 Handle<Code> result =
1362 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1363 return result;
1364 }
1365 if (code->kind() == Code::STUB) {
1366 ASSERT(code->major_key() == CodeStub::CallFunction ||
1367 code->major_key() == CodeStub::StackCheck);
1368 Handle<Code> result =
1369 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1370 return result;
1371 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001372
1373 UNREACHABLE();
1374 return Handle<Code>::null();
1375}
1376
1377
1378// Simple function for returning the source positions for active break points.
1379Handle<Object> Debug::GetSourceBreakLocations(
1380 Handle<SharedFunctionInfo> shared) {
1381 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1382 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1383 if (debug_info->GetBreakPointCount() == 0) {
1384 return Handle<Object>(Heap::undefined_value());
1385 }
1386 Handle<FixedArray> locations =
1387 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1388 int count = 0;
1389 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1390 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1391 BreakPointInfo* break_point_info =
1392 BreakPointInfo::cast(debug_info->break_points()->get(i));
1393 if (break_point_info->GetBreakPointCount() > 0) {
1394 locations->set(count++, break_point_info->statement_position());
1395 }
1396 }
1397 }
1398 return locations;
1399}
1400
1401
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001402void Debug::NewBreak(StackFrame::Id break_frame_id) {
1403 thread_local_.break_frame_id_ = break_frame_id;
1404 thread_local_.break_id_ = ++thread_local_.break_count_;
1405}
1406
1407
1408void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1409 thread_local_.break_frame_id_ = break_frame_id;
1410 thread_local_.break_id_ = break_id;
1411}
1412
1413
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001414// Handle stepping into a function.
1415void Debug::HandleStepIn(Handle<JSFunction> function,
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001416 Handle<Object> holder,
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001417 Address fp,
1418 bool is_constructor) {
1419 // If the frame pointer is not supplied by the caller find it.
1420 if (fp == 0) {
1421 StackFrameIterator it;
1422 it.Advance();
1423 // For constructor functions skip another frame.
1424 if (is_constructor) {
1425 ASSERT(it.frame()->is_construct());
1426 it.Advance();
1427 }
1428 fp = it.frame()->fp();
1429 }
1430
1431 // Flood the function with one-shot break points if it is called from where
1432 // step into was requested.
1433 if (fp == Debug::step_in_fp()) {
1434 // Don't allow step into functions in the native context.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001435 if (!function->IsBuiltin()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001436 if (function->shared()->code() ==
1437 Builtins::builtin(Builtins::FunctionApply) ||
1438 function->shared()->code() ==
1439 Builtins::builtin(Builtins::FunctionCall)) {
1440 // Handle function.apply and function.call separately to flood the
1441 // function to be called and not the code for Builtins::FunctionApply or
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001442 // Builtins::FunctionCall. The receiver of call/apply is the target
1443 // function.
sgjesse@chromium.org0b6db592009-07-30 14:48:31 +00001444 if (!holder.is_null() && holder->IsJSFunction() &&
1445 !JSFunction::cast(*holder)->IsBuiltin()) {
kasperl@chromium.orgdefbd102009-07-13 14:04:26 +00001446 Handle<SharedFunctionInfo> shared_info(
1447 JSFunction::cast(*holder)->shared());
1448 Debug::FloodWithOneShot(shared_info);
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001449 }
1450 } else {
1451 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1452 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001453 }
1454 }
1455}
1456
1457
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001458void Debug::ClearStepping() {
1459 // Clear the various stepping setup.
1460 ClearOneShot();
1461 ClearStepIn();
ager@chromium.orga1645e22009-09-09 19:27:10 +00001462 ClearStepOut();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001463 ClearStepNext();
1464
1465 // Clear multiple step counter.
1466 thread_local_.step_count_ = 0;
1467}
1468
1469// Clears all the one-shot break points that are currently set. Normally this
1470// function is called each time a break point is hit as one shot break points
1471// are used to support stepping.
1472void Debug::ClearOneShot() {
1473 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001474 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001475 // removed from the list.
1476
1477 DebugInfoListNode* node = debug_info_list_;
1478 while (node != NULL) {
1479 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1480 while (!it.Done()) {
1481 it.ClearOneShot();
1482 it.Next();
1483 }
1484 node = node->next();
1485 }
1486}
1487
1488
1489void Debug::ActivateStepIn(StackFrame* frame) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001490 ASSERT(!StepOutActive());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001491 thread_local_.step_into_fp_ = frame->fp();
1492}
1493
1494
1495void Debug::ClearStepIn() {
1496 thread_local_.step_into_fp_ = 0;
1497}
1498
1499
ager@chromium.orga1645e22009-09-09 19:27:10 +00001500void Debug::ActivateStepOut(StackFrame* frame) {
1501 ASSERT(!StepInActive());
1502 thread_local_.step_out_fp_ = frame->fp();
1503}
1504
1505
1506void Debug::ClearStepOut() {
1507 thread_local_.step_out_fp_ = 0;
1508}
1509
1510
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001511void Debug::ClearStepNext() {
1512 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001513 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001514 thread_local_.last_fp_ = 0;
1515}
1516
1517
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001518// Ensures the debug information is present for shared.
1519bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1520 // Return if we already have the debug info for shared.
1521 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001522
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001523 // Ensure shared in compiled. Return false if this failed.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001524 if (!EnsureCompiled(shared, CLEAR_EXCEPTION)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001525
1526 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001527 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001528
1529 // Add debug info to the list.
1530 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1531 node->set_next(debug_info_list_);
1532 debug_info_list_ = node;
1533
1534 // Now there is at least one break point.
1535 has_break_points_ = true;
1536
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001537 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001538}
1539
1540
1541void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1542 ASSERT(debug_info_list_ != NULL);
1543 // Run through the debug info objects to find this one and remove it.
1544 DebugInfoListNode* prev = NULL;
1545 DebugInfoListNode* current = debug_info_list_;
1546 while (current != NULL) {
1547 if (*current->debug_info() == *debug_info) {
1548 // Unlink from list. If prev is NULL we are looking at the first element.
1549 if (prev == NULL) {
1550 debug_info_list_ = current->next();
1551 } else {
1552 prev->set_next(current->next());
1553 }
1554 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1555 delete current;
1556
1557 // If there are no more debug info objects there are not more break
1558 // points.
1559 has_break_points_ = debug_info_list_ != NULL;
1560
1561 return;
1562 }
1563 // Move to next in list.
1564 prev = current;
1565 current = current->next();
1566 }
1567 UNREACHABLE();
1568}
1569
1570
1571void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001572 HandleScope scope;
1573
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001574 // Get the executing function in which the debug break occurred.
1575 Handle<SharedFunctionInfo> shared =
1576 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001577 if (!EnsureDebugInfo(shared)) {
1578 // Return if we failed to retrieve the debug info.
1579 return;
1580 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001581 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1582 Handle<Code> code(debug_info->code());
1583 Handle<Code> original_code(debug_info->original_code());
1584#ifdef DEBUG
1585 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001586 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001587 ASSERT(frame_code.is_identical_to(code));
1588#endif
1589
1590 // Find the call address in the running code. This address holds the call to
1591 // either a DebugBreakXXX or to the debug break return entry code if the
1592 // break point is still active after processing the break point.
ager@chromium.org4af710e2009-09-15 12:20:11 +00001593 Address addr = frame->pc() - Assembler::kCallTargetAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001594
1595 // Check if the location is at JS exit.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001596 bool at_js_return = false;
1597 bool break_at_js_return_active = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001598 RelocIterator it(debug_info->code());
1599 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001600 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
ager@chromium.orga1645e22009-09-09 19:27:10 +00001601 at_js_return = (it.rinfo()->pc() ==
1602 addr - Assembler::kPatchReturnSequenceAddressOffset);
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00001603 break_at_js_return_active = it.rinfo()->IsPatchedReturnSequence();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001604 }
1605 it.next();
1606 }
1607
1608 // Handle the jump to continue execution after break point depending on the
1609 // break location.
ager@chromium.orga1645e22009-09-09 19:27:10 +00001610 if (at_js_return) {
1611 // If the break point as return is still active jump to the corresponding
1612 // place in the original code. If not the break point was removed during
1613 // break point processing.
1614 if (break_at_js_return_active) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001615 addr += original_code->instruction_start() - code->instruction_start();
1616 }
1617
sgjesse@chromium.org911335c2009-08-19 12:59:44 +00001618 // Move back to where the call instruction sequence started.
1619 thread_local_.after_break_target_ =
1620 addr - Assembler::kPatchReturnSequenceAddressOffset;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621 } else {
1622 // Check if there still is a debug break call at the target address. If the
1623 // break point has been removed it will have disappeared. If it have
1624 // disappeared don't try to look in the original code as the running code
1625 // will have the right address. This takes care of the case where the last
1626 // break point is removed from the function and therefore no "original code"
1627 // is available. If the debug break call is still there find the address in
1628 // the original code.
1629 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1630 // If the break point is still there find the call address which was
1631 // overwritten in the original code by the call to DebugBreakXXX.
1632
1633 // Find the corresponding address in the original code.
1634 addr += original_code->instruction_start() - code->instruction_start();
1635 }
1636
1637 // Install jump to the call address in the original code. This will be the
1638 // call which was overwritten by the call to DebugBreakXXX.
1639 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1640 }
1641}
1642
1643
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001644bool Debug::IsDebugGlobal(GlobalObject* global) {
1645 return IsLoaded() && global == Debug::debug_context()->global();
1646}
1647
1648
ager@chromium.org32912102009-01-16 10:38:43 +00001649void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001650 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001651 ASSERT(Top::context() == *Debug::debug_context());
1652
1653 // Clear the mirror cache.
1654 Handle<String> function_name =
1655 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1656 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1657 ASSERT(fun->IsJSFunction());
1658 bool caught_exception;
1659 Handle<Object> js_object = Execution::TryCall(
1660 Handle<JSFunction>::cast(fun),
1661 Handle<JSObject>(Debug::debug_context()->global()),
1662 0, NULL, &caught_exception);
1663}
1664
1665
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001666void Debug::CreateScriptCache() {
1667 HandleScope scope;
1668
1669 // Perform two GCs to get rid of all unreferenced scripts. The first GC gets
1670 // rid of all the cached script wrappers and the second gets rid of the
1671 // scripts which is no longer referenced.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001672 Heap::CollectAllGarbage(false);
1673 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001674
1675 ASSERT(script_cache_ == NULL);
1676 script_cache_ = new ScriptCache();
1677
1678 // Scan heap for Script objects.
1679 int count = 0;
1680 HeapIterator iterator;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001681 for (HeapObject* obj = iterator.next(); obj != NULL; obj = iterator.next()) {
sgjesse@chromium.org152a0b02009-10-07 13:50:16 +00001682 if (obj->IsScript() && Script::cast(obj)->HasValidSource()) {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001683 script_cache_->Add(Handle<Script>(Script::cast(obj)));
1684 count++;
1685 }
1686 }
1687}
1688
1689
1690void Debug::DestroyScriptCache() {
1691 // Get rid of the script cache if it was created.
1692 if (script_cache_ != NULL) {
1693 delete script_cache_;
1694 script_cache_ = NULL;
1695 }
1696}
1697
1698
1699void Debug::AddScriptToScriptCache(Handle<Script> script) {
1700 if (script_cache_ != NULL) {
1701 script_cache_->Add(script);
1702 }
1703}
1704
1705
1706Handle<FixedArray> Debug::GetLoadedScripts() {
1707 // Create and fill the script cache when the loaded scripts is requested for
1708 // the first time.
1709 if (script_cache_ == NULL) {
1710 CreateScriptCache();
1711 }
1712
1713 // If the script cache is not active just return an empty array.
1714 ASSERT(script_cache_ != NULL);
1715 if (script_cache_ == NULL) {
1716 Factory::NewFixedArray(0);
1717 }
1718
1719 // Perform GC to get unreferenced scripts evicted from the cache before
1720 // returning the content.
ager@chromium.orgab99eea2009-08-25 07:05:41 +00001721 Heap::CollectAllGarbage(false);
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001722
1723 // Get the scripts from the cache.
1724 return script_cache_->GetScripts();
1725}
1726
1727
1728void Debug::AfterGarbageCollection() {
1729 // Generate events for collected scripts.
1730 if (script_cache_ != NULL) {
1731 script_cache_->ProcessCollectedScripts();
1732 }
1733}
1734
1735
ager@chromium.org71daaf62009-04-01 07:22:49 +00001736Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001737Handle<Object> Debugger::event_listener_ = Handle<Object>();
1738Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001739bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001740bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001741bool Debugger::never_unload_debugger_ = false;
ager@chromium.org5ec48922009-05-05 07:25:34 +00001742v8::Debug::MessageHandler2 Debugger::message_handler_ = NULL;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001743bool Debugger::debugger_unload_pending_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001744v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001745Mutex* Debugger::dispatch_handler_access_ = OS::CreateMutex();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00001746v8::Debug::DebugMessageDispatchHandler
1747 Debugger::debug_message_dispatch_handler_ = NULL;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00001748MessageDispatchHelperThread* Debugger::message_dispatch_helper_thread_ = NULL;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001749int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001750DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001751LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001752Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001753
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001754
1755Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1756 int argc, Object*** argv,
1757 bool* caught_exception) {
1758 ASSERT(Top::context() == *Debug::debug_context());
1759
1760 // Create the execution state object.
1761 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1762 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1763 ASSERT(constructor->IsJSFunction());
1764 if (!constructor->IsJSFunction()) {
1765 *caught_exception = true;
1766 return Factory::undefined_value();
1767 }
1768 Handle<Object> js_object = Execution::TryCall(
1769 Handle<JSFunction>::cast(constructor),
1770 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1771 caught_exception);
1772 return js_object;
1773}
1774
1775
1776Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1777 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001778 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001779 const int argc = 1;
1780 Object** argv[argc] = { break_id.location() };
1781 return MakeJSObject(CStrVector("MakeExecutionState"),
1782 argc, argv, caught_exception);
1783}
1784
1785
1786Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1787 Handle<Object> break_points_hit,
1788 bool* caught_exception) {
1789 // Create the new break event object.
1790 const int argc = 2;
1791 Object** argv[argc] = { exec_state.location(),
1792 break_points_hit.location() };
1793 return MakeJSObject(CStrVector("MakeBreakEvent"),
1794 argc,
1795 argv,
1796 caught_exception);
1797}
1798
1799
1800Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1801 Handle<Object> exception,
1802 bool uncaught,
1803 bool* caught_exception) {
1804 // Create the new exception event object.
1805 const int argc = 3;
1806 Object** argv[argc] = { exec_state.location(),
1807 exception.location(),
1808 uncaught ? Factory::true_value().location() :
1809 Factory::false_value().location()};
1810 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1811 argc, argv, caught_exception);
1812}
1813
1814
1815Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1816 bool* caught_exception) {
1817 // Create the new function event object.
1818 const int argc = 1;
1819 Object** argv[argc] = { function.location() };
1820 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1821 argc, argv, caught_exception);
1822}
1823
1824
1825Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001826 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001827 bool* caught_exception) {
1828 // Create the compile event object.
1829 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001830 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001831 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001832 Object** argv[argc] = { exec_state.location(),
1833 script_wrapper.location(),
1834 before ? Factory::true_value().location() :
1835 Factory::false_value().location() };
1836
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001837 return MakeJSObject(CStrVector("MakeCompileEvent"),
1838 argc,
1839 argv,
1840 caught_exception);
1841}
1842
1843
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001844Handle<Object> Debugger::MakeScriptCollectedEvent(int id,
1845 bool* caught_exception) {
1846 // Create the script collected event object.
1847 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1848 Handle<Object> id_object = Handle<Smi>(Smi::FromInt(id));
1849 const int argc = 2;
1850 Object** argv[argc] = { exec_state.location(), id_object.location() };
1851
1852 return MakeJSObject(CStrVector("MakeScriptCollectedEvent"),
1853 argc,
1854 argv,
1855 caught_exception);
1856}
1857
1858
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1860 HandleScope scope;
1861
1862 // Bail out based on state or if there is no listener for this event
1863 if (Debug::InDebugger()) return;
1864 if (!Debugger::EventActive(v8::Exception)) return;
1865
1866 // Bail out if exception breaks are not active
1867 if (uncaught) {
1868 // Uncaught exceptions are reported by either flags.
1869 if (!(Debug::break_on_uncaught_exception() ||
1870 Debug::break_on_exception())) return;
1871 } else {
1872 // Caught exceptions are reported is activated.
1873 if (!Debug::break_on_exception()) return;
1874 }
1875
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001876 // Enter the debugger.
1877 EnterDebugger debugger;
1878 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001879
1880 // Clear all current stepping setup.
1881 Debug::ClearStepping();
1882 // Create the event data object.
1883 bool caught_exception = false;
1884 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1885 Handle<Object> event_data;
1886 if (!caught_exception) {
1887 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1888 &caught_exception);
1889 }
1890 // Bail out and don't call debugger if exception.
1891 if (caught_exception) {
1892 return;
1893 }
1894
ager@chromium.org5ec48922009-05-05 07:25:34 +00001895 // Process debug event.
1896 ProcessDebugEvent(v8::Exception, Handle<JSObject>::cast(event_data), false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001897 // Return to continue execution from where the exception was thrown.
1898}
1899
1900
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001901void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1902 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001903 HandleScope scope;
1904
kasper.lund212ac232008-07-16 07:07:30 +00001905 // Debugger has already been entered by caller.
1906 ASSERT(Top::context() == *Debug::debug_context());
1907
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001908 // Bail out if there is no listener for this event
1909 if (!Debugger::EventActive(v8::Break)) return;
1910
1911 // Debugger must be entered in advance.
1912 ASSERT(Top::context() == *Debug::debug_context());
1913
1914 // Create the event data object.
1915 bool caught_exception = false;
1916 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1917 Handle<Object> event_data;
1918 if (!caught_exception) {
1919 event_data = MakeBreakEvent(exec_state, break_points_hit,
1920 &caught_exception);
1921 }
1922 // Bail out and don't call debugger if exception.
1923 if (caught_exception) {
1924 return;
1925 }
1926
ager@chromium.org5ec48922009-05-05 07:25:34 +00001927 // Process debug event.
1928 ProcessDebugEvent(v8::Break,
1929 Handle<JSObject>::cast(event_data),
1930 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001931}
1932
1933
1934void Debugger::OnBeforeCompile(Handle<Script> script) {
1935 HandleScope scope;
1936
1937 // Bail out based on state or if there is no listener for this event
1938 if (Debug::InDebugger()) return;
1939 if (compiling_natives()) return;
1940 if (!EventActive(v8::BeforeCompile)) return;
1941
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001942 // Enter the debugger.
1943 EnterDebugger debugger;
1944 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001945
1946 // Create the event data object.
1947 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001948 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001949 // Bail out and don't call debugger if exception.
1950 if (caught_exception) {
1951 return;
1952 }
1953
ager@chromium.org5ec48922009-05-05 07:25:34 +00001954 // Process debug event.
1955 ProcessDebugEvent(v8::BeforeCompile,
1956 Handle<JSObject>::cast(event_data),
1957 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001958}
1959
1960
1961// Handle debugger actions when a new script is compiled.
1962void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001963 HandleScope scope;
1964
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001965 // Add the newly compiled script to the script cache.
1966 Debug::AddScriptToScriptCache(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001967
1968 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001969 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001970
kasperl@chromium.org71affb52009-05-26 05:44:31 +00001971 // No compile events while compiling natives.
1972 if (compiling_natives()) return;
1973
iposva@chromium.org245aa852009-02-10 00:49:54 +00001974 // Store whether in debugger before entering debugger.
1975 bool in_debugger = Debug::InDebugger();
1976
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001977 // Enter the debugger.
1978 EnterDebugger debugger;
1979 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001980
1981 // If debugging there might be script break points registered for this
1982 // script. Make sure that these break points are set.
1983
1984 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1985 Handle<Object> update_script_break_points =
1986 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1987 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1988 if (!update_script_break_points->IsJSFunction()) {
1989 return;
1990 }
1991 ASSERT(update_script_break_points->IsJSFunction());
1992
1993 // Wrap the script object in a proper JS object before passing it
1994 // to JavaScript.
1995 Handle<JSValue> wrapper = GetScriptWrapper(script);
1996
1997 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001998 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001999 const int argc = 1;
2000 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
2001 Handle<Object> result = Execution::TryCall(
2002 Handle<JSFunction>::cast(update_script_break_points),
2003 Top::builtins(), argc, argv,
2004 &caught_exception);
2005 if (caught_exception) {
2006 return;
2007 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002008 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00002009 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002010 if (!Debugger::EventActive(v8::AfterCompile)) return;
2011
2012 // Create the compile state object.
2013 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00002014 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002015 &caught_exception);
2016 // Bail out and don't call debugger if exception.
2017 if (caught_exception) {
2018 return;
2019 }
ager@chromium.org5ec48922009-05-05 07:25:34 +00002020 // Process debug event.
2021 ProcessDebugEvent(v8::AfterCompile,
2022 Handle<JSObject>::cast(event_data),
2023 true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002024}
2025
2026
2027void Debugger::OnNewFunction(Handle<JSFunction> function) {
2028 return;
2029 HandleScope scope;
2030
2031 // Bail out based on state or if there is no listener for this event
2032 if (Debug::InDebugger()) return;
2033 if (compiling_natives()) return;
2034 if (!Debugger::EventActive(v8::NewFunction)) return;
2035
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00002036 // Enter the debugger.
2037 EnterDebugger debugger;
2038 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002039
2040 // Create the event object.
2041 bool caught_exception = false;
2042 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
2043 // Bail out and don't call debugger if exception.
2044 if (caught_exception) {
2045 return;
2046 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002047 // Process debug event.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002048 ProcessDebugEvent(v8::NewFunction, Handle<JSObject>::cast(event_data), true);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002049}
2050
2051
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002052void Debugger::OnScriptCollected(int id) {
2053 HandleScope scope;
2054
2055 // No more to do if not debugging.
2056 if (!IsDebuggerActive()) return;
2057 if (!Debugger::EventActive(v8::ScriptCollected)) return;
2058
2059 // Enter the debugger.
2060 EnterDebugger debugger;
2061 if (debugger.FailedToEnter()) return;
2062
2063 // Create the script collected state object.
2064 bool caught_exception = false;
2065 Handle<Object> event_data = MakeScriptCollectedEvent(id,
2066 &caught_exception);
2067 // Bail out and don't call debugger if exception.
2068 if (caught_exception) {
2069 return;
2070 }
2071
2072 // Process debug event.
2073 ProcessDebugEvent(v8::ScriptCollected,
2074 Handle<JSObject>::cast(event_data),
2075 true);
2076}
2077
2078
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002079void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002080 Handle<JSObject> event_data,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002081 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002082 HandleScope scope;
2083
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002084 // Clear any pending debug break if this is a real break.
2085 if (!auto_continue) {
2086 Debug::clear_interrupt_pending(DEBUGBREAK);
2087 }
2088
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002089 // Create the execution state.
2090 bool caught_exception = false;
2091 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2092 if (caught_exception) {
2093 return;
2094 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002095 // First notify the message handler if any.
2096 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002097 NotifyMessageHandler(event,
2098 Handle<JSObject>::cast(exec_state),
2099 event_data,
2100 auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002101 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00002102 // Notify registered debug event listener. This can be either a C or a
2103 // JavaScript function.
2104 if (!event_listener_.is_null()) {
2105 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002106 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002107 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002108 v8::Debug::EventCallback callback =
2109 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002110 callback(event,
2111 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002112 v8::Utils::ToLocal(event_data),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002113 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002114 } else {
2115 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00002116 ASSERT(event_listener_->IsJSFunction());
2117 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002118
2119 // Invoke the JavaScript debug event listener.
2120 const int argc = 4;
2121 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
2122 exec_state.location(),
ager@chromium.org5ec48922009-05-05 07:25:34 +00002123 Handle<Object>::cast(event_data).location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00002124 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002125 Handle<Object> result = Execution::TryCall(fun, Top::global(),
2126 argc, argv, &caught_exception);
ager@chromium.org18ad94b2009-09-02 08:22:29 +00002127 // Silently ignore exceptions from debug event listeners.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002128 }
2129 }
2130}
2131
2132
ager@chromium.org71daaf62009-04-01 07:22:49 +00002133void Debugger::UnloadDebugger() {
2134 // Make sure that there are no breakpoints left.
2135 Debug::ClearAllBreakPoints();
2136
2137 // Unload the debugger if feasible.
2138 if (!never_unload_debugger_) {
2139 Debug::Unload();
2140 }
2141
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002142 // Clear the flag indicating that the debugger should be unloaded.
2143 debugger_unload_pending_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00002144}
2145
2146
ager@chromium.org41826e72009-03-30 13:30:57 +00002147void Debugger::NotifyMessageHandler(v8::DebugEvent event,
ager@chromium.org5ec48922009-05-05 07:25:34 +00002148 Handle<JSObject> exec_state,
2149 Handle<JSObject> event_data,
ager@chromium.org41826e72009-03-30 13:30:57 +00002150 bool auto_continue) {
2151 HandleScope scope;
2152
2153 if (!Debug::Load()) return;
2154
2155 // Process the individual events.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002156 bool sendEventMessage = false;
ager@chromium.org41826e72009-03-30 13:30:57 +00002157 switch (event) {
2158 case v8::Break:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002159 sendEventMessage = !auto_continue;
ager@chromium.org41826e72009-03-30 13:30:57 +00002160 break;
2161 case v8::Exception:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002162 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002163 break;
2164 case v8::BeforeCompile:
2165 break;
2166 case v8::AfterCompile:
ager@chromium.org5ec48922009-05-05 07:25:34 +00002167 sendEventMessage = true;
ager@chromium.org41826e72009-03-30 13:30:57 +00002168 break;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002169 case v8::ScriptCollected:
2170 sendEventMessage = true;
2171 break;
ager@chromium.org41826e72009-03-30 13:30:57 +00002172 case v8::NewFunction:
2173 break;
2174 default:
2175 UNREACHABLE();
2176 }
2177
ager@chromium.org5ec48922009-05-05 07:25:34 +00002178 // The debug command interrupt flag might have been set when the command was
2179 // added. It should be enough to clear the flag only once while we are in the
2180 // debugger.
2181 ASSERT(Debug::InDebugger());
2182 StackGuard::Continue(DEBUGCOMMAND);
2183
2184 // Notify the debugger that a debug event has occurred unless auto continue is
2185 // active in which case no event is send.
2186 if (sendEventMessage) {
2187 MessageImpl message = MessageImpl::NewEvent(
2188 event,
2189 auto_continue,
2190 Handle<JSObject>::cast(exec_state),
2191 Handle<JSObject>::cast(event_data));
2192 InvokeMessageHandler(message);
2193 }
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +00002194
2195 // If auto continue don't make the event cause a break, but process messages
2196 // in the queue if any. For script collected events don't even process
2197 // messages in the queue as the execution state might not be what is expected
2198 // by the client.
ager@chromium.org6ffc2172009-05-29 19:20:16 +00002199 if ((auto_continue && !HasCommands()) || event == v8::ScriptCollected) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002200 return;
2201 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002202
ager@chromium.org41826e72009-03-30 13:30:57 +00002203 v8::TryCatch try_catch;
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002204
2205 // DebugCommandProcessor goes here.
2206 v8::Local<v8::Object> cmd_processor;
2207 {
2208 v8::Local<v8::Object> api_exec_state =
2209 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
2210 v8::Local<v8::String> fun_name =
2211 v8::String::New("debugCommandProcessor");
2212 v8::Local<v8::Function> fun =
2213 v8::Function::Cast(*api_exec_state->Get(fun_name));
2214
2215 v8::Handle<v8::Boolean> running =
2216 auto_continue ? v8::True() : v8::False();
2217 static const int kArgc = 1;
2218 v8::Handle<Value> argv[kArgc] = { running };
2219 cmd_processor = v8::Object::Cast(*fun->Call(api_exec_state, kArgc, argv));
2220 if (try_catch.HasCaught()) {
2221 PrintLn(try_catch.Exception());
2222 return;
2223 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002224 }
2225
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002226 bool running = auto_continue;
2227
ager@chromium.org41826e72009-03-30 13:30:57 +00002228 // Process requests from the debugger.
2229 while (true) {
2230 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002231 if (Debugger::host_dispatch_handler_) {
2232 // In case there is a host dispatch - do periodic dispatches.
2233 if (!command_received_->Wait(host_dispatch_micros_)) {
2234 // Timout expired, do the dispatch.
2235 Debugger::host_dispatch_handler_();
2236 continue;
2237 }
2238 } else {
2239 // In case there is no host dispatch - just wait.
2240 command_received_->Wait();
2241 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002242
ager@chromium.org41826e72009-03-30 13:30:57 +00002243 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002244 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00002245 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00002246 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002247 // Delete command text and user data.
2248 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002249 return;
2250 }
2251
ager@chromium.org41826e72009-03-30 13:30:57 +00002252 // Invoke JavaScript to process the debug request.
2253 v8::Local<v8::String> fun_name;
2254 v8::Local<v8::Function> fun;
2255 v8::Local<v8::Value> request;
2256 v8::TryCatch try_catch;
2257 fun_name = v8::String::New("processDebugRequest");
2258 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002259
2260 request = v8::String::New(command.text().start(),
2261 command.text().length());
ager@chromium.org41826e72009-03-30 13:30:57 +00002262 static const int kArgc = 1;
2263 v8::Handle<Value> argv[kArgc] = { request };
2264 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
2265
2266 // Get the response.
2267 v8::Local<v8::String> response;
ager@chromium.org41826e72009-03-30 13:30:57 +00002268 if (!try_catch.HasCaught()) {
2269 // Get response string.
2270 if (!response_val->IsUndefined()) {
2271 response = v8::String::Cast(*response_val);
2272 } else {
2273 response = v8::String::New("");
2274 }
2275
2276 // Log the JSON request/response.
2277 if (FLAG_trace_debug_json) {
2278 PrintLn(request);
2279 PrintLn(response);
2280 }
2281
2282 // Get the running state.
2283 fun_name = v8::String::New("isRunning");
2284 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
2285 static const int kArgc = 1;
2286 v8::Handle<Value> argv[kArgc] = { response };
2287 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
2288 if (!try_catch.HasCaught()) {
2289 running = running_val->ToBoolean()->Value();
2290 }
2291 } else {
2292 // In case of failure the result text is the exception text.
2293 response = try_catch.Exception()->ToString();
2294 }
2295
ager@chromium.org41826e72009-03-30 13:30:57 +00002296 // Return the result.
ager@chromium.org5ec48922009-05-05 07:25:34 +00002297 MessageImpl message = MessageImpl::NewResponse(
2298 event,
2299 running,
2300 Handle<JSObject>::cast(exec_state),
2301 Handle<JSObject>::cast(event_data),
2302 Handle<String>(Utils::OpenHandle(*response)),
2303 command.client_data());
2304 InvokeMessageHandler(message);
2305 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00002306
2307 // Return from debug event processing if either the VM is put into the
2308 // runnning state (through a continue command) or auto continue is active
2309 // and there are no more commands queued.
christian.plesner.hansen@gmail.com9d58c2b2009-10-16 11:48:38 +00002310 if (running && !HasCommands()) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002311 return;
2312 }
2313 }
2314}
2315
2316
iposva@chromium.org245aa852009-02-10 00:49:54 +00002317void Debugger::SetEventListener(Handle<Object> callback,
2318 Handle<Object> data) {
2319 HandleScope scope;
2320
2321 // Clear the global handles for the event listener and the event listener data
2322 // object.
2323 if (!event_listener_.is_null()) {
2324 GlobalHandles::Destroy(
2325 reinterpret_cast<Object**>(event_listener_.location()));
2326 event_listener_ = Handle<Object>();
2327 }
2328 if (!event_listener_data_.is_null()) {
2329 GlobalHandles::Destroy(
2330 reinterpret_cast<Object**>(event_listener_data_.location()));
2331 event_listener_data_ = Handle<Object>();
2332 }
2333
2334 // If there is a new debug event listener register it together with its data
2335 // object.
2336 if (!callback->IsUndefined() && !callback->IsNull()) {
2337 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
2338 if (data.is_null()) {
2339 data = Factory::undefined_value();
2340 }
2341 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
2342 }
2343
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002344 ListenersChanged();
iposva@chromium.org245aa852009-02-10 00:49:54 +00002345}
2346
2347
ager@chromium.org5ec48922009-05-05 07:25:34 +00002348void Debugger::SetMessageHandler(v8::Debug::MessageHandler2 handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002349 ScopedLock with(debugger_access_);
2350
ager@chromium.org381abbb2009-02-25 13:23:22 +00002351 message_handler_ = handler;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002352 ListenersChanged();
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002353 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002354 // Send an empty command to the debugger if in a break to make JavaScript
2355 // run again if the debugger is closed.
2356 if (Debug::InDebugger()) {
2357 ProcessCommand(Vector<const uint16_t>::empty());
2358 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002359 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002360}
2361
2362
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002363void Debugger::ListenersChanged() {
2364 if (IsDebuggerActive()) {
2365 // Disable the compilation cache when the debugger is active.
2366 CompilationCache::Disable();
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002367 debugger_unload_pending_ = false;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002368 } else {
2369 CompilationCache::Enable();
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002370 // Unload the debugger if event listener and message handler cleared.
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002371 // Schedule this for later, because we may be in non-V8 thread.
2372 debugger_unload_pending_ = true;
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002373 }
2374}
2375
2376
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002377void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
2378 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00002379 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002380 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00002381}
2382
2383
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002384void Debugger::SetDebugMessageDispatchHandler(
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002385 v8::Debug::DebugMessageDispatchHandler handler, bool provide_locker) {
2386 ScopedLock with(dispatch_handler_access_);
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002387 debug_message_dispatch_handler_ = handler;
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002388
2389 if (provide_locker && message_dispatch_helper_thread_ == NULL) {
2390 message_dispatch_helper_thread_ = new MessageDispatchHelperThread;
2391 message_dispatch_helper_thread_->Start();
2392 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002393}
2394
2395
ager@chromium.org41826e72009-03-30 13:30:57 +00002396// Calls the registered debug message handler. This callback is part of the
ager@chromium.org5ec48922009-05-05 07:25:34 +00002397// public API.
2398void Debugger::InvokeMessageHandler(MessageImpl message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002399 ScopedLock with(debugger_access_);
2400
ager@chromium.org381abbb2009-02-25 13:23:22 +00002401 if (message_handler_ != NULL) {
ager@chromium.org5ec48922009-05-05 07:25:34 +00002402 message_handler_(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002403 }
ager@chromium.org41826e72009-03-30 13:30:57 +00002404}
2405
2406
2407// Puts a command coming from the public API on the queue. Creates
2408// a copy of the command string managed by the debugger. Up to this
2409// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002410// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002411void Debugger::ProcessCommand(Vector<const uint16_t> command,
2412 v8::Debug::ClientData* client_data) {
2413 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002414 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002415 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002416 command.length()),
2417 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002418 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002419 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002420 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002421
2422 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002423 if (!Debug::InDebugger()) {
2424 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002425 }
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002426
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002427 MessageDispatchHelperThread* dispatch_thread;
2428 {
2429 ScopedLock with(dispatch_handler_access_);
2430 dispatch_thread = message_dispatch_helper_thread_;
2431 }
2432
2433 if (dispatch_thread == NULL) {
2434 CallMessageDispatchHandler();
2435 } else {
2436 dispatch_thread->Schedule();
ager@chromium.orgc4c92722009-11-18 14:12:51 +00002437 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002438}
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
fschneider@chromium.org0c20e672010-01-14 15:28:53 +00002480static void StubMessageHandler2(const v8::Debug::Message& message) {
2481 // Simply ignore message.
2482}
2483
2484
2485bool Debugger::StartAgent(const char* name, int port,
2486 bool wait_for_connection) {
2487 if (wait_for_connection) {
2488 // Suspend V8 if it is already running or set V8 to suspend whenever
2489 // it starts.
2490 // Provide stub message handler; V8 auto-continues each suspend
2491 // when there is no message handler; we doesn't need it.
2492 // Once become suspended, V8 will stay so indefinitely long, until remote
2493 // debugger connects and issues "continue" command.
2494 Debugger::message_handler_ = StubMessageHandler2;
2495 v8::Debug::DebugBreak();
2496 }
2497
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002498 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002499 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002500 agent_->Start();
2501 return true;
2502 }
2503
2504 return false;
2505}
2506
2507
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002508void Debugger::StopAgent() {
2509 if (agent_ != NULL) {
2510 agent_->Shutdown();
2511 agent_->Join();
2512 delete agent_;
2513 agent_ = NULL;
2514 }
2515}
2516
2517
sgjesse@chromium.orgc5145742009-10-07 09:00:33 +00002518void Debugger::WaitForAgent() {
2519 if (agent_ != NULL)
2520 agent_->WaitUntilListening();
2521}
2522
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002523
2524void Debugger::CallMessageDispatchHandler() {
2525 v8::Debug::DebugMessageDispatchHandler handler;
2526 {
2527 ScopedLock with(dispatch_handler_access_);
2528 handler = Debugger::debug_message_dispatch_handler_;
2529 }
2530 if (handler != NULL) {
2531 handler();
2532 }
2533}
2534
2535
ager@chromium.org5ec48922009-05-05 07:25:34 +00002536MessageImpl MessageImpl::NewEvent(DebugEvent event,
2537 bool running,
2538 Handle<JSObject> exec_state,
2539 Handle<JSObject> event_data) {
2540 MessageImpl message(true, event, running,
2541 exec_state, event_data, Handle<String>(), NULL);
2542 return message;
2543}
2544
2545
2546MessageImpl MessageImpl::NewResponse(DebugEvent event,
2547 bool running,
2548 Handle<JSObject> exec_state,
2549 Handle<JSObject> event_data,
2550 Handle<String> response_json,
2551 v8::Debug::ClientData* client_data) {
2552 MessageImpl message(false, event, running,
2553 exec_state, event_data, response_json, client_data);
2554 return message;
2555}
2556
2557
2558MessageImpl::MessageImpl(bool is_event,
2559 DebugEvent event,
2560 bool running,
2561 Handle<JSObject> exec_state,
2562 Handle<JSObject> event_data,
2563 Handle<String> response_json,
2564 v8::Debug::ClientData* client_data)
2565 : is_event_(is_event),
2566 event_(event),
2567 running_(running),
2568 exec_state_(exec_state),
2569 event_data_(event_data),
2570 response_json_(response_json),
2571 client_data_(client_data) {}
2572
2573
2574bool MessageImpl::IsEvent() const {
2575 return is_event_;
2576}
2577
2578
2579bool MessageImpl::IsResponse() const {
2580 return !is_event_;
2581}
2582
2583
2584DebugEvent MessageImpl::GetEvent() const {
2585 return event_;
2586}
2587
2588
2589bool MessageImpl::WillStartRunning() const {
2590 return running_;
2591}
2592
2593
2594v8::Handle<v8::Object> MessageImpl::GetExecutionState() const {
2595 return v8::Utils::ToLocal(exec_state_);
2596}
2597
2598
2599v8::Handle<v8::Object> MessageImpl::GetEventData() const {
2600 return v8::Utils::ToLocal(event_data_);
2601}
2602
2603
2604v8::Handle<v8::String> MessageImpl::GetJSON() const {
2605 v8::HandleScope scope;
2606
2607 if (IsEvent()) {
2608 // Call toJSONProtocol on the debug event object.
2609 Handle<Object> fun = GetProperty(event_data_, "toJSONProtocol");
2610 if (!fun->IsJSFunction()) {
2611 return v8::Handle<v8::String>();
2612 }
2613 bool caught_exception;
2614 Handle<Object> json = Execution::TryCall(Handle<JSFunction>::cast(fun),
2615 event_data_,
2616 0, NULL, &caught_exception);
2617 if (caught_exception || !json->IsString()) {
2618 return v8::Handle<v8::String>();
2619 }
2620 return scope.Close(v8::Utils::ToLocal(Handle<String>::cast(json)));
2621 } else {
2622 return v8::Utils::ToLocal(response_json_);
2623 }
2624}
2625
2626
2627v8::Handle<v8::Context> MessageImpl::GetEventContext() const {
kasperl@chromium.org71affb52009-05-26 05:44:31 +00002628 Handle<Context> context = Debug::debugger_entry()->GetContext();
2629 // Top::context() may have been NULL when "script collected" event occured.
2630 if (*context == NULL) {
2631 ASSERT(event_ == v8::ScriptCollected);
2632 return v8::Local<v8::Context>();
2633 }
2634 Handle<Context> global_context(context->global_context());
2635 return v8::Utils::ToLocal(global_context);
ager@chromium.org5ec48922009-05-05 07:25:34 +00002636}
2637
2638
2639v8::Debug::ClientData* MessageImpl::GetClientData() const {
2640 return client_data_;
2641}
2642
2643
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002644CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2645 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002646}
2647
2648
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002649CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2650 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002651 : text_(text),
2652 client_data_(data) {
2653}
2654
2655
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002656CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002657}
2658
2659
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002660void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002661 text_.Dispose();
2662 delete client_data_;
2663 client_data_ = NULL;
2664}
2665
2666
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002667CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2668 v8::Debug::ClientData* data) {
2669 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002670}
2671
2672
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002673CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2674 size_(size) {
2675 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002676}
2677
2678
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002679CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002680 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002681 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002682 m.Dispose();
2683 }
kasper.lund7276f142008-07-30 08:49:36 +00002684 DeleteArray(messages_);
2685}
2686
2687
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002688CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002689 ASSERT(!IsEmpty());
2690 int result = start_;
2691 start_ = (start_ + 1) % size_;
2692 return messages_[result];
2693}
2694
2695
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002696void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002697 if ((end_ + 1) % size_ == start_) {
2698 Expand();
2699 }
2700 messages_[end_] = message;
2701 end_ = (end_ + 1) % size_;
2702}
2703
2704
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002705void CommandMessageQueue::Expand() {
2706 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002707 while (!IsEmpty()) {
2708 new_queue.Put(Get());
2709 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002710 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002711 *this = new_queue;
2712 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002713 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2714 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002715 // Automatic destructor called on new_queue, freeing array_to_free.
2716}
2717
2718
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002719LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2720 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002721 lock_ = OS::CreateMutex();
2722}
2723
2724
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002725LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002726 delete lock_;
2727}
2728
2729
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002730bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002731 ScopedLock sl(lock_);
2732 return queue_.IsEmpty();
2733}
2734
2735
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002736CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002737 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002738 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002739 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002740 return result;
2741}
2742
2743
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002744void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002745 ScopedLock sl(lock_);
2746 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002747 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002748}
2749
2750
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002751void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002752 ScopedLock sl(lock_);
2753 queue_.Clear();
2754}
2755
sgjesse@chromium.orgb302e562010-02-03 11:26:59 +00002756
2757MessageDispatchHelperThread::MessageDispatchHelperThread()
2758 : sem_(OS::CreateSemaphore(0)), mutex_(OS::CreateMutex()),
2759 already_signalled_(false) {
2760}
2761
2762
2763MessageDispatchHelperThread::~MessageDispatchHelperThread() {
2764 delete mutex_;
2765 delete sem_;
2766}
2767
2768
2769void MessageDispatchHelperThread::Schedule() {
2770 {
2771 ScopedLock lock(mutex_);
2772 if (already_signalled_) {
2773 return;
2774 }
2775 already_signalled_ = true;
2776 }
2777 sem_->Signal();
2778}
2779
2780
2781void MessageDispatchHelperThread::Run() {
2782 while (true) {
2783 sem_->Wait();
2784 {
2785 ScopedLock lock(mutex_);
2786 already_signalled_ = false;
2787 }
2788 {
2789 Locker locker;
2790 Debugger::CallMessageDispatchHandler();
2791 }
2792 }
2793}
2794
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002795#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002796
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002797} } // namespace v8::internal