blob: 32a96a83a5be4c981e30b3801686d98b7a0bac4d [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"
34#include "compiler.h"
35#include "debug.h"
36#include "execution.h"
37#include "global-handles.h"
ager@chromium.org65dad4b2009-04-23 08:48:43 +000038#include "ic.h"
39#include "ic-inl.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000040#include "natives.h"
41#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000042#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000043
44namespace v8 { namespace internal {
45
ager@chromium.org65dad4b2009-04-23 08:48:43 +000046#ifdef ENABLE_DEBUGGER_SUPPORT
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000047static void PrintLn(v8::Local<v8::Value> value) {
48 v8::Local<v8::String> s = value->ToString();
49 char* data = NewArray<char>(s->Length() + 1);
50 if (data == NULL) {
51 V8::FatalProcessOutOfMemory("PrintLn");
52 return;
53 }
54 s->WriteAscii(data);
55 PrintF("%s\n", data);
56 DeleteArray(data);
57}
58
59
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000060static Handle<Code> ComputeCallDebugBreak(int argc) {
61 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
62}
63
64
65static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
66 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
67}
68
69
70BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
71 BreakLocatorType type) {
72 debug_info_ = debug_info;
73 type_ = type;
74 reloc_iterator_ = NULL;
75 reloc_iterator_original_ = NULL;
76 Reset(); // Initialize the rest of the member variables.
77}
78
79
80BreakLocationIterator::~BreakLocationIterator() {
81 ASSERT(reloc_iterator_ != NULL);
82 ASSERT(reloc_iterator_original_ != NULL);
83 delete reloc_iterator_;
84 delete reloc_iterator_original_;
85}
86
87
88void BreakLocationIterator::Next() {
89 AssertNoAllocation nogc;
90 ASSERT(!RinfoDone());
91
92 // Iterate through reloc info for code and original code stopping at each
93 // breakable code target.
94 bool first = break_point_ == -1;
95 while (!RinfoDone()) {
96 if (!first) RinfoNext();
97 first = false;
98 if (RinfoDone()) return;
99
ager@chromium.org236ad962008-09-25 09:45:57 +0000100 // Whenever a statement position or (plain) position is passed update the
101 // current value of these.
102 if (RelocInfo::IsPosition(rmode())) {
103 if (RelocInfo::IsStatementPosition(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000104 statement_position_ =
105 rinfo()->data() - debug_info_->shared()->start_position();
106 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000107 // Always update the position as we don't want that to be before the
108 // statement position.
109 position_ = rinfo()->data() - debug_info_->shared()->start_position();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000110 ASSERT(position_ >= 0);
111 ASSERT(statement_position_ >= 0);
112 }
113
114 // Check for breakable code target. Look in the original code as setting
115 // break points can cause the code targets in the running (debugged) code to
116 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000117 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000118 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000119 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.org236ad962008-09-25 09:45:57 +0000120 if (code->is_inline_cache_stub() || RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000121 break_point_++;
122 return;
123 }
124 if (code->kind() == Code::STUB) {
125 if (type_ == ALL_BREAK_LOCATIONS) {
126 if (Debug::IsBreakStub(code)) {
127 break_point_++;
128 return;
129 }
130 } else {
131 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
132 if (Debug::IsSourceBreakStub(code)) {
133 break_point_++;
134 return;
135 }
136 }
137 }
138 }
139
140 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000141 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000142 // Set the positions to the end of the function.
143 if (debug_info_->shared()->HasSourceCode()) {
144 position_ = debug_info_->shared()->end_position() -
145 debug_info_->shared()->start_position();
146 } else {
147 position_ = 0;
148 }
149 statement_position_ = position_;
150 break_point_++;
151 return;
152 }
153 }
154}
155
156
157void BreakLocationIterator::Next(int count) {
158 while (count > 0) {
159 Next();
160 count--;
161 }
162}
163
164
165// Find the break point closest to the supplied address.
166void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
167 // Run through all break points to locate the one closest to the address.
168 int closest_break_point = 0;
169 int distance = kMaxInt;
170 while (!Done()) {
171 // Check if this break point is closer that what was previously found.
172 if (this->pc() < pc && pc - this->pc() < distance) {
173 closest_break_point = break_point();
174 distance = pc - this->pc();
175 // Check whether we can't get any closer.
176 if (distance == 0) break;
177 }
178 Next();
179 }
180
181 // Move to the break point found.
182 Reset();
183 Next(closest_break_point);
184}
185
186
187// Find the break point closest to the supplied source position.
188void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
189 // Run through all break points to locate the one closest to the source
190 // position.
191 int closest_break_point = 0;
192 int distance = kMaxInt;
193 while (!Done()) {
194 // Check if this break point is closer that what was previously found.
195 if (position <= statement_position() &&
196 statement_position() - position < distance) {
197 closest_break_point = break_point();
198 distance = statement_position() - position;
199 // Check whether we can't get any closer.
200 if (distance == 0) break;
201 }
202 Next();
203 }
204
205 // Move to the break point found.
206 Reset();
207 Next(closest_break_point);
208}
209
210
211void BreakLocationIterator::Reset() {
212 // Create relocation iterators for the two code objects.
213 if (reloc_iterator_ != NULL) delete reloc_iterator_;
214 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
215 reloc_iterator_ = new RelocIterator(debug_info_->code());
216 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
217
218 // Position at the first break point.
219 break_point_ = -1;
220 position_ = 1;
221 statement_position_ = 1;
222 Next();
223}
224
225
226bool BreakLocationIterator::Done() const {
227 return RinfoDone();
228}
229
230
231void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
232 // If there is not already a real break point here patch code with debug
233 // break.
234 if (!HasBreakPoint()) {
235 SetDebugBreak();
236 }
237 ASSERT(IsDebugBreak());
238 // Set the break point information.
239 DebugInfo::SetBreakPoint(debug_info_, code_position(),
240 position(), statement_position(),
241 break_point_object);
242}
243
244
245void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
246 // Clear the break point information.
247 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
248 // If there are no more break points here remove the debug break.
249 if (!HasBreakPoint()) {
250 ClearDebugBreak();
251 ASSERT(!IsDebugBreak());
252 }
253}
254
255
256void BreakLocationIterator::SetOneShot() {
257 // If there is a real break point here no more to do.
258 if (HasBreakPoint()) {
259 ASSERT(IsDebugBreak());
260 return;
261 }
262
263 // Patch code with debug break.
264 SetDebugBreak();
265}
266
267
268void BreakLocationIterator::ClearOneShot() {
269 // If there is a real break point here no more to do.
270 if (HasBreakPoint()) {
271 ASSERT(IsDebugBreak());
272 return;
273 }
274
275 // Patch code removing debug break.
276 ClearDebugBreak();
277 ASSERT(!IsDebugBreak());
278}
279
280
281void BreakLocationIterator::SetDebugBreak() {
282 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000283 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000284 // function twice might happen when stepping in a function with an exception
285 // handler as the handler and the function is the same.
286 if (IsDebugBreak()) {
287 return;
288 }
289
ager@chromium.org236ad962008-09-25 09:45:57 +0000290 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000291 // Patch the frame exit code with a break point.
292 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000293 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000294 // Patch the IC call.
295 SetDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000296 }
297 ASSERT(IsDebugBreak());
298}
299
300
301void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000302 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000303 // Restore the frame exit code.
304 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000305 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000306 // Patch the IC call.
307 ClearDebugBreakAtIC();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000308 }
309 ASSERT(!IsDebugBreak());
310}
311
312
313void BreakLocationIterator::PrepareStepIn() {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000314 HandleScope scope;
315
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000316 // Step in can only be prepared if currently positioned on an IC call or
317 // construct call.
318 Address target = rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000319 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000320 if (code->is_call_stub()) {
321 // Step in through IC call is handled by the runtime system. Therefore make
322 // sure that the any current IC is cleared and the runtime system is
323 // called. If the executing code has a debug break at the location change
324 // the call in the original code as it is the code there that will be
325 // executed in place of the debug break call.
326 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
327 if (IsDebugBreak()) {
328 original_rinfo()->set_target_address(stub->entry());
329 } else {
330 rinfo()->set_target_address(stub->entry());
331 }
332 } else {
v8.team.kasperl727e9952008-09-02 14:56:44 +0000333 // Step in through constructs call requires no changes to the running code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000334 ASSERT(RelocInfo::IsConstructCall(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000335 }
336}
337
338
339// Check whether the break point is at a position which will exit the function.
340bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000341 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000342}
343
344
345bool BreakLocationIterator::HasBreakPoint() {
346 return debug_info_->HasBreakPoint(code_position());
347}
348
349
350// Check whether there is a debug break at the current position.
351bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000352 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000353 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000354 } else {
355 return Debug::IsDebugBreak(rinfo()->target_address());
356 }
357}
358
359
ager@chromium.org65dad4b2009-04-23 08:48:43 +0000360void BreakLocationIterator::SetDebugBreakAtIC() {
361 // Patch the original code with the current address as the current address
362 // might have changed by the inline caching since the code was copied.
363 original_rinfo()->set_target_address(rinfo()->target_address());
364
365 RelocInfo::Mode mode = rmode();
366 if (RelocInfo::IsCodeTarget(mode)) {
367 Address target = rinfo()->target_address();
368 Handle<Code> code(Code::GetCodeFromTargetAddress(target));
369
370 // Patch the code to invoke the builtin debug break function matching the
371 // calling convention used by the call site.
372 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(code, mode));
373 rinfo()->set_target_address(dbgbrk_code->entry());
374
375 // For stubs that refer back to an inlined version clear the cached map for
376 // the inlined case to always go through the IC. As long as the break point
377 // is set the patching performed by the runtime system will take place in
378 // the code copy and will therefore have no effect on the running code
379 // keeping it from using the inlined code.
380 if (code->is_keyed_load_stub() && KeyedLoadIC::HasInlinedVersion(pc())) {
381 KeyedLoadIC::ClearInlinedVersion(pc());
382 }
383 }
384}
385
386
387void BreakLocationIterator::ClearDebugBreakAtIC() {
388 // Patch the code to the original invoke.
389 rinfo()->set_target_address(original_rinfo()->target_address());
390}
391
392
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000393Object* BreakLocationIterator::BreakPointObjects() {
394 return debug_info_->GetBreakPointObjects(code_position());
395}
396
397
ager@chromium.org381abbb2009-02-25 13:23:22 +0000398// Clear out all the debug break code. This is ONLY supposed to be used when
399// shutting down the debugger as it will leave the break point information in
400// DebugInfo even though the code is patched back to the non break point state.
401void BreakLocationIterator::ClearAllDebugBreak() {
402 while (!Done()) {
403 ClearDebugBreak();
404 Next();
405 }
406}
407
408
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000409bool BreakLocationIterator::RinfoDone() const {
410 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
411 return reloc_iterator_->done();
412}
413
414
415void BreakLocationIterator::RinfoNext() {
416 reloc_iterator_->next();
417 reloc_iterator_original_->next();
418#ifdef DEBUG
419 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
420 if (!reloc_iterator_->done()) {
421 ASSERT(rmode() == original_rmode());
422 }
423#endif
424}
425
426
427bool Debug::has_break_points_ = false;
428DebugInfoListNode* Debug::debug_info_list_ = NULL;
429
430
431// Threading support.
432void Debug::ThreadInit() {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000433 thread_local_.break_count_ = 0;
434 thread_local_.break_id_ = 0;
435 thread_local_.break_frame_id_ = StackFrame::NO_ID;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000436 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000437 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000438 thread_local_.step_count_ = 0;
439 thread_local_.last_fp_ = 0;
440 thread_local_.step_into_fp_ = 0;
441 thread_local_.after_break_target_ = 0;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000442 thread_local_.debugger_entry_ = NULL;
443 thread_local_.preemption_pending_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000444}
445
446
447JSCallerSavedBuffer Debug::registers_;
448Debug::ThreadLocal Debug::thread_local_;
449
450
451char* Debug::ArchiveDebug(char* storage) {
452 char* to = storage;
453 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
454 to += sizeof(ThreadLocal);
455 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
456 ThreadInit();
457 ASSERT(to <= storage + ArchiveSpacePerThread());
458 return storage + ArchiveSpacePerThread();
459}
460
461
462char* Debug::RestoreDebug(char* storage) {
463 char* from = storage;
464 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
465 from += sizeof(ThreadLocal);
466 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
467 ASSERT(from <= storage + ArchiveSpacePerThread());
468 return storage + ArchiveSpacePerThread();
469}
470
471
472int Debug::ArchiveSpacePerThread() {
473 return sizeof(ThreadLocal) + sizeof(registers_);
474}
475
476
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000477// Default break enabled.
478bool Debug::disable_break_ = false;
479
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000480// Default call debugger on uncaught exception.
481bool Debug::break_on_exception_ = false;
482bool Debug::break_on_uncaught_exception_ = true;
483
484Handle<Context> Debug::debug_context_ = Handle<Context>();
485Code* Debug::debug_break_return_entry_ = NULL;
486Code* Debug::debug_break_return_ = NULL;
487
488
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000489void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000490 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
491 RemoveDebugInfo(node->debug_info());
492#ifdef DEBUG
493 node = Debug::debug_info_list_;
494 while (node != NULL) {
495 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
496 node = node->next();
497 }
498#endif
499}
500
501
502DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
503 // Globalize the request debug info object and make it weak.
504 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
505 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
506 this, Debug::HandleWeakDebugInfo);
507}
508
509
510DebugInfoListNode::~DebugInfoListNode() {
511 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
512}
513
514
515void Debug::Setup(bool create_heap_objects) {
516 ThreadInit();
517 if (create_heap_objects) {
518 // Get code to handle entry to debug break on return.
519 debug_break_return_entry_ =
520 Builtins::builtin(Builtins::Return_DebugBreakEntry);
521 ASSERT(debug_break_return_entry_->IsCode());
522
523 // Get code to handle debug break on return.
524 debug_break_return_ =
525 Builtins::builtin(Builtins::Return_DebugBreak);
526 ASSERT(debug_break_return_->IsCode());
527 }
528}
529
530
531bool Debug::CompileDebuggerScript(int index) {
532 HandleScope scope;
533
kasper.lund44510672008-07-25 07:37:58 +0000534 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000535 if (index == -1) {
536 return false;
537 }
kasper.lund44510672008-07-25 07:37:58 +0000538
539 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000540 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
541 Vector<const char> name = Natives::GetScriptName(index);
542 Handle<String> script_name = Factory::NewStringFromAscii(name);
543
544 // Compile the script.
545 bool allow_natives_syntax = FLAG_allow_natives_syntax;
546 FLAG_allow_natives_syntax = true;
547 Handle<JSFunction> boilerplate;
548 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL);
549 FLAG_allow_natives_syntax = allow_natives_syntax;
550
551 // Silently ignore stack overflows during compilation.
552 if (boilerplate.is_null()) {
553 ASSERT(Top::has_pending_exception());
554 Top::clear_pending_exception();
555 return false;
556 }
557
kasper.lund44510672008-07-25 07:37:58 +0000558 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000559 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000560 bool caught_exception = false;
561 Handle<JSFunction> function =
562 Factory::NewFunctionFromBoilerplate(boilerplate, context);
563 Handle<Object> result =
564 Execution::TryCall(function, Handle<Object>(context->global()),
565 0, NULL, &caught_exception);
566
567 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000568 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000569 Handle<Object> message = MessageHandler::MakeMessageObject(
570 "error_loading_debugger", NULL, HandleVector<Object>(&result, 1),
571 Handle<String>());
572 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000573 return false;
574 }
575
kasper.lund44510672008-07-25 07:37:58 +0000576 // Mark this script as native and return successfully.
577 Handle<Script> script(Script::cast(function->shared()->script()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578 script->set_type(Smi::FromInt(SCRIPT_TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579 return true;
580}
581
582
583bool Debug::Load() {
584 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000585 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000586
kasper.lund44510672008-07-25 07:37:58 +0000587 // Bail out if we're already in the process of compiling the native
588 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000589 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
590 return false;
591 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000592
593 // Disable breakpoints and interrupts while compiling and running the
594 // debugger scripts including the context creation code.
595 DisableBreak disable(true);
596 PostponeInterruptsScope postpone;
597
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000598 // Create the debugger context.
599 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000600 Handle<Context> context =
601 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
602 v8::Handle<ObjectTemplate>(),
603 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000604
kasper.lund44510672008-07-25 07:37:58 +0000605 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000606 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000607 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000608
609 // Expose the builtins object in the debugger context.
610 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
611 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
612 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000613
614 // Compile the JavaScript for the debugger in the debugger context.
615 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000616 bool caught_exception =
617 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
618 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000619 Debugger::set_compiling_natives(false);
620
mads.s.agercbaa0602008-08-14 13:41:48 +0000621 // Make sure we mark the debugger as not loading before we might
622 // return.
623 Debugger::set_loading_debugger(false);
624
kasper.lund44510672008-07-25 07:37:58 +0000625 // Check for caught exceptions.
626 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000627
628 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000629 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000630 return true;
631}
632
633
634void Debug::Unload() {
635 // Return debugger is not loaded.
636 if (!IsLoaded()) {
637 return;
638 }
639
640 // Clear debugger context global handle.
641 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
642 debug_context_ = Handle<Context>();
643}
644
645
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000646// Set the flag indicating that preemption happened during debugging.
647void Debug::PreemptionWhileInDebugger() {
648 ASSERT(InDebugger());
649 Debug::set_preemption_pending(true);
650}
651
652
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000653void Debug::Iterate(ObjectVisitor* v) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000654 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_entry_)));
655 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000656}
657
658
659Object* Debug::Break(Arguments args) {
660 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000661 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000662
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000663 // Get the top-most JavaScript frame.
664 JavaScriptFrameIterator it;
665 JavaScriptFrame* frame = it.frame();
666
667 // Just continue if breaks are disabled or debugger cannot be loaded.
668 if (disable_break() || !Load()) {
669 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000670 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000671 }
672
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000673 // Enter the debugger.
674 EnterDebugger debugger;
675 if (debugger.FailedToEnter()) {
676 return Heap::undefined_value();
677 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000678
kasper.lund44510672008-07-25 07:37:58 +0000679 // Postpone interrupt during breakpoint processing.
680 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000681
682 // Get the debug info (create it if it does not exist).
683 Handle<SharedFunctionInfo> shared =
684 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
685 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
686
687 // Find the break point where execution has stopped.
688 BreakLocationIterator break_location_iterator(debug_info,
689 ALL_BREAK_LOCATIONS);
690 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
691
692 // Check whether step next reached a new statement.
693 if (!StepNextContinue(&break_location_iterator, frame)) {
694 // Decrease steps left if performing multiple steps.
695 if (thread_local_.step_count_ > 0) {
696 thread_local_.step_count_--;
697 }
698 }
699
700 // If there is one or more real break points check whether any of these are
701 // triggered.
702 Handle<Object> break_points_hit(Heap::undefined_value());
703 if (break_location_iterator.HasBreakPoint()) {
704 Handle<Object> break_point_objects =
705 Handle<Object>(break_location_iterator.BreakPointObjects());
706 break_points_hit = CheckBreakPoints(break_point_objects);
707 }
708
709 // Notify debugger if a real break point is triggered or if performing single
710 // stepping with no more steps to perform. Otherwise do another step.
711 if (!break_points_hit->IsUndefined() ||
712 (thread_local_.last_step_action_ != StepNone &&
713 thread_local_.step_count_ == 0)) {
714 // Clear all current stepping setup.
715 ClearStepping();
716
717 // Notify the debug event listeners.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +0000718 Debugger::OnDebugBreak(break_points_hit, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000719 } else if (thread_local_.last_step_action_ != StepNone) {
720 // Hold on to last step action as it is cleared by the call to
721 // ClearStepping.
722 StepAction step_action = thread_local_.last_step_action_;
723 int step_count = thread_local_.step_count_;
724
725 // Clear all current stepping setup.
726 ClearStepping();
727
728 // Set up for the remaining steps.
729 PrepareStep(step_action, step_count);
730 }
731
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000732 // Install jump to the call address which was overwritten.
733 SetAfterBreakTarget(frame);
734
mads.s.ager31e71382008-08-13 09:32:07 +0000735 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000736}
737
738
739// Check the break point objects for whether one or more are actually
740// triggered. This function returns a JSArray with the break point objects
741// which is triggered.
742Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
743 int break_points_hit_count = 0;
744 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
745
v8.team.kasperl727e9952008-09-02 14:56:44 +0000746 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000747 ASSERT(!break_point_objects->IsUndefined());
748 if (break_point_objects->IsFixedArray()) {
749 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
750 for (int i = 0; i < array->length(); i++) {
751 Handle<Object> o(array->get(i));
752 if (CheckBreakPoint(o)) {
753 break_points_hit->SetElement(break_points_hit_count++, *o);
754 }
755 }
756 } else {
757 if (CheckBreakPoint(break_point_objects)) {
758 break_points_hit->SetElement(break_points_hit_count++,
759 *break_point_objects);
760 }
761 }
762
763 // Return undefined if no break points where triggered.
764 if (break_points_hit_count == 0) {
765 return Factory::undefined_value();
766 }
767 return break_points_hit;
768}
769
770
771// Check whether a single break point object is triggered.
772bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000773 HandleScope scope;
774
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000775 // Ignore check if break point object is not a JSObject.
776 if (!break_point_object->IsJSObject()) return true;
777
778 // Get the function CheckBreakPoint (defined in debug.js).
779 Handle<JSFunction> check_break_point =
780 Handle<JSFunction>(JSFunction::cast(
781 debug_context()->global()->GetProperty(
782 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
783
784 // Get the break id as an object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000785 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786
787 // Call HandleBreakPointx.
788 bool caught_exception = false;
789 const int argc = 2;
790 Object** argv[argc] = {
791 break_id.location(),
792 reinterpret_cast<Object**>(break_point_object.location())
793 };
794 Handle<Object> result = Execution::TryCall(check_break_point,
795 Top::builtins(), argc, argv,
796 &caught_exception);
797
798 // If exception or non boolean result handle as not triggered
799 if (caught_exception || !result->IsBoolean()) {
800 return false;
801 }
802
803 // Return whether the break point is triggered.
804 return *result == Heap::true_value();
805}
806
807
808// Check whether the function has debug information.
809bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
810 return !shared->debug_info()->IsUndefined();
811}
812
813
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000814// Return the debug info for this function. EnsureDebugInfo must be called
815// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000816Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000817 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000818 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
819}
820
821
822void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
823 int source_position,
824 Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000825 HandleScope scope;
826
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000827 if (!EnsureDebugInfo(shared)) {
828 // Return if retrieving debug info failed.
829 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000830 }
831
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000832 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000833 // Source positions starts with zero.
834 ASSERT(source_position >= 0);
835
836 // Find the break point and change it.
837 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
838 it.FindBreakLocationFromPosition(source_position);
839 it.SetBreakPoint(break_point_object);
840
841 // At least one active break point now.
842 ASSERT(debug_info->GetBreakPointCount() > 0);
843}
844
845
846void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
ager@chromium.org381abbb2009-02-25 13:23:22 +0000847 HandleScope scope;
848
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000849 DebugInfoListNode* node = debug_info_list_;
850 while (node != NULL) {
851 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
852 break_point_object);
853 if (!result->IsUndefined()) {
854 // Get information in the break point.
855 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
856 Handle<DebugInfo> debug_info = node->debug_info();
857 Handle<SharedFunctionInfo> shared(debug_info->shared());
858 int source_position = break_point_info->statement_position()->value();
859
860 // Source positions starts with zero.
861 ASSERT(source_position >= 0);
862
863 // Find the break point and clear it.
864 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
865 it.FindBreakLocationFromPosition(source_position);
866 it.ClearBreakPoint(break_point_object);
867
868 // If there are no more break points left remove the debug info for this
869 // function.
870 if (debug_info->GetBreakPointCount() == 0) {
871 RemoveDebugInfo(debug_info);
872 }
873
874 return;
875 }
876 node = node->next();
877 }
878}
879
880
ager@chromium.org381abbb2009-02-25 13:23:22 +0000881void Debug::ClearAllBreakPoints() {
882 DebugInfoListNode* node = debug_info_list_;
883 while (node != NULL) {
884 // Remove all debug break code.
885 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
886 it.ClearAllDebugBreak();
887 node = node->next();
888 }
889
890 // Remove all debug info.
891 while (debug_info_list_ != NULL) {
892 RemoveDebugInfo(debug_info_list_->debug_info());
893 }
894}
895
896
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000897void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000898 // Make sure the function has setup the debug info.
899 if (!EnsureDebugInfo(shared)) {
900 // Return if we failed to retrieve the debug info.
901 return;
902 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000903
904 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000905 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000906 while (!it.Done()) {
907 it.SetOneShot();
908 it.Next();
909 }
910}
911
912
913void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000914 // Iterate through the JavaScript stack looking for handlers.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000915 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000916 if (id == StackFrame::NO_ID) {
917 // If there is no JavaScript stack don't do anything.
918 return;
919 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000920 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
921 JavaScriptFrame* frame = it.frame();
922 if (frame->HasHandler()) {
923 Handle<SharedFunctionInfo> shared =
924 Handle<SharedFunctionInfo>(
925 JSFunction::cast(frame->function())->shared());
926 // Flood the function with the catch block with break points
927 FloodWithOneShot(shared);
928 return;
929 }
930 }
931}
932
933
934void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
935 if (type == BreakUncaughtException) {
936 break_on_uncaught_exception_ = enable;
937 } else {
938 break_on_exception_ = enable;
939 }
940}
941
942
943void Debug::PrepareStep(StepAction step_action, int step_count) {
944 HandleScope scope;
945 ASSERT(Debug::InDebugger());
946
947 // Remember this step action and count.
948 thread_local_.last_step_action_ = step_action;
949 thread_local_.step_count_ = step_count;
950
951 // Get the frame where the execution has stopped and skip the debug frame if
952 // any. The debug frame will only be present if execution was stopped due to
953 // hitting a break point. In other situations (e.g. unhandled exception) the
954 // debug frame is not present.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +0000955 StackFrame::Id id = break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000956 if (id == StackFrame::NO_ID) {
957 // If there is no JavaScript stack don't do anything.
958 return;
959 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000960 JavaScriptFrameIterator frames_it(id);
961 JavaScriptFrame* frame = frames_it.frame();
962
963 // First of all ensure there is one-shot break points in the top handler
964 // if any.
965 FloodHandlerWithOneShot();
966
967 // If the function on the top frame is unresolved perform step out. This will
968 // be the case when calling unknown functions and having the debugger stopped
969 // in an unhandled exception.
970 if (!frame->function()->IsJSFunction()) {
971 // Step out: Find the calling JavaScript frame and flood it with
972 // breakpoints.
973 frames_it.Advance();
974 // Fill the function to return to with one-shot break points.
975 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
976 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
977 return;
978 }
979
980 // Get the debug info (create it if it does not exist).
981 Handle<SharedFunctionInfo> shared =
982 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000983 if (!EnsureDebugInfo(shared)) {
984 // Return if ensuring debug info failed.
985 return;
986 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000987 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
988
989 // Find the break location where execution has stopped.
990 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
991 it.FindBreakLocationFromAddress(frame->pc());
992
993 // Compute whether or not the target is a call target.
994 bool is_call_target = false;
ager@chromium.org236ad962008-09-25 09:45:57 +0000995 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000996 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000997 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000998 if (code->is_call_stub()) is_call_target = true;
999 }
1000
v8.team.kasperl727e9952008-09-02 14:56:44 +00001001 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001002 if (it.IsExit() || step_action == StepOut) {
1003 // Step out: If there is a JavaScript caller frame, we need to
1004 // flood it with breakpoints.
1005 frames_it.Advance();
1006 if (!frames_it.done()) {
1007 // Fill the function to return to with one-shot break points.
1008 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
1009 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1010 }
ager@chromium.org236ad962008-09-25 09:45:57 +00001011 } else if (!(is_call_target || RelocInfo::IsConstructCall(it.rmode())) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001012 step_action == StepNext || step_action == StepMin) {
1013 // Step next or step min.
1014
1015 // Fill the current function with one-shot break points.
1016 FloodWithOneShot(shared);
1017
1018 // Remember source position and frame to handle step next.
1019 thread_local_.last_statement_position_ =
1020 debug_info->code()->SourceStatementPosition(frame->pc());
1021 thread_local_.last_fp_ = frame->fp();
1022 } else {
1023 // Fill the current function with one-shot break points even for step in on
1024 // a call target as the function called might be a native function for
1025 // which step in will not stop.
1026 FloodWithOneShot(shared);
1027
1028 // Step in or Step in min
1029 it.PrepareStepIn();
1030 ActivateStepIn(frame);
1031 }
1032}
1033
1034
1035// Check whether the current debug break should be reported to the debugger. It
1036// is used to have step next and step in only report break back to the debugger
1037// if on a different frame or in a different statement. In some situations
1038// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +00001039// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001040// steps before reporting break back to the debugger.
1041bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
1042 JavaScriptFrame* frame) {
1043 // If the step last action was step next or step in make sure that a new
1044 // statement is hit.
1045 if (thread_local_.last_step_action_ == StepNext ||
1046 thread_local_.last_step_action_ == StepIn) {
1047 // Never continue if returning from function.
1048 if (break_location_iterator->IsExit()) return false;
1049
1050 // Continue if we are still on the same frame and in the same statement.
1051 int current_statement_position =
1052 break_location_iterator->code()->SourceStatementPosition(frame->pc());
1053 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +00001054 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001055 }
1056
1057 // No step next action - don't continue.
1058 return false;
1059}
1060
1061
1062// Check whether the code object at the specified address is a debug break code
1063// object.
1064bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001065 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001066 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001067}
1068
1069
1070// Check whether a code stub with the specified major key is a possible break
1071// point location when looking for source break locations.
1072bool Debug::IsSourceBreakStub(Code* code) {
1073 CodeStub::Major major_key = code->major_key();
1074 return major_key == CodeStub::CallFunction;
1075}
1076
1077
1078// Check whether a code stub with the specified major key is a possible break
1079// location.
1080bool Debug::IsBreakStub(Code* code) {
1081 CodeStub::Major major_key = code->major_key();
1082 return major_key == CodeStub::CallFunction ||
1083 major_key == CodeStub::StackCheck;
1084}
1085
1086
1087// Find the builtin to use for invoking the debug break
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001088Handle<Code> Debug::FindDebugBreak(Handle<Code> code, RelocInfo::Mode mode) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001089 // Find the builtin debug break function matching the calling convention
1090 // used by the call site.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001091 if (code->is_inline_cache_stub()) {
1092 if (code->is_call_stub()) {
1093 return ComputeCallDebugBreak(code->arguments_count());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001094 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001095 if (code->is_load_stub()) {
1096 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1097 }
1098 if (code->is_store_stub()) {
1099 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1100 }
1101 if (code->is_keyed_load_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001102 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001103 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001104 return result;
1105 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001106 if (code->is_keyed_store_stub()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001107 Handle<Code> result =
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001108 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001109 return result;
1110 }
1111 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001112 if (RelocInfo::IsConstructCall(mode)) {
1113 Handle<Code> result =
1114 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1115 return result;
1116 }
1117 if (code->kind() == Code::STUB) {
1118 ASSERT(code->major_key() == CodeStub::CallFunction ||
1119 code->major_key() == CodeStub::StackCheck);
1120 Handle<Code> result =
1121 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1122 return result;
1123 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001124
1125 UNREACHABLE();
1126 return Handle<Code>::null();
1127}
1128
1129
1130// Simple function for returning the source positions for active break points.
1131Handle<Object> Debug::GetSourceBreakLocations(
1132 Handle<SharedFunctionInfo> shared) {
1133 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1134 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1135 if (debug_info->GetBreakPointCount() == 0) {
1136 return Handle<Object>(Heap::undefined_value());
1137 }
1138 Handle<FixedArray> locations =
1139 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1140 int count = 0;
1141 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1142 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1143 BreakPointInfo* break_point_info =
1144 BreakPointInfo::cast(debug_info->break_points()->get(i));
1145 if (break_point_info->GetBreakPointCount() > 0) {
1146 locations->set(count++, break_point_info->statement_position());
1147 }
1148 }
1149 }
1150 return locations;
1151}
1152
1153
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001154void Debug::NewBreak(StackFrame::Id break_frame_id) {
1155 thread_local_.break_frame_id_ = break_frame_id;
1156 thread_local_.break_id_ = ++thread_local_.break_count_;
1157}
1158
1159
1160void Debug::SetBreak(StackFrame::Id break_frame_id, int break_id) {
1161 thread_local_.break_frame_id_ = break_frame_id;
1162 thread_local_.break_id_ = break_id;
1163}
1164
1165
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001166// Handle stepping into a function.
1167void Debug::HandleStepIn(Handle<JSFunction> function,
1168 Address fp,
1169 bool is_constructor) {
1170 // If the frame pointer is not supplied by the caller find it.
1171 if (fp == 0) {
1172 StackFrameIterator it;
1173 it.Advance();
1174 // For constructor functions skip another frame.
1175 if (is_constructor) {
1176 ASSERT(it.frame()->is_construct());
1177 it.Advance();
1178 }
1179 fp = it.frame()->fp();
1180 }
1181
1182 // Flood the function with one-shot break points if it is called from where
1183 // step into was requested.
1184 if (fp == Debug::step_in_fp()) {
1185 // Don't allow step into functions in the native context.
1186 if (function->context()->global() != Top::context()->builtins()) {
kasperl@chromium.orgacae3782009-04-11 09:17:08 +00001187 if (function->shared()->code() ==
1188 Builtins::builtin(Builtins::FunctionApply) ||
1189 function->shared()->code() ==
1190 Builtins::builtin(Builtins::FunctionCall)) {
1191 // Handle function.apply and function.call separately to flood the
1192 // function to be called and not the code for Builtins::FunctionApply or
1193 // Builtins::FunctionCall. At the point of the call IC to call either
1194 // Builtins::FunctionApply or Builtins::FunctionCall the expression
1195 // stack has the following content:
1196 // symbol "apply" or "call"
1197 // function apply or call was called on
1198 // receiver for apply or call (first parameter to apply or call)
1199 // ... further arguments to apply or call.
1200 JavaScriptFrameIterator it;
1201 ASSERT(it.frame()->fp() == fp);
1202 ASSERT(it.frame()->GetExpression(1)->IsJSFunction());
1203 if (it.frame()->GetExpression(1)->IsJSFunction()) {
1204 Handle<JSFunction>
1205 actual_function(JSFunction::cast(it.frame()->GetExpression(1)));
1206 Handle<SharedFunctionInfo> actual_shared(actual_function->shared());
1207 Debug::FloodWithOneShot(actual_shared);
1208 }
1209 } else {
1210 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1211 }
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001212 }
1213 }
1214}
1215
1216
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001217void Debug::ClearStepping() {
1218 // Clear the various stepping setup.
1219 ClearOneShot();
1220 ClearStepIn();
1221 ClearStepNext();
1222
1223 // Clear multiple step counter.
1224 thread_local_.step_count_ = 0;
1225}
1226
1227// Clears all the one-shot break points that are currently set. Normally this
1228// function is called each time a break point is hit as one shot break points
1229// are used to support stepping.
1230void Debug::ClearOneShot() {
1231 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001232 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001233 // removed from the list.
1234
1235 DebugInfoListNode* node = debug_info_list_;
1236 while (node != NULL) {
1237 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1238 while (!it.Done()) {
1239 it.ClearOneShot();
1240 it.Next();
1241 }
1242 node = node->next();
1243 }
1244}
1245
1246
1247void Debug::ActivateStepIn(StackFrame* frame) {
1248 thread_local_.step_into_fp_ = frame->fp();
1249}
1250
1251
1252void Debug::ClearStepIn() {
1253 thread_local_.step_into_fp_ = 0;
1254}
1255
1256
1257void Debug::ClearStepNext() {
1258 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001259 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001260 thread_local_.last_fp_ = 0;
1261}
1262
1263
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001264bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1265 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001266 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001267}
1268
1269
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001270// Ensures the debug information is present for shared.
1271bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1272 // Return if we already have the debug info for shared.
1273 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001274
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001275 // Ensure shared in compiled. Return false if this failed.
1276 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001277
1278 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001279 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001280
1281 // Add debug info to the list.
1282 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1283 node->set_next(debug_info_list_);
1284 debug_info_list_ = node;
1285
1286 // Now there is at least one break point.
1287 has_break_points_ = true;
1288
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001289 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001290}
1291
1292
1293void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1294 ASSERT(debug_info_list_ != NULL);
1295 // Run through the debug info objects to find this one and remove it.
1296 DebugInfoListNode* prev = NULL;
1297 DebugInfoListNode* current = debug_info_list_;
1298 while (current != NULL) {
1299 if (*current->debug_info() == *debug_info) {
1300 // Unlink from list. If prev is NULL we are looking at the first element.
1301 if (prev == NULL) {
1302 debug_info_list_ = current->next();
1303 } else {
1304 prev->set_next(current->next());
1305 }
1306 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1307 delete current;
1308
1309 // If there are no more debug info objects there are not more break
1310 // points.
1311 has_break_points_ = debug_info_list_ != NULL;
1312
1313 return;
1314 }
1315 // Move to next in list.
1316 prev = current;
1317 current = current->next();
1318 }
1319 UNREACHABLE();
1320}
1321
1322
1323void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001324 HandleScope scope;
1325
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001326 // Get the executing function in which the debug break occurred.
1327 Handle<SharedFunctionInfo> shared =
1328 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001329 if (!EnsureDebugInfo(shared)) {
1330 // Return if we failed to retrieve the debug info.
1331 return;
1332 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001333 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1334 Handle<Code> code(debug_info->code());
1335 Handle<Code> original_code(debug_info->original_code());
1336#ifdef DEBUG
1337 // Get the code which is actually executing.
kasperl@chromium.org061ef742009-02-27 12:16:20 +00001338 Handle<Code> frame_code(frame->code());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001339 ASSERT(frame_code.is_identical_to(code));
1340#endif
1341
1342 // Find the call address in the running code. This address holds the call to
1343 // either a DebugBreakXXX or to the debug break return entry code if the
1344 // break point is still active after processing the break point.
1345 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1346
1347 // Check if the location is at JS exit.
1348 bool at_js_exit = false;
1349 RelocIterator it(debug_info->code());
1350 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001351 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001352 at_js_exit = it.rinfo()->pc() == addr - 1;
1353 }
1354 it.next();
1355 }
1356
1357 // Handle the jump to continue execution after break point depending on the
1358 // break location.
1359 if (at_js_exit) {
1360 // First check if the call in the code is still the debug break return
1361 // entry code. If it is the break point is still active. If not the break
1362 // point was removed during break point processing.
1363 if (Assembler::target_address_at(addr) ==
1364 debug_break_return_entry()->entry()) {
1365 // Break point still active. Jump to the corresponding place in the
1366 // original code.
1367 addr += original_code->instruction_start() - code->instruction_start();
1368 }
1369
1370 // Move one byte back to where the call instruction was placed.
1371 thread_local_.after_break_target_ = addr - 1;
1372 } else {
1373 // Check if there still is a debug break call at the target address. If the
1374 // break point has been removed it will have disappeared. If it have
1375 // disappeared don't try to look in the original code as the running code
1376 // will have the right address. This takes care of the case where the last
1377 // break point is removed from the function and therefore no "original code"
1378 // is available. If the debug break call is still there find the address in
1379 // the original code.
1380 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1381 // If the break point is still there find the call address which was
1382 // overwritten in the original code by the call to DebugBreakXXX.
1383
1384 // Find the corresponding address in the original code.
1385 addr += original_code->instruction_start() - code->instruction_start();
1386 }
1387
1388 // Install jump to the call address in the original code. This will be the
1389 // call which was overwritten by the call to DebugBreakXXX.
1390 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1391 }
1392}
1393
1394
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001395bool Debug::IsDebugGlobal(GlobalObject* global) {
1396 return IsLoaded() && global == Debug::debug_context()->global();
1397}
1398
1399
ager@chromium.org32912102009-01-16 10:38:43 +00001400void Debug::ClearMirrorCache() {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001401 HandleScope scope;
ager@chromium.org32912102009-01-16 10:38:43 +00001402 ASSERT(Top::context() == *Debug::debug_context());
1403
1404 // Clear the mirror cache.
1405 Handle<String> function_name =
1406 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1407 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1408 ASSERT(fun->IsJSFunction());
1409 bool caught_exception;
1410 Handle<Object> js_object = Execution::TryCall(
1411 Handle<JSFunction>::cast(fun),
1412 Handle<JSObject>(Debug::debug_context()->global()),
1413 0, NULL, &caught_exception);
1414}
1415
1416
ager@chromium.org71daaf62009-04-01 07:22:49 +00001417Mutex* Debugger::debugger_access_ = OS::CreateMutex();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001418Handle<Object> Debugger::event_listener_ = Handle<Object>();
1419Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001420bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001421bool Debugger::is_loading_debugger_ = false;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001422bool Debugger::never_unload_debugger_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001423DebugMessageThread* Debugger::message_thread_ = NULL;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001424v8::Debug::MessageHandler Debugger::message_handler_ = NULL;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001425bool Debugger::message_handler_cleared_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001426v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
1427int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001428DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org41826e72009-03-30 13:30:57 +00001429LockingMessageQueue Debugger::command_queue_(kQueueInitialSize);
1430LockingMessageQueue Debugger::message_queue_(kQueueInitialSize);
1431Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
1432Semaphore* Debugger::message_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001433
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001434
1435Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1436 int argc, Object*** argv,
1437 bool* caught_exception) {
1438 ASSERT(Top::context() == *Debug::debug_context());
1439
1440 // Create the execution state object.
1441 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1442 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1443 ASSERT(constructor->IsJSFunction());
1444 if (!constructor->IsJSFunction()) {
1445 *caught_exception = true;
1446 return Factory::undefined_value();
1447 }
1448 Handle<Object> js_object = Execution::TryCall(
1449 Handle<JSFunction>::cast(constructor),
1450 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1451 caught_exception);
1452 return js_object;
1453}
1454
1455
1456Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1457 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001458 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001459 const int argc = 1;
1460 Object** argv[argc] = { break_id.location() };
1461 return MakeJSObject(CStrVector("MakeExecutionState"),
1462 argc, argv, caught_exception);
1463}
1464
1465
1466Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1467 Handle<Object> break_points_hit,
1468 bool* caught_exception) {
1469 // Create the new break event object.
1470 const int argc = 2;
1471 Object** argv[argc] = { exec_state.location(),
1472 break_points_hit.location() };
1473 return MakeJSObject(CStrVector("MakeBreakEvent"),
1474 argc,
1475 argv,
1476 caught_exception);
1477}
1478
1479
1480Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1481 Handle<Object> exception,
1482 bool uncaught,
1483 bool* caught_exception) {
1484 // Create the new exception event object.
1485 const int argc = 3;
1486 Object** argv[argc] = { exec_state.location(),
1487 exception.location(),
1488 uncaught ? Factory::true_value().location() :
1489 Factory::false_value().location()};
1490 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1491 argc, argv, caught_exception);
1492}
1493
1494
1495Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1496 bool* caught_exception) {
1497 // Create the new function event object.
1498 const int argc = 1;
1499 Object** argv[argc] = { function.location() };
1500 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1501 argc, argv, caught_exception);
1502}
1503
1504
1505Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001506 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001507 bool* caught_exception) {
1508 // Create the compile event object.
1509 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001510 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001511 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001512 Object** argv[argc] = { exec_state.location(),
1513 script_wrapper.location(),
1514 before ? Factory::true_value().location() :
1515 Factory::false_value().location() };
1516
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001517 return MakeJSObject(CStrVector("MakeCompileEvent"),
1518 argc,
1519 argv,
1520 caught_exception);
1521}
1522
1523
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001524void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1525 HandleScope scope;
1526
1527 // Bail out based on state or if there is no listener for this event
1528 if (Debug::InDebugger()) return;
1529 if (!Debugger::EventActive(v8::Exception)) return;
1530
1531 // Bail out if exception breaks are not active
1532 if (uncaught) {
1533 // Uncaught exceptions are reported by either flags.
1534 if (!(Debug::break_on_uncaught_exception() ||
1535 Debug::break_on_exception())) return;
1536 } else {
1537 // Caught exceptions are reported is activated.
1538 if (!Debug::break_on_exception()) return;
1539 }
1540
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001541 // Enter the debugger.
1542 EnterDebugger debugger;
1543 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001544
1545 // Clear all current stepping setup.
1546 Debug::ClearStepping();
1547 // Create the event data object.
1548 bool caught_exception = false;
1549 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1550 Handle<Object> event_data;
1551 if (!caught_exception) {
1552 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1553 &caught_exception);
1554 }
1555 // Bail out and don't call debugger if exception.
1556 if (caught_exception) {
1557 return;
1558 }
1559
1560 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001561 ProcessDebugEvent(v8::Exception, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001562 // Return to continue execution from where the exception was thrown.
1563}
1564
1565
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001566void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1567 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001568 HandleScope scope;
1569
kasper.lund212ac232008-07-16 07:07:30 +00001570 // Debugger has already been entered by caller.
1571 ASSERT(Top::context() == *Debug::debug_context());
1572
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001573 // Bail out if there is no listener for this event
1574 if (!Debugger::EventActive(v8::Break)) return;
1575
1576 // Debugger must be entered in advance.
1577 ASSERT(Top::context() == *Debug::debug_context());
1578
1579 // Create the event data object.
1580 bool caught_exception = false;
1581 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1582 Handle<Object> event_data;
1583 if (!caught_exception) {
1584 event_data = MakeBreakEvent(exec_state, break_points_hit,
1585 &caught_exception);
1586 }
1587 // Bail out and don't call debugger if exception.
1588 if (caught_exception) {
1589 return;
1590 }
1591
1592 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001593 ProcessDebugEvent(v8::Break, event_data, auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001594}
1595
1596
1597void Debugger::OnBeforeCompile(Handle<Script> script) {
1598 HandleScope scope;
1599
1600 // Bail out based on state or if there is no listener for this event
1601 if (Debug::InDebugger()) return;
1602 if (compiling_natives()) return;
1603 if (!EventActive(v8::BeforeCompile)) return;
1604
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001605 // Enter the debugger.
1606 EnterDebugger debugger;
1607 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608
1609 // Create the event data object.
1610 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001611 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001612 // Bail out and don't call debugger if exception.
1613 if (caught_exception) {
1614 return;
1615 }
1616
1617 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001618 ProcessDebugEvent(v8::BeforeCompile, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001619}
1620
1621
1622// Handle debugger actions when a new script is compiled.
1623void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001624 HandleScope scope;
1625
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001626 // No compile events while compiling natives.
1627 if (compiling_natives()) return;
1628
1629 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001630 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001631
iposva@chromium.org245aa852009-02-10 00:49:54 +00001632 // Store whether in debugger before entering debugger.
1633 bool in_debugger = Debug::InDebugger();
1634
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001635 // Enter the debugger.
1636 EnterDebugger debugger;
1637 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001638
1639 // If debugging there might be script break points registered for this
1640 // script. Make sure that these break points are set.
1641
1642 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1643 Handle<Object> update_script_break_points =
1644 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1645 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1646 if (!update_script_break_points->IsJSFunction()) {
1647 return;
1648 }
1649 ASSERT(update_script_break_points->IsJSFunction());
1650
1651 // Wrap the script object in a proper JS object before passing it
1652 // to JavaScript.
1653 Handle<JSValue> wrapper = GetScriptWrapper(script);
1654
1655 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001656 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001657 const int argc = 1;
1658 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1659 Handle<Object> result = Execution::TryCall(
1660 Handle<JSFunction>::cast(update_script_break_points),
1661 Top::builtins(), argc, argv,
1662 &caught_exception);
1663 if (caught_exception) {
1664 return;
1665 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001666 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00001667 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001668 if (!Debugger::EventActive(v8::AfterCompile)) return;
1669
1670 // Create the compile state object.
1671 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001672 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001673 &caught_exception);
1674 // Bail out and don't call debugger if exception.
1675 if (caught_exception) {
1676 return;
1677 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001678 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001679 ProcessDebugEvent(v8::AfterCompile, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001680}
1681
1682
1683void Debugger::OnNewFunction(Handle<JSFunction> function) {
1684 return;
1685 HandleScope scope;
1686
1687 // Bail out based on state or if there is no listener for this event
1688 if (Debug::InDebugger()) return;
1689 if (compiling_natives()) return;
1690 if (!Debugger::EventActive(v8::NewFunction)) return;
1691
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001692 // Enter the debugger.
1693 EnterDebugger debugger;
1694 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001695
1696 // Create the event object.
1697 bool caught_exception = false;
1698 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1699 // Bail out and don't call debugger if exception.
1700 if (caught_exception) {
1701 return;
1702 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001703 // Process debug event.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001704 ProcessDebugEvent(v8::NewFunction, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705}
1706
1707
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001708void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001709 Handle<Object> event_data,
1710 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001711 HandleScope scope;
1712
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001713 // Create the execution state.
1714 bool caught_exception = false;
1715 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1716 if (caught_exception) {
1717 return;
1718 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001719 // First notify the message handler if any.
1720 if (message_handler_ != NULL) {
1721 NotifyMessageHandler(event, exec_state, event_data, auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001722 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001723 // Notify registered debug event listener. This can be either a C or a
1724 // JavaScript function.
1725 if (!event_listener_.is_null()) {
1726 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001727 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001728 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001729 v8::Debug::EventCallback callback =
1730 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001731 callback(event,
1732 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
1733 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data)),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001734 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001735 } else {
1736 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001737 ASSERT(event_listener_->IsJSFunction());
1738 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001739
1740 // Invoke the JavaScript debug event listener.
1741 const int argc = 4;
1742 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1743 exec_state.location(),
1744 event_data.location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001745 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001746 Handle<Object> result = Execution::TryCall(fun, Top::global(),
1747 argc, argv, &caught_exception);
1748 if (caught_exception) {
1749 // Silently ignore exceptions from debug event listeners.
1750 }
1751 }
1752 }
ager@chromium.org32912102009-01-16 10:38:43 +00001753
1754 // Clear the mirror cache.
1755 Debug::ClearMirrorCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001756}
1757
1758
ager@chromium.org71daaf62009-04-01 07:22:49 +00001759void Debugger::UnloadDebugger() {
1760 // Make sure that there are no breakpoints left.
1761 Debug::ClearAllBreakPoints();
1762
1763 // Unload the debugger if feasible.
1764 if (!never_unload_debugger_) {
1765 Debug::Unload();
1766 }
1767
1768 // Clear the flag indicating that the message handler was recently cleared.
1769 message_handler_cleared_ = false;
1770}
1771
1772
ager@chromium.org41826e72009-03-30 13:30:57 +00001773void Debugger::NotifyMessageHandler(v8::DebugEvent event,
1774 Handle<Object> exec_state,
1775 Handle<Object> event_data,
1776 bool auto_continue) {
1777 HandleScope scope;
1778
1779 if (!Debug::Load()) return;
1780
1781 // Process the individual events.
1782 bool interactive = false;
1783 switch (event) {
1784 case v8::Break:
1785 interactive = true; // Break event is always interactive
1786 break;
1787 case v8::Exception:
1788 interactive = true; // Exception event is always interactive
1789 break;
1790 case v8::BeforeCompile:
1791 break;
1792 case v8::AfterCompile:
1793 break;
1794 case v8::NewFunction:
1795 break;
1796 default:
1797 UNREACHABLE();
1798 }
1799
1800 // Done if not interactive.
1801 if (!interactive) return;
1802
1803 // Get the DebugCommandProcessor.
1804 v8::Local<v8::Object> api_exec_state =
1805 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
1806 v8::Local<v8::String> fun_name =
1807 v8::String::New("debugCommandProcessor");
1808 v8::Local<v8::Function> fun =
1809 v8::Function::Cast(*api_exec_state->Get(fun_name));
1810 v8::TryCatch try_catch;
1811 v8::Local<v8::Object> cmd_processor =
1812 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
1813 if (try_catch.HasCaught()) {
1814 PrintLn(try_catch.Exception());
1815 return;
1816 }
1817
1818 // Notify the debugger that a debug event has occurred unless auto continue is
1819 // active in which case no event is send.
1820 if (!auto_continue) {
1821 bool success = SendEventMessage(event_data);
1822 if (!success) {
1823 // If failed to notify debugger just continue running.
1824 return;
1825 }
1826 }
1827
1828 // Process requests from the debugger.
1829 while (true) {
1830 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001831 if (Debugger::host_dispatch_handler_) {
1832 // In case there is a host dispatch - do periodic dispatches.
1833 if (!command_received_->Wait(host_dispatch_micros_)) {
1834 // Timout expired, do the dispatch.
1835 Debugger::host_dispatch_handler_();
1836 continue;
1837 }
1838 } else {
1839 // In case there is no host dispatch - just wait.
1840 command_received_->Wait();
1841 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001842
1843 // The debug command interrupt flag might have been set when the command was
1844 // added.
1845 StackGuard::Continue(DEBUGCOMMAND);
1846
1847 // Get the command from the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001848 Message command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00001849 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00001850 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001851 // Delete command text and user data.
1852 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00001853 return;
1854 }
1855
ager@chromium.org41826e72009-03-30 13:30:57 +00001856 // Invoke JavaScript to process the debug request.
1857 v8::Local<v8::String> fun_name;
1858 v8::Local<v8::Function> fun;
1859 v8::Local<v8::Value> request;
1860 v8::TryCatch try_catch;
1861 fun_name = v8::String::New("processDebugRequest");
1862 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001863
1864 request = v8::String::New(command.text().start(),
1865 command.text().length());
1866 command.text().Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00001867 static const int kArgc = 1;
1868 v8::Handle<Value> argv[kArgc] = { request };
1869 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
1870
1871 // Get the response.
1872 v8::Local<v8::String> response;
1873 bool running = false;
1874 if (!try_catch.HasCaught()) {
1875 // Get response string.
1876 if (!response_val->IsUndefined()) {
1877 response = v8::String::Cast(*response_val);
1878 } else {
1879 response = v8::String::New("");
1880 }
1881
1882 // Log the JSON request/response.
1883 if (FLAG_trace_debug_json) {
1884 PrintLn(request);
1885 PrintLn(response);
1886 }
1887
1888 // Get the running state.
1889 fun_name = v8::String::New("isRunning");
1890 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
1891 static const int kArgc = 1;
1892 v8::Handle<Value> argv[kArgc] = { response };
1893 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
1894 if (!try_catch.HasCaught()) {
1895 running = running_val->ToBoolean()->Value();
1896 }
1897 } else {
1898 // In case of failure the result text is the exception text.
1899 response = try_catch.Exception()->ToString();
1900 }
1901
ager@chromium.org41826e72009-03-30 13:30:57 +00001902 // Return the result.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001903 SendMessage(Message::NewOutput(response, command.client_data()));
ager@chromium.org41826e72009-03-30 13:30:57 +00001904
1905 // Return from debug event processing if either the VM is put into the
1906 // runnning state (through a continue command) or auto continue is active
1907 // and there are no more commands queued.
1908 if (running || (auto_continue && !HasCommands())) {
1909 return;
1910 }
1911 }
1912}
1913
1914
iposva@chromium.org245aa852009-02-10 00:49:54 +00001915void Debugger::SetEventListener(Handle<Object> callback,
1916 Handle<Object> data) {
1917 HandleScope scope;
1918
1919 // Clear the global handles for the event listener and the event listener data
1920 // object.
1921 if (!event_listener_.is_null()) {
1922 GlobalHandles::Destroy(
1923 reinterpret_cast<Object**>(event_listener_.location()));
1924 event_listener_ = Handle<Object>();
1925 }
1926 if (!event_listener_data_.is_null()) {
1927 GlobalHandles::Destroy(
1928 reinterpret_cast<Object**>(event_listener_data_.location()));
1929 event_listener_data_ = Handle<Object>();
1930 }
1931
1932 // If there is a new debug event listener register it together with its data
1933 // object.
1934 if (!callback->IsUndefined() && !callback->IsNull()) {
1935 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
1936 if (data.is_null()) {
1937 data = Factory::undefined_value();
1938 }
1939 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
1940 }
1941
ager@chromium.org71daaf62009-04-01 07:22:49 +00001942 // Unload the debugger if event listener cleared.
1943 if (callback->IsUndefined()) {
1944 UnloadDebugger();
1945 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001946}
1947
1948
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001949void Debugger::SetMessageHandler(v8::Debug::MessageHandler handler,
ager@chromium.org41826e72009-03-30 13:30:57 +00001950 bool message_handler_thread) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001951 ScopedLock with(debugger_access_);
1952
ager@chromium.org381abbb2009-02-25 13:23:22 +00001953 message_handler_ = handler;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001954 if (handler != NULL) {
1955 if (!message_thread_ && message_handler_thread) {
1956 message_thread_ = new DebugMessageThread();
1957 message_thread_->Start();
1958 }
1959 } else {
1960 // Indicate that the message handler was recently cleared.
1961 message_handler_cleared_ = true;
1962
1963 // Send an empty command to the debugger if in a break to make JavaScript
1964 // run again if the debugger is closed.
1965 if (Debug::InDebugger()) {
1966 ProcessCommand(Vector<const uint16_t>::empty());
1967 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001968 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001969}
1970
1971
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001972void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
1973 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001974 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001975 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001976}
1977
1978
ager@chromium.org41826e72009-03-30 13:30:57 +00001979// Calls the registered debug message handler. This callback is part of the
1980// public API. Messages are kept internally as Vector<uint16_t> strings, which
1981// are allocated in various places and deallocated by the calling function
1982// sometime after this call.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001983void Debugger::InvokeMessageHandler(Message message) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001984 ScopedLock with(debugger_access_);
1985
ager@chromium.org381abbb2009-02-25 13:23:22 +00001986 if (message_handler_ != NULL) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001987 message_handler_(message.text().start(),
1988 message.text().length(),
1989 message.client_data());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001990 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001991 message.Dispose();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001992}
1993
1994
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001995void Debugger::SendMessage(Message message) {
ager@chromium.org41826e72009-03-30 13:30:57 +00001996 if (message_thread_ == NULL) {
1997 // If there is no message thread just invoke the message handler from the
1998 // V8 thread.
1999 InvokeMessageHandler(message);
2000 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002001 // Put the message coming from V8 on the queue. The text and user data will
2002 // be destroyed by the message thread.
ager@chromium.org41826e72009-03-30 13:30:57 +00002003 Logger::DebugTag("Put message on event message_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002004 message_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002005 message_received_->Signal();
2006 }
2007}
2008
2009
2010bool Debugger::SendEventMessage(Handle<Object> event_data) {
2011 v8::HandleScope scope;
2012 // Call toJSONProtocol on the debug event object.
2013 v8::Local<v8::Object> api_event_data =
2014 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data));
2015 v8::Local<v8::String> fun_name = v8::String::New("toJSONProtocol");
2016 v8::Local<v8::Function> fun =
2017 v8::Function::Cast(*api_event_data->Get(fun_name));
2018 v8::TryCatch try_catch;
2019 v8::Local<v8::Value> json_event = *fun->Call(api_event_data, 0, NULL);
2020 v8::Local<v8::String> json_event_string;
2021 if (!try_catch.HasCaught()) {
2022 if (!json_event->IsUndefined()) {
2023 json_event_string = json_event->ToString();
2024 if (FLAG_trace_debug_json) {
2025 PrintLn(json_event_string);
2026 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002027 SendMessage(Message::NewOutput(
2028 json_event_string,
2029 NULL /* no user data since there was no request */));
ager@chromium.org41826e72009-03-30 13:30:57 +00002030 } else {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002031 SendMessage(Message::NewEmptyMessage());
ager@chromium.org41826e72009-03-30 13:30:57 +00002032 }
2033 } else {
2034 PrintLn(try_catch.Exception());
2035 return false;
2036 }
2037 return true;
2038}
2039
2040
2041// Puts a command coming from the public API on the queue. Creates
2042// a copy of the command string managed by the debugger. Up to this
2043// point, the command data was managed by the API client. Called
2044// by the API client thread. This is where the API client hands off
2045// processing of the command to the DebugMessageThread thread.
2046// The new copy of the command is destroyed in HandleCommand().
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002047void Debugger::ProcessCommand(Vector<const uint16_t> command,
2048 v8::Debug::ClientData* client_data) {
2049 // Need to cast away const.
2050 Message message = Message::NewCommand(
ager@chromium.org41826e72009-03-30 13:30:57 +00002051 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002052 command.length()),
2053 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002054 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002055 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002056 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002057
2058 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002059 if (!Debug::InDebugger()) {
2060 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002061 }
2062}
2063
2064
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002065bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002066 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002067}
2068
2069
ager@chromium.org71daaf62009-04-01 07:22:49 +00002070bool Debugger::IsDebuggerActive() {
2071 ScopedLock with(debugger_access_);
2072
2073 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002074}
2075
2076
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002077Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2078 Handle<Object> data,
2079 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002080 // When calling functions in the debugger prevent it from beeing unloaded.
2081 Debugger::never_unload_debugger_ = true;
2082
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002083 // Enter the debugger.
2084 EnterDebugger debugger;
2085 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2086 return Factory::undefined_value();
2087 }
2088
2089 // Create the execution state.
2090 bool caught_exception = false;
2091 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2092 if (caught_exception) {
2093 return Factory::undefined_value();
2094 }
2095
2096 static const int kArgc = 2;
2097 Object** argv[kArgc] = { exec_state.location(), data.location() };
2098 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2099 kArgc, argv, pending_exception);
2100 return result;
2101}
2102
2103
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002104bool Debugger::StartAgent(const char* name, int port) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002105 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002106 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002107 agent_->Start();
2108 return true;
2109 }
2110
2111 return false;
2112}
2113
2114
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002115void Debugger::StopAgent() {
2116 if (agent_ != NULL) {
2117 agent_->Shutdown();
2118 agent_->Join();
2119 delete agent_;
2120 agent_ = NULL;
2121 }
2122}
2123
2124
ager@chromium.org41826e72009-03-30 13:30:57 +00002125void Debugger::TearDown() {
2126 if (message_thread_ != NULL) {
2127 message_thread_->Stop();
2128 delete message_thread_;
2129 message_thread_ = NULL;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002130 }
2131}
2132
2133
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002134void DebugMessageThread::Run() {
kasper.lund7276f142008-07-30 08:49:36 +00002135 // Sends debug events to an installed debugger message callback.
ager@chromium.org41826e72009-03-30 13:30:57 +00002136 while (keep_running_) {
kasper.lund7276f142008-07-30 08:49:36 +00002137 // Wait and Get are paired so that semaphore count equals queue length.
ager@chromium.org41826e72009-03-30 13:30:57 +00002138 Debugger::message_received_->Wait();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002139 Logger::DebugTag("Get message from event message_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002140 Message message = Debugger::message_queue_.Get();
2141 if (message.text().length() > 0) {
ager@chromium.org41826e72009-03-30 13:30:57 +00002142 Debugger::InvokeMessageHandler(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002143 } else {
2144 message.Dispose();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002145 }
2146 }
2147}
2148
2149
ager@chromium.org41826e72009-03-30 13:30:57 +00002150void DebugMessageThread::Stop() {
2151 keep_running_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002152 Debugger::SendMessage(Message::NewEmptyMessage());
ager@chromium.org41826e72009-03-30 13:30:57 +00002153 Join();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002154}
2155
kasper.lund7276f142008-07-30 08:49:36 +00002156
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002157Message::Message() : text_(Vector<uint16_t>::empty()),
2158 client_data_(NULL) {
2159}
2160
2161
2162Message::Message(const Vector<uint16_t>& text,
2163 v8::Debug::ClientData* data)
2164 : text_(text),
2165 client_data_(data) {
2166}
2167
2168
2169Message::~Message() {
2170}
2171
2172
2173void Message::Dispose() {
2174 text_.Dispose();
2175 delete client_data_;
2176 client_data_ = NULL;
2177}
2178
2179
2180Message Message::NewCommand(const Vector<uint16_t>& command,
2181 v8::Debug::ClientData* data) {
2182 return Message(command.Clone(), data);
2183}
2184
2185
2186Message Message::NewOutput(v8::Handle<v8::String> output,
2187 v8::Debug::ClientData* data) {
2188 Vector<uint16_t> text;
2189 if (!output.IsEmpty()) {
2190 // Do not include trailing '\0'.
2191 text = Vector<uint16_t>::New(output->Length());
2192 output->Write(text.start(), 0, output->Length());
2193 }
2194 return Message(text, data);
2195}
2196
2197
2198Message Message::NewEmptyMessage() {
2199 return Message();
2200}
2201
2202
kasper.lund7276f142008-07-30 08:49:36 +00002203MessageQueue::MessageQueue(int size) : start_(0), end_(0), size_(size) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002204 messages_ = NewArray<Message>(size);
kasper.lund7276f142008-07-30 08:49:36 +00002205}
2206
2207
2208MessageQueue::~MessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002209 while (!IsEmpty()) {
2210 Message m = Get();
2211 m.Dispose();
2212 }
kasper.lund7276f142008-07-30 08:49:36 +00002213 DeleteArray(messages_);
2214}
2215
2216
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002217Message MessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002218 ASSERT(!IsEmpty());
2219 int result = start_;
2220 start_ = (start_ + 1) % size_;
2221 return messages_[result];
2222}
2223
2224
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002225void MessageQueue::Put(const Message& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002226 if ((end_ + 1) % size_ == start_) {
2227 Expand();
2228 }
2229 messages_[end_] = message;
2230 end_ = (end_ + 1) % size_;
2231}
2232
2233
2234void MessageQueue::Expand() {
2235 MessageQueue new_queue(size_ * 2);
2236 while (!IsEmpty()) {
2237 new_queue.Put(Get());
2238 }
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002239 Message* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002240 *this = new_queue;
2241 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002242 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2243 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002244 // Automatic destructor called on new_queue, freeing array_to_free.
2245}
2246
2247
2248LockingMessageQueue::LockingMessageQueue(int size) : queue_(size) {
2249 lock_ = OS::CreateMutex();
2250}
2251
2252
2253LockingMessageQueue::~LockingMessageQueue() {
2254 delete lock_;
2255}
2256
2257
2258bool LockingMessageQueue::IsEmpty() const {
2259 ScopedLock sl(lock_);
2260 return queue_.IsEmpty();
2261}
2262
2263
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002264Message LockingMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002265 ScopedLock sl(lock_);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002266 Message result = queue_.Get();
2267 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002268 return result;
2269}
2270
2271
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002272void LockingMessageQueue::Put(const Message& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002273 ScopedLock sl(lock_);
2274 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002275 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002276}
2277
2278
2279void LockingMessageQueue::Clear() {
2280 ScopedLock sl(lock_);
2281 queue_.Clear();
2282}
2283
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002284#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002285
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002286} } // namespace v8::internal