blob: ef059addc8eaf3848e70f75c6fecde63db89a45b [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())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000288 // This path is currently only used on IA32 as JSExitFrame on ARM uses a
289 // stub.
290 // Patch the JS frame exit code with a debug break call. See
291 // VisitReturnStatement and ExitJSFrame in codegen-ia32.cc for the
292 // precise return instructions sequence.
293 ASSERT(Debug::kIa32JSReturnSequenceLength >=
294 Debug::kIa32CallInstructionLength);
295 rinfo()->patch_code_with_call(Debug::debug_break_return_entry()->entry(),
296 Debug::kIa32JSReturnSequenceLength - Debug::kIa32CallInstructionLength);
297 } else {
298 // Patch the original code with the current address as the current address
299 // might have changed by the inline caching since the code was copied.
300 original_rinfo()->set_target_address(rinfo()->target_address());
301
302 // Patch the code to invoke the builtin debug break function matching the
303 // calling convention used by the call site.
304 Handle<Code> dbgbrk_code(Debug::FindDebugBreak(rinfo()));
305 rinfo()->set_target_address(dbgbrk_code->entry());
306 }
307 ASSERT(IsDebugBreak());
308}
309
310
311void BreakLocationIterator::ClearDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000312 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000313 // Restore the JS frame exit code.
314 rinfo()->patch_code(original_rinfo()->pc(),
315 Debug::kIa32JSReturnSequenceLength);
316 } else {
317 // Patch the code to the original invoke.
318 rinfo()->set_target_address(original_rinfo()->target_address());
319 }
320 ASSERT(!IsDebugBreak());
321}
322
323
324void BreakLocationIterator::PrepareStepIn() {
325 // Step in can only be prepared if currently positioned on an IC call or
326 // construct call.
327 Address target = rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000328 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000329 if (code->is_call_stub()) {
330 // Step in through IC call is handled by the runtime system. Therefore make
331 // sure that the any current IC is cleared and the runtime system is
332 // called. If the executing code has a debug break at the location change
333 // the call in the original code as it is the code there that will be
334 // executed in place of the debug break call.
335 Handle<Code> stub = ComputeCallDebugPrepareStepIn(code->arguments_count());
336 if (IsDebugBreak()) {
337 original_rinfo()->set_target_address(stub->entry());
338 } else {
339 rinfo()->set_target_address(stub->entry());
340 }
341 } else {
v8.team.kasperl727e9952008-09-02 14:56:44 +0000342 // Step in through constructs call requires no changes to the running code.
ager@chromium.org236ad962008-09-25 09:45:57 +0000343 ASSERT(RelocInfo::IsConstructCall(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000344 }
345}
346
347
348// Check whether the break point is at a position which will exit the function.
349bool BreakLocationIterator::IsExit() const {
ager@chromium.org236ad962008-09-25 09:45:57 +0000350 return (RelocInfo::IsJSReturn(rmode()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000351}
352
353
354bool BreakLocationIterator::HasBreakPoint() {
355 return debug_info_->HasBreakPoint(code_position());
356}
357
358
359// Check whether there is a debug break at the current position.
360bool BreakLocationIterator::IsDebugBreak() {
ager@chromium.org236ad962008-09-25 09:45:57 +0000361 if (RelocInfo::IsJSReturn(rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000362 // This is IA32 specific but works as long as the ARM version
363 // still uses a stub for JSExitFrame.
364 //
365 // TODO(1240753): Make the test architecture independent or split
366 // parts of the debugger into architecture dependent files.
367 return (*(rinfo()->pc()) == 0xE8);
368 } else {
369 return Debug::IsDebugBreak(rinfo()->target_address());
370 }
371}
372
373
374Object* BreakLocationIterator::BreakPointObjects() {
375 return debug_info_->GetBreakPointObjects(code_position());
376}
377
378
379bool BreakLocationIterator::RinfoDone() const {
380 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
381 return reloc_iterator_->done();
382}
383
384
385void BreakLocationIterator::RinfoNext() {
386 reloc_iterator_->next();
387 reloc_iterator_original_->next();
388#ifdef DEBUG
389 ASSERT(reloc_iterator_->done() == reloc_iterator_original_->done());
390 if (!reloc_iterator_->done()) {
391 ASSERT(rmode() == original_rmode());
392 }
393#endif
394}
395
396
397bool Debug::has_break_points_ = false;
398DebugInfoListNode* Debug::debug_info_list_ = NULL;
399
400
401// Threading support.
402void Debug::ThreadInit() {
403 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +0000404 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000405 thread_local_.step_count_ = 0;
406 thread_local_.last_fp_ = 0;
407 thread_local_.step_into_fp_ = 0;
408 thread_local_.after_break_target_ = 0;
409}
410
411
412JSCallerSavedBuffer Debug::registers_;
413Debug::ThreadLocal Debug::thread_local_;
414
415
416char* Debug::ArchiveDebug(char* storage) {
417 char* to = storage;
418 memcpy(to, reinterpret_cast<char*>(&thread_local_), sizeof(ThreadLocal));
419 to += sizeof(ThreadLocal);
420 memcpy(to, reinterpret_cast<char*>(&registers_), sizeof(registers_));
421 ThreadInit();
422 ASSERT(to <= storage + ArchiveSpacePerThread());
423 return storage + ArchiveSpacePerThread();
424}
425
426
427char* Debug::RestoreDebug(char* storage) {
428 char* from = storage;
429 memcpy(reinterpret_cast<char*>(&thread_local_), from, sizeof(ThreadLocal));
430 from += sizeof(ThreadLocal);
431 memcpy(reinterpret_cast<char*>(&registers_), from, sizeof(registers_));
432 ASSERT(from <= storage + ArchiveSpacePerThread());
433 return storage + ArchiveSpacePerThread();
434}
435
436
437int Debug::ArchiveSpacePerThread() {
438 return sizeof(ThreadLocal) + sizeof(registers_);
439}
440
441
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000442// Default break enabled.
443bool Debug::disable_break_ = false;
444
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000445// Default call debugger on uncaught exception.
446bool Debug::break_on_exception_ = false;
447bool Debug::break_on_uncaught_exception_ = true;
448
449Handle<Context> Debug::debug_context_ = Handle<Context>();
450Code* Debug::debug_break_return_entry_ = NULL;
451Code* Debug::debug_break_return_ = NULL;
452
453
kasperl@chromium.org5a8ca6c2008-10-23 13:57:19 +0000454void Debug::HandleWeakDebugInfo(v8::Persistent<v8::Value> obj, void* data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000455 DebugInfoListNode* node = reinterpret_cast<DebugInfoListNode*>(data);
456 RemoveDebugInfo(node->debug_info());
457#ifdef DEBUG
458 node = Debug::debug_info_list_;
459 while (node != NULL) {
460 ASSERT(node != reinterpret_cast<DebugInfoListNode*>(data));
461 node = node->next();
462 }
463#endif
464}
465
466
467DebugInfoListNode::DebugInfoListNode(DebugInfo* debug_info): next_(NULL) {
468 // Globalize the request debug info object and make it weak.
469 debug_info_ = Handle<DebugInfo>::cast((GlobalHandles::Create(debug_info)));
470 GlobalHandles::MakeWeak(reinterpret_cast<Object**>(debug_info_.location()),
471 this, Debug::HandleWeakDebugInfo);
472}
473
474
475DebugInfoListNode::~DebugInfoListNode() {
476 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_info_.location()));
477}
478
479
480void Debug::Setup(bool create_heap_objects) {
481 ThreadInit();
482 if (create_heap_objects) {
483 // Get code to handle entry to debug break on return.
484 debug_break_return_entry_ =
485 Builtins::builtin(Builtins::Return_DebugBreakEntry);
486 ASSERT(debug_break_return_entry_->IsCode());
487
488 // Get code to handle debug break on return.
489 debug_break_return_ =
490 Builtins::builtin(Builtins::Return_DebugBreak);
491 ASSERT(debug_break_return_->IsCode());
492 }
493}
494
495
496bool Debug::CompileDebuggerScript(int index) {
497 HandleScope scope;
498
kasper.lund44510672008-07-25 07:37:58 +0000499 // Bail out if the index is invalid.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000500 if (index == -1) {
501 return false;
502 }
kasper.lund44510672008-07-25 07:37:58 +0000503
504 // Find source and name for the requested script.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000505 Handle<String> source_code = Bootstrapper::NativesSourceLookup(index);
506 Vector<const char> name = Natives::GetScriptName(index);
507 Handle<String> script_name = Factory::NewStringFromAscii(name);
508
509 // Compile the script.
510 bool allow_natives_syntax = FLAG_allow_natives_syntax;
511 FLAG_allow_natives_syntax = true;
512 Handle<JSFunction> boilerplate;
513 boilerplate = Compiler::Compile(source_code, script_name, 0, 0, NULL, NULL);
514 FLAG_allow_natives_syntax = allow_natives_syntax;
515
516 // Silently ignore stack overflows during compilation.
517 if (boilerplate.is_null()) {
518 ASSERT(Top::has_pending_exception());
519 Top::clear_pending_exception();
520 return false;
521 }
522
kasper.lund44510672008-07-25 07:37:58 +0000523 // Execute the boilerplate function in the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000524 Handle<Context> context = Top::global_context();
kasper.lund44510672008-07-25 07:37:58 +0000525 bool caught_exception = false;
526 Handle<JSFunction> function =
527 Factory::NewFunctionFromBoilerplate(boilerplate, context);
528 Handle<Object> result =
529 Execution::TryCall(function, Handle<Object>(context->global()),
530 0, NULL, &caught_exception);
531
532 // Check for caught exceptions.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000533 if (caught_exception) {
ager@chromium.org9258b6b2008-09-11 09:11:10 +0000534 Handle<Object> message = MessageHandler::MakeMessageObject(
535 "error_loading_debugger", NULL, HandleVector<Object>(&result, 1),
536 Handle<String>());
537 MessageHandler::ReportMessage(NULL, message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000538 return false;
539 }
540
kasper.lund44510672008-07-25 07:37:58 +0000541 // Mark this script as native and return successfully.
542 Handle<Script> script(Script::cast(function->shared()->script()));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000543 script->set_type(Smi::FromInt(SCRIPT_TYPE_NATIVE));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000544 return true;
545}
546
547
548bool Debug::Load() {
549 // Return if debugger is already loaded.
kasper.lund212ac232008-07-16 07:07:30 +0000550 if (IsLoaded()) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000551
kasper.lund44510672008-07-25 07:37:58 +0000552 // Bail out if we're already in the process of compiling the native
553 // JavaScript source code for the debugger.
mads.s.agercbaa0602008-08-14 13:41:48 +0000554 if (Debugger::compiling_natives() || Debugger::is_loading_debugger())
555 return false;
556 Debugger::set_loading_debugger(true);
kasper.lund44510672008-07-25 07:37:58 +0000557
558 // Disable breakpoints and interrupts while compiling and running the
559 // debugger scripts including the context creation code.
560 DisableBreak disable(true);
561 PostponeInterruptsScope postpone;
562
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000563 // Create the debugger context.
564 HandleScope scope;
kasper.lund44510672008-07-25 07:37:58 +0000565 Handle<Context> context =
566 Bootstrapper::CreateEnvironment(Handle<Object>::null(),
567 v8::Handle<ObjectTemplate>(),
568 NULL);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000569
kasper.lund44510672008-07-25 07:37:58 +0000570 // Use the debugger context.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000571 SaveContext save;
kasper.lund44510672008-07-25 07:37:58 +0000572 Top::set_context(*context);
kasper.lund44510672008-07-25 07:37:58 +0000573
574 // Expose the builtins object in the debugger context.
575 Handle<String> key = Factory::LookupAsciiSymbol("builtins");
576 Handle<GlobalObject> global = Handle<GlobalObject>(context->global());
577 SetProperty(global, key, Handle<Object>(global->builtins()), NONE);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000578
579 // Compile the JavaScript for the debugger in the debugger context.
580 Debugger::set_compiling_natives(true);
kasper.lund44510672008-07-25 07:37:58 +0000581 bool caught_exception =
582 !CompileDebuggerScript(Natives::GetIndex("mirror")) ||
583 !CompileDebuggerScript(Natives::GetIndex("debug"));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000584 Debugger::set_compiling_natives(false);
585
mads.s.agercbaa0602008-08-14 13:41:48 +0000586 // Make sure we mark the debugger as not loading before we might
587 // return.
588 Debugger::set_loading_debugger(false);
589
kasper.lund44510672008-07-25 07:37:58 +0000590 // Check for caught exceptions.
591 if (caught_exception) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000592
593 // Debugger loaded.
kasper.lund44510672008-07-25 07:37:58 +0000594 debug_context_ = Handle<Context>::cast(GlobalHandles::Create(*context));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000595 return true;
596}
597
598
599void Debug::Unload() {
600 // Return debugger is not loaded.
601 if (!IsLoaded()) {
602 return;
603 }
604
605 // Clear debugger context global handle.
606 GlobalHandles::Destroy(reinterpret_cast<Object**>(debug_context_.location()));
607 debug_context_ = Handle<Context>();
608}
609
610
611void Debug::Iterate(ObjectVisitor* v) {
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000612#define VISIT(field) v->VisitPointer(bit_cast<Object**, Code**>(&(field)));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000613 VISIT(debug_break_return_entry_);
614 VISIT(debug_break_return_);
615#undef VISIT
616}
617
618
619Object* Debug::Break(Arguments args) {
620 HandleScope scope;
mads.s.ager31e71382008-08-13 09:32:07 +0000621 ASSERT(args.length() == 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000622
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000623 // Get the top-most JavaScript frame.
624 JavaScriptFrameIterator it;
625 JavaScriptFrame* frame = it.frame();
626
627 // Just continue if breaks are disabled or debugger cannot be loaded.
628 if (disable_break() || !Load()) {
629 SetAfterBreakTarget(frame);
mads.s.ager31e71382008-08-13 09:32:07 +0000630 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000631 }
632
kasperl@chromium.org41044eb2008-10-06 08:24:46 +0000633 // Enter the debugger.
634 EnterDebugger debugger;
635 if (debugger.FailedToEnter()) {
636 return Heap::undefined_value();
637 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000638
kasper.lund44510672008-07-25 07:37:58 +0000639 // Postpone interrupt during breakpoint processing.
640 PostponeInterruptsScope postpone;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000641
642 // Get the debug info (create it if it does not exist).
643 Handle<SharedFunctionInfo> shared =
644 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
645 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
646
647 // Find the break point where execution has stopped.
648 BreakLocationIterator break_location_iterator(debug_info,
649 ALL_BREAK_LOCATIONS);
650 break_location_iterator.FindBreakLocationFromAddress(frame->pc());
651
652 // Check whether step next reached a new statement.
653 if (!StepNextContinue(&break_location_iterator, frame)) {
654 // Decrease steps left if performing multiple steps.
655 if (thread_local_.step_count_ > 0) {
656 thread_local_.step_count_--;
657 }
658 }
659
660 // If there is one or more real break points check whether any of these are
661 // triggered.
662 Handle<Object> break_points_hit(Heap::undefined_value());
663 if (break_location_iterator.HasBreakPoint()) {
664 Handle<Object> break_point_objects =
665 Handle<Object>(break_location_iterator.BreakPointObjects());
666 break_points_hit = CheckBreakPoints(break_point_objects);
667 }
668
669 // Notify debugger if a real break point is triggered or if performing single
670 // stepping with no more steps to perform. Otherwise do another step.
671 if (!break_points_hit->IsUndefined() ||
672 (thread_local_.last_step_action_ != StepNone &&
673 thread_local_.step_count_ == 0)) {
674 // Clear all current stepping setup.
675 ClearStepping();
676
677 // Notify the debug event listeners.
678 Debugger::OnDebugBreak(break_points_hit);
679 } else if (thread_local_.last_step_action_ != StepNone) {
680 // Hold on to last step action as it is cleared by the call to
681 // ClearStepping.
682 StepAction step_action = thread_local_.last_step_action_;
683 int step_count = thread_local_.step_count_;
684
685 // Clear all current stepping setup.
686 ClearStepping();
687
688 // Set up for the remaining steps.
689 PrepareStep(step_action, step_count);
690 }
691
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000692 // Install jump to the call address which was overwritten.
693 SetAfterBreakTarget(frame);
694
mads.s.ager31e71382008-08-13 09:32:07 +0000695 return Heap::undefined_value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000696}
697
698
699// Check the break point objects for whether one or more are actually
700// triggered. This function returns a JSArray with the break point objects
701// which is triggered.
702Handle<Object> Debug::CheckBreakPoints(Handle<Object> break_point_objects) {
703 int break_points_hit_count = 0;
704 Handle<JSArray> break_points_hit = Factory::NewJSArray(1);
705
v8.team.kasperl727e9952008-09-02 14:56:44 +0000706 // If there are multiple break points they are in a FixedArray.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000707 ASSERT(!break_point_objects->IsUndefined());
708 if (break_point_objects->IsFixedArray()) {
709 Handle<FixedArray> array(FixedArray::cast(*break_point_objects));
710 for (int i = 0; i < array->length(); i++) {
711 Handle<Object> o(array->get(i));
712 if (CheckBreakPoint(o)) {
713 break_points_hit->SetElement(break_points_hit_count++, *o);
714 }
715 }
716 } else {
717 if (CheckBreakPoint(break_point_objects)) {
718 break_points_hit->SetElement(break_points_hit_count++,
719 *break_point_objects);
720 }
721 }
722
723 // Return undefined if no break points where triggered.
724 if (break_points_hit_count == 0) {
725 return Factory::undefined_value();
726 }
727 return break_points_hit;
728}
729
730
731// Check whether a single break point object is triggered.
732bool Debug::CheckBreakPoint(Handle<Object> break_point_object) {
733 // Ignore check if break point object is not a JSObject.
734 if (!break_point_object->IsJSObject()) return true;
735
736 // Get the function CheckBreakPoint (defined in debug.js).
737 Handle<JSFunction> check_break_point =
738 Handle<JSFunction>(JSFunction::cast(
739 debug_context()->global()->GetProperty(
740 *Factory::LookupAsciiSymbol("IsBreakPointTriggered"))));
741
742 // Get the break id as an object.
743 Handle<Object> break_id = Factory::NewNumberFromInt(Top::break_id());
744
745 // Call HandleBreakPointx.
746 bool caught_exception = false;
747 const int argc = 2;
748 Object** argv[argc] = {
749 break_id.location(),
750 reinterpret_cast<Object**>(break_point_object.location())
751 };
752 Handle<Object> result = Execution::TryCall(check_break_point,
753 Top::builtins(), argc, argv,
754 &caught_exception);
755
756 // If exception or non boolean result handle as not triggered
757 if (caught_exception || !result->IsBoolean()) {
758 return false;
759 }
760
761 // Return whether the break point is triggered.
762 return *result == Heap::true_value();
763}
764
765
766// Check whether the function has debug information.
767bool Debug::HasDebugInfo(Handle<SharedFunctionInfo> shared) {
768 return !shared->debug_info()->IsUndefined();
769}
770
771
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000772// Return the debug info for this function. EnsureDebugInfo must be called
773// prior to ensure the debug info has been generated for shared.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000774Handle<DebugInfo> Debug::GetDebugInfo(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000775 ASSERT(HasDebugInfo(shared));
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000776 return Handle<DebugInfo>(DebugInfo::cast(shared->debug_info()));
777}
778
779
780void Debug::SetBreakPoint(Handle<SharedFunctionInfo> shared,
781 int source_position,
782 Handle<Object> break_point_object) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000783 if (!EnsureDebugInfo(shared)) {
784 // Return if retrieving debug info failed.
785 return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000786 }
787
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000788 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000789 // Source positions starts with zero.
790 ASSERT(source_position >= 0);
791
792 // Find the break point and change it.
793 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
794 it.FindBreakLocationFromPosition(source_position);
795 it.SetBreakPoint(break_point_object);
796
797 // At least one active break point now.
798 ASSERT(debug_info->GetBreakPointCount() > 0);
799}
800
801
802void Debug::ClearBreakPoint(Handle<Object> break_point_object) {
803 DebugInfoListNode* node = debug_info_list_;
804 while (node != NULL) {
805 Object* result = DebugInfo::FindBreakPointInfo(node->debug_info(),
806 break_point_object);
807 if (!result->IsUndefined()) {
808 // Get information in the break point.
809 BreakPointInfo* break_point_info = BreakPointInfo::cast(result);
810 Handle<DebugInfo> debug_info = node->debug_info();
811 Handle<SharedFunctionInfo> shared(debug_info->shared());
812 int source_position = break_point_info->statement_position()->value();
813
814 // Source positions starts with zero.
815 ASSERT(source_position >= 0);
816
817 // Find the break point and clear it.
818 BreakLocationIterator it(debug_info, SOURCE_BREAK_LOCATIONS);
819 it.FindBreakLocationFromPosition(source_position);
820 it.ClearBreakPoint(break_point_object);
821
822 // If there are no more break points left remove the debug info for this
823 // function.
824 if (debug_info->GetBreakPointCount() == 0) {
825 RemoveDebugInfo(debug_info);
826 }
827
828 return;
829 }
830 node = node->next();
831 }
832}
833
834
835void Debug::FloodWithOneShot(Handle<SharedFunctionInfo> shared) {
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000836 // Make sure the function has setup the debug info.
837 if (!EnsureDebugInfo(shared)) {
838 // Return if we failed to retrieve the debug info.
839 return;
840 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000841
842 // Flood the function with break points.
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000843 BreakLocationIterator it(GetDebugInfo(shared), ALL_BREAK_LOCATIONS);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000844 while (!it.Done()) {
845 it.SetOneShot();
846 it.Next();
847 }
848}
849
850
851void Debug::FloodHandlerWithOneShot() {
ager@chromium.org8bb60582008-12-11 12:02:20 +0000852 // Iterate through the JavaScript stack looking for handlers.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000853 StackFrame::Id id = Top::break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000854 if (id == StackFrame::NO_ID) {
855 // If there is no JavaScript stack don't do anything.
856 return;
857 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000858 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
859 JavaScriptFrame* frame = it.frame();
860 if (frame->HasHandler()) {
861 Handle<SharedFunctionInfo> shared =
862 Handle<SharedFunctionInfo>(
863 JSFunction::cast(frame->function())->shared());
864 // Flood the function with the catch block with break points
865 FloodWithOneShot(shared);
866 return;
867 }
868 }
869}
870
871
872void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
873 if (type == BreakUncaughtException) {
874 break_on_uncaught_exception_ = enable;
875 } else {
876 break_on_exception_ = enable;
877 }
878}
879
880
881void Debug::PrepareStep(StepAction step_action, int step_count) {
882 HandleScope scope;
883 ASSERT(Debug::InDebugger());
884
885 // Remember this step action and count.
886 thread_local_.last_step_action_ = step_action;
887 thread_local_.step_count_ = step_count;
888
889 // Get the frame where the execution has stopped and skip the debug frame if
890 // any. The debug frame will only be present if execution was stopped due to
891 // hitting a break point. In other situations (e.g. unhandled exception) the
892 // debug frame is not present.
893 StackFrame::Id id = Top::break_frame_id();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000894 if (id == StackFrame::NO_ID) {
895 // If there is no JavaScript stack don't do anything.
896 return;
897 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000898 JavaScriptFrameIterator frames_it(id);
899 JavaScriptFrame* frame = frames_it.frame();
900
901 // First of all ensure there is one-shot break points in the top handler
902 // if any.
903 FloodHandlerWithOneShot();
904
905 // If the function on the top frame is unresolved perform step out. This will
906 // be the case when calling unknown functions and having the debugger stopped
907 // in an unhandled exception.
908 if (!frame->function()->IsJSFunction()) {
909 // Step out: Find the calling JavaScript frame and flood it with
910 // breakpoints.
911 frames_it.Advance();
912 // Fill the function to return to with one-shot break points.
913 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
914 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
915 return;
916 }
917
918 // Get the debug info (create it if it does not exist).
919 Handle<SharedFunctionInfo> shared =
920 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000921 if (!EnsureDebugInfo(shared)) {
922 // Return if ensuring debug info failed.
923 return;
924 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
926
927 // Find the break location where execution has stopped.
928 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
929 it.FindBreakLocationFromAddress(frame->pc());
930
931 // Compute whether or not the target is a call target.
932 bool is_call_target = false;
ager@chromium.org236ad962008-09-25 09:45:57 +0000933 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000934 Address target = it.rinfo()->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +0000935 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000936 if (code->is_call_stub()) is_call_target = true;
937 }
938
v8.team.kasperl727e9952008-09-02 14:56:44 +0000939 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000940 if (it.IsExit() || step_action == StepOut) {
941 // Step out: If there is a JavaScript caller frame, we need to
942 // flood it with breakpoints.
943 frames_it.Advance();
944 if (!frames_it.done()) {
945 // Fill the function to return to with one-shot break points.
946 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
947 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
948 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000949 } else if (!(is_call_target || RelocInfo::IsConstructCall(it.rmode())) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000950 step_action == StepNext || step_action == StepMin) {
951 // Step next or step min.
952
953 // Fill the current function with one-shot break points.
954 FloodWithOneShot(shared);
955
956 // Remember source position and frame to handle step next.
957 thread_local_.last_statement_position_ =
958 debug_info->code()->SourceStatementPosition(frame->pc());
959 thread_local_.last_fp_ = frame->fp();
960 } else {
961 // Fill the current function with one-shot break points even for step in on
962 // a call target as the function called might be a native function for
963 // which step in will not stop.
964 FloodWithOneShot(shared);
965
966 // Step in or Step in min
967 it.PrepareStepIn();
968 ActivateStepIn(frame);
969 }
970}
971
972
973// Check whether the current debug break should be reported to the debugger. It
974// is used to have step next and step in only report break back to the debugger
975// if on a different frame or in a different statement. In some situations
976// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +0000977// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000978// steps before reporting break back to the debugger.
979bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
980 JavaScriptFrame* frame) {
981 // If the step last action was step next or step in make sure that a new
982 // statement is hit.
983 if (thread_local_.last_step_action_ == StepNext ||
984 thread_local_.last_step_action_ == StepIn) {
985 // Never continue if returning from function.
986 if (break_location_iterator->IsExit()) return false;
987
988 // Continue if we are still on the same frame and in the same statement.
989 int current_statement_position =
990 break_location_iterator->code()->SourceStatementPosition(frame->pc());
991 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +0000992 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000993 }
994
995 // No step next action - don't continue.
996 return false;
997}
998
999
1000// Check whether the code object at the specified address is a debug break code
1001// object.
1002bool Debug::IsDebugBreak(Address addr) {
ager@chromium.org8bb60582008-12-11 12:02:20 +00001003 Code* code = Code::GetCodeFromTargetAddress(addr);
kasper.lund7276f142008-07-30 08:49:36 +00001004 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001005}
1006
1007
1008// Check whether a code stub with the specified major key is a possible break
1009// point location when looking for source break locations.
1010bool Debug::IsSourceBreakStub(Code* code) {
1011 CodeStub::Major major_key = code->major_key();
1012 return major_key == CodeStub::CallFunction;
1013}
1014
1015
1016// Check whether a code stub with the specified major key is a possible break
1017// location.
1018bool Debug::IsBreakStub(Code* code) {
1019 CodeStub::Major major_key = code->major_key();
1020 return major_key == CodeStub::CallFunction ||
1021 major_key == CodeStub::StackCheck;
1022}
1023
1024
1025// Find the builtin to use for invoking the debug break
1026Handle<Code> Debug::FindDebugBreak(RelocInfo* rinfo) {
1027 // Find the builtin debug break function matching the calling convention
1028 // used by the call site.
ager@chromium.org236ad962008-09-25 09:45:57 +00001029 RelocInfo::Mode mode = rinfo->rmode();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001030
ager@chromium.org236ad962008-09-25 09:45:57 +00001031 if (RelocInfo::IsCodeTarget(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001032 Address target = rinfo->target_address();
ager@chromium.org8bb60582008-12-11 12:02:20 +00001033 Code* code = Code::GetCodeFromTargetAddress(target);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001034 if (code->is_inline_cache_stub()) {
1035 if (code->is_call_stub()) {
1036 return ComputeCallDebugBreak(code->arguments_count());
1037 }
1038 if (code->is_load_stub()) {
1039 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1040 }
1041 if (code->is_store_stub()) {
1042 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1043 }
1044 if (code->is_keyed_load_stub()) {
1045 Handle<Code> result =
1046 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1047 return result;
1048 }
1049 if (code->is_keyed_store_stub()) {
1050 Handle<Code> result =
1051 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1052 return result;
1053 }
1054 }
ager@chromium.org236ad962008-09-25 09:45:57 +00001055 if (RelocInfo::IsConstructCall(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001056 Handle<Code> result =
1057 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1058 return result;
1059 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001060 if (code->kind() == Code::STUB) {
1061 ASSERT(code->major_key() == CodeStub::CallFunction ||
1062 code->major_key() == CodeStub::StackCheck);
1063 Handle<Code> result =
1064 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1065 return result;
1066 }
1067 }
1068
1069 UNREACHABLE();
1070 return Handle<Code>::null();
1071}
1072
1073
1074// Simple function for returning the source positions for active break points.
1075Handle<Object> Debug::GetSourceBreakLocations(
1076 Handle<SharedFunctionInfo> shared) {
1077 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1078 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1079 if (debug_info->GetBreakPointCount() == 0) {
1080 return Handle<Object>(Heap::undefined_value());
1081 }
1082 Handle<FixedArray> locations =
1083 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1084 int count = 0;
1085 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1086 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1087 BreakPointInfo* break_point_info =
1088 BreakPointInfo::cast(debug_info->break_points()->get(i));
1089 if (break_point_info->GetBreakPointCount() > 0) {
1090 locations->set(count++, break_point_info->statement_position());
1091 }
1092 }
1093 }
1094 return locations;
1095}
1096
1097
christian.plesner.hansen@gmail.com37abdec2009-01-06 14:43:28 +00001098// Handle stepping into a function.
1099void Debug::HandleStepIn(Handle<JSFunction> function,
1100 Address fp,
1101 bool is_constructor) {
1102 // If the frame pointer is not supplied by the caller find it.
1103 if (fp == 0) {
1104 StackFrameIterator it;
1105 it.Advance();
1106 // For constructor functions skip another frame.
1107 if (is_constructor) {
1108 ASSERT(it.frame()->is_construct());
1109 it.Advance();
1110 }
1111 fp = it.frame()->fp();
1112 }
1113
1114 // Flood the function with one-shot break points if it is called from where
1115 // step into was requested.
1116 if (fp == Debug::step_in_fp()) {
1117 // Don't allow step into functions in the native context.
1118 if (function->context()->global() != Top::context()->builtins()) {
1119 Debug::FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
1120 }
1121 }
1122}
1123
1124
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001125void Debug::ClearStepping() {
1126 // Clear the various stepping setup.
1127 ClearOneShot();
1128 ClearStepIn();
1129 ClearStepNext();
1130
1131 // Clear multiple step counter.
1132 thread_local_.step_count_ = 0;
1133}
1134
1135// Clears all the one-shot break points that are currently set. Normally this
1136// function is called each time a break point is hit as one shot break points
1137// are used to support stepping.
1138void Debug::ClearOneShot() {
1139 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001140 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001141 // removed from the list.
1142
1143 DebugInfoListNode* node = debug_info_list_;
1144 while (node != NULL) {
1145 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1146 while (!it.Done()) {
1147 it.ClearOneShot();
1148 it.Next();
1149 }
1150 node = node->next();
1151 }
1152}
1153
1154
1155void Debug::ActivateStepIn(StackFrame* frame) {
1156 thread_local_.step_into_fp_ = frame->fp();
1157}
1158
1159
1160void Debug::ClearStepIn() {
1161 thread_local_.step_into_fp_ = 0;
1162}
1163
1164
1165void Debug::ClearStepNext() {
1166 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001167 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001168 thread_local_.last_fp_ = 0;
1169}
1170
1171
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001172bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1173 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001174 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001175}
1176
1177
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001178// Ensures the debug information is present for shared.
1179bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1180 // Return if we already have the debug info for shared.
1181 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001182
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001183 // Ensure shared in compiled. Return false if this failed.
1184 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001185
1186 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001187 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001188
1189 // Add debug info to the list.
1190 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1191 node->set_next(debug_info_list_);
1192 debug_info_list_ = node;
1193
1194 // Now there is at least one break point.
1195 has_break_points_ = true;
1196
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001197 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001198}
1199
1200
1201void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1202 ASSERT(debug_info_list_ != NULL);
1203 // Run through the debug info objects to find this one and remove it.
1204 DebugInfoListNode* prev = NULL;
1205 DebugInfoListNode* current = debug_info_list_;
1206 while (current != NULL) {
1207 if (*current->debug_info() == *debug_info) {
1208 // Unlink from list. If prev is NULL we are looking at the first element.
1209 if (prev == NULL) {
1210 debug_info_list_ = current->next();
1211 } else {
1212 prev->set_next(current->next());
1213 }
1214 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1215 delete current;
1216
1217 // If there are no more debug info objects there are not more break
1218 // points.
1219 has_break_points_ = debug_info_list_ != NULL;
1220
1221 return;
1222 }
1223 // Move to next in list.
1224 prev = current;
1225 current = current->next();
1226 }
1227 UNREACHABLE();
1228}
1229
1230
1231void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
1232 // Get the executing function in which the debug break occurred.
1233 Handle<SharedFunctionInfo> shared =
1234 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001235 if (!EnsureDebugInfo(shared)) {
1236 // Return if we failed to retrieve the debug info.
1237 return;
1238 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001239 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1240 Handle<Code> code(debug_info->code());
1241 Handle<Code> original_code(debug_info->original_code());
1242#ifdef DEBUG
1243 // Get the code which is actually executing.
1244 Handle<Code> frame_code(frame->FindCode());
1245 ASSERT(frame_code.is_identical_to(code));
1246#endif
1247
1248 // Find the call address in the running code. This address holds the call to
1249 // either a DebugBreakXXX or to the debug break return entry code if the
1250 // break point is still active after processing the break point.
1251 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1252
1253 // Check if the location is at JS exit.
1254 bool at_js_exit = false;
1255 RelocIterator it(debug_info->code());
1256 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001257 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001258 at_js_exit = it.rinfo()->pc() == addr - 1;
1259 }
1260 it.next();
1261 }
1262
1263 // Handle the jump to continue execution after break point depending on the
1264 // break location.
1265 if (at_js_exit) {
1266 // First check if the call in the code is still the debug break return
1267 // entry code. If it is the break point is still active. If not the break
1268 // point was removed during break point processing.
1269 if (Assembler::target_address_at(addr) ==
1270 debug_break_return_entry()->entry()) {
1271 // Break point still active. Jump to the corresponding place in the
1272 // original code.
1273 addr += original_code->instruction_start() - code->instruction_start();
1274 }
1275
1276 // Move one byte back to where the call instruction was placed.
1277 thread_local_.after_break_target_ = addr - 1;
1278 } else {
1279 // Check if there still is a debug break call at the target address. If the
1280 // break point has been removed it will have disappeared. If it have
1281 // disappeared don't try to look in the original code as the running code
1282 // will have the right address. This takes care of the case where the last
1283 // break point is removed from the function and therefore no "original code"
1284 // is available. If the debug break call is still there find the address in
1285 // the original code.
1286 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1287 // If the break point is still there find the call address which was
1288 // overwritten in the original code by the call to DebugBreakXXX.
1289
1290 // Find the corresponding address in the original code.
1291 addr += original_code->instruction_start() - code->instruction_start();
1292 }
1293
1294 // Install jump to the call address in the original code. This will be the
1295 // call which was overwritten by the call to DebugBreakXXX.
1296 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1297 }
1298}
1299
1300
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001301bool Debug::IsDebugGlobal(GlobalObject* global) {
1302 return IsLoaded() && global == Debug::debug_context()->global();
1303}
1304
1305
ager@chromium.org32912102009-01-16 10:38:43 +00001306void Debug::ClearMirrorCache() {
1307 ASSERT(Top::context() == *Debug::debug_context());
1308
1309 // Clear the mirror cache.
1310 Handle<String> function_name =
1311 Factory::LookupSymbol(CStrVector("ClearMirrorCache"));
1312 Handle<Object> fun(Top::global()->GetProperty(*function_name));
1313 ASSERT(fun->IsJSFunction());
1314 bool caught_exception;
1315 Handle<Object> js_object = Execution::TryCall(
1316 Handle<JSFunction>::cast(fun),
1317 Handle<JSObject>(Debug::debug_context()->global()),
1318 0, NULL, &caught_exception);
1319}
1320
1321
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001322bool Debugger::debugger_active_ = false;
1323bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001324bool Debugger::is_loading_debugger_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001325DebugMessageThread* Debugger::message_thread_ = NULL;
1326v8::DebugMessageHandler Debugger::debug_message_handler_ = NULL;
1327void* Debugger::debug_message_handler_data_ = NULL;
1328
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001329
1330Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1331 int argc, Object*** argv,
1332 bool* caught_exception) {
1333 ASSERT(Top::context() == *Debug::debug_context());
1334
1335 // Create the execution state object.
1336 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1337 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1338 ASSERT(constructor->IsJSFunction());
1339 if (!constructor->IsJSFunction()) {
1340 *caught_exception = true;
1341 return Factory::undefined_value();
1342 }
1343 Handle<Object> js_object = Execution::TryCall(
1344 Handle<JSFunction>::cast(constructor),
1345 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1346 caught_exception);
1347 return js_object;
1348}
1349
1350
1351Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1352 // Create the execution state object.
1353 Handle<Object> break_id = Factory::NewNumberFromInt(Top::break_id());
1354 const int argc = 1;
1355 Object** argv[argc] = { break_id.location() };
1356 return MakeJSObject(CStrVector("MakeExecutionState"),
1357 argc, argv, caught_exception);
1358}
1359
1360
1361Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1362 Handle<Object> break_points_hit,
1363 bool* caught_exception) {
1364 // Create the new break event object.
1365 const int argc = 2;
1366 Object** argv[argc] = { exec_state.location(),
1367 break_points_hit.location() };
1368 return MakeJSObject(CStrVector("MakeBreakEvent"),
1369 argc,
1370 argv,
1371 caught_exception);
1372}
1373
1374
1375Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1376 Handle<Object> exception,
1377 bool uncaught,
1378 bool* caught_exception) {
1379 // Create the new exception event object.
1380 const int argc = 3;
1381 Object** argv[argc] = { exec_state.location(),
1382 exception.location(),
1383 uncaught ? Factory::true_value().location() :
1384 Factory::false_value().location()};
1385 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1386 argc, argv, caught_exception);
1387}
1388
1389
1390Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1391 bool* caught_exception) {
1392 // Create the new function event object.
1393 const int argc = 1;
1394 Object** argv[argc] = { function.location() };
1395 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1396 argc, argv, caught_exception);
1397}
1398
1399
1400Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
1401 Handle<Object> script_function,
1402 bool* caught_exception) {
1403 // Create the compile event object.
1404 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1405 Handle<Object> script_source(script->source());
1406 Handle<Object> script_name(script->name());
1407 const int argc = 3;
1408 Object** argv[argc] = { script_source.location(),
1409 script_name.location(),
1410 script_function.location() };
1411 return MakeJSObject(CStrVector("MakeCompileEvent"),
1412 argc,
1413 argv,
1414 caught_exception);
1415}
1416
1417
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001418void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1419 HandleScope scope;
1420
1421 // Bail out based on state or if there is no listener for this event
1422 if (Debug::InDebugger()) return;
1423 if (!Debugger::EventActive(v8::Exception)) return;
1424
1425 // Bail out if exception breaks are not active
1426 if (uncaught) {
1427 // Uncaught exceptions are reported by either flags.
1428 if (!(Debug::break_on_uncaught_exception() ||
1429 Debug::break_on_exception())) return;
1430 } else {
1431 // Caught exceptions are reported is activated.
1432 if (!Debug::break_on_exception()) return;
1433 }
1434
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001435 // Enter the debugger.
1436 EnterDebugger debugger;
1437 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001438
1439 // Clear all current stepping setup.
1440 Debug::ClearStepping();
1441 // Create the event data object.
1442 bool caught_exception = false;
1443 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1444 Handle<Object> event_data;
1445 if (!caught_exception) {
1446 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1447 &caught_exception);
1448 }
1449 // Bail out and don't call debugger if exception.
1450 if (caught_exception) {
1451 return;
1452 }
1453
1454 // Process debug event
1455 ProcessDebugEvent(v8::Exception, event_data);
1456 // Return to continue execution from where the exception was thrown.
1457}
1458
1459
1460void Debugger::OnDebugBreak(Handle<Object> break_points_hit) {
1461 HandleScope scope;
1462
kasper.lund212ac232008-07-16 07:07:30 +00001463 // Debugger has already been entered by caller.
1464 ASSERT(Top::context() == *Debug::debug_context());
1465
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001466 // Bail out if there is no listener for this event
1467 if (!Debugger::EventActive(v8::Break)) return;
1468
1469 // Debugger must be entered in advance.
1470 ASSERT(Top::context() == *Debug::debug_context());
1471
1472 // Create the event data object.
1473 bool caught_exception = false;
1474 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1475 Handle<Object> event_data;
1476 if (!caught_exception) {
1477 event_data = MakeBreakEvent(exec_state, break_points_hit,
1478 &caught_exception);
1479 }
1480 // Bail out and don't call debugger if exception.
1481 if (caught_exception) {
1482 return;
1483 }
1484
1485 // Process debug event
1486 ProcessDebugEvent(v8::Break, event_data);
1487}
1488
1489
1490void Debugger::OnBeforeCompile(Handle<Script> script) {
1491 HandleScope scope;
1492
1493 // Bail out based on state or if there is no listener for this event
1494 if (Debug::InDebugger()) return;
1495 if (compiling_natives()) return;
1496 if (!EventActive(v8::BeforeCompile)) return;
1497
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001498 // Enter the debugger.
1499 EnterDebugger debugger;
1500 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001501
1502 // Create the event data object.
1503 bool caught_exception = false;
1504 Handle<Object> event_data = MakeCompileEvent(script,
1505 Factory::undefined_value(),
1506 &caught_exception);
1507 // Bail out and don't call debugger if exception.
1508 if (caught_exception) {
1509 return;
1510 }
1511
1512 // Process debug event
1513 ProcessDebugEvent(v8::BeforeCompile, event_data);
1514}
1515
1516
1517// Handle debugger actions when a new script is compiled.
1518void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001519 HandleScope scope;
1520
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001521 // No compile events while compiling natives.
1522 if (compiling_natives()) return;
1523
1524 // No more to do if not debugging.
1525 if (!debugger_active()) return;
1526
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001527 // Enter the debugger.
1528 EnterDebugger debugger;
1529 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001530
1531 // If debugging there might be script break points registered for this
1532 // script. Make sure that these break points are set.
1533
1534 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1535 Handle<Object> update_script_break_points =
1536 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1537 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1538 if (!update_script_break_points->IsJSFunction()) {
1539 return;
1540 }
1541 ASSERT(update_script_break_points->IsJSFunction());
1542
1543 // Wrap the script object in a proper JS object before passing it
1544 // to JavaScript.
1545 Handle<JSValue> wrapper = GetScriptWrapper(script);
1546
1547 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001548 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001549 const int argc = 1;
1550 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1551 Handle<Object> result = Execution::TryCall(
1552 Handle<JSFunction>::cast(update_script_break_points),
1553 Top::builtins(), argc, argv,
1554 &caught_exception);
1555 if (caught_exception) {
1556 return;
1557 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001558 // Bail out based on state or if there is no listener for this event
1559 if (Debug::InDebugger()) return;
1560 if (!Debugger::EventActive(v8::AfterCompile)) return;
1561
1562 // Create the compile state object.
1563 Handle<Object> event_data = MakeCompileEvent(script,
1564 Factory::undefined_value(),
1565 &caught_exception);
1566 // Bail out and don't call debugger if exception.
1567 if (caught_exception) {
1568 return;
1569 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001570 // Process debug event
1571 ProcessDebugEvent(v8::AfterCompile, event_data);
1572}
1573
1574
1575void Debugger::OnNewFunction(Handle<JSFunction> function) {
1576 return;
1577 HandleScope scope;
1578
1579 // Bail out based on state or if there is no listener for this event
1580 if (Debug::InDebugger()) return;
1581 if (compiling_natives()) return;
1582 if (!Debugger::EventActive(v8::NewFunction)) return;
1583
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001584 // Enter the debugger.
1585 EnterDebugger debugger;
1586 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001587
1588 // Create the event object.
1589 bool caught_exception = false;
1590 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1591 // Bail out and don't call debugger if exception.
1592 if (caught_exception) {
1593 return;
1594 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001595 // Process debug event.
1596 ProcessDebugEvent(v8::NewFunction, event_data);
1597}
1598
1599
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001600void Debugger::ProcessDebugEvent(v8::DebugEvent event,
1601 Handle<Object> event_data) {
1602 // Create the execution state.
1603 bool caught_exception = false;
1604 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1605 if (caught_exception) {
1606 return;
1607 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001608 // First notify the builtin debugger.
1609 if (message_thread_ != NULL) {
1610 message_thread_->DebugEvent(event, exec_state, event_data);
1611 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001612 // Notify registered debug event listeners. The list can contain both C and
1613 // JavaScript functions.
1614 v8::NeanderArray listeners(Factory::debug_event_listeners());
1615 int length = listeners.length();
1616 for (int i = 0; i < length; i++) {
1617 if (listeners.get(i)->IsUndefined()) continue; // Skip deleted ones.
1618 v8::NeanderObject listener(JSObject::cast(listeners.get(i)));
1619 Handle<Object> callback_data(listener.get(1));
1620 if (listener.get(0)->IsProxy()) {
1621 // C debug event listener.
1622 Handle<Proxy> callback_obj(Proxy::cast(listener.get(0)));
1623 v8::DebugEventCallback callback =
1624 FUNCTION_CAST<v8::DebugEventCallback>(callback_obj->proxy());
1625 callback(event,
1626 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
1627 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data)),
1628 v8::Utils::ToLocal(callback_data));
1629 } else {
1630 // JavaScript debug event listener.
1631 ASSERT(listener.get(0)->IsJSFunction());
1632 Handle<JSFunction> fun(JSFunction::cast(listener.get(0)));
1633
1634 // Invoke the JavaScript debug event listener.
1635 const int argc = 4;
1636 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1637 exec_state.location(),
1638 event_data.location(),
1639 callback_data.location() };
1640 Handle<Object> result = Execution::TryCall(fun, Top::global(),
1641 argc, argv, &caught_exception);
1642 if (caught_exception) {
1643 // Silently ignore exceptions from debug event listeners.
1644 }
1645 }
1646 }
ager@chromium.org32912102009-01-16 10:38:43 +00001647
1648 // Clear the mirror cache.
1649 Debug::ClearMirrorCache();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001650}
1651
1652
1653void Debugger::SetMessageHandler(v8::DebugMessageHandler handler, void* data) {
1654 debug_message_handler_ = handler;
1655 debug_message_handler_data_ = data;
1656 if (!message_thread_) {
1657 message_thread_ = new DebugMessageThread();
1658 message_thread_->Start();
1659 }
1660 UpdateActiveDebugger();
1661}
1662
1663
kasper.lund7276f142008-07-30 08:49:36 +00001664// Posts an output message from the debugger to the debug_message_handler
1665// callback. This callback is part of the public API. Messages are
1666// kept internally as Vector<uint16_t> strings, which are allocated in various
1667// places and deallocated by the calling function sometime after this call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001668void Debugger::SendMessage(Vector< uint16_t> message) {
1669 if (debug_message_handler_ != NULL) {
1670 debug_message_handler_(message.start(), message.length(),
1671 debug_message_handler_data_);
1672 }
1673}
1674
1675
1676void Debugger::ProcessCommand(Vector<const uint16_t> command) {
1677 if (message_thread_ != NULL) {
1678 message_thread_->ProcessCommand(
1679 Vector<uint16_t>(const_cast<uint16_t *>(command.start()),
1680 command.length()));
1681 }
1682}
1683
1684
1685void Debugger::UpdateActiveDebugger() {
1686 v8::NeanderArray listeners(Factory::debug_event_listeners());
1687 int length = listeners.length();
1688 bool active_listener = false;
1689 for (int i = 0; i < length && !active_listener; i++) {
1690 active_listener = !listeners.get(i)->IsUndefined();
1691 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001692 set_debugger_active((Debugger::message_thread_ != NULL &&
1693 Debugger::debug_message_handler_ != NULL) ||
1694 active_listener);
1695 if (!debugger_active() && message_thread_)
1696 message_thread_->OnDebuggerInactive();
1697}
1698
1699
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001700Handle<Object> Debugger::Call(Handle<JSFunction> fun,
1701 Handle<Object> data,
1702 bool* pending_exception) {
1703 // Enter the debugger.
1704 EnterDebugger debugger;
1705 if (debugger.FailedToEnter() || !debugger.HasJavaScriptFrames()) {
1706 return Factory::undefined_value();
1707 }
1708
1709 // Create the execution state.
1710 bool caught_exception = false;
1711 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1712 if (caught_exception) {
1713 return Factory::undefined_value();
1714 }
1715
1716 static const int kArgc = 2;
1717 Object** argv[kArgc] = { exec_state.location(), data.location() };
1718 Handle<Object> result = Execution::Call(fun, Factory::undefined_value(),
1719 kArgc, argv, pending_exception);
1720 return result;
1721}
1722
1723
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001724DebugMessageThread::DebugMessageThread()
1725 : host_running_(true),
kasper.lund7276f142008-07-30 08:49:36 +00001726 command_queue_(kQueueInitialSize),
1727 message_queue_(kQueueInitialSize) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001728 command_received_ = OS::CreateSemaphore(0);
kasper.lund7276f142008-07-30 08:49:36 +00001729 message_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001730}
1731
kasper.lund7276f142008-07-30 08:49:36 +00001732// Does not free resources held by DebugMessageThread
1733// because this cannot be done thread-safely.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001734DebugMessageThread::~DebugMessageThread() {
1735}
1736
1737
kasper.lund7276f142008-07-30 08:49:36 +00001738// Puts an event coming from V8 on the queue. Creates
1739// a copy of the JSON formatted event string managed by the V8.
1740// Called by the V8 thread.
1741// The new copy of the event string is destroyed in Run().
1742void DebugMessageThread::SendMessage(Vector<uint16_t> message) {
1743 Vector<uint16_t> message_copy = message.Clone();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001744 Logger::DebugTag("Put message on event message_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001745 message_queue_.Put(message_copy);
1746 message_received_->Signal();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001747}
1748
1749
ager@chromium.org8bb60582008-12-11 12:02:20 +00001750bool DebugMessageThread::SetEventJSONFromEvent(Handle<Object> event_data) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001751 v8::HandleScope scope;
1752 // Call toJSONProtocol on the debug event object.
1753 v8::Local<v8::Object> api_event_data =
1754 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data));
1755 v8::Local<v8::String> fun_name = v8::String::New("toJSONProtocol");
1756 v8::Local<v8::Function> fun =
1757 v8::Function::Cast(*api_event_data->Get(fun_name));
1758 v8::TryCatch try_catch;
kasper.lund7276f142008-07-30 08:49:36 +00001759 v8::Local<v8::Value> json_event = *fun->Call(api_event_data, 0, NULL);
1760 v8::Local<v8::String> json_event_string;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001761 if (!try_catch.HasCaught()) {
kasper.lund7276f142008-07-30 08:49:36 +00001762 if (!json_event->IsUndefined()) {
1763 json_event_string = json_event->ToString();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001764 if (FLAG_trace_debug_json) {
kasper.lund7276f142008-07-30 08:49:36 +00001765 PrintLn(json_event_string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001766 }
kasper.lund7276f142008-07-30 08:49:36 +00001767 v8::String::Value val(json_event_string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001768 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001769 json_event_string->Length());
kasper.lund7276f142008-07-30 08:49:36 +00001770 SendMessage(str);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001771 } else {
kasper.lund7276f142008-07-30 08:49:36 +00001772 SendMessage(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001773 }
1774 } else {
1775 PrintLn(try_catch.Exception());
ager@chromium.org8bb60582008-12-11 12:02:20 +00001776 return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777 }
ager@chromium.org8bb60582008-12-11 12:02:20 +00001778 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001779}
1780
1781
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001782void DebugMessageThread::Run() {
kasper.lund7276f142008-07-30 08:49:36 +00001783 // Sends debug events to an installed debugger message callback.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001784 while (true) {
kasper.lund7276f142008-07-30 08:49:36 +00001785 // Wait and Get are paired so that semaphore count equals queue length.
1786 message_received_->Wait();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001787 Logger::DebugTag("Get message from event message_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001788 Vector<uint16_t> message = message_queue_.Get();
1789 if (message.length() > 0) {
1790 Debugger::SendMessage(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001791 }
1792 }
1793}
1794
1795
kasper.lund44510672008-07-25 07:37:58 +00001796// This method is called by the V8 thread whenever a debug event occurs in
1797// the VM.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001798void DebugMessageThread::DebugEvent(v8::DebugEvent event,
1799 Handle<Object> exec_state,
1800 Handle<Object> event_data) {
kasper.lund212ac232008-07-16 07:07:30 +00001801 if (!Debug::Load()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001802
1803 // Process the individual events.
1804 bool interactive = false;
1805 switch (event) {
1806 case v8::Break:
v8.team.kasperl727e9952008-09-02 14:56:44 +00001807 interactive = true; // Break event is always interactive
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001808 break;
1809 case v8::Exception:
v8.team.kasperl727e9952008-09-02 14:56:44 +00001810 interactive = true; // Exception event is always interactive
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001811 break;
1812 case v8::BeforeCompile:
1813 break;
1814 case v8::AfterCompile:
1815 break;
1816 case v8::NewFunction:
1817 break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001818 default:
1819 UNREACHABLE();
1820 }
1821
1822 // Done if not interactive.
1823 if (!interactive) return;
1824
1825 // Get the DebugCommandProcessor.
1826 v8::Local<v8::Object> api_exec_state =
1827 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
1828 v8::Local<v8::String> fun_name =
1829 v8::String::New("debugCommandProcessor");
1830 v8::Local<v8::Function> fun =
1831 v8::Function::Cast(*api_exec_state->Get(fun_name));
1832 v8::TryCatch try_catch;
1833 v8::Local<v8::Object> cmd_processor =
1834 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
1835 if (try_catch.HasCaught()) {
1836 PrintLn(try_catch.Exception());
1837 return;
1838 }
1839
v8.team.kasperl727e9952008-09-02 14:56:44 +00001840 // Notify the debugger that a debug event has occurred.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001841 bool success = SetEventJSONFromEvent(event_data);
1842 if (!success) {
1843 // If failed to notify debugger just continue running.
1844 return;
1845 }
kasper.lund7276f142008-07-30 08:49:36 +00001846
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001847 // Wait for requests from the debugger.
ager@chromium.org8bb60582008-12-11 12:02:20 +00001848 host_running_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001849 while (true) {
kasper.lund7276f142008-07-30 08:49:36 +00001850 command_received_->Wait();
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001851 Logger::DebugTag("Got request from command queue, in interactive loop.");
kasper.lund7276f142008-07-30 08:49:36 +00001852 Vector<uint16_t> command = command_queue_.Get();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001853 ASSERT(!host_running_);
1854 if (!Debugger::debugger_active()) {
1855 host_running_ = true;
1856 return;
1857 }
1858
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001859 // Invoke the JavaScript to process the debug request.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001860 v8::Local<v8::String> fun_name;
1861 v8::Local<v8::Function> fun;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001862 v8::Local<v8::Value> request;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001863 v8::TryCatch try_catch;
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001864 fun_name = v8::String::New("processDebugRequest");
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001865 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001866 request = v8::String::New(reinterpret_cast<uint16_t*>(command.start()),
kasper.lund7276f142008-07-30 08:49:36 +00001867 command.length());
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001868 static const int kArgc = 1;
1869 v8::Handle<Value> argv[kArgc] = { request };
1870 v8::Local<v8::Value> response_val = fun->Call(cmd_processor, kArgc, argv);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001871
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001872 // Get the response.
1873 v8::Local<v8::String> response;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001874 bool running = false;
1875 if (!try_catch.HasCaught()) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001876 // Get response string.
1877 if (!response_val->IsUndefined()) {
1878 response = v8::String::Cast(*response_val);
1879 } else {
1880 response = v8::String::New("");
1881 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001882
1883 // Log the JSON request/response.
1884 if (FLAG_trace_debug_json) {
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001885 PrintLn(request);
1886 PrintLn(response);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001887 }
1888
1889 // Get the running state.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001890 fun_name = v8::String::New("isRunning");
1891 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
1892 static const int kArgc = 1;
1893 v8::Handle<Value> argv[kArgc] = { response };
1894 v8::Local<v8::Value> running_val = fun->Call(cmd_processor, kArgc, argv);
1895 if (!try_catch.HasCaught()) {
1896 running = running_val->ToBoolean()->Value();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001897 }
1898 } else {
1899 // In case of failure the result text is the exception text.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001900 response = try_catch.Exception()->ToString();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001901 }
1902
1903 // Convert text result to C string.
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001904 v8::String::Value val(response);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001905 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
ager@chromium.orga74f0da2008-12-03 16:05:52 +00001906 response->Length());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001907
kasper.lund7276f142008-07-30 08:49:36 +00001908 // Set host_running_ correctly for nested debugger evaluations.
1909 host_running_ = running;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001910
1911 // Return the result.
kasper.lund7276f142008-07-30 08:49:36 +00001912 SendMessage(str);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001913
1914 // Return from debug event processing is VM should be running.
1915 if (running) {
1916 return;
1917 }
1918 }
1919}
1920
1921
kasper.lund7276f142008-07-30 08:49:36 +00001922// Puts a command coming from the public API on the queue. Creates
1923// a copy of the command string managed by the debugger. Up to this
1924// point, the command data was managed by the API client. Called
1925// by the API client thread. This is where the API client hands off
1926// processing of the command to the DebugMessageThread thread.
1927// The new copy of the command is destroyed in HandleCommand().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001928void DebugMessageThread::ProcessCommand(Vector<uint16_t> command) {
kasper.lund7276f142008-07-30 08:49:36 +00001929 Vector<uint16_t> command_copy = command.Clone();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001930 Logger::DebugTag("Put command on command_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001931 command_queue_.Put(command_copy);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001932 command_received_->Signal();
1933}
1934
1935
1936void DebugMessageThread::OnDebuggerInactive() {
kasper.lund7276f142008-07-30 08:49:36 +00001937 // Send an empty command to the debugger if in a break to make JavaScript run
1938 // again if the debugger is closed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001939 if (!host_running_) {
kasper.lund7276f142008-07-30 08:49:36 +00001940 ProcessCommand(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001941 }
1942}
1943
kasper.lund7276f142008-07-30 08:49:36 +00001944
1945MessageQueue::MessageQueue(int size) : start_(0), end_(0), size_(size) {
1946 messages_ = NewArray<Vector<uint16_t> >(size);
1947}
1948
1949
1950MessageQueue::~MessageQueue() {
1951 DeleteArray(messages_);
1952}
1953
1954
1955Vector<uint16_t> MessageQueue::Get() {
1956 ASSERT(!IsEmpty());
1957 int result = start_;
1958 start_ = (start_ + 1) % size_;
1959 return messages_[result];
1960}
1961
1962
1963void MessageQueue::Put(const Vector<uint16_t>& message) {
1964 if ((end_ + 1) % size_ == start_) {
1965 Expand();
1966 }
1967 messages_[end_] = message;
1968 end_ = (end_ + 1) % size_;
1969}
1970
1971
1972void MessageQueue::Expand() {
1973 MessageQueue new_queue(size_ * 2);
1974 while (!IsEmpty()) {
1975 new_queue.Put(Get());
1976 }
1977 Vector<uint16_t>* array_to_free = messages_;
1978 *this = new_queue;
1979 new_queue.messages_ = array_to_free;
1980 // Automatic destructor called on new_queue, freeing array_to_free.
1981}
1982
1983
1984LockingMessageQueue::LockingMessageQueue(int size) : queue_(size) {
1985 lock_ = OS::CreateMutex();
1986}
1987
1988
1989LockingMessageQueue::~LockingMessageQueue() {
1990 delete lock_;
1991}
1992
1993
1994bool LockingMessageQueue::IsEmpty() const {
1995 ScopedLock sl(lock_);
1996 return queue_.IsEmpty();
1997}
1998
1999
2000Vector<uint16_t> LockingMessageQueue::Get() {
2001 ScopedLock sl(lock_);
2002 Vector<uint16_t> result = queue_.Get();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002003 Logger::DebugEvent("Get", result);
kasper.lund7276f142008-07-30 08:49:36 +00002004 return result;
2005}
2006
2007
2008void LockingMessageQueue::Put(const Vector<uint16_t>& message) {
2009 ScopedLock sl(lock_);
2010 queue_.Put(message);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00002011 Logger::DebugEvent("Put", message);
kasper.lund7276f142008-07-30 08:49:36 +00002012}
2013
2014
2015void LockingMessageQueue::Clear() {
2016 ScopedLock sl(lock_);
2017 queue_.Clear();
2018}
2019
2020
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00002021} } // namespace v8::internal