blob: 7acc117d81b8077fa8c6dfb33cf52ba2c9e292d9 [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();
116 Code* code = Debug::GetCodeTarget(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();
328 Code* code = Debug::GetCodeTarget(target);
329 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() {
852 StackFrame::Id id = Top::break_frame_id();
853 for (JavaScriptFrameIterator it(id); !it.done(); it.Advance()) {
854 JavaScriptFrame* frame = it.frame();
855 if (frame->HasHandler()) {
856 Handle<SharedFunctionInfo> shared =
857 Handle<SharedFunctionInfo>(
858 JSFunction::cast(frame->function())->shared());
859 // Flood the function with the catch block with break points
860 FloodWithOneShot(shared);
861 return;
862 }
863 }
864}
865
866
867void Debug::ChangeBreakOnException(ExceptionBreakType type, bool enable) {
868 if (type == BreakUncaughtException) {
869 break_on_uncaught_exception_ = enable;
870 } else {
871 break_on_exception_ = enable;
872 }
873}
874
875
876void Debug::PrepareStep(StepAction step_action, int step_count) {
877 HandleScope scope;
878 ASSERT(Debug::InDebugger());
879
880 // Remember this step action and count.
881 thread_local_.last_step_action_ = step_action;
882 thread_local_.step_count_ = step_count;
883
884 // Get the frame where the execution has stopped and skip the debug frame if
885 // any. The debug frame will only be present if execution was stopped due to
886 // hitting a break point. In other situations (e.g. unhandled exception) the
887 // debug frame is not present.
888 StackFrame::Id id = Top::break_frame_id();
889 JavaScriptFrameIterator frames_it(id);
890 JavaScriptFrame* frame = frames_it.frame();
891
892 // First of all ensure there is one-shot break points in the top handler
893 // if any.
894 FloodHandlerWithOneShot();
895
896 // If the function on the top frame is unresolved perform step out. This will
897 // be the case when calling unknown functions and having the debugger stopped
898 // in an unhandled exception.
899 if (!frame->function()->IsJSFunction()) {
900 // Step out: Find the calling JavaScript frame and flood it with
901 // breakpoints.
902 frames_it.Advance();
903 // Fill the function to return to with one-shot break points.
904 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
905 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
906 return;
907 }
908
909 // Get the debug info (create it if it does not exist).
910 Handle<SharedFunctionInfo> shared =
911 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +0000912 if (!EnsureDebugInfo(shared)) {
913 // Return if ensuring debug info failed.
914 return;
915 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000916 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
917
918 // Find the break location where execution has stopped.
919 BreakLocationIterator it(debug_info, ALL_BREAK_LOCATIONS);
920 it.FindBreakLocationFromAddress(frame->pc());
921
922 // Compute whether or not the target is a call target.
923 bool is_call_target = false;
ager@chromium.org236ad962008-09-25 09:45:57 +0000924 if (RelocInfo::IsCodeTarget(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000925 Address target = it.rinfo()->target_address();
926 Code* code = Debug::GetCodeTarget(target);
927 if (code->is_call_stub()) is_call_target = true;
928 }
929
v8.team.kasperl727e9952008-09-02 14:56:44 +0000930 // If this is the last break code target step out is the only possibility.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000931 if (it.IsExit() || step_action == StepOut) {
932 // Step out: If there is a JavaScript caller frame, we need to
933 // flood it with breakpoints.
934 frames_it.Advance();
935 if (!frames_it.done()) {
936 // Fill the function to return to with one-shot break points.
937 JSFunction* function = JSFunction::cast(frames_it.frame()->function());
938 FloodWithOneShot(Handle<SharedFunctionInfo>(function->shared()));
939 }
ager@chromium.org236ad962008-09-25 09:45:57 +0000940 } else if (!(is_call_target || RelocInfo::IsConstructCall(it.rmode())) ||
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000941 step_action == StepNext || step_action == StepMin) {
942 // Step next or step min.
943
944 // Fill the current function with one-shot break points.
945 FloodWithOneShot(shared);
946
947 // Remember source position and frame to handle step next.
948 thread_local_.last_statement_position_ =
949 debug_info->code()->SourceStatementPosition(frame->pc());
950 thread_local_.last_fp_ = frame->fp();
951 } else {
952 // Fill the current function with one-shot break points even for step in on
953 // a call target as the function called might be a native function for
954 // which step in will not stop.
955 FloodWithOneShot(shared);
956
957 // Step in or Step in min
958 it.PrepareStepIn();
959 ActivateStepIn(frame);
960 }
961}
962
963
964// Check whether the current debug break should be reported to the debugger. It
965// is used to have step next and step in only report break back to the debugger
966// if on a different frame or in a different statement. In some situations
967// there will be several break points in the same statement when the code is
v8.team.kasperl727e9952008-09-02 14:56:44 +0000968// flooded with one-shot break points. This function helps to perform several
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000969// steps before reporting break back to the debugger.
970bool Debug::StepNextContinue(BreakLocationIterator* break_location_iterator,
971 JavaScriptFrame* frame) {
972 // If the step last action was step next or step in make sure that a new
973 // statement is hit.
974 if (thread_local_.last_step_action_ == StepNext ||
975 thread_local_.last_step_action_ == StepIn) {
976 // Never continue if returning from function.
977 if (break_location_iterator->IsExit()) return false;
978
979 // Continue if we are still on the same frame and in the same statement.
980 int current_statement_position =
981 break_location_iterator->code()->SourceStatementPosition(frame->pc());
982 return thread_local_.last_fp_ == frame->fp() &&
ager@chromium.org236ad962008-09-25 09:45:57 +0000983 thread_local_.last_statement_position_ == current_statement_position;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000984 }
985
986 // No step next action - don't continue.
987 return false;
988}
989
990
991// Check whether the code object at the specified address is a debug break code
992// object.
993bool Debug::IsDebugBreak(Address addr) {
994 Code* code = GetCodeTarget(addr);
kasper.lund7276f142008-07-30 08:49:36 +0000995 return code->ic_state() == DEBUG_BREAK;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +0000996}
997
998
999// Check whether a code stub with the specified major key is a possible break
1000// point location when looking for source break locations.
1001bool Debug::IsSourceBreakStub(Code* code) {
1002 CodeStub::Major major_key = code->major_key();
1003 return major_key == CodeStub::CallFunction;
1004}
1005
1006
1007// Check whether a code stub with the specified major key is a possible break
1008// location.
1009bool Debug::IsBreakStub(Code* code) {
1010 CodeStub::Major major_key = code->major_key();
1011 return major_key == CodeStub::CallFunction ||
1012 major_key == CodeStub::StackCheck;
1013}
1014
1015
1016// Find the builtin to use for invoking the debug break
1017Handle<Code> Debug::FindDebugBreak(RelocInfo* rinfo) {
1018 // Find the builtin debug break function matching the calling convention
1019 // used by the call site.
ager@chromium.org236ad962008-09-25 09:45:57 +00001020 RelocInfo::Mode mode = rinfo->rmode();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001021
ager@chromium.org236ad962008-09-25 09:45:57 +00001022 if (RelocInfo::IsCodeTarget(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001023 Address target = rinfo->target_address();
1024 Code* code = Debug::GetCodeTarget(target);
1025 if (code->is_inline_cache_stub()) {
1026 if (code->is_call_stub()) {
1027 return ComputeCallDebugBreak(code->arguments_count());
1028 }
1029 if (code->is_load_stub()) {
1030 return Handle<Code>(Builtins::builtin(Builtins::LoadIC_DebugBreak));
1031 }
1032 if (code->is_store_stub()) {
1033 return Handle<Code>(Builtins::builtin(Builtins::StoreIC_DebugBreak));
1034 }
1035 if (code->is_keyed_load_stub()) {
1036 Handle<Code> result =
1037 Handle<Code>(Builtins::builtin(Builtins::KeyedLoadIC_DebugBreak));
1038 return result;
1039 }
1040 if (code->is_keyed_store_stub()) {
1041 Handle<Code> result =
1042 Handle<Code>(Builtins::builtin(Builtins::KeyedStoreIC_DebugBreak));
1043 return result;
1044 }
1045 }
ager@chromium.org236ad962008-09-25 09:45:57 +00001046 if (RelocInfo::IsConstructCall(mode)) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001047 Handle<Code> result =
1048 Handle<Code>(Builtins::builtin(Builtins::ConstructCall_DebugBreak));
1049 return result;
1050 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001051 if (code->kind() == Code::STUB) {
1052 ASSERT(code->major_key() == CodeStub::CallFunction ||
1053 code->major_key() == CodeStub::StackCheck);
1054 Handle<Code> result =
1055 Handle<Code>(Builtins::builtin(Builtins::StubNoRegisters_DebugBreak));
1056 return result;
1057 }
1058 }
1059
1060 UNREACHABLE();
1061 return Handle<Code>::null();
1062}
1063
1064
1065// Simple function for returning the source positions for active break points.
1066Handle<Object> Debug::GetSourceBreakLocations(
1067 Handle<SharedFunctionInfo> shared) {
1068 if (!HasDebugInfo(shared)) return Handle<Object>(Heap::undefined_value());
1069 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1070 if (debug_info->GetBreakPointCount() == 0) {
1071 return Handle<Object>(Heap::undefined_value());
1072 }
1073 Handle<FixedArray> locations =
1074 Factory::NewFixedArray(debug_info->GetBreakPointCount());
1075 int count = 0;
1076 for (int i = 0; i < debug_info->break_points()->length(); i++) {
1077 if (!debug_info->break_points()->get(i)->IsUndefined()) {
1078 BreakPointInfo* break_point_info =
1079 BreakPointInfo::cast(debug_info->break_points()->get(i));
1080 if (break_point_info->GetBreakPointCount() > 0) {
1081 locations->set(count++, break_point_info->statement_position());
1082 }
1083 }
1084 }
1085 return locations;
1086}
1087
1088
1089void Debug::ClearStepping() {
1090 // Clear the various stepping setup.
1091 ClearOneShot();
1092 ClearStepIn();
1093 ClearStepNext();
1094
1095 // Clear multiple step counter.
1096 thread_local_.step_count_ = 0;
1097}
1098
1099// Clears all the one-shot break points that are currently set. Normally this
1100// function is called each time a break point is hit as one shot break points
1101// are used to support stepping.
1102void Debug::ClearOneShot() {
1103 // The current implementation just runs through all the breakpoints. When the
v8.team.kasperl727e9952008-09-02 14:56:44 +00001104 // last break point for a function is removed that function is automatically
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001105 // removed from the list.
1106
1107 DebugInfoListNode* node = debug_info_list_;
1108 while (node != NULL) {
1109 BreakLocationIterator it(node->debug_info(), ALL_BREAK_LOCATIONS);
1110 while (!it.Done()) {
1111 it.ClearOneShot();
1112 it.Next();
1113 }
1114 node = node->next();
1115 }
1116}
1117
1118
1119void Debug::ActivateStepIn(StackFrame* frame) {
1120 thread_local_.step_into_fp_ = frame->fp();
1121}
1122
1123
1124void Debug::ClearStepIn() {
1125 thread_local_.step_into_fp_ = 0;
1126}
1127
1128
1129void Debug::ClearStepNext() {
1130 thread_local_.last_step_action_ = StepNone;
ager@chromium.org236ad962008-09-25 09:45:57 +00001131 thread_local_.last_statement_position_ = RelocInfo::kNoPosition;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001132 thread_local_.last_fp_ = 0;
1133}
1134
1135
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001136bool Debug::EnsureCompiled(Handle<SharedFunctionInfo> shared) {
1137 if (shared->is_compiled()) return true;
ager@chromium.org3bf7b912008-11-17 09:09:45 +00001138 return CompileLazyShared(shared, CLEAR_EXCEPTION, 0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001139}
1140
1141
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001142// Ensures the debug information is present for shared.
1143bool Debug::EnsureDebugInfo(Handle<SharedFunctionInfo> shared) {
1144 // Return if we already have the debug info for shared.
1145 if (HasDebugInfo(shared)) return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001146
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001147 // Ensure shared in compiled. Return false if this failed.
1148 if (!EnsureCompiled(shared)) return false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001149
1150 // Create the debug info object.
v8.team.kasperl727e9952008-09-02 14:56:44 +00001151 Handle<DebugInfo> debug_info = Factory::NewDebugInfo(shared);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001152
1153 // Add debug info to the list.
1154 DebugInfoListNode* node = new DebugInfoListNode(*debug_info);
1155 node->set_next(debug_info_list_);
1156 debug_info_list_ = node;
1157
1158 // Now there is at least one break point.
1159 has_break_points_ = true;
1160
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001161 return true;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001162}
1163
1164
1165void Debug::RemoveDebugInfo(Handle<DebugInfo> debug_info) {
1166 ASSERT(debug_info_list_ != NULL);
1167 // Run through the debug info objects to find this one and remove it.
1168 DebugInfoListNode* prev = NULL;
1169 DebugInfoListNode* current = debug_info_list_;
1170 while (current != NULL) {
1171 if (*current->debug_info() == *debug_info) {
1172 // Unlink from list. If prev is NULL we are looking at the first element.
1173 if (prev == NULL) {
1174 debug_info_list_ = current->next();
1175 } else {
1176 prev->set_next(current->next());
1177 }
1178 current->debug_info()->shared()->set_debug_info(Heap::undefined_value());
1179 delete current;
1180
1181 // If there are no more debug info objects there are not more break
1182 // points.
1183 has_break_points_ = debug_info_list_ != NULL;
1184
1185 return;
1186 }
1187 // Move to next in list.
1188 prev = current;
1189 current = current->next();
1190 }
1191 UNREACHABLE();
1192}
1193
1194
1195void Debug::SetAfterBreakTarget(JavaScriptFrame* frame) {
1196 // Get the executing function in which the debug break occurred.
1197 Handle<SharedFunctionInfo> shared =
1198 Handle<SharedFunctionInfo>(JSFunction::cast(frame->function())->shared());
kasper.lundbd3ec4e2008-07-09 11:06:54 +00001199 if (!EnsureDebugInfo(shared)) {
1200 // Return if we failed to retrieve the debug info.
1201 return;
1202 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001203 Handle<DebugInfo> debug_info = GetDebugInfo(shared);
1204 Handle<Code> code(debug_info->code());
1205 Handle<Code> original_code(debug_info->original_code());
1206#ifdef DEBUG
1207 // Get the code which is actually executing.
1208 Handle<Code> frame_code(frame->FindCode());
1209 ASSERT(frame_code.is_identical_to(code));
1210#endif
1211
1212 // Find the call address in the running code. This address holds the call to
1213 // either a DebugBreakXXX or to the debug break return entry code if the
1214 // break point is still active after processing the break point.
1215 Address addr = frame->pc() - Assembler::kTargetAddrToReturnAddrDist;
1216
1217 // Check if the location is at JS exit.
1218 bool at_js_exit = false;
1219 RelocIterator it(debug_info->code());
1220 while (!it.done()) {
ager@chromium.org236ad962008-09-25 09:45:57 +00001221 if (RelocInfo::IsJSReturn(it.rinfo()->rmode())) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001222 at_js_exit = it.rinfo()->pc() == addr - 1;
1223 }
1224 it.next();
1225 }
1226
1227 // Handle the jump to continue execution after break point depending on the
1228 // break location.
1229 if (at_js_exit) {
1230 // First check if the call in the code is still the debug break return
1231 // entry code. If it is the break point is still active. If not the break
1232 // point was removed during break point processing.
1233 if (Assembler::target_address_at(addr) ==
1234 debug_break_return_entry()->entry()) {
1235 // Break point still active. Jump to the corresponding place in the
1236 // original code.
1237 addr += original_code->instruction_start() - code->instruction_start();
1238 }
1239
1240 // Move one byte back to where the call instruction was placed.
1241 thread_local_.after_break_target_ = addr - 1;
1242 } else {
1243 // Check if there still is a debug break call at the target address. If the
1244 // break point has been removed it will have disappeared. If it have
1245 // disappeared don't try to look in the original code as the running code
1246 // will have the right address. This takes care of the case where the last
1247 // break point is removed from the function and therefore no "original code"
1248 // is available. If the debug break call is still there find the address in
1249 // the original code.
1250 if (IsDebugBreak(Assembler::target_address_at(addr))) {
1251 // If the break point is still there find the call address which was
1252 // overwritten in the original code by the call to DebugBreakXXX.
1253
1254 // Find the corresponding address in the original code.
1255 addr += original_code->instruction_start() - code->instruction_start();
1256 }
1257
1258 // Install jump to the call address in the original code. This will be the
1259 // call which was overwritten by the call to DebugBreakXXX.
1260 thread_local_.after_break_target_ = Assembler::target_address_at(addr);
1261 }
1262}
1263
1264
1265Code* Debug::GetCodeTarget(Address target) {
1266 // Maybe this can be refactored with the stuff in ic-inl.h?
1267 Code* result =
1268 Code::cast(HeapObject::FromAddress(target - Code::kHeaderSize));
1269 return result;
1270}
1271
1272
1273bool Debug::IsDebugGlobal(GlobalObject* global) {
1274 return IsLoaded() && global == Debug::debug_context()->global();
1275}
1276
1277
1278bool Debugger::debugger_active_ = false;
1279bool Debugger::compiling_natives_ = false;
mads.s.agercbaa0602008-08-14 13:41:48 +00001280bool Debugger::is_loading_debugger_ = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001281DebugMessageThread* Debugger::message_thread_ = NULL;
1282v8::DebugMessageHandler Debugger::debug_message_handler_ = NULL;
1283void* Debugger::debug_message_handler_data_ = NULL;
1284
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001285
1286Handle<Object> Debugger::MakeJSObject(Vector<const char> constructor_name,
1287 int argc, Object*** argv,
1288 bool* caught_exception) {
1289 ASSERT(Top::context() == *Debug::debug_context());
1290
1291 // Create the execution state object.
1292 Handle<String> constructor_str = Factory::LookupSymbol(constructor_name);
1293 Handle<Object> constructor(Top::global()->GetProperty(*constructor_str));
1294 ASSERT(constructor->IsJSFunction());
1295 if (!constructor->IsJSFunction()) {
1296 *caught_exception = true;
1297 return Factory::undefined_value();
1298 }
1299 Handle<Object> js_object = Execution::TryCall(
1300 Handle<JSFunction>::cast(constructor),
1301 Handle<JSObject>(Debug::debug_context()->global()), argc, argv,
1302 caught_exception);
1303 return js_object;
1304}
1305
1306
1307Handle<Object> Debugger::MakeExecutionState(bool* caught_exception) {
1308 // Create the execution state object.
1309 Handle<Object> break_id = Factory::NewNumberFromInt(Top::break_id());
1310 const int argc = 1;
1311 Object** argv[argc] = { break_id.location() };
1312 return MakeJSObject(CStrVector("MakeExecutionState"),
1313 argc, argv, caught_exception);
1314}
1315
1316
1317Handle<Object> Debugger::MakeBreakEvent(Handle<Object> exec_state,
1318 Handle<Object> break_points_hit,
1319 bool* caught_exception) {
1320 // Create the new break event object.
1321 const int argc = 2;
1322 Object** argv[argc] = { exec_state.location(),
1323 break_points_hit.location() };
1324 return MakeJSObject(CStrVector("MakeBreakEvent"),
1325 argc,
1326 argv,
1327 caught_exception);
1328}
1329
1330
1331Handle<Object> Debugger::MakeExceptionEvent(Handle<Object> exec_state,
1332 Handle<Object> exception,
1333 bool uncaught,
1334 bool* caught_exception) {
1335 // Create the new exception event object.
1336 const int argc = 3;
1337 Object** argv[argc] = { exec_state.location(),
1338 exception.location(),
1339 uncaught ? Factory::true_value().location() :
1340 Factory::false_value().location()};
1341 return MakeJSObject(CStrVector("MakeExceptionEvent"),
1342 argc, argv, caught_exception);
1343}
1344
1345
1346Handle<Object> Debugger::MakeNewFunctionEvent(Handle<Object> function,
1347 bool* caught_exception) {
1348 // Create the new function event object.
1349 const int argc = 1;
1350 Object** argv[argc] = { function.location() };
1351 return MakeJSObject(CStrVector("MakeNewFunctionEvent"),
1352 argc, argv, caught_exception);
1353}
1354
1355
1356Handle<Object> Debugger::MakeCompileEvent(Handle<Script> script,
1357 Handle<Object> script_function,
1358 bool* caught_exception) {
1359 // Create the compile event object.
1360 Handle<Object> exec_state = MakeExecutionState(caught_exception);
1361 Handle<Object> script_source(script->source());
1362 Handle<Object> script_name(script->name());
1363 const int argc = 3;
1364 Object** argv[argc] = { script_source.location(),
1365 script_name.location(),
1366 script_function.location() };
1367 return MakeJSObject(CStrVector("MakeCompileEvent"),
1368 argc,
1369 argv,
1370 caught_exception);
1371}
1372
1373
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001374void Debugger::OnException(Handle<Object> exception, bool uncaught) {
1375 HandleScope scope;
1376
1377 // Bail out based on state or if there is no listener for this event
1378 if (Debug::InDebugger()) return;
1379 if (!Debugger::EventActive(v8::Exception)) return;
1380
1381 // Bail out if exception breaks are not active
1382 if (uncaught) {
1383 // Uncaught exceptions are reported by either flags.
1384 if (!(Debug::break_on_uncaught_exception() ||
1385 Debug::break_on_exception())) return;
1386 } else {
1387 // Caught exceptions are reported is activated.
1388 if (!Debug::break_on_exception()) return;
1389 }
1390
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001391 // Enter the debugger.
1392 EnterDebugger debugger;
1393 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001394
1395 // Clear all current stepping setup.
1396 Debug::ClearStepping();
1397 // Create the event data object.
1398 bool caught_exception = false;
1399 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1400 Handle<Object> event_data;
1401 if (!caught_exception) {
1402 event_data = MakeExceptionEvent(exec_state, exception, uncaught,
1403 &caught_exception);
1404 }
1405 // Bail out and don't call debugger if exception.
1406 if (caught_exception) {
1407 return;
1408 }
1409
1410 // Process debug event
1411 ProcessDebugEvent(v8::Exception, event_data);
1412 // Return to continue execution from where the exception was thrown.
1413}
1414
1415
1416void Debugger::OnDebugBreak(Handle<Object> break_points_hit) {
1417 HandleScope scope;
1418
kasper.lund212ac232008-07-16 07:07:30 +00001419 // Debugger has already been entered by caller.
1420 ASSERT(Top::context() == *Debug::debug_context());
1421
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001422 // Bail out if there is no listener for this event
1423 if (!Debugger::EventActive(v8::Break)) return;
1424
1425 // Debugger must be entered in advance.
1426 ASSERT(Top::context() == *Debug::debug_context());
1427
1428 // Create the event data object.
1429 bool caught_exception = false;
1430 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1431 Handle<Object> event_data;
1432 if (!caught_exception) {
1433 event_data = MakeBreakEvent(exec_state, break_points_hit,
1434 &caught_exception);
1435 }
1436 // Bail out and don't call debugger if exception.
1437 if (caught_exception) {
1438 return;
1439 }
1440
1441 // Process debug event
1442 ProcessDebugEvent(v8::Break, event_data);
1443}
1444
1445
1446void Debugger::OnBeforeCompile(Handle<Script> script) {
1447 HandleScope scope;
1448
1449 // Bail out based on state or if there is no listener for this event
1450 if (Debug::InDebugger()) return;
1451 if (compiling_natives()) return;
1452 if (!EventActive(v8::BeforeCompile)) return;
1453
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001454 // Enter the debugger.
1455 EnterDebugger debugger;
1456 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001457
1458 // Create the event data object.
1459 bool caught_exception = false;
1460 Handle<Object> event_data = MakeCompileEvent(script,
1461 Factory::undefined_value(),
1462 &caught_exception);
1463 // Bail out and don't call debugger if exception.
1464 if (caught_exception) {
1465 return;
1466 }
1467
1468 // Process debug event
1469 ProcessDebugEvent(v8::BeforeCompile, event_data);
1470}
1471
1472
1473// Handle debugger actions when a new script is compiled.
1474void Debugger::OnAfterCompile(Handle<Script> script, Handle<JSFunction> fun) {
kasper.lund212ac232008-07-16 07:07:30 +00001475 HandleScope scope;
1476
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001477 // No compile events while compiling natives.
1478 if (compiling_natives()) return;
1479
1480 // No more to do if not debugging.
1481 if (!debugger_active()) return;
1482
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001483 // Enter the debugger.
1484 EnterDebugger debugger;
1485 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001486
1487 // If debugging there might be script break points registered for this
1488 // script. Make sure that these break points are set.
1489
1490 // Get the function UpdateScriptBreakPoints (defined in debug-delay.js).
1491 Handle<Object> update_script_break_points =
1492 Handle<Object>(Debug::debug_context()->global()->GetProperty(
1493 *Factory::LookupAsciiSymbol("UpdateScriptBreakPoints")));
1494 if (!update_script_break_points->IsJSFunction()) {
1495 return;
1496 }
1497 ASSERT(update_script_break_points->IsJSFunction());
1498
1499 // Wrap the script object in a proper JS object before passing it
1500 // to JavaScript.
1501 Handle<JSValue> wrapper = GetScriptWrapper(script);
1502
1503 // Call UpdateScriptBreakPoints expect no exceptions.
kasper.lund212ac232008-07-16 07:07:30 +00001504 bool caught_exception = false;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001505 const int argc = 1;
1506 Object** argv[argc] = { reinterpret_cast<Object**>(wrapper.location()) };
1507 Handle<Object> result = Execution::TryCall(
1508 Handle<JSFunction>::cast(update_script_break_points),
1509 Top::builtins(), argc, argv,
1510 &caught_exception);
1511 if (caught_exception) {
1512 return;
1513 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001514 // Bail out based on state or if there is no listener for this event
1515 if (Debug::InDebugger()) return;
1516 if (!Debugger::EventActive(v8::AfterCompile)) return;
1517
1518 // Create the compile state object.
1519 Handle<Object> event_data = MakeCompileEvent(script,
1520 Factory::undefined_value(),
1521 &caught_exception);
1522 // Bail out and don't call debugger if exception.
1523 if (caught_exception) {
1524 return;
1525 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001526 // Process debug event
1527 ProcessDebugEvent(v8::AfterCompile, event_data);
1528}
1529
1530
1531void Debugger::OnNewFunction(Handle<JSFunction> function) {
1532 return;
1533 HandleScope scope;
1534
1535 // Bail out based on state or if there is no listener for this event
1536 if (Debug::InDebugger()) return;
1537 if (compiling_natives()) return;
1538 if (!Debugger::EventActive(v8::NewFunction)) return;
1539
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001540 // Enter the debugger.
1541 EnterDebugger debugger;
1542 if (debugger.FailedToEnter()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001543
1544 // Create the event object.
1545 bool caught_exception = false;
1546 Handle<Object> event_data = MakeNewFunctionEvent(function, &caught_exception);
1547 // Bail out and don't call debugger if exception.
1548 if (caught_exception) {
1549 return;
1550 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001551 // Process debug event.
1552 ProcessDebugEvent(v8::NewFunction, event_data);
1553}
1554
1555
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001556void Debugger::ProcessDebugEvent(v8::DebugEvent event,
1557 Handle<Object> event_data) {
1558 // Create the execution state.
1559 bool caught_exception = false;
1560 Handle<Object> exec_state = MakeExecutionState(&caught_exception);
1561 if (caught_exception) {
1562 return;
1563 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001564 // First notify the builtin debugger.
1565 if (message_thread_ != NULL) {
1566 message_thread_->DebugEvent(event, exec_state, event_data);
1567 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001568 // Notify registered debug event listeners. The list can contain both C and
1569 // JavaScript functions.
1570 v8::NeanderArray listeners(Factory::debug_event_listeners());
1571 int length = listeners.length();
1572 for (int i = 0; i < length; i++) {
1573 if (listeners.get(i)->IsUndefined()) continue; // Skip deleted ones.
1574 v8::NeanderObject listener(JSObject::cast(listeners.get(i)));
1575 Handle<Object> callback_data(listener.get(1));
1576 if (listener.get(0)->IsProxy()) {
1577 // C debug event listener.
1578 Handle<Proxy> callback_obj(Proxy::cast(listener.get(0)));
1579 v8::DebugEventCallback callback =
1580 FUNCTION_CAST<v8::DebugEventCallback>(callback_obj->proxy());
1581 callback(event,
1582 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state)),
1583 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data)),
1584 v8::Utils::ToLocal(callback_data));
1585 } else {
1586 // JavaScript debug event listener.
1587 ASSERT(listener.get(0)->IsJSFunction());
1588 Handle<JSFunction> fun(JSFunction::cast(listener.get(0)));
1589
1590 // Invoke the JavaScript debug event listener.
1591 const int argc = 4;
1592 Object** argv[argc] = { Handle<Object>(Smi::FromInt(event)).location(),
1593 exec_state.location(),
1594 event_data.location(),
1595 callback_data.location() };
1596 Handle<Object> result = Execution::TryCall(fun, Top::global(),
1597 argc, argv, &caught_exception);
1598 if (caught_exception) {
1599 // Silently ignore exceptions from debug event listeners.
1600 }
1601 }
1602 }
1603}
1604
1605
1606void Debugger::SetMessageHandler(v8::DebugMessageHandler handler, void* data) {
1607 debug_message_handler_ = handler;
1608 debug_message_handler_data_ = data;
1609 if (!message_thread_) {
1610 message_thread_ = new DebugMessageThread();
1611 message_thread_->Start();
1612 }
1613 UpdateActiveDebugger();
1614}
1615
1616
kasper.lund7276f142008-07-30 08:49:36 +00001617// Posts an output message from the debugger to the debug_message_handler
1618// callback. This callback is part of the public API. Messages are
1619// kept internally as Vector<uint16_t> strings, which are allocated in various
1620// places and deallocated by the calling function sometime after this call.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001621void Debugger::SendMessage(Vector< uint16_t> message) {
1622 if (debug_message_handler_ != NULL) {
1623 debug_message_handler_(message.start(), message.length(),
1624 debug_message_handler_data_);
1625 }
1626}
1627
1628
1629void Debugger::ProcessCommand(Vector<const uint16_t> command) {
1630 if (message_thread_ != NULL) {
1631 message_thread_->ProcessCommand(
1632 Vector<uint16_t>(const_cast<uint16_t *>(command.start()),
1633 command.length()));
1634 }
1635}
1636
1637
1638void Debugger::UpdateActiveDebugger() {
1639 v8::NeanderArray listeners(Factory::debug_event_listeners());
1640 int length = listeners.length();
1641 bool active_listener = false;
1642 for (int i = 0; i < length && !active_listener; i++) {
1643 active_listener = !listeners.get(i)->IsUndefined();
1644 }
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001645 set_debugger_active((Debugger::message_thread_ != NULL &&
1646 Debugger::debug_message_handler_ != NULL) ||
1647 active_listener);
1648 if (!debugger_active() && message_thread_)
1649 message_thread_->OnDebuggerInactive();
1650}
1651
1652
1653DebugMessageThread::DebugMessageThread()
1654 : host_running_(true),
kasper.lund7276f142008-07-30 08:49:36 +00001655 command_queue_(kQueueInitialSize),
1656 message_queue_(kQueueInitialSize) {
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001657 command_received_ = OS::CreateSemaphore(0);
kasper.lund7276f142008-07-30 08:49:36 +00001658 message_received_ = OS::CreateSemaphore(0);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001659}
1660
kasper.lund7276f142008-07-30 08:49:36 +00001661// Does not free resources held by DebugMessageThread
1662// because this cannot be done thread-safely.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001663DebugMessageThread::~DebugMessageThread() {
1664}
1665
1666
kasper.lund7276f142008-07-30 08:49:36 +00001667// Puts an event coming from V8 on the queue. Creates
1668// a copy of the JSON formatted event string managed by the V8.
1669// Called by the V8 thread.
1670// The new copy of the event string is destroyed in Run().
1671void DebugMessageThread::SendMessage(Vector<uint16_t> message) {
1672 Vector<uint16_t> message_copy = message.Clone();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001673 Logger::DebugTag("Put message on event message_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001674 message_queue_.Put(message_copy);
1675 message_received_->Signal();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001676}
1677
1678
1679void DebugMessageThread::SetEventJSONFromEvent(Handle<Object> event_data) {
1680 v8::HandleScope scope;
1681 // Call toJSONProtocol on the debug event object.
1682 v8::Local<v8::Object> api_event_data =
1683 v8::Utils::ToLocal(Handle<JSObject>::cast(event_data));
1684 v8::Local<v8::String> fun_name = v8::String::New("toJSONProtocol");
1685 v8::Local<v8::Function> fun =
1686 v8::Function::Cast(*api_event_data->Get(fun_name));
1687 v8::TryCatch try_catch;
kasper.lund7276f142008-07-30 08:49:36 +00001688 v8::Local<v8::Value> json_event = *fun->Call(api_event_data, 0, NULL);
1689 v8::Local<v8::String> json_event_string;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001690 if (!try_catch.HasCaught()) {
kasper.lund7276f142008-07-30 08:49:36 +00001691 if (!json_event->IsUndefined()) {
1692 json_event_string = json_event->ToString();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001693 if (FLAG_trace_debug_json) {
kasper.lund7276f142008-07-30 08:49:36 +00001694 PrintLn(json_event_string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001695 }
kasper.lund7276f142008-07-30 08:49:36 +00001696 v8::String::Value val(json_event_string);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001697 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
kasperl@chromium.org41044eb2008-10-06 08:24:46 +00001698 json_event_string->Length());
kasper.lund7276f142008-07-30 08:49:36 +00001699 SendMessage(str);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001700 } else {
kasper.lund7276f142008-07-30 08:49:36 +00001701 SendMessage(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001702 }
1703 } else {
1704 PrintLn(try_catch.Exception());
kasper.lund7276f142008-07-30 08:49:36 +00001705 SendMessage(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001706 }
1707}
1708
1709
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001710void DebugMessageThread::Run() {
kasper.lund7276f142008-07-30 08:49:36 +00001711 // Sends debug events to an installed debugger message callback.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001712 while (true) {
kasper.lund7276f142008-07-30 08:49:36 +00001713 // Wait and Get are paired so that semaphore count equals queue length.
1714 message_received_->Wait();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001715 Logger::DebugTag("Get message from event message_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001716 Vector<uint16_t> message = message_queue_.Get();
1717 if (message.length() > 0) {
1718 Debugger::SendMessage(message);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001719 }
1720 }
1721}
1722
1723
kasper.lund44510672008-07-25 07:37:58 +00001724// This method is called by the V8 thread whenever a debug event occurs in
1725// the VM.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001726void DebugMessageThread::DebugEvent(v8::DebugEvent event,
1727 Handle<Object> exec_state,
1728 Handle<Object> event_data) {
kasper.lund212ac232008-07-16 07:07:30 +00001729 if (!Debug::Load()) return;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001730
1731 // Process the individual events.
1732 bool interactive = false;
1733 switch (event) {
1734 case v8::Break:
v8.team.kasperl727e9952008-09-02 14:56:44 +00001735 interactive = true; // Break event is always interactive
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001736 break;
1737 case v8::Exception:
v8.team.kasperl727e9952008-09-02 14:56:44 +00001738 interactive = true; // Exception event is always interactive
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001739 break;
1740 case v8::BeforeCompile:
1741 break;
1742 case v8::AfterCompile:
1743 break;
1744 case v8::NewFunction:
1745 break;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001746 default:
1747 UNREACHABLE();
1748 }
1749
1750 // Done if not interactive.
1751 if (!interactive) return;
1752
1753 // Get the DebugCommandProcessor.
1754 v8::Local<v8::Object> api_exec_state =
1755 v8::Utils::ToLocal(Handle<JSObject>::cast(exec_state));
1756 v8::Local<v8::String> fun_name =
1757 v8::String::New("debugCommandProcessor");
1758 v8::Local<v8::Function> fun =
1759 v8::Function::Cast(*api_exec_state->Get(fun_name));
1760 v8::TryCatch try_catch;
1761 v8::Local<v8::Object> cmd_processor =
1762 v8::Object::Cast(*fun->Call(api_exec_state, 0, NULL));
1763 if (try_catch.HasCaught()) {
1764 PrintLn(try_catch.Exception());
1765 return;
1766 }
1767
v8.team.kasperl727e9952008-09-02 14:56:44 +00001768 // Notify the debugger that a debug event has occurred.
kasper.lund7276f142008-07-30 08:49:36 +00001769 host_running_ = false;
1770 SetEventJSONFromEvent(event_data);
1771
1772 // Wait for commands from the debugger.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001773 while (true) {
kasper.lund7276f142008-07-30 08:49:36 +00001774 command_received_->Wait();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001775 Logger::DebugTag("Get command from command queue, in interactive loop.");
kasper.lund7276f142008-07-30 08:49:36 +00001776 Vector<uint16_t> command = command_queue_.Get();
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001777 ASSERT(!host_running_);
1778 if (!Debugger::debugger_active()) {
1779 host_running_ = true;
1780 return;
1781 }
1782
1783 // Invoke the JavaScript to convert the debug command line to a JSON
kasper.lund7276f142008-07-30 08:49:36 +00001784 // request, invoke the JSON request and convert the JSON response to a text
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001785 // representation.
1786 v8::Local<v8::String> fun_name;
1787 v8::Local<v8::Function> fun;
1788 v8::Local<v8::Value> args[1];
1789 v8::TryCatch try_catch;
1790 fun_name = v8::String::New("processDebugCommand");
1791 fun = v8::Function::Cast(*cmd_processor->Get(fun_name));
kasper.lund7276f142008-07-30 08:49:36 +00001792 args[0] = v8::String::New(reinterpret_cast<uint16_t*>(command.start()),
1793 command.length());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001794 v8::Local<v8::Value> result_val = fun->Call(cmd_processor, 1, args);
1795
1796 // Get the result of the command.
1797 v8::Local<v8::String> result_string;
1798 bool running = false;
1799 if (!try_catch.HasCaught()) {
1800 // Get the result as an object.
1801 v8::Local<v8::Object> result = v8::Object::Cast(*result_val);
1802
1803 // Log the JSON request/response.
1804 if (FLAG_trace_debug_json) {
1805 PrintLn(result->Get(v8::String::New("request")));
1806 PrintLn(result->Get(v8::String::New("response")));
1807 }
1808
1809 // Get the running state.
1810 running = result->Get(v8::String::New("running"))->ToBoolean()->Value();
1811
1812 // Get result text.
1813 v8::Local<v8::Value> text_result =
1814 result->Get(v8::String::New("response"));
1815 if (!text_result->IsUndefined()) {
1816 result_string = text_result->ToString();
1817 } else {
1818 result_string = v8::String::New("");
1819 }
1820 } else {
1821 // In case of failure the result text is the exception text.
1822 result_string = try_catch.Exception()->ToString();
1823 }
1824
1825 // Convert text result to C string.
1826 v8::String::Value val(result_string);
1827 Vector<uint16_t> str(reinterpret_cast<uint16_t*>(*val),
1828 result_string->Length());
1829
kasper.lund7276f142008-07-30 08:49:36 +00001830 // Set host_running_ correctly for nested debugger evaluations.
1831 host_running_ = running;
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001832
1833 // Return the result.
kasper.lund7276f142008-07-30 08:49:36 +00001834 SendMessage(str);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001835
1836 // Return from debug event processing is VM should be running.
1837 if (running) {
1838 return;
1839 }
1840 }
1841}
1842
1843
kasper.lund7276f142008-07-30 08:49:36 +00001844// Puts a command coming from the public API on the queue. Creates
1845// a copy of the command string managed by the debugger. Up to this
1846// point, the command data was managed by the API client. Called
1847// by the API client thread. This is where the API client hands off
1848// processing of the command to the DebugMessageThread thread.
1849// The new copy of the command is destroyed in HandleCommand().
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001850void DebugMessageThread::ProcessCommand(Vector<uint16_t> command) {
kasper.lund7276f142008-07-30 08:49:36 +00001851 Vector<uint16_t> command_copy = command.Clone();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001852 Logger::DebugTag("Put command on command_queue.");
kasper.lund7276f142008-07-30 08:49:36 +00001853 command_queue_.Put(command_copy);
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001854 command_received_->Signal();
1855}
1856
1857
1858void DebugMessageThread::OnDebuggerInactive() {
kasper.lund7276f142008-07-30 08:49:36 +00001859 // Send an empty command to the debugger if in a break to make JavaScript run
1860 // again if the debugger is closed.
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001861 if (!host_running_) {
kasper.lund7276f142008-07-30 08:49:36 +00001862 ProcessCommand(Vector<uint16_t>::empty());
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001863 }
1864}
1865
kasper.lund7276f142008-07-30 08:49:36 +00001866
1867MessageQueue::MessageQueue(int size) : start_(0), end_(0), size_(size) {
1868 messages_ = NewArray<Vector<uint16_t> >(size);
1869}
1870
1871
1872MessageQueue::~MessageQueue() {
1873 DeleteArray(messages_);
1874}
1875
1876
1877Vector<uint16_t> MessageQueue::Get() {
1878 ASSERT(!IsEmpty());
1879 int result = start_;
1880 start_ = (start_ + 1) % size_;
1881 return messages_[result];
1882}
1883
1884
1885void MessageQueue::Put(const Vector<uint16_t>& message) {
1886 if ((end_ + 1) % size_ == start_) {
1887 Expand();
1888 }
1889 messages_[end_] = message;
1890 end_ = (end_ + 1) % size_;
1891}
1892
1893
1894void MessageQueue::Expand() {
1895 MessageQueue new_queue(size_ * 2);
1896 while (!IsEmpty()) {
1897 new_queue.Put(Get());
1898 }
1899 Vector<uint16_t>* array_to_free = messages_;
1900 *this = new_queue;
1901 new_queue.messages_ = array_to_free;
1902 // Automatic destructor called on new_queue, freeing array_to_free.
1903}
1904
1905
1906LockingMessageQueue::LockingMessageQueue(int size) : queue_(size) {
1907 lock_ = OS::CreateMutex();
1908}
1909
1910
1911LockingMessageQueue::~LockingMessageQueue() {
1912 delete lock_;
1913}
1914
1915
1916bool LockingMessageQueue::IsEmpty() const {
1917 ScopedLock sl(lock_);
1918 return queue_.IsEmpty();
1919}
1920
1921
1922Vector<uint16_t> LockingMessageQueue::Get() {
1923 ScopedLock sl(lock_);
1924 Vector<uint16_t> result = queue_.Get();
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001925 Logger::DebugEvent("Get", result);
kasper.lund7276f142008-07-30 08:49:36 +00001926 return result;
1927}
1928
1929
1930void LockingMessageQueue::Put(const Vector<uint16_t>& message) {
1931 ScopedLock sl(lock_);
1932 queue_.Put(message);
mads.s.ager@gmail.com769cc962008-08-06 10:02:49 +00001933 Logger::DebugEvent("Put", message);
kasper.lund7276f142008-07-30 08:49:36 +00001934}
1935
1936
1937void LockingMessageQueue::Clear() {
1938 ScopedLock sl(lock_);
1939 queue_.Clear();
1940}
1941
1942
christian.plesner.hansen43d26ec2008-07-03 15:10:15 +00001943} } // namespace v8::internal