blob: 239a373b27357ce09189c1df5ac20d314adf7710 [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;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001423v8::Debug::MessageHandler Debugger::message_handler_ = NULL;
ager@chromium.org71daaf62009-04-01 07:22:49 +00001424bool Debugger::message_handler_cleared_ = false;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001425v8::Debug::HostDispatchHandler Debugger::host_dispatch_handler_ = NULL;
1426int Debugger::host_dispatch_micros_ = 100 * 1000;
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001427DebuggerAgent* Debugger::agent_ = NULL;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001428LockingCommandMessageQueue Debugger::command_queue_(kQueueInitialSize);
ager@chromium.org41826e72009-03-30 13:30:57 +00001429Semaphore* Debugger::command_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001430
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001431
1432Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1433 int argc, Object*** argv,
1434 bool* caught_exception) {
1435 ASSERT(Top::context() == *Debug::debug_context());
1436
1437 // Create the execution state object.
1438 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1439 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1440 ASSERT(constructor->IsJSFunction());
1441 if (!constructor->IsJSFunction()) {
1442 *caught_exception = true;
1443 return Factory::undefined_value();
1444 }
1445 Handle<Object> js_object = Execution::TryCall(
1446 Handle<JSFunction>::cast(constructor),
1447 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1448 caught_exception);
1449 return js_object;
1450}
1451
1452
1453Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1454 // Create the execution state object.
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00001455 Handle<Object> break_id = Factory::NewNumberFromInt(Debug::break_id());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001456 const int argc = 1;
1457 Object** argv[argc] = { break_id.location() };
1458 return MakeJSObject(CStrVector("MakeExecutionState"),
1459 argc, argv, caught_exception);
1460}
1461
1462
1463Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1464 Handle<Object> break_points_hit,
1465 bool* caught_exception) {
1466 // Create the new break event object.
1467 const int argc = 2;
1468 Object** argv[argc] = { exec_state.location(),
1469 break_points_hit.location() };
1470 return MakeJSObject(CStrVector("MakeBreakEvent"),
1471 argc,
1472 argv,
1473 caught_exception);
1474}
1475
1476
1477Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1478 Handle<Object> exception,
1479 bool uncaught,
1480 bool* caught_exception) {
1481 // Create the new exception event object.
1482 const int argc = 3;
1483 Object** argv[argc] = { exec_state.location(),
1484 exception.location(),
1485 uncaught ? Factory::true_value().location() :
1486 Factory::false_value().location()};
1487 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1488 argc, argv, caught_exception);
1489}
1490
1491
1492Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1493 bool* caught_exception) {
1494 // Create the new function event object.
1495 const int argc = 1;
1496 Object** argv[argc] = { function.location() };
1497 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1498 argc, argv, caught_exception);
1499}
1500
1501
1502Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001503 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001504 bool* caught_exception) {
1505 // Create the compile event object.
1506 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001507 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001508 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001509 Object** argv[argc] = { exec_state.location(),
1510 script_wrapper.location(),
1511 before ? Factory::true_value().location() :
1512 Factory::false_value().location() };
1513
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001514 return MakeJSObject(CStrVector("MakeCompileEvent"),
1515 argc,
1516 argv,
1517 caught_exception);
1518}
1519
1520
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001521void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1522 HandleScope scope;
1523
1524 // Bail out based on state or if there is no listener for this event
1525 if (Debug::InDebugger()) return;
1526 if (!Debugger::EventActive(v8::Exception)) return;
1527
1528 // Bail out if exception breaks are not active
1529 if (uncaught) {
1530 // Uncaught exceptions are reported by either flags.
1531 if (!(Debug::break_on_uncaught_exception() ||
1532 Debug::break_on_exception())) return;
1533 } else {
1534 // Caught exceptions are reported is activated.
1535 if (!Debug::break_on_exception()) return;
1536 }
1537
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001538 // Enter the debugger.
1539 EnterDebugger debugger;
1540 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001541
1542 // Clear all current stepping setup.
1543 Debug::ClearStepping();
1544 // Create the event data object.
1545 bool caught_exception = false;
1546 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1547 Handle<Object> event_data;
1548 if (!caught_exception) {
1549 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1550 &caught_exception);
1551 }
1552 // Bail out and don't call debugger if exception.
1553 if (caught_exception) {
1554 return;
1555 }
1556
1557 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001558 ProcessDebugEvent(v8::Exception, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001559 // Return to continue execution from where the exception was thrown.
1560}
1561
1562
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001563void Debugger::OnDebugBreak(Handle<Object> break_points_hit,
1564 bool auto_continue) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001565 HandleScope scope;
1566
kasper.lund212ac232008-07-16 07:07:30 +00001567 // Debugger has already been entered by caller.
1568 ASSERT(Top::context() == *Debug::debug_context());
1569
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001570 // Bail out if there is no listener for this event
1571 if (!Debugger::EventActive(v8::Break)) return;
1572
1573 // Debugger must be entered in advance.
1574 ASSERT(Top::context() == *Debug::debug_context());
1575
1576 // Create the event data object.
1577 bool caught_exception = false;
1578 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1579 Handle<Object> event_data;
1580 if (!caught_exception) {
1581 event_data = MakeBreakEvent(exec_state, break_points_hit,
1582 &caught_exception);
1583 }
1584 // Bail out and don't call debugger if exception.
1585 if (caught_exception) {
1586 return;
1587 }
1588
1589 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001590 ProcessDebugEvent(v8::Break, event_data, auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001591}
1592
1593
1594void Debugger::OnBeforeCompile(Handle<Script> script) {
1595 HandleScope scope;
1596
1597 // Bail out based on state or if there is no listener for this event
1598 if (Debug::InDebugger()) return;
1599 if (compiling_natives()) return;
1600 if (!EventActive(v8::BeforeCompile)) return;
1601
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001602 // Enter the debugger.
1603 EnterDebugger debugger;
1604 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001605
1606 // Create the event data object.
1607 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001608 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001609 // Bail out and don't call debugger if exception.
1610 if (caught_exception) {
1611 return;
1612 }
1613
1614 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001615 ProcessDebugEvent(v8::BeforeCompile, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001616}
1617
1618
1619// Handle debugger actions when a new script is compiled.
1620void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001621 HandleScope scope;
1622
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001623 // No compile events while compiling natives.
1624 if (compiling_natives()) return;
1625
1626 // No more to do if not debugging.
ager@chromium.org71daaf62009-04-01 07:22:49 +00001627 if (!IsDebuggerActive()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001628
iposva@chromium.org245aa852009-02-10 00:49:54 +00001629 // Store whether in debugger before entering debugger.
1630 bool in_debugger = Debug::InDebugger();
1631
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001632 // Enter the debugger.
1633 EnterDebugger debugger;
1634 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001635
1636 // If debugging there might be script break points registered for this
1637 // script. Make sure that these break points are set.
1638
1639 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1640 Handle<Object> update_script_break_points =
1641 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1642 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1643 if (!update_script_break_points->IsJSFunction()) {
1644 return;
1645 }
1646 ASSERT(update_script_break_points->IsJSFunction());
1647
1648 // Wrap the script object in a proper JS object before passing it
1649 // to JavaScript.
1650 Handle<JSValue> wrapper = GetScriptWrapper(script);
1651
1652 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001653 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001654 const int argc = 1;
1655 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1656 Handle<Object> result = Execution::TryCall(
1657 Handle<JSFunction>::cast(update_script_break_points),
1658 Top::builtins(), argc, argv,
1659 &caught_exception);
1660 if (caught_exception) {
1661 return;
1662 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001663 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00001664 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001665 if (!Debugger::EventActive(v8::AfterCompile)) return;
1666
1667 // Create the compile state object.
1668 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001669 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001670 &caught_exception);
1671 // Bail out and don't call debugger if exception.
1672 if (caught_exception) {
1673 return;
1674 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001675 // Process debug event
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001676 ProcessDebugEvent(v8::AfterCompile, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001677}
1678
1679
1680void Debugger::OnNewFunction(Handle<JSFunction> function) {
1681 return;
1682 HandleScope scope;
1683
1684 // Bail out based on state or if there is no listener for this event
1685 if (Debug::InDebugger()) return;
1686 if (compiling_natives()) return;
1687 if (!Debugger::EventActive(v8::NewFunction)) return;
1688
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001689 // Enter the debugger.
1690 EnterDebugger debugger;
1691 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001692
1693 // Create the event object.
1694 bool caught_exception = false;
1695 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1696 // Bail out and don't call debugger if exception.
1697 if (caught_exception) {
1698 return;
1699 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001700 // Process debug event.
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001701 ProcessDebugEvent(v8::NewFunction, event_data, false);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001702}
1703
1704
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705void Debugger::ProcessDebugEvent(v8::DebugEvent event,
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00001706 Handle<Object> event_data,
1707 bool auto_continue) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001708 HandleScope scope;
1709
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001710 // Create the execution state.
1711 bool caught_exception = false;
1712 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1713 if (caught_exception) {
1714 return;
1715 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001716 // First notify the message handler if any.
1717 if (message_handler_ != NULL) {
1718 NotifyMessageHandler(event, exec_state, event_data, auto_continue);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001719 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001720 // Notify registered debug event listener. This can be either a C or a
1721 // JavaScript function.
1722 if (!event_listener_.is_null()) {
1723 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001724 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001725 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001726 v8::Debug::EventCallback callback =
1727 FUNCTION_CAST<v8::Debug::EventCallback>(callback_obj->proxy());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001728 callback(event,
1729 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
1730 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data)),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001731 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001732 } else {
1733 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001734 ASSERT(event_listener_->IsJSFunction());
1735 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001736
1737 // Invoke the JavaScript debug event listener.
1738 const int argc = 4;
1739 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1740 exec_state.location(),
1741 event_data.location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001742 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001743 Handle<Object> result = Execution::TryCall(fun, Top::global(),
1744 argc, argv, &caught_exception);
1745 if (caught_exception) {
1746 // Silently ignore exceptions from debug event listeners.
1747 }
1748 }
1749 }
ager@chromium.org32912102009-01-16 10:38:43 +00001750
1751 // Clear the mirror cache.
1752 Debug::ClearMirrorCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001753}
1754
1755
ager@chromium.org71daaf62009-04-01 07:22:49 +00001756void Debugger::UnloadDebugger() {
1757 // Make sure that there are no breakpoints left.
1758 Debug::ClearAllBreakPoints();
1759
1760 // Unload the debugger if feasible.
1761 if (!never_unload_debugger_) {
1762 Debug::Unload();
1763 }
1764
1765 // Clear the flag indicating that the message handler was recently cleared.
1766 message_handler_cleared_ = false;
1767}
1768
1769
ager@chromium.org41826e72009-03-30 13:30:57 +00001770void Debugger::NotifyMessageHandler(v8::DebugEvent event,
1771 Handle<Object> exec_state,
1772 Handle<Object> event_data,
1773 bool auto_continue) {
1774 HandleScope scope;
1775
1776 if (!Debug::Load()) return;
1777
1778 // Process the individual events.
1779 bool interactive = false;
1780 switch (event) {
1781 case v8::Break:
1782 interactive = true; // Break event is always interactive
1783 break;
1784 case v8::Exception:
1785 interactive = true; // Exception event is always interactive
1786 break;
1787 case v8::BeforeCompile:
1788 break;
1789 case v8::AfterCompile:
1790 break;
1791 case v8::NewFunction:
1792 break;
1793 default:
1794 UNREACHABLE();
1795 }
1796
1797 // Done if not interactive.
1798 if (!interactive) return;
1799
1800 // Get the DebugCommandProcessor.
1801 v8::Local<v8::Object> api_exec_state =
1802 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
1803 v8::Local<v8::String> fun_name =
1804 v8::String::New("debugCommandProcessor");
1805 v8::Local<v8::Function> fun =
1806 v8::Function::Cast(*api_exec_state->Get(fun_name));
1807 v8::TryCatch try_catch;
1808 v8::Local<v8::Object> cmd_processor =
1809 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
1810 if (try_catch.HasCaught()) {
1811 PrintLn(try_catch.Exception());
1812 return;
1813 }
1814
1815 // Notify the debugger that a debug event has occurred unless auto continue is
1816 // active in which case no event is send.
1817 if (!auto_continue) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001818 bool success = InvokeMessageHandlerWithEvent(event_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00001819 if (!success) {
1820 // If failed to notify debugger just continue running.
1821 return;
1822 }
1823 }
1824
1825 // Process requests from the debugger.
1826 while (true) {
1827 // Wait for new command in the queue.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001828 if (Debugger::host_dispatch_handler_) {
1829 // In case there is a host dispatch - do periodic dispatches.
1830 if (!command_received_->Wait(host_dispatch_micros_)) {
1831 // Timout expired, do the dispatch.
1832 Debugger::host_dispatch_handler_();
1833 continue;
1834 }
1835 } else {
1836 // In case there is no host dispatch - just wait.
1837 command_received_->Wait();
1838 }
ager@chromium.org41826e72009-03-30 13:30:57 +00001839
1840 // The debug command interrupt flag might have been set when the command was
1841 // added.
1842 StackGuard::Continue(DEBUGCOMMAND);
1843
1844 // Get the command from the queue.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001845 CommandMessage command = command_queue_.Get();
ager@chromium.org41826e72009-03-30 13:30:57 +00001846 Logger::DebugTag("Got request from command queue, in interactive loop.");
ager@chromium.org71daaf62009-04-01 07:22:49 +00001847 if (!Debugger::IsDebuggerActive()) {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001848 // Delete command text and user data.
1849 command.Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00001850 return;
1851 }
1852
ager@chromium.org41826e72009-03-30 13:30:57 +00001853 // Invoke JavaScript to process the debug request.
1854 v8::Local<v8::String> fun_name;
1855 v8::Local<v8::Function> fun;
1856 v8::Local<v8::Value> request;
1857 v8::TryCatch try_catch;
1858 fun_name = v8::String::New("processDebugRequest");
1859 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001860
1861 request = v8::String::New(command.text().start(),
1862 command.text().length());
1863 command.text().Dispose();
ager@chromium.org41826e72009-03-30 13:30:57 +00001864 static const int kArgc = 1;
1865 v8::Handle<Value> argv[kArgc] = { request };
1866 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
1867
1868 // Get the response.
1869 v8::Local<v8::String> response;
1870 bool running = false;
1871 if (!try_catch.HasCaught()) {
1872 // Get response string.
1873 if (!response_val->IsUndefined()) {
1874 response = v8::String::Cast(*response_val);
1875 } else {
1876 response = v8::String::New("");
1877 }
1878
1879 // Log the JSON request/response.
1880 if (FLAG_trace_debug_json) {
1881 PrintLn(request);
1882 PrintLn(response);
1883 }
1884
1885 // Get the running state.
1886 fun_name = v8::String::New("isRunning");
1887 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
1888 static const int kArgc = 1;
1889 v8::Handle<Value> argv[kArgc] = { response };
1890 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
1891 if (!try_catch.HasCaught()) {
1892 running = running_val->ToBoolean()->Value();
1893 }
1894 } else {
1895 // In case of failure the result text is the exception text.
1896 response = try_catch.Exception()->ToString();
1897 }
1898
ager@chromium.org41826e72009-03-30 13:30:57 +00001899 // Return the result.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001900 InvokeMessageHandler(response, command.client_data());
ager@chromium.org41826e72009-03-30 13:30:57 +00001901
1902 // Return from debug event processing if either the VM is put into the
1903 // runnning state (through a continue command) or auto continue is active
1904 // and there are no more commands queued.
1905 if (running || (auto_continue && !HasCommands())) {
1906 return;
1907 }
1908 }
1909}
1910
1911
iposva@chromium.org245aa852009-02-10 00:49:54 +00001912void Debugger::SetEventListener(Handle<Object> callback,
1913 Handle<Object> data) {
1914 HandleScope scope;
1915
1916 // Clear the global handles for the event listener and the event listener data
1917 // object.
1918 if (!event_listener_.is_null()) {
1919 GlobalHandles::Destroy(
1920 reinterpret_cast<Object**>(event_listener_.location()));
1921 event_listener_ = Handle<Object>();
1922 }
1923 if (!event_listener_data_.is_null()) {
1924 GlobalHandles::Destroy(
1925 reinterpret_cast<Object**>(event_listener_data_.location()));
1926 event_listener_data_ = Handle<Object>();
1927 }
1928
1929 // If there is a new debug event listener register it together with its data
1930 // object.
1931 if (!callback->IsUndefined() && !callback->IsNull()) {
1932 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
1933 if (data.is_null()) {
1934 data = Factory::undefined_value();
1935 }
1936 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
1937 }
1938
ager@chromium.org71daaf62009-04-01 07:22:49 +00001939 // Unload the debugger if event listener cleared.
1940 if (callback->IsUndefined()) {
1941 UnloadDebugger();
1942 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001943}
1944
1945
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001946void Debugger::SetMessageHandler(v8::Debug::MessageHandler handler) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001947 ScopedLock with(debugger_access_);
1948
ager@chromium.org381abbb2009-02-25 13:23:22 +00001949 message_handler_ = handler;
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001950 if (handler == NULL) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001951 // Indicate that the message handler was recently cleared.
1952 message_handler_cleared_ = true;
1953
1954 // Send an empty command to the debugger if in a break to make JavaScript
1955 // run again if the debugger is closed.
1956 if (Debug::InDebugger()) {
1957 ProcessCommand(Vector<const uint16_t>::empty());
1958 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001959 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001960}
1961
1962
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001963void Debugger::SetHostDispatchHandler(v8::Debug::HostDispatchHandler handler,
1964 int period) {
ager@chromium.org381abbb2009-02-25 13:23:22 +00001965 host_dispatch_handler_ = handler;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00001966 host_dispatch_micros_ = period * 1000;
ager@chromium.org381abbb2009-02-25 13:23:22 +00001967}
1968
1969
ager@chromium.org41826e72009-03-30 13:30:57 +00001970// Calls the registered debug message handler. This callback is part of the
1971// public API. Messages are kept internally as Vector<uint16_t> strings, which
1972// are allocated in various places and deallocated by the calling function
1973// sometime after this call.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001974void Debugger::InvokeMessageHandler(v8::Handle<v8::String> output,
1975 v8::Debug::ClientData* data) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00001976 ScopedLock with(debugger_access_);
1977
ager@chromium.org381abbb2009-02-25 13:23:22 +00001978 if (message_handler_ != NULL) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001979 Vector<uint16_t> text = Vector<uint16_t>::New(output->Length());
1980 output->Write(text.start(), 0, output->Length());
1981
1982 message_handler_(text.start(),
1983 text.length(),
1984 data);
1985
1986 text.Dispose();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001987 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001988 delete data;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001989}
1990
1991
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00001992bool Debugger::InvokeMessageHandlerWithEvent(Handle<Object> event_data) {
ager@chromium.org41826e72009-03-30 13:30:57 +00001993 v8::HandleScope scope;
1994 // Call toJSONProtocol on the debug event object.
1995 v8::Local<v8::Object> api_event_data =
1996 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data));
1997 v8::Local<v8::String> fun_name = v8::String::New("toJSONProtocol");
1998 v8::Local<v8::Function> fun =
1999 v8::Function::Cast(*api_event_data->Get(fun_name));
2000 v8::TryCatch try_catch;
2001 v8::Local<v8::Value> json_event = *fun->Call(api_event_data, 0, NULL);
2002 v8::Local<v8::String> json_event_string;
2003 if (!try_catch.HasCaught()) {
2004 if (!json_event->IsUndefined()) {
2005 json_event_string = json_event->ToString();
2006 if (FLAG_trace_debug_json) {
2007 PrintLn(json_event_string);
2008 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002009 InvokeMessageHandler(json_event_string,
2010 NULL /* no user data since there was no request */);
ager@chromium.org41826e72009-03-30 13:30:57 +00002011 } else {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002012 InvokeMessageHandler(v8::String::Empty(), NULL);
ager@chromium.org41826e72009-03-30 13:30:57 +00002013 }
2014 } else {
2015 PrintLn(try_catch.Exception());
2016 return false;
2017 }
2018 return true;
2019}
2020
2021
2022// Puts a command coming from the public API on the queue. Creates
2023// a copy of the command string managed by the debugger. Up to this
2024// point, the command data was managed by the API client. Called
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002025// by the API client thread.
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002026void Debugger::ProcessCommand(Vector<const uint16_t> command,
2027 v8::Debug::ClientData* client_data) {
2028 // Need to cast away const.
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002029 CommandMessage message = CommandMessage::New(
ager@chromium.org41826e72009-03-30 13:30:57 +00002030 Vector<uint16_t>(const_cast<uint16_t*>(command.start()),
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002031 command.length()),
2032 client_data);
ager@chromium.org41826e72009-03-30 13:30:57 +00002033 Logger::DebugTag("Put command on command_queue.");
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002034 command_queue_.Put(message);
ager@chromium.org41826e72009-03-30 13:30:57 +00002035 command_received_->Signal();
sgjesse@chromium.org3afc1582009-04-16 22:31:44 +00002036
2037 // Set the debug command break flag to have the command processed.
ager@chromium.org41826e72009-03-30 13:30:57 +00002038 if (!Debug::InDebugger()) {
2039 StackGuard::DebugCommand();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002040 }
2041}
2042
2043
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002044bool Debugger::HasCommands() {
ager@chromium.org41826e72009-03-30 13:30:57 +00002045 return !command_queue_.IsEmpty();
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002046}
2047
2048
ager@chromium.org71daaf62009-04-01 07:22:49 +00002049bool Debugger::IsDebuggerActive() {
2050 ScopedLock with(debugger_access_);
2051
2052 return message_handler_ != NULL || !event_listener_.is_null();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002053}
2054
2055
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002056Handle<Object> Debugger::Call(Handle<JSFunction> fun,
2057 Handle<Object> data,
2058 bool* pending_exception) {
ager@chromium.org71daaf62009-04-01 07:22:49 +00002059 // When calling functions in the debugger prevent it from beeing unloaded.
2060 Debugger::never_unload_debugger_ = true;
2061
ager@chromium.orga74f0da2008-12-03 16:05:52 +00002062 // Enter the debugger.
2063 EnterDebugger debugger;
2064 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
2065 return Factory::undefined_value();
2066 }
2067
2068 // Create the execution state.
2069 bool caught_exception = false;
2070 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
2071 if (caught_exception) {
2072 return Factory::undefined_value();
2073 }
2074
2075 static const int kArgc = 2;
2076 Object** argv[kArgc] = { exec_state.location(), data.location() };
2077 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
2078 kArgc, argv, pending_exception);
2079 return result;
2080}
2081
2082
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002083bool Debugger::StartAgent(const char* name, int port) {
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002084 if (Socket::Setup()) {
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002085 agent_ = new DebuggerAgent(name, port);
kasperl@chromium.org7be3c992009-03-12 07:19:55 +00002086 agent_->Start();
2087 return true;
2088 }
2089
2090 return false;
2091}
2092
2093
ager@chromium.orgbb29dc92009-03-24 13:25:23 +00002094void Debugger::StopAgent() {
2095 if (agent_ != NULL) {
2096 agent_->Shutdown();
2097 agent_->Join();
2098 delete agent_;
2099 agent_ = NULL;
2100 }
2101}
2102
2103
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002104CommandMessage::CommandMessage() : text_(Vector<uint16_t>::empty()),
2105 client_data_(NULL) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002106}
2107
2108
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002109CommandMessage::CommandMessage(const Vector<uint16_t>& text,
2110 v8::Debug::ClientData* data)
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002111 : text_(text),
2112 client_data_(data) {
2113}
2114
2115
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002116CommandMessage::~CommandMessage() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002117}
2118
2119
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002120void CommandMessage::Dispose() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002121 text_.Dispose();
2122 delete client_data_;
2123 client_data_ = NULL;
2124}
2125
2126
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002127CommandMessage CommandMessage::New(const Vector<uint16_t>& command,
2128 v8::Debug::ClientData* data) {
2129 return CommandMessage(command.Clone(), data);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002130}
2131
2132
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002133CommandMessageQueue::CommandMessageQueue(int size) : start_(0), end_(0),
2134 size_(size) {
2135 messages_ = NewArray<CommandMessage>(size);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002136}
2137
2138
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002139CommandMessageQueue::~CommandMessageQueue() {
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002140 while (!IsEmpty()) {
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002141 CommandMessage m = Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002142 m.Dispose();
2143 }
kasper.lund7276f142008-07-30 08:49:36 +00002144 DeleteArray(messages_);
2145}
2146
2147
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002148CommandMessage CommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002149 ASSERT(!IsEmpty());
2150 int result = start_;
2151 start_ = (start_ + 1) % size_;
2152 return messages_[result];
2153}
2154
2155
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002156void CommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002157 if ((end_ + 1) % size_ == start_) {
2158 Expand();
2159 }
2160 messages_[end_] = message;
2161 end_ = (end_ + 1) % size_;
2162}
2163
2164
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002165void CommandMessageQueue::Expand() {
2166 CommandMessageQueue new_queue(size_ * 2);
kasper.lund7276f142008-07-30 08:49:36 +00002167 while (!IsEmpty()) {
2168 new_queue.Put(Get());
2169 }
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002170 CommandMessage* array_to_free = messages_;
kasper.lund7276f142008-07-30 08:49:36 +00002171 *this = new_queue;
2172 new_queue.messages_ = array_to_free;
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002173 // Make the new_queue empty so that it doesn't call Dispose on any messages.
2174 new_queue.start_ = new_queue.end_;
kasper.lund7276f142008-07-30 08:49:36 +00002175 // Automatic destructor called on new_queue, freeing array_to_free.
2176}
2177
2178
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002179LockingCommandMessageQueue::LockingCommandMessageQueue(int size)
2180 : queue_(size) {
kasper.lund7276f142008-07-30 08:49:36 +00002181 lock_ = OS::CreateMutex();
2182}
2183
2184
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002185LockingCommandMessageQueue::~LockingCommandMessageQueue() {
kasper.lund7276f142008-07-30 08:49:36 +00002186 delete lock_;
2187}
2188
2189
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002190bool LockingCommandMessageQueue::IsEmpty() const {
kasper.lund7276f142008-07-30 08:49:36 +00002191 ScopedLock sl(lock_);
2192 return queue_.IsEmpty();
2193}
2194
2195
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002196CommandMessage LockingCommandMessageQueue::Get() {
kasper.lund7276f142008-07-30 08:49:36 +00002197 ScopedLock sl(lock_);
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002198 CommandMessage result = queue_.Get();
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002199 Logger::DebugEvent("Get", result.text());
kasper.lund7276f142008-07-30 08:49:36 +00002200 return result;
2201}
2202
2203
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002204void LockingCommandMessageQueue::Put(const CommandMessage& message) {
kasper.lund7276f142008-07-30 08:49:36 +00002205 ScopedLock sl(lock_);
2206 queue_.Put(message);
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002207 Logger::DebugEvent("Put", message.text());
kasper.lund7276f142008-07-30 08:49:36 +00002208}
2209
2210
ager@chromium.org3a37e9b2009-04-27 09:26:21 +00002211void LockingCommandMessageQueue::Clear() {
kasper.lund7276f142008-07-30 08:49:36 +00002212 ScopedLock sl(lock_);
2213 queue_.Clear();
2214}
2215
ager@chromium.org65dad4b2009-04-23 08:48:43 +00002216#endif // ENABLE_DEBUGGER_SUPPORT
kasper.lund7276f142008-07-30 08:49:36 +00002217
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002218} } // namespace v8::internal