blob: 86352c8fd9f1dc3b2e14a67d174081b972550370 [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"
38#include "natives.h"
39#include "stub-cache.h"
kasper.lund7276f142008-07-30 08:49:36 +000040#include "log.h"
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000041
42namespace v8 { namespace internal {
43
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000044static void PrintLn(v8::Local<v8::Value> value) {
45 v8::Local<v8::String> s = value->ToString();
46 char* data = NewArray<char>(s->Length() + 1);
47 if (data == NULL) {
48 V8::FatalProcessOutOfMemory("PrintLn");
49 return;
50 }
51 s->WriteAscii(data);
52 PrintF("%s\n", data);
53 DeleteArray(data);
54}
55
56
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +000057static Handle<Code> ComputeCallDebugBreak(int argc) {
58 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugBreak(argc), Code);
59}
60
61
62static Handle<Code> ComputeCallDebugPrepareStepIn(int argc) {
63 CALL_HEAP_FUNCTION(StubCache::ComputeCallDebugPrepareStepIn(argc), Code);
64}
65
66
67BreakLocationIterator::BreakLocationIterator(Handle<DebugInfo> debug_info,
68 BreakLocatorType type) {
69 debug_info_ = debug_info;
70 type_ = type;
71 reloc_iterator_ = NULL;
72 reloc_iterator_original_ = NULL;
73 Reset(); // Initialize the rest of the member variables.
74}
75
76
77BreakLocationIterator::~BreakLocationIterator() {
78 ASSERT(reloc_iterator_ != NULL);
79 ASSERT(reloc_iterator_original_ != NULL);
80 delete reloc_iterator_;
81 delete reloc_iterator_original_;
82}
83
84
85void BreakLocationIterator::Next() {
86 AssertNoAllocation nogc;
87 ASSERT(!RinfoDone());
88
89 // Iterate through reloc info for code and original code stopping at each
90 // breakable code target.
91 bool first = break_point_ == -1;
92 while (!RinfoDone()) {
93 if (!first) RinfoNext();
94 first = false;
95 if (RinfoDone()) return;
96
ager@chromium.org236ad962008-09-25 09:45:57 +000097 // Whenever a statement position or (plain) position is passed update the
98 // current value of these.
99 if (RelocInfo::IsPosition(rmode())) {
100 if (RelocInfo::IsStatementPosition(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000101 statement_position_ =
102 rinfo()->data() - debug_info_->shared()->start_position();
103 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000104 // Always update the position as we don't want that to be before the
105 // statement position.
106 position_ = rinfo()->data() - debug_info_->shared()->start_position();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000107 ASSERT(position_ >= 0);
108 ASSERT(statement_position_ >= 0);
109 }
110
111 // Check for breakable code target. Look in the original code as setting
112 // break points can cause the code targets in the running (debugged) code to
113 // be of a different kind than in the original code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000114 if (RelocInfo::IsCodeTarget(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000115 Address target = original_rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000116 Code* code = Code::GetCodeFromTargetAddress(target);
ager@chromium.org236ad962008-09-25 09:45:57 +0000117 if (code->is_inline_cache_stub() || RelocInfo::IsConstructCall(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000118 break_point_++;
119 return;
120 }
121 if (code->kind() == Code::STUB) {
122 if (type_ == ALL_BREAK_LOCATIONS) {
123 if (Debug::IsBreakStub(code)) {
124 break_point_++;
125 return;
126 }
127 } else {
128 ASSERT(type_ == SOURCE_BREAK_LOCATIONS);
129 if (Debug::IsSourceBreakStub(code)) {
130 break_point_++;
131 return;
132 }
133 }
134 }
135 }
136
137 // Check for break at return.
ager@chromium.org236ad962008-09-25 09:45:57 +0000138 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000139 // Set the positions to the end of the function.
140 if (debug_info_->shared()->HasSourceCode()) {
141 position_ = debug_info_->shared()->end_position() -
142 debug_info_->shared()->start_position();
143 } else {
144 position_ = 0;
145 }
146 statement_position_ = position_;
147 break_point_++;
148 return;
149 }
150 }
151}
152
153
154void BreakLocationIterator::Next(int count) {
155 while (count > 0) {
156 Next();
157 count--;
158 }
159}
160
161
162// Find the break point closest to the supplied address.
163void BreakLocationIterator::FindBreakLocationFromAddress(Address pc) {
164 // Run through all break points to locate the one closest to the address.
165 int closest_break_point = 0;
166 int distance = kMaxInt;
167 while (!Done()) {
168 // Check if this break point is closer that what was previously found.
169 if (this->pc() < pc && pc - this->pc() < distance) {
170 closest_break_point = break_point();
171 distance = pc - this->pc();
172 // Check whether we can't get any closer.
173 if (distance == 0) break;
174 }
175 Next();
176 }
177
178 // Move to the break point found.
179 Reset();
180 Next(closest_break_point);
181}
182
183
184// Find the break point closest to the supplied source position.
185void BreakLocationIterator::FindBreakLocationFromPosition(int position) {
186 // Run through all break points to locate the one closest to the source
187 // position.
188 int closest_break_point = 0;
189 int distance = kMaxInt;
190 while (!Done()) {
191 // Check if this break point is closer that what was previously found.
192 if (position <= statement_position() &&
193 statement_position() - position < distance) {
194 closest_break_point = break_point();
195 distance = statement_position() - position;
196 // Check whether we can't get any closer.
197 if (distance == 0) break;
198 }
199 Next();
200 }
201
202 // Move to the break point found.
203 Reset();
204 Next(closest_break_point);
205}
206
207
208void BreakLocationIterator::Reset() {
209 // Create relocation iterators for the two code objects.
210 if (reloc_iterator_ != NULL) delete reloc_iterator_;
211 if (reloc_iterator_original_ != NULL) delete reloc_iterator_original_;
212 reloc_iterator_ = new RelocIterator(debug_info_->code());
213 reloc_iterator_original_ = new RelocIterator(debug_info_->original_code());
214
215 // Position at the first break point.
216 break_point_ = -1;
217 position_ = 1;
218 statement_position_ = 1;
219 Next();
220}
221
222
223bool BreakLocationIterator::Done() const {
224 return RinfoDone();
225}
226
227
228void BreakLocationIterator::SetBreakPoint(Handle<Object> break_point_object) {
229 // If there is not already a real break point here patch code with debug
230 // break.
231 if (!HasBreakPoint()) {
232 SetDebugBreak();
233 }
234 ASSERT(IsDebugBreak());
235 // Set the break point information.
236 DebugInfo::SetBreakPoint(debug_info_, code_position(),
237 position(), statement_position(),
238 break_point_object);
239}
240
241
242void BreakLocationIterator::ClearBreakPoint(Handle<Object> break_point_object) {
243 // Clear the break point information.
244 DebugInfo::ClearBreakPoint(debug_info_, code_position(), break_point_object);
245 // If there are no more break points here remove the debug break.
246 if (!HasBreakPoint()) {
247 ClearDebugBreak();
248 ASSERT(!IsDebugBreak());
249 }
250}
251
252
253void BreakLocationIterator::SetOneShot() {
254 // If there is a real break point here no more to do.
255 if (HasBreakPoint()) {
256 ASSERT(IsDebugBreak());
257 return;
258 }
259
260 // Patch code with debug break.
261 SetDebugBreak();
262}
263
264
265void BreakLocationIterator::ClearOneShot() {
266 // If there is a real break point here no more to do.
267 if (HasBreakPoint()) {
268 ASSERT(IsDebugBreak());
269 return;
270 }
271
272 // Patch code removing debug break.
273 ClearDebugBreak();
274 ASSERT(!IsDebugBreak());
275}
276
277
278void BreakLocationIterator::SetDebugBreak() {
279 // If there is already a break point here just return. This might happen if
v8.team.kasperl727e9952008-09-02 14:56:44 +0000280 // the same code is flooded with break points twice. Flooding the same
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000281 // function twice might happen when stepping in a function with an exception
282 // handler as the handler and the function is the same.
283 if (IsDebugBreak()) {
284 return;
285 }
286
ager@chromium.org236ad962008-09-25 09:45:57 +0000287 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000288 // Patch the frame exit code with a break point.
289 SetDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000290 } else {
291 // Patch the original code with the current address as the current address
292 // might have changed by the inline caching since the code was copied.
293 original_rinfo()->set_target_address(rinfo()->target_address());
294
295 // Patch the code to invoke the builtin debug break function matching the
296 // calling convention used by the call site.
297 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(rinfo()));
298 rinfo()->set_target_address(dbgbrk_code->entry());
299 }
300 ASSERT(IsDebugBreak());
301}
302
303
304void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000305 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000306 // Restore the frame exit code.
307 ClearDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000308 } else {
309 // Patch the code to the original invoke.
310 rinfo()->set_target_address(original_rinfo()->target_address());
311 }
312 ASSERT(!IsDebugBreak());
313}
314
315
316void BreakLocationIterator::PrepareStepIn() {
317 // Step in can only be prepared if currently positioned on an IC call or
318 // construct call.
319 Address target = rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000320 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000321 if (code->is_call_stub()) {
322 // Step in through IC call is handled by the runtime system. Therefore make
323 // sure that the any current IC is cleared and the runtime system is
324 // called. If the executing code has a debug break at the location change
325 // the call in the original code as it is the code there that will be
326 // executed in place of the debug break call.
327 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
328 if (IsDebugBreak()) {
329 original_rinfo()->set_target_address(stub->entry());
330 } else {
331 rinfo()->set_target_address(stub->entry());
332 }
333 } else {
v8.team.kasperl727e9952008-09-02 14:56:44 +0000334 // Step in through constructs call requires no changes to the running code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000335 ASSERT(RelocInfo::IsConstructCall(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000336 }
337}
338
339
340// Check whether the break point is at a position which will exit the function.
341bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000342 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000343}
344
345
346bool BreakLocationIterator::HasBreakPoint() {
347 return debug_info_->HasBreakPoint(code_position());
348}
349
350
351// Check whether there is a debug break at the current position.
352bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000353 if (RelocInfo::IsJSReturn(rmode())) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000354 return IsDebugBreakAtReturn();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000355 } else {
356 return Debug::IsDebugBreak(rinfo()->target_address());
357 }
358}
359
360
361Object* BreakLocationIterator::BreakPointObjects() {
362 return debug_info_->GetBreakPointObjects(code_position());
363}
364
365
366bool BreakLocationIterator::RinfoDone() const {
367 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
368 return reloc_iterator_->done();
369}
370
371
372void BreakLocationIterator::RinfoNext() {
373 reloc_iterator_->next();
374 reloc_iterator_original_->next();
375#ifdef DEBUG
376 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
377 if (!reloc_iterator_->done()) {
378 ASSERT(rmode() == original_rmode());
379 }
380#endif
381}
382
383
384bool Debug::has_break_points_ = false;
385DebugInfoListNode* Debug::debug_info_list_ = NULL;
386
387
388// Threading support.
389void Debug::ThreadInit() {
390 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000391 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000392 thread_local_.step_count_ = 0;
393 thread_local_.last_fp_ = 0;
394 thread_local_.step_into_fp_ = 0;
395 thread_local_.after_break_target_ = 0;
396}
397
398
399JSCallerSavedBuffer Debug::registers_;
400Debug::ThreadLocal Debug::thread_local_;
401
402
403char* Debug::ArchiveDebug(char* storage) {
404 char* to = storage;
405 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
406 to += sizeof(ThreadLocal);
407 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
408 ThreadInit();
409 ASSERT(to <= storage + ArchiveSpacePerThread());
410 return storage + ArchiveSpacePerThread();
411}
412
413
414char* Debug::RestoreDebug(char* storage) {
415 char* from = storage;
416 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
417 from += sizeof(ThreadLocal);
418 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
419 ASSERT(from <= storage + ArchiveSpacePerThread());
420 return storage + ArchiveSpacePerThread();
421}
422
423
424int Debug::ArchiveSpacePerThread() {
425 return sizeof(ThreadLocal) + sizeof(registers_);
426}
427
428
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000429// Default break enabled.
430bool Debug::disable_break_ = false;
431
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000432// Default call debugger on uncaught exception.
433bool Debug::break_on_exception_ = false;
434bool Debug::break_on_uncaught_exception_ = true;
435
436Handle<Context> Debug::debug_context_ = Handle<Context>();
437Code* Debug::debug_break_return_entry_ = NULL;
438Code* Debug::debug_break_return_ = NULL;
439
440
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000441void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000442 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
443 RemoveDebugInfo(node->debug_info());
444#ifdef DEBUG
445 node = Debug::debug_info_list_;
446 while (node != NULL) {
447 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
448 node = node->next();
449 }
450#endif
451}
452
453
454DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
455 // Globalize the request debug info object and make it weak.
456 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
457 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
458 this, Debug::HandleWeakDebugInfo);
459}
460
461
462DebugInfoListNode::~DebugInfoListNode() {
463 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
464}
465
466
467void Debug::Setup(bool create_heap_objects) {
468 ThreadInit();
469 if (create_heap_objects) {
470 // Get code to handle entry to debug break on return.
471 debug_break_return_entry_ =
472 Builtins::builtin(Builtins::Return_DebugBreakEntry);
473 ASSERT(debug_break_return_entry_->IsCode());
474
475 // Get code to handle debug break on return.
476 debug_break_return_ =
477 Builtins::builtin(Builtins::Return_DebugBreak);
478 ASSERT(debug_break_return_->IsCode());
479 }
480}
481
482
483bool Debug::CompileDebuggerScript(int index) {
484 HandleScope scope;
485
kasper.lund44510672008-07-25 07:37:58 +0000486 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000487 if (index == -1) {
488 return false;
489 }
kasper.lund44510672008-07-25 07:37:58 +0000490
491 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000492 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
493 Vector<const char> name = Natives::GetScriptName(index);
494 Handle<String> script_name = Factory::NewStringFromAscii(name);
495
496 // Compile the script.
497 bool allow_natives_syntax = FLAG_allow_natives_syntax;
498 FLAG_allow_natives_syntax = true;
499 Handle<JSFunction> boilerplate;
500 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL);
501 FLAG_allow_natives_syntax = allow_natives_syntax;
502
503 // Silently ignore stack overflows during compilation.
504 if (boilerplate.is_null()) {
505 ASSERT(Top::has_pending_exception());
506 Top::clear_pending_exception();
507 return false;
508 }
509
kasper.lund44510672008-07-25 07:37:58 +0000510 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000511 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000512 bool caught_exception = false;
513 Handle<JSFunction> function =
514 Factory::NewFunctionFromBoilerplate(boilerplate, context);
515 Handle<Object> result =
516 Execution::TryCall(function, Handle<Object>(context->global()),
517 0, NULL, &caught_exception);
518
519 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000520 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000521 Handle<Object> message = MessageHandler::MakeMessageObject(
522 "error_loading_debugger", NULL, HandleVector<Object>(&result, 1),
523 Handle<String>());
524 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000525 return false;
526 }
527
kasper.lund44510672008-07-25 07:37:58 +0000528 // Mark this script as native and return successfully.
529 Handle<Script> script(Script::cast(function->shared()->script()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000530 script->set_type(Smi::FromInt(SCRIPT_TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000531 return true;
532}
533
534
535bool Debug::Load() {
536 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000537 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000538
kasper.lund44510672008-07-25 07:37:58 +0000539 // Bail out if we're already in the process of compiling the native
540 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000541 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
542 return false;
543 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000544
545 // Disable breakpoints and interrupts while compiling and running the
546 // debugger scripts including the context creation code.
547 DisableBreak disable(true);
548 PostponeInterruptsScope postpone;
549
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000550 // Create the debugger context.
551 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000552 Handle<Context> context =
553 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
554 v8::Handle<ObjectTemplate>(),
555 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000556
kasper.lund44510672008-07-25 07:37:58 +0000557 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000558 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000559 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000560
561 // Expose the builtins object in the debugger context.
562 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
563 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
564 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000565
566 // Compile the JavaScript for the debugger in the debugger context.
567 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000568 bool caught_exception =
569 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
570 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000571 Debugger::set_compiling_natives(false);
572
mads.s.agercbaa0602008-08-14 13:41:48 +0000573 // Make sure we mark the debugger as not loading before we might
574 // return.
575 Debugger::set_loading_debugger(false);
576
kasper.lund44510672008-07-25 07:37:58 +0000577 // Check for caught exceptions.
578 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000579
580 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000581 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000582 return true;
583}
584
585
586void Debug::Unload() {
587 // Return debugger is not loaded.
588 if (!IsLoaded()) {
589 return;
590 }
591
592 // Clear debugger context global handle.
593 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
594 debug_context_ = Handle<Context>();
595}
596
597
598void Debug::Iterate(ObjectVisitor* v) {
iposva@chromium.org245aa852009-02-10 00:49:54 +0000599 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_entry_)));
600 v->VisitPointer(bit_cast<Object**, Code**>(&(debug_break_return_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000601}
602
603
604Object* Debug::Break(Arguments args) {
605 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000606 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000607
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000608 // Get the top-most JavaScript frame.
609 JavaScriptFrameIterator it;
610 JavaScriptFrame* frame = it.frame();
611
612 // Just continue if breaks are disabled or debugger cannot be loaded.
613 if (disable_break() || !Load()) {
614 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000615 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000616 }
617
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000618 // Enter the debugger.
619 EnterDebugger debugger;
620 if (debugger.FailedToEnter()) {
621 return Heap::undefined_value();
622 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000623
kasper.lund44510672008-07-25 07:37:58 +0000624 // Postpone interrupt during breakpoint processing.
625 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000626
627 // Get the debug info (create it if it does not exist).
628 Handle<SharedFunctionInfo> shared =
629 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
630 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
631
632 // Find the break point where execution has stopped.
633 BreakLocationIterator break_location_iterator(debug_info,
634 ALL_BREAK_LOCATIONS);
635 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
636
637 // Check whether step next reached a new statement.
638 if (!StepNextContinue(&break_location_iterator, frame)) {
639 // Decrease steps left if performing multiple steps.
640 if (thread_local_.step_count_ > 0) {
641 thread_local_.step_count_--;
642 }
643 }
644
645 // If there is one or more real break points check whether any of these are
646 // triggered.
647 Handle<Object> break_points_hit(Heap::undefined_value());
648 if (break_location_iterator.HasBreakPoint()) {
649 Handle<Object> break_point_objects =
650 Handle<Object>(break_location_iterator.BreakPointObjects());
651 break_points_hit = CheckBreakPoints(break_point_objects);
652 }
653
654 // Notify debugger if a real break point is triggered or if performing single
655 // stepping with no more steps to perform. Otherwise do another step.
656 if (!break_points_hit->IsUndefined() ||
657 (thread_local_.last_step_action_ != StepNone &&
658 thread_local_.step_count_ == 0)) {
659 // Clear all current stepping setup.
660 ClearStepping();
661
662 // Notify the debug event listeners.
663 Debugger::OnDebugBreak(break_points_hit);
664 } else if (thread_local_.last_step_action_ != StepNone) {
665 // Hold on to last step action as it is cleared by the call to
666 // ClearStepping.
667 StepAction step_action = thread_local_.last_step_action_;
668 int step_count = thread_local_.step_count_;
669
670 // Clear all current stepping setup.
671 ClearStepping();
672
673 // Set up for the remaining steps.
674 PrepareStep(step_action, step_count);
675 }
676
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000677 // Install jump to the call address which was overwritten.
678 SetAfterBreakTarget(frame);
679
mads.s.ager31e71382008-08-13 09:32:07 +0000680 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000681}
682
683
684// Check the break point objects for whether one or more are actually
685// triggered. This function returns a JSArray with the break point objects
686// which is triggered.
687Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
688 int break_points_hit_count = 0;
689 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
690
v8.team.kasperl727e9952008-09-02 14:56:44 +0000691 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000692 ASSERT(!break_point_objects->IsUndefined());
693 if (break_point_objects->IsFixedArray()) {
694 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
695 for (int i = 0; i < array->length(); i++) {
696 Handle<Object> o(array->get(i));
697 if (CheckBreakPoint(o)) {
698 break_points_hit->SetElement(break_points_hit_count++, *o);
699 }
700 }
701 } else {
702 if (CheckBreakPoint(break_point_objects)) {
703 break_points_hit->SetElement(break_points_hit_count++,
704 *break_point_objects);
705 }
706 }
707
708 // Return undefined if no break points where triggered.
709 if (break_points_hit_count == 0) {
710 return Factory::undefined_value();
711 }
712 return break_points_hit;
713}
714
715
716// Check whether a single break point object is triggered.
717bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
718 // Ignore check if break point object is not a JSObject.
719 if (!break_point_object->IsJSObject()) return true;
720
721 // Get the function CheckBreakPoint (defined in debug.js).
722 Handle<JSFunction> check_break_point =
723 Handle<JSFunction>(JSFunction::cast(
724 debug_context()->global()->GetProperty(
725 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
726
727 // Get the break id as an object.
728 Handle<Object> break_id = Factory::NewNumberFromInt(Top::break_id());
729
730 // Call HandleBreakPointx.
731 bool caught_exception = false;
732 const int argc = 2;
733 Object** argv[argc] = {
734 break_id.location(),
735 reinterpret_cast<Object**>(break_point_object.location())
736 };
737 Handle<Object> result = Execution::TryCall(check_break_point,
738 Top::builtins(), argc, argv,
739 &caught_exception);
740
741 // If exception or non boolean result handle as not triggered
742 if (caught_exception || !result->IsBoolean()) {
743 return false;
744 }
745
746 // Return whether the break point is triggered.
747 return *result == Heap::true_value();
748}
749
750
751// Check whether the function has debug information.
752bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
753 return !shared->debug_info()->IsUndefined();
754}
755
756
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000757// Return the debug info for this function. EnsureDebugInfo must be called
758// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000759Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000760 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000761 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
762}
763
764
765void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
766 int source_position,
767 Handle<Object> break_point_object) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000768 if (!EnsureDebugInfo(shared)) {
769 // Return if retrieving debug info failed.
770 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000771 }
772
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000773 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000774 // Source positions starts with zero.
775 ASSERT(source_position >= 0);
776
777 // Find the break point and change it.
778 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
779 it.FindBreakLocationFromPosition(source_position);
780 it.SetBreakPoint(break_point_object);
781
782 // At least one active break point now.
783 ASSERT(debug_info->GetBreakPointCount() > 0);
784}
785
786
787void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
788 DebugInfoListNode* node = debug_info_list_;
789 while (node != NULL) {
790 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
791 break_point_object);
792 if (!result->IsUndefined()) {
793 // Get information in the break point.
794 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
795 Handle<DebugInfo> debug_info = node->debug_info();
796 Handle<SharedFunctionInfo> shared(debug_info->shared());
797 int source_position = break_point_info->statement_position()->value();
798
799 // Source positions starts with zero.
800 ASSERT(source_position >= 0);
801
802 // Find the break point and clear it.
803 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
804 it.FindBreakLocationFromPosition(source_position);
805 it.ClearBreakPoint(break_point_object);
806
807 // If there are no more break points left remove the debug info for this
808 // function.
809 if (debug_info->GetBreakPointCount() == 0) {
810 RemoveDebugInfo(debug_info);
811 }
812
813 return;
814 }
815 node = node->next();
816 }
817}
818
819
820void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000821 // Make sure the function has setup the debug info.
822 if (!EnsureDebugInfo(shared)) {
823 // Return if we failed to retrieve the debug info.
824 return;
825 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000826
827 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000828 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000829 while (!it.Done()) {
830 it.SetOneShot();
831 it.Next();
832 }
833}
834
835
836void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000837 // Iterate through the JavaScript stack looking for handlers.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000838 StackFrame::Id id = Top::break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000839 if (id == StackFrame::NO_ID) {
840 // If there is no JavaScript stack don't do anything.
841 return;
842 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000843 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
844 JavaScriptFrame* frame = it.frame();
845 if (frame->HasHandler()) {
846 Handle<SharedFunctionInfo> shared =
847 Handle<SharedFunctionInfo>(
848 JSFunction::cast(frame->function())->shared());
849 // Flood the function with the catch block with break points
850 FloodWithOneShot(shared);
851 return;
852 }
853 }
854}
855
856
857void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
858 if (type == BreakUncaughtException) {
859 break_on_uncaught_exception_ = enable;
860 } else {
861 break_on_exception_ = enable;
862 }
863}
864
865
866void Debug::PrepareStep(StepAction step_action, int step_count) {
867 HandleScope scope;
868 ASSERT(Debug::InDebugger());
869
870 // Remember this step action and count.
871 thread_local_.last_step_action_ = step_action;
872 thread_local_.step_count_ = step_count;
873
874 // Get the frame where the execution has stopped and skip the debug frame if
875 // any. The debug frame will only be present if execution was stopped due to
876 // hitting a break point. In other situations (e.g. unhandled exception) the
877 // debug frame is not present.
878 StackFrame::Id id = Top::break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000879 if (id == StackFrame::NO_ID) {
880 // If there is no JavaScript stack don't do anything.
881 return;
882 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000883 JavaScriptFrameIterator frames_it(id);
884 JavaScriptFrame* frame = frames_it.frame();
885
886 // First of all ensure there is one-shot break points in the top handler
887 // if any.
888 FloodHandlerWithOneShot();
889
890 // If the function on the top frame is unresolved perform step out. This will
891 // be the case when calling unknown functions and having the debugger stopped
892 // in an unhandled exception.
893 if (!frame->function()->IsJSFunction()) {
894 // Step out: Find the calling JavaScript frame and flood it with
895 // breakpoints.
896 frames_it.Advance();
897 // Fill the function to return to with one-shot break points.
898 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
899 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
900 return;
901 }
902
903 // Get the debug info (create it if it does not exist).
904 Handle<SharedFunctionInfo> shared =
905 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000906 if (!EnsureDebugInfo(shared)) {
907 // Return if ensuring debug info failed.
908 return;
909 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000910 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
911
912 // Find the break location where execution has stopped.
913 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
914 it.FindBreakLocationFromAddress(frame->pc());
915
916 // Compute whether or not the target is a call target.
917 bool is_call_target = false;
ager@chromium.org236ad962008-09-25 09:45:57 +0000918 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000919 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000920 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000921 if (code->is_call_stub()) is_call_target = true;
922 }
923
v8.team.kasperl727e9952008-09-02 14:56:44 +0000924 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 if (it.IsExit() || step_action == StepOut) {
926 // Step out: If there is a JavaScript caller frame, we need to
927 // flood it with breakpoints.
928 frames_it.Advance();
929 if (!frames_it.done()) {
930 // Fill the function to return to with one-shot break points.
931 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
932 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
933 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000934 } else if (!(is_call_target || RelocInfo::IsConstructCall(it.rmode())) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000935 step_action == StepNext || step_action == StepMin) {
936 // Step next or step min.
937
938 // Fill the current function with one-shot break points.
939 FloodWithOneShot(shared);
940
941 // Remember source position and frame to handle step next.
942 thread_local_.last_statement_position_ =
943 debug_info->code()->SourceStatementPosition(frame->pc());
944 thread_local_.last_fp_ = frame->fp();
945 } else {
946 // Fill the current function with one-shot break points even for step in on
947 // a call target as the function called might be a native function for
948 // which step in will not stop.
949 FloodWithOneShot(shared);
950
951 // Step in or Step in min
952 it.PrepareStepIn();
953 ActivateStepIn(frame);
954 }
955}
956
957
958// Check whether the current debug break should be reported to the debugger. It
959// is used to have step next and step in only report break back to the debugger
960// if on a different frame or in a different statement. In some situations
961// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +0000962// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000963// steps before reporting break back to the debugger.
964bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
965 JavaScriptFrame* frame) {
966 // If the step last action was step next or step in make sure that a new
967 // statement is hit.
968 if (thread_local_.last_step_action_ == StepNext ||
969 thread_local_.last_step_action_ == StepIn) {
970 // Never continue if returning from function.
971 if (break_location_iterator->IsExit()) return false;
972
973 // Continue if we are still on the same frame and in the same statement.
974 int current_statement_position =
975 break_location_iterator->code()->SourceStatementPosition(frame->pc());
976 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +0000977 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000978 }
979
980 // No step next action - don't continue.
981 return false;
982}
983
984
985// Check whether the code object at the specified address is a debug break code
986// object.
987bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000988 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000989 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000990}
991
992
993// Check whether a code stub with the specified major key is a possible break
994// point location when looking for source break locations.
995bool Debug::IsSourceBreakStub(Code* code) {
996 CodeStub::Major major_key = code->major_key();
997 return major_key == CodeStub::CallFunction;
998}
999
1000
1001// Check whether a code stub with the specified major key is a possible break
1002// location.
1003bool Debug::IsBreakStub(Code* code) {
1004 CodeStub::Major major_key = code->major_key();
1005 return major_key == CodeStub::CallFunction ||
1006 major_key == CodeStub::StackCheck;
1007}
1008
1009
1010// Find the builtin to use for invoking the debug break
1011Handle<Code> Debug::FindDebugBreak(RelocInfo* rinfo) {
1012 // Find the builtin debug break function matching the calling convention
1013 // used by the call site.
ager@chromium.org236ad962008-09-25 09:45:57 +00001014 RelocInfo::Mode mode = rinfo->rmode();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001015
ager@chromium.org236ad962008-09-25 09:45:57 +00001016 if (RelocInfo::IsCodeTarget(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001017 Address target = rinfo->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001018 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001019 if (code->is_inline_cache_stub()) {
1020 if (code->is_call_stub()) {
1021 return ComputeCallDebugBreak(code->arguments_count());
1022 }
1023 if (code->is_load_stub()) {
1024 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1025 }
1026 if (code->is_store_stub()) {
1027 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1028 }
1029 if (code->is_keyed_load_stub()) {
1030 Handle<Code> result =
1031 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1032 return result;
1033 }
1034 if (code->is_keyed_store_stub()) {
1035 Handle<Code> result =
1036 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1037 return result;
1038 }
1039 }
ager@chromium.org236ad962008-09-25 09:45:57 +00001040 if (RelocInfo::IsConstructCall(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001041 Handle<Code> result =
1042 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1043 return result;
1044 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001045 if (code->kind() == Code::STUB) {
1046 ASSERT(code->major_key() == CodeStub::CallFunction ||
1047 code->major_key() == CodeStub::StackCheck);
1048 Handle<Code> result =
1049 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1050 return result;
1051 }
1052 }
1053
1054 UNREACHABLE();
1055 return Handle<Code>::null();
1056}
1057
1058
1059// Simple function for returning the source positions for active break points.
1060Handle<Object> Debug::GetSourceBreakLocations(
1061 Handle<SharedFunctionInfo> shared) {
1062 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1063 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1064 if (debug_info->GetBreakPointCount() == 0) {
1065 return Handle<Object>(Heap::undefined_value());
1066 }
1067 Handle<FixedArray> locations =
1068 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1069 int count = 0;
1070 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1071 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1072 BreakPointInfo* break_point_info =
1073 BreakPointInfo::cast(debug_info->break_points()->get(i));
1074 if (break_point_info->GetBreakPointCount() > 0) {
1075 locations->set(count++, break_point_info->statement_position());
1076 }
1077 }
1078 }
1079 return locations;
1080}
1081
1082
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001083// Handle stepping into a function.
1084void Debug::HandleStepIn(Handle<JSFunction> function,
1085 Address fp,
1086 bool is_constructor) {
1087 // If the frame pointer is not supplied by the caller find it.
1088 if (fp == 0) {
1089 StackFrameIterator it;
1090 it.Advance();
1091 // For constructor functions skip another frame.
1092 if (is_constructor) {
1093 ASSERT(it.frame()->is_construct());
1094 it.Advance();
1095 }
1096 fp = it.frame()->fp();
1097 }
1098
1099 // Flood the function with one-shot break points if it is called from where
1100 // step into was requested.
1101 if (fp == Debug::step_in_fp()) {
1102 // Don't allow step into functions in the native context.
1103 if (function->context()->global() != Top::context()->builtins()) {
1104 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1105 }
1106 }
1107}
1108
1109
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001110void Debug::ClearStepping() {
1111 // Clear the various stepping setup.
1112 ClearOneShot();
1113 ClearStepIn();
1114 ClearStepNext();
1115
1116 // Clear multiple step counter.
1117 thread_local_.step_count_ = 0;
1118}
1119
1120// Clears all the one-shot break points that are currently set. Normally this
1121// function is called each time a break point is hit as one shot break points
1122// are used to support stepping.
1123void Debug::ClearOneShot() {
1124 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001125 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001126 // removed from the list.
1127
1128 DebugInfoListNode* node = debug_info_list_;
1129 while (node != NULL) {
1130 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1131 while (!it.Done()) {
1132 it.ClearOneShot();
1133 it.Next();
1134 }
1135 node = node->next();
1136 }
1137}
1138
1139
1140void Debug::ActivateStepIn(StackFrame* frame) {
1141 thread_local_.step_into_fp_ = frame->fp();
1142}
1143
1144
1145void Debug::ClearStepIn() {
1146 thread_local_.step_into_fp_ = 0;
1147}
1148
1149
1150void Debug::ClearStepNext() {
1151 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001152 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001153 thread_local_.last_fp_ = 0;
1154}
1155
1156
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001157bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1158 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001159 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001160}
1161
1162
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001163// Ensures the debug information is present for shared.
1164bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1165 // Return if we already have the debug info for shared.
1166 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001167
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001168 // Ensure shared in compiled. Return false if this failed.
1169 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001170
1171 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001172 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001173
1174 // Add debug info to the list.
1175 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1176 node->set_next(debug_info_list_);
1177 debug_info_list_ = node;
1178
1179 // Now there is at least one break point.
1180 has_break_points_ = true;
1181
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001182 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001183}
1184
1185
1186void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1187 ASSERT(debug_info_list_ != NULL);
1188 // Run through the debug info objects to find this one and remove it.
1189 DebugInfoListNode* prev = NULL;
1190 DebugInfoListNode* current = debug_info_list_;
1191 while (current != NULL) {
1192 if (*current->debug_info() == *debug_info) {
1193 // Unlink from list. If prev is NULL we are looking at the first element.
1194 if (prev == NULL) {
1195 debug_info_list_ = current->next();
1196 } else {
1197 prev->set_next(current->next());
1198 }
1199 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1200 delete current;
1201
1202 // If there are no more debug info objects there are not more break
1203 // points.
1204 has_break_points_ = debug_info_list_ != NULL;
1205
1206 return;
1207 }
1208 // Move to next in list.
1209 prev = current;
1210 current = current->next();
1211 }
1212 UNREACHABLE();
1213}
1214
1215
1216void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
1217 // Get the executing function in which the debug break occurred.
1218 Handle<SharedFunctionInfo> shared =
1219 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001220 if (!EnsureDebugInfo(shared)) {
1221 // Return if we failed to retrieve the debug info.
1222 return;
1223 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001224 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1225 Handle<Code> code(debug_info->code());
1226 Handle<Code> original_code(debug_info->original_code());
1227#ifdef DEBUG
1228 // Get the code which is actually executing.
1229 Handle<Code> frame_code(frame->FindCode());
1230 ASSERT(frame_code.is_identical_to(code));
1231#endif
1232
1233 // Find the call address in the running code. This address holds the call to
1234 // either a DebugBreakXXX or to the debug break return entry code if the
1235 // break point is still active after processing the break point.
1236 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1237
1238 // Check if the location is at JS exit.
1239 bool at_js_exit = false;
1240 RelocIterator it(debug_info->code());
1241 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001242 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001243 at_js_exit = it.rinfo()->pc() == addr - 1;
1244 }
1245 it.next();
1246 }
1247
1248 // Handle the jump to continue execution after break point depending on the
1249 // break location.
1250 if (at_js_exit) {
1251 // First check if the call in the code is still the debug break return
1252 // entry code. If it is the break point is still active. If not the break
1253 // point was removed during break point processing.
1254 if (Assembler::target_address_at(addr) ==
1255 debug_break_return_entry()->entry()) {
1256 // Break point still active. Jump to the corresponding place in the
1257 // original code.
1258 addr += original_code->instruction_start() - code->instruction_start();
1259 }
1260
1261 // Move one byte back to where the call instruction was placed.
1262 thread_local_.after_break_target_ = addr - 1;
1263 } else {
1264 // Check if there still is a debug break call at the target address. If the
1265 // break point has been removed it will have disappeared. If it have
1266 // disappeared don't try to look in the original code as the running code
1267 // will have the right address. This takes care of the case where the last
1268 // break point is removed from the function and therefore no "original code"
1269 // is available. If the debug break call is still there find the address in
1270 // the original code.
1271 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1272 // If the break point is still there find the call address which was
1273 // overwritten in the original code by the call to DebugBreakXXX.
1274
1275 // Find the corresponding address in the original code.
1276 addr += original_code->instruction_start() - code->instruction_start();
1277 }
1278
1279 // Install jump to the call address in the original code. This will be the
1280 // call which was overwritten by the call to DebugBreakXXX.
1281 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1282 }
1283}
1284
1285
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001286bool Debug::IsDebugGlobal(GlobalObject* global) {
1287 return IsLoaded() && global == Debug::debug_context()->global();
1288}
1289
1290
ager@chromium.org32912102009-01-16 10:38:43 +00001291void Debug::ClearMirrorCache() {
1292 ASSERT(Top::context() == *Debug::debug_context());
1293
1294 // Clear the mirror cache.
1295 Handle<String> function_name =
1296 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1297 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1298 ASSERT(fun->IsJSFunction());
1299 bool caught_exception;
1300 Handle<Object> js_object = Execution::TryCall(
1301 Handle<JSFunction>::cast(fun),
1302 Handle<JSObject>(Debug::debug_context()->global()),
1303 0, NULL, &caught_exception);
1304}
1305
1306
iposva@chromium.org245aa852009-02-10 00:49:54 +00001307Handle<Object> Debugger::event_listener_ = Handle<Object>();
1308Handle<Object> Debugger::event_listener_data_ = Handle<Object>();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001309bool Debugger::debugger_active_ = false;
1310bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001311bool Debugger::is_loading_debugger_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001312DebugMessageThread* Debugger::message_thread_ = NULL;
1313v8::DebugMessageHandler Debugger::debug_message_handler_ = NULL;
1314void* Debugger::debug_message_handler_data_ = NULL;
1315
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001316
1317Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1318 int argc, Object*** argv,
1319 bool* caught_exception) {
1320 ASSERT(Top::context() == *Debug::debug_context());
1321
1322 // Create the execution state object.
1323 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1324 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1325 ASSERT(constructor->IsJSFunction());
1326 if (!constructor->IsJSFunction()) {
1327 *caught_exception = true;
1328 return Factory::undefined_value();
1329 }
1330 Handle<Object> js_object = Execution::TryCall(
1331 Handle<JSFunction>::cast(constructor),
1332 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1333 caught_exception);
1334 return js_object;
1335}
1336
1337
1338Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1339 // Create the execution state object.
1340 Handle<Object> break_id = Factory::NewNumberFromInt(Top::break_id());
1341 const int argc = 1;
1342 Object** argv[argc] = { break_id.location() };
1343 return MakeJSObject(CStrVector("MakeExecutionState"),
1344 argc, argv, caught_exception);
1345}
1346
1347
1348Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1349 Handle<Object> break_points_hit,
1350 bool* caught_exception) {
1351 // Create the new break event object.
1352 const int argc = 2;
1353 Object** argv[argc] = { exec_state.location(),
1354 break_points_hit.location() };
1355 return MakeJSObject(CStrVector("MakeBreakEvent"),
1356 argc,
1357 argv,
1358 caught_exception);
1359}
1360
1361
1362Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1363 Handle<Object> exception,
1364 bool uncaught,
1365 bool* caught_exception) {
1366 // Create the new exception event object.
1367 const int argc = 3;
1368 Object** argv[argc] = { exec_state.location(),
1369 exception.location(),
1370 uncaught ? Factory::true_value().location() :
1371 Factory::false_value().location()};
1372 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1373 argc, argv, caught_exception);
1374}
1375
1376
1377Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1378 bool* caught_exception) {
1379 // Create the new function event object.
1380 const int argc = 1;
1381 Object** argv[argc] = { function.location() };
1382 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1383 argc, argv, caught_exception);
1384}
1385
1386
1387Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001388 bool before,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001389 bool* caught_exception) {
1390 // Create the compile event object.
1391 Handle<Object> exec_state = MakeExecutionState(caught_exception);
iposva@chromium.org245aa852009-02-10 00:49:54 +00001392 Handle<Object> script_wrapper = GetScriptWrapper(script);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001393 const int argc = 3;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001394 Object** argv[argc] = { exec_state.location(),
1395 script_wrapper.location(),
1396 before ? Factory::true_value().location() :
1397 Factory::false_value().location() };
1398
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001399 return MakeJSObject(CStrVector("MakeCompileEvent"),
1400 argc,
1401 argv,
1402 caught_exception);
1403}
1404
1405
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001406void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1407 HandleScope scope;
1408
1409 // Bail out based on state or if there is no listener for this event
1410 if (Debug::InDebugger()) return;
1411 if (!Debugger::EventActive(v8::Exception)) return;
1412
1413 // Bail out if exception breaks are not active
1414 if (uncaught) {
1415 // Uncaught exceptions are reported by either flags.
1416 if (!(Debug::break_on_uncaught_exception() ||
1417 Debug::break_on_exception())) return;
1418 } else {
1419 // Caught exceptions are reported is activated.
1420 if (!Debug::break_on_exception()) return;
1421 }
1422
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001423 // Enter the debugger.
1424 EnterDebugger debugger;
1425 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001426
1427 // Clear all current stepping setup.
1428 Debug::ClearStepping();
1429 // Create the event data object.
1430 bool caught_exception = false;
1431 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1432 Handle<Object> event_data;
1433 if (!caught_exception) {
1434 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1435 &caught_exception);
1436 }
1437 // Bail out and don't call debugger if exception.
1438 if (caught_exception) {
1439 return;
1440 }
1441
1442 // Process debug event
1443 ProcessDebugEvent(v8::Exception, event_data);
1444 // Return to continue execution from where the exception was thrown.
1445}
1446
1447
1448void Debugger::OnDebugBreak(Handle<Object> break_points_hit) {
1449 HandleScope scope;
1450
kasper.lund212ac232008-07-16 07:07:30 +00001451 // Debugger has already been entered by caller.
1452 ASSERT(Top::context() == *Debug::debug_context());
1453
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001454 // Bail out if there is no listener for this event
1455 if (!Debugger::EventActive(v8::Break)) return;
1456
1457 // Debugger must be entered in advance.
1458 ASSERT(Top::context() == *Debug::debug_context());
1459
1460 // Create the event data object.
1461 bool caught_exception = false;
1462 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1463 Handle<Object> event_data;
1464 if (!caught_exception) {
1465 event_data = MakeBreakEvent(exec_state, break_points_hit,
1466 &caught_exception);
1467 }
1468 // Bail out and don't call debugger if exception.
1469 if (caught_exception) {
1470 return;
1471 }
1472
1473 // Process debug event
1474 ProcessDebugEvent(v8::Break, event_data);
1475}
1476
1477
1478void Debugger::OnBeforeCompile(Handle<Script> script) {
1479 HandleScope scope;
1480
1481 // Bail out based on state or if there is no listener for this event
1482 if (Debug::InDebugger()) return;
1483 if (compiling_natives()) return;
1484 if (!EventActive(v8::BeforeCompile)) return;
1485
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001486 // Enter the debugger.
1487 EnterDebugger debugger;
1488 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001489
1490 // Create the event data object.
1491 bool caught_exception = false;
iposva@chromium.org245aa852009-02-10 00:49:54 +00001492 Handle<Object> event_data = MakeCompileEvent(script, true, &caught_exception);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001493 // Bail out and don't call debugger if exception.
1494 if (caught_exception) {
1495 return;
1496 }
1497
1498 // Process debug event
1499 ProcessDebugEvent(v8::BeforeCompile, event_data);
1500}
1501
1502
1503// Handle debugger actions when a new script is compiled.
1504void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001505 HandleScope scope;
1506
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001507 // No compile events while compiling natives.
1508 if (compiling_natives()) return;
1509
1510 // No more to do if not debugging.
1511 if (!debugger_active()) return;
1512
iposva@chromium.org245aa852009-02-10 00:49:54 +00001513 // Store whether in debugger before entering debugger.
1514 bool in_debugger = Debug::InDebugger();
1515
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001516 // Enter the debugger.
1517 EnterDebugger debugger;
1518 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001519
1520 // If debugging there might be script break points registered for this
1521 // script. Make sure that these break points are set.
1522
1523 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1524 Handle<Object> update_script_break_points =
1525 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1526 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1527 if (!update_script_break_points->IsJSFunction()) {
1528 return;
1529 }
1530 ASSERT(update_script_break_points->IsJSFunction());
1531
1532 // Wrap the script object in a proper JS object before passing it
1533 // to JavaScript.
1534 Handle<JSValue> wrapper = GetScriptWrapper(script);
1535
1536 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001537 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001538 const int argc = 1;
1539 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1540 Handle<Object> result = Execution::TryCall(
1541 Handle<JSFunction>::cast(update_script_break_points),
1542 Top::builtins(), argc, argv,
1543 &caught_exception);
1544 if (caught_exception) {
1545 return;
1546 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001547 // Bail out based on state or if there is no listener for this event
iposva@chromium.org245aa852009-02-10 00:49:54 +00001548 if (in_debugger) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001549 if (!Debugger::EventActive(v8::AfterCompile)) return;
1550
1551 // Create the compile state object.
1552 Handle<Object> event_data = MakeCompileEvent(script,
iposva@chromium.org245aa852009-02-10 00:49:54 +00001553 false,
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001554 &caught_exception);
1555 // Bail out and don't call debugger if exception.
1556 if (caught_exception) {
1557 return;
1558 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001559 // Process debug event
1560 ProcessDebugEvent(v8::AfterCompile, event_data);
1561}
1562
1563
1564void Debugger::OnNewFunction(Handle<JSFunction> function) {
1565 return;
1566 HandleScope scope;
1567
1568 // Bail out based on state or if there is no listener for this event
1569 if (Debug::InDebugger()) return;
1570 if (compiling_natives()) return;
1571 if (!Debugger::EventActive(v8::NewFunction)) return;
1572
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001573 // Enter the debugger.
1574 EnterDebugger debugger;
1575 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001576
1577 // Create the event object.
1578 bool caught_exception = false;
1579 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1580 // Bail out and don't call debugger if exception.
1581 if (caught_exception) {
1582 return;
1583 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001584 // Process debug event.
1585 ProcessDebugEvent(v8::NewFunction, event_data);
1586}
1587
1588
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001589void Debugger::ProcessDebugEvent(v8::DebugEvent event,
1590 Handle<Object> event_data) {
1591 // Create the execution state.
1592 bool caught_exception = false;
1593 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1594 if (caught_exception) {
1595 return;
1596 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001597 // First notify the builtin debugger.
1598 if (message_thread_ != NULL) {
1599 message_thread_->DebugEvent(event, exec_state, event_data);
1600 }
iposva@chromium.org245aa852009-02-10 00:49:54 +00001601 // Notify registered debug event listener. This can be either a C or a
1602 // JavaScript function.
1603 if (!event_listener_.is_null()) {
1604 if (event_listener_->IsProxy()) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001605 // C debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001606 Handle<Proxy> callback_obj(Handle<Proxy>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001607 v8::DebugEventCallback callback =
1608 FUNCTION_CAST<v8::DebugEventCallback>(callback_obj->proxy());
1609 callback(event,
1610 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
1611 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data)),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001612 v8::Utils::ToLocal(Handle<Object>::cast(event_listener_data_)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001613 } else {
1614 // JavaScript debug event listener.
iposva@chromium.org245aa852009-02-10 00:49:54 +00001615 ASSERT(event_listener_->IsJSFunction());
1616 Handle<JSFunction> fun(Handle<JSFunction>::cast(event_listener_));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001617
1618 // Invoke the JavaScript debug event listener.
1619 const int argc = 4;
1620 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1621 exec_state.location(),
1622 event_data.location(),
iposva@chromium.org245aa852009-02-10 00:49:54 +00001623 event_listener_data_.location() };
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001624 Handle<Object> result = Execution::TryCall(fun, Top::global(),
1625 argc, argv, &caught_exception);
1626 if (caught_exception) {
1627 // Silently ignore exceptions from debug event listeners.
1628 }
1629 }
1630 }
ager@chromium.org32912102009-01-16 10:38:43 +00001631
1632 // Clear the mirror cache.
1633 Debug::ClearMirrorCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001634}
1635
1636
iposva@chromium.org245aa852009-02-10 00:49:54 +00001637void Debugger::SetEventListener(Handle<Object> callback,
1638 Handle<Object> data) {
1639 HandleScope scope;
1640
1641 // Clear the global handles for the event listener and the event listener data
1642 // object.
1643 if (!event_listener_.is_null()) {
1644 GlobalHandles::Destroy(
1645 reinterpret_cast<Object**>(event_listener_.location()));
1646 event_listener_ = Handle<Object>();
1647 }
1648 if (!event_listener_data_.is_null()) {
1649 GlobalHandles::Destroy(
1650 reinterpret_cast<Object**>(event_listener_data_.location()));
1651 event_listener_data_ = Handle<Object>();
1652 }
1653
1654 // If there is a new debug event listener register it together with its data
1655 // object.
1656 if (!callback->IsUndefined() && !callback->IsNull()) {
1657 event_listener_ = Handle<Object>::cast(GlobalHandles::Create(*callback));
1658 if (data.is_null()) {
1659 data = Factory::undefined_value();
1660 }
1661 event_listener_data_ = Handle<Object>::cast(GlobalHandles::Create(*data));
1662 }
1663
1664 UpdateActiveDebugger();
1665}
1666
1667
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001668void Debugger::SetMessageHandler(v8::DebugMessageHandler handler, void* data) {
1669 debug_message_handler_ = handler;
1670 debug_message_handler_data_ = data;
1671 if (!message_thread_) {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001672 message_thread_ = new DebugMessageThread();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001673 message_thread_->Start();
1674 }
1675 UpdateActiveDebugger();
1676}
1677
1678
kasper.lund7276f142008-07-30 08:49:36 +00001679// Posts an output message from the debugger to the debug_message_handler
1680// callback. This callback is part of the public API. Messages are
1681// kept internally as Vector<uint16_t> strings, which are allocated in various
1682// places and deallocated by the calling function sometime after this call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001683void Debugger::SendMessage(Vector< uint16_t> message) {
1684 if (debug_message_handler_ != NULL) {
1685 debug_message_handler_(message.start(), message.length(),
1686 debug_message_handler_data_);
1687 }
1688}
1689
1690
1691void Debugger::ProcessCommand(Vector<const uint16_t> command) {
1692 if (message_thread_ != NULL) {
1693 message_thread_->ProcessCommand(
1694 Vector<uint16_t>(const_cast<uint16_t *>(command.start()),
1695 command.length()));
1696 }
1697}
1698
1699
1700void Debugger::UpdateActiveDebugger() {
iposva@chromium.org245aa852009-02-10 00:49:54 +00001701 set_debugger_active((message_thread_ != NULL &&
1702 debug_message_handler_ != NULL) ||
1703 !event_listener_.is_null());
1704 if (!debugger_active() && message_thread_) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001705 message_thread_->OnDebuggerInactive();
iposva@chromium.org245aa852009-02-10 00:49:54 +00001706 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001707}
1708
1709
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001710Handle<Object> Debugger::Call(Handle<JSFunction> fun,
1711 Handle<Object> data,
1712 bool* pending_exception) {
1713 // Enter the debugger.
1714 EnterDebugger debugger;
1715 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
1716 return Factory::undefined_value();
1717 }
1718
1719 // Create the execution state.
1720 bool caught_exception = false;
1721 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1722 if (caught_exception) {
1723 return Factory::undefined_value();
1724 }
1725
1726 static const int kArgc = 2;
1727 Object** argv[kArgc] = { exec_state.location(), data.location() };
1728 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
1729 kArgc, argv, pending_exception);
1730 return result;
1731}
1732
1733
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001734DebugMessageThread::DebugMessageThread()
1735 : host_running_(true),
kasper.lund7276f142008-07-30 08:49:36 +00001736 command_queue_(kQueueInitialSize),
1737 message_queue_(kQueueInitialSize) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001738 command_received_ = OS::CreateSemaphore(0);
kasper.lund7276f142008-07-30 08:49:36 +00001739 message_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001740}
1741
kasper.lund7276f142008-07-30 08:49:36 +00001742// Does not free resources held by DebugMessageThread
1743// because this cannot be done thread-safely.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001744DebugMessageThread::~DebugMessageThread() {
1745}
1746
1747
kasper.lund7276f142008-07-30 08:49:36 +00001748// Puts an event coming from V8 on the queue. Creates
1749// a copy of the JSON formatted event string managed by the V8.
1750// Called by the V8 thread.
1751// The new copy of the event string is destroyed in Run().
1752void DebugMessageThread::SendMessage(Vector<uint16_t> message) {
1753 Vector<uint16_t> message_copy = message.Clone();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001754 Logger::DebugTag("Put message on event message_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001755 message_queue_.Put(message_copy);
1756 message_received_->Signal();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001757}
1758
1759
ager@chromium.org8bb60582008-12-11 12:02:20 +00001760bool DebugMessageThread::SetEventJSONFromEvent(Handle<Object> event_data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001761 v8::HandleScope scope;
1762 // Call toJSONProtocol on the debug event object.
1763 v8::Local<v8::Object> api_event_data =
1764 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data));
1765 v8::Local<v8::String> fun_name = v8::String::New("toJSONProtocol");
1766 v8::Local<v8::Function> fun =
1767 v8::Function::Cast(*api_event_data->Get(fun_name));
1768 v8::TryCatch try_catch;
kasper.lund7276f142008-07-30 08:49:36 +00001769 v8::Local<v8::Value> json_event = *fun->Call(api_event_data, 0, NULL);
1770 v8::Local<v8::String> json_event_string;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001771 if (!try_catch.HasCaught()) {
kasper.lund7276f142008-07-30 08:49:36 +00001772 if (!json_event->IsUndefined()) {
1773 json_event_string = json_event->ToString();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001774 if (FLAG_trace_debug_json) {
kasper.lund7276f142008-07-30 08:49:36 +00001775 PrintLn(json_event_string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001776 }
kasper.lund7276f142008-07-30 08:49:36 +00001777 v8::String::Value val(json_event_string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001778 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001779 json_event_string->Length());
kasper.lund7276f142008-07-30 08:49:36 +00001780 SendMessage(str);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001781 } else {
kasper.lund7276f142008-07-30 08:49:36 +00001782 SendMessage(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001783 }
1784 } else {
1785 PrintLn(try_catch.Exception());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001786 return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001787 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001788 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001789}
1790
1791
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001792void DebugMessageThread::Run() {
kasper.lund7276f142008-07-30 08:49:36 +00001793 // Sends debug events to an installed debugger message callback.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001794 while (true) {
kasper.lund7276f142008-07-30 08:49:36 +00001795 // Wait and Get are paired so that semaphore count equals queue length.
1796 message_received_->Wait();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001797 Logger::DebugTag("Get message from event message_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001798 Vector<uint16_t> message = message_queue_.Get();
1799 if (message.length() > 0) {
1800 Debugger::SendMessage(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001801 }
1802 }
1803}
1804
1805
kasper.lund44510672008-07-25 07:37:58 +00001806// This method is called by the V8 thread whenever a debug event occurs in
1807// the VM.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001808void DebugMessageThread::DebugEvent(v8::DebugEvent event,
1809 Handle<Object> exec_state,
1810 Handle<Object> event_data) {
kasper.lund212ac232008-07-16 07:07:30 +00001811 if (!Debug::Load()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001812
1813 // Process the individual events.
1814 bool interactive = false;
1815 switch (event) {
1816 case v8::Break:
v8.team.kasperl727e9952008-09-02 14:56:44 +00001817 interactive = true; // Break event is always interactive
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001818 break;
1819 case v8::Exception:
v8.team.kasperl727e9952008-09-02 14:56:44 +00001820 interactive = true; // Exception event is always interactive
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001821 break;
1822 case v8::BeforeCompile:
1823 break;
1824 case v8::AfterCompile:
1825 break;
1826 case v8::NewFunction:
1827 break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001828 default:
1829 UNREACHABLE();
1830 }
1831
1832 // Done if not interactive.
1833 if (!interactive) return;
1834
1835 // Get the DebugCommandProcessor.
1836 v8::Local<v8::Object> api_exec_state =
1837 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
1838 v8::Local<v8::String> fun_name =
1839 v8::String::New("debugCommandProcessor");
1840 v8::Local<v8::Function> fun =
1841 v8::Function::Cast(*api_exec_state->Get(fun_name));
1842 v8::TryCatch try_catch;
1843 v8::Local<v8::Object> cmd_processor =
1844 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
1845 if (try_catch.HasCaught()) {
1846 PrintLn(try_catch.Exception());
1847 return;
1848 }
1849
v8.team.kasperl727e9952008-09-02 14:56:44 +00001850 // Notify the debugger that a debug event has occurred.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001851 bool success = SetEventJSONFromEvent(event_data);
1852 if (!success) {
1853 // If failed to notify debugger just continue running.
1854 return;
1855 }
kasper.lund7276f142008-07-30 08:49:36 +00001856
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001857 // Wait for requests from the debugger.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001858 host_running_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001859 while (true) {
kasper.lund7276f142008-07-30 08:49:36 +00001860 command_received_->Wait();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001861 Logger::DebugTag("Got request from command queue, in interactive loop.");
kasper.lund7276f142008-07-30 08:49:36 +00001862 Vector<uint16_t> command = command_queue_.Get();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001863 ASSERT(!host_running_);
1864 if (!Debugger::debugger_active()) {
1865 host_running_ = true;
1866 return;
1867 }
1868
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001869 // Invoke the JavaScript to process the debug request.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001870 v8::Local<v8::String> fun_name;
1871 v8::Local<v8::Function> fun;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001872 v8::Local<v8::Value> request;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001873 v8::TryCatch try_catch;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001874 fun_name = v8::String::New("processDebugRequest");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001875 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001876 request = v8::String::New(reinterpret_cast<uint16_t*>(command.start()),
kasper.lund7276f142008-07-30 08:49:36 +00001877 command.length());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001878 static const int kArgc = 1;
1879 v8::Handle<Value> argv[kArgc] = { request };
1880 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001881
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001882 // Get the response.
1883 v8::Local<v8::String> response;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001884 bool running = false;
1885 if (!try_catch.HasCaught()) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001886 // Get response string.
1887 if (!response_val->IsUndefined()) {
1888 response = v8::String::Cast(*response_val);
1889 } else {
1890 response = v8::String::New("");
1891 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001892
1893 // Log the JSON request/response.
1894 if (FLAG_trace_debug_json) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001895 PrintLn(request);
1896 PrintLn(response);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001897 }
1898
1899 // Get the running state.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001900 fun_name = v8::String::New("isRunning");
1901 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
1902 static const int kArgc = 1;
1903 v8::Handle<Value> argv[kArgc] = { response };
1904 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
1905 if (!try_catch.HasCaught()) {
1906 running = running_val->ToBoolean()->Value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001907 }
1908 } else {
1909 // In case of failure the result text is the exception text.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001910 response = try_catch.Exception()->ToString();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001911 }
1912
1913 // Convert text result to C string.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001914 v8::String::Value val(response);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001915 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001916 response->Length());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001917
kasper.lund7276f142008-07-30 08:49:36 +00001918 // Set host_running_ correctly for nested debugger evaluations.
1919 host_running_ = running;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001920
1921 // Return the result.
kasper.lund7276f142008-07-30 08:49:36 +00001922 SendMessage(str);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001923
1924 // Return from debug event processing is VM should be running.
1925 if (running) {
1926 return;
1927 }
1928 }
1929}
1930
1931
kasper.lund7276f142008-07-30 08:49:36 +00001932// Puts a command coming from the public API on the queue. Creates
1933// a copy of the command string managed by the debugger. Up to this
1934// point, the command data was managed by the API client. Called
1935// by the API client thread. This is where the API client hands off
1936// processing of the command to the DebugMessageThread thread.
1937// The new copy of the command is destroyed in HandleCommand().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001938void DebugMessageThread::ProcessCommand(Vector<uint16_t> command) {
kasper.lund7276f142008-07-30 08:49:36 +00001939 Vector<uint16_t> command_copy = command.Clone();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001940 Logger::DebugTag("Put command on command_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001941 command_queue_.Put(command_copy);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001942 command_received_->Signal();
1943}
1944
1945
1946void DebugMessageThread::OnDebuggerInactive() {
kasper.lund7276f142008-07-30 08:49:36 +00001947 // Send an empty command to the debugger if in a break to make JavaScript run
1948 // again if the debugger is closed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001949 if (!host_running_) {
kasper.lund7276f142008-07-30 08:49:36 +00001950 ProcessCommand(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001951 }
1952}
1953
kasper.lund7276f142008-07-30 08:49:36 +00001954
1955MessageQueue::MessageQueue(int size) : start_(0), end_(0), size_(size) {
1956 messages_ = NewArray<Vector<uint16_t> >(size);
1957}
1958
1959
1960MessageQueue::~MessageQueue() {
1961 DeleteArray(messages_);
1962}
1963
1964
1965Vector<uint16_t> MessageQueue::Get() {
1966 ASSERT(!IsEmpty());
1967 int result = start_;
1968 start_ = (start_ + 1) % size_;
1969 return messages_[result];
1970}
1971
1972
1973void MessageQueue::Put(const Vector<uint16_t>& message) {
1974 if ((end_ + 1) % size_ == start_) {
1975 Expand();
1976 }
1977 messages_[end_] = message;
1978 end_ = (end_ + 1) % size_;
1979}
1980
1981
1982void MessageQueue::Expand() {
1983 MessageQueue new_queue(size_ * 2);
1984 while (!IsEmpty()) {
1985 new_queue.Put(Get());
1986 }
1987 Vector<uint16_t>* array_to_free = messages_;
1988 *this = new_queue;
1989 new_queue.messages_ = array_to_free;
1990 // Automatic destructor called on new_queue, freeing array_to_free.
1991}
1992
1993
1994LockingMessageQueue::LockingMessageQueue(int size) : queue_(size) {
1995 lock_ = OS::CreateMutex();
1996}
1997
1998
1999LockingMessageQueue::~LockingMessageQueue() {
2000 delete lock_;
2001}
2002
2003
2004bool LockingMessageQueue::IsEmpty() const {
2005 ScopedLock sl(lock_);
2006 return queue_.IsEmpty();
2007}
2008
2009
2010Vector<uint16_t> LockingMessageQueue::Get() {
2011 ScopedLock sl(lock_);
2012 Vector<uint16_t> result = queue_.Get();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002013 Logger::DebugEvent("Get", result);
kasper.lund7276f142008-07-30 08:49:36 +00002014 return result;
2015}
2016
2017
2018void LockingMessageQueue::Put(const Vector<uint16_t>& message) {
2019 ScopedLock sl(lock_);
2020 queue_.Put(message);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002021 Logger::DebugEvent("Put", message);
kasper.lund7276f142008-07-30 08:49:36 +00002022}
2023
2024
2025void LockingMessageQueue::Clear() {
2026 ScopedLock sl(lock_);
2027 queue_.Clear();
2028}
2029
2030
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002031} } // namespace v8::internal